El TecnoBaúl de Kiquenet

Kiquenet boring stories

Archive for 22 enero 2015

Modify machine.config (config files) using Powershell

Posted by kiquenet en 22 enero 2015

ConfigurationManager

$config = [System.Configuration.ConfigurationManager]::OpenMachineConfiguration() 

"{0,-25}     {1,25}"  -f "   Name", "   Allow Definition"
"{0,-25}     {1,25}"  -f "   —-", "   —————-"
$i = 0 

foreach ($section in $config.Sections) 

     "{0,-25}     {1,25}" -f $section.SectionInformation.Name,$section.SectionInformation.AllowExeDefinition 
     $i++ 

"Total number of sections: {0}" -f $i

get-content and DocumentElement

$xml = [xml](get-content $machineConfig)
$xml.Save($machineConfig + "_$currentDate")
$root = $xml.get_DocumentElement()
$system_web = $root."system.web"
if ($system_web.machineKey -eq $nul) {
$machineKey = $xml.CreateElement("machineKey")
$a = $system_web.AppendChild($machineKey)
}
$system_web.SelectSingleNode("machineKey").SetAttribute("validationKey","$validationKey")
$system_web.SelectSingleNode("machineKey").SetAttribute("decryptionKey","$decryptionKey")
$system_web.SelectSingleNode("machineKey").SetAttribute("validation","$validation")
$a = $xml.Save($machineConfig)

XmlDocument

if (!$origXml.configuration.’system.serviceModel’.bindings)
{
    $tempXmlDoc = new-object System.Xml.XmlDocument
    $tempXmlDoc.LoadXml($newXml)
    $newNode = $origXml.ImportNode($tempXmlDoc.DocumentElement, $true)
    $origXml.configuration.’system.serviceModel’.AppendChild($newNode)
}

Sources:
http://sunauskas.com/blog/edit-config-file-with-powershell/
http://geekswithblogs.net/nharrison/archive/2011/05/25/updating-the-machine.config–with-powershell.aspx

http://pshscripts.blogspot.com.es/2009/02/get-machineconfig.html
http://jeffgraves.me/2012/06/05/read-write-net-machine-key-with-powershell/
http://stackoverflow.com/questions/10342657/how-can-i-add-a-section-to-a-web-config-using-powershell

Posted in PowerShell, Scripts | Etiquetado: , , | Leave a Comment »

Installing PowerShell Active Directory Module for Windows 8.1

Posted by kiquenet en 21 enero 2015

STEP 1.) Download and install Remote Server Administration Tools (RSAT) for Windows 8.1
http://www.microsoft.com/en-us/download/details.aspx?id=39296

STEP 2.) For x64, install Windows8.1-KB2693643-x64.msu

STEP 3.) Active Feature

Select AD DS and AD LDS Tools and then select Active Directory Module for Windows PowerShell.

To turn off specific tools

  1. On the desktop, hover in the upper right corner of the screen, and then click Settings.
  2. On the Desktop menu, click Control Panel.
  3. Click Programs, and then in Programs and Features, click Turn Windows features on or off.
  4. In the Windows Features dialog box, expand Remote Server Administration Tools, and then expand either Role Administration Tools or Feature Administration Tools.
  5. Clear the check boxes for any tools that you want to turn off. Click OK, and then close Control Panel.

STEP 4.)
Open a PowerShell prompt and type PS C:\> Get-Module –ListAvailable.

STEP 5.)

To ensure the Active Directory Module is present, using PowerShell type PS C:> Import-Module ActiveDirectory.

NOTE: You will need to do this for every PowerShell session.

If you wish to have the Active Directory Module automatically loaded any time you run PowerShell, prepare a shortcut with the following content: %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory

STEP 6.)

PS C:> Get-ADGroupMember "MY CUSTOM GROUP IN AD" | select name

Appenders:

Installation and Uninstallation of MSU in silent mode
http://msiworld.blogspot.com.es/2012/04/silent-install-and-uninstall-of-msu.html

MSU are the Microsoft Update files.
You can easily install the MSU file silently without reboot with the following command line:
wusa.exe Windows6.1-KB123456-x86.msu /quiet /norestart
To Uninstall it Silently you need to follow this simple procedure:
1) Run this command:
expand c:\temp\Windows6.0-KB123456-x86.msu –F:Windows6.0-KB123456-x86.xml c:\temp
2) This will create an XML file in temp folder as per the name above.
Edit this xml in notepad.
3)Find the assemblyidentity tag. Then, note the values of the following attributes:

  • The name attribute
  • The publickeytoken attribute
  • The processArchitecture attribute
  • The version attribute

4) Use the below command to uninstall the MSU from your machine.
start /w pkgmgr /up:name~publickeytoken~processArchitecture~~version
Note: The variables above need to be replaced by the vaules you have copied in step 3.

Using powershell view http://powershell.org/wp/forums/topic/installing-msu-via-powershell-psexec/ and http://www.nigelboulton.co.uk/2011/01/installing-a-windows-hotfix-on-multiple-machines-using-a-powershell-script/#comment-23005 and http://randygray.com/powershell-install-multiple-windows-updates-msu/

Sources:

https://support.software.dell.com/es-es/appassure/kb/117489

Posted in PowerShell, Scripts | Etiquetado: , , , | Leave a Comment »

Working with Active Directory in C#

Posted by kiquenet en 15 enero 2015

Tools

Sysinternals ADExplorer
http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx

LDAP Browser (Softerra)
http://www.ldapadministrator.com/softerra-ldap-browser.htm

Classes .NET

System.DirectoryServices.DirectoryEntry

System.DirectoryServices.AccountManagement.PrincipalContext

Helpers and Snippet C#

http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/all-operations-on-active-directory-ad-using-C-Sharp/

http://stackoverflow.com/questions/23693209/how-to-get-all-the-users-details-from-active-directory-using-ldap

http://www.snippetsource.net/Snippet/109/helper-to-get-properties-of-directoryentry-in-c

https://github.com/KnowMoreIT/CloudPanel-Legacy/blob/967d1739940842deb548bd5867df0223f9deae0e/CloudPanel.Modules.ActiveDirectory/UserPrincipalExt.cs

http://sahanganepola.blogspot.com.es/2009/01/how-to-change-active-directory-user.html

http://stackoverflow.com/questions/1433383/net-ldap-paths-utilities-c

LDAP

Ports: 389 , 636
http://blog.evanmc.com/?p=9

References

Here is AD user attributes reference(in case you would like to get something else). Note: not all attributes

http://www.kouti.com/tables/userattributes.htm

Sources:
http://stackoverflow.com/questions/12623637/cant-get-user-from-directoryentry
http://www.codeproject.com/Questions/446296/LDAP-connection-using-PrincipalContext

Posted in .NET | Etiquetado: , | Leave a Comment »

Arrays in Powershell

Posted by kiquenet en 9 enero 2015

Collections, Hashtables, Arrays, strings
https://www.simple-talk.com/sysadmin/powershell/powershell-one-liners–collections,-hashtables,-arrays-and-strings/

Define Array

$configs = @(

     "C:\tfs\Arquitectura\ConnectionStrings.config"; 
     "C:\tfs\VSIntegration\Test\App.config"; 
)

Foreach Array

for( $i = 0; $i -lt $configs.length; $i++) {
  $config = $configs[$i]
 
  Write-Host setting $config
 
}

Alternative

function ConvertTo-MyTypeOfItem
{
    PARAM (
        [ValidatePattern("([^_]+_){3}[^_]+")]
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$StringToParse
    )

    PROCESS {
        $custId, $invId, $prodId, [int]$value = $StringToParse -split "_"
        $myObject = New-Object PSObject -Property @{
            CustomerID = $custId;
            InvoiceID = $invId;
            ProductID = $prodId;
            Value = $value
        }
        Write-Output $myObject
    }
}

# In the test scenario I have replaced getting the list of files
# with an array of names. Just uncomment the first and second lines
# following this comment and remove the other $baseNames setter, to
# get the $baseNames from the file listing

#$files = Get-ChildItem test *.txt
#$baseNames = $files.BaseName
$baseNames = @(
    "cust1_inv1_prod1_1";
    "cust2_inv2_prod2_2";
    "cust3_inv3_prod3_3";
    "cust4_inv4_prod4_4";
)

$myObjectArray = $baseNames | ConvertTo-MyTypeOfItem

$myObjectArray

Sources:
http://stackoverflow.com/questions/21884828/powershell-array-to-store-strings
http://stackoverflow.com/questions/25191803/powershell-cli-foreach-loop-with-multiple-arrays
http://www.powershellpro.com/powershell-tutorial-introduction/variables-arrays-hashes/

Posted in PowerShell, Scripts | Etiquetado: , | Leave a Comment »

Members, Contributor, Groups, Identities in TFS

Posted by kiquenet en 5 enero 2015

Get members of TFS Group

private List<Identity> ListContributors()
{
    const string projectName = "<<TFS PROJECT NAME>>";
    const string groupName = "Contributors";
    const string projectUri = "<<TFS PROJECT COLLECTION OR URL TFS SERVER>>";

    TfsTeamProjectCollection projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(projectUri));
    ICommonStructureService css = (ICommonStructureService) projectCollection.GetService(typeof(ICommonStructureService));
    IGroupSecurityService gss = projectCollection.GetService<IGroupSecurityService>();

    // get the tfs project
    var projectList = css.ListAllProjects();
    var project = projectList.FirstOrDefault(o => o.Name.Contains(projectName));

    // project doesn’t exist
    if (project == null) return null;

    // get the tfs group
    var groupList = gss.ListApplicationGroups(project.Uri);
    var group = groupList.FirstOrDefault(o => o.DisplayName.Contains(groupName));  // you can also use DisplayName or AccountName. AccountName is empty for me.

    // group doesn’t exist
    if (group == null) return null;

    Identity sids = gss.ReadIdentity(SearchFactor.Sid, group.Sid, QueryMembership.Expanded);

    // there are no users
    if (sids.Members.Length == 0) return null;

    // convert to a list
    List<Identity> contributors = gss.ReadIdentities(SearchFactor.Sid, sids.Members, QueryMembership.Expanded).ToList();

    return contributors;
}

Add SID to a Readers group

# load the required dll
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")

function get-tfs
{
    param(
    [string] $serverName = $(throw ‘serverName is required’)
    )

    $propertiesToAdd = (
        (‘VCS’, ‘Microsoft.TeamFoundation.VersionControl.Client’, ‘Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer’),
        (‘WIT’, ‘Microsoft.TeamFoundation.WorkItemTracking.Client’, ‘Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore’),
        (‘CSS’, ‘Microsoft.TeamFoundation’, ‘Microsoft.TeamFoundation.Server.ICommonStructureService’),
        (‘GSS’, ‘Microsoft.TeamFoundation’, ‘Microsoft.TeamFoundation.Server.IGroupSecurityService’)
    )

    [psobject] $tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($serverName)
    foreach ($entry in $propertiesToAdd) {
        $scriptBlock = ‘
            [System.Reflection.Assembly]::LoadWithPartialName("{0}") > $null
            $this.GetService([{1}])
        ‘ -f $entry[1],$entry[2]
        $tfs | add-member scriptproperty $entry[0] $ExecutionContext.InvokeCommand.NewScriptBlock($scriptBlock)
    }
    return $tfs
}
#set the TFS server url
[psobject] $tfs = get-tfs -serverName
http://YourTfsServer:8080/tfs/YourColleciton

$items = $tfs.vcs.GetAllTeamProjects( ‘True’ )
    $items | foreach-object -process {
    $proj = $_
    $readers = $tfs.GSS.ListApplicationGroups($proj.Name) | ?{$_.DisplayName -eq ‘Readers’ }

    $tfs.GSS.AddMemberToApplicationGroup($readers.Sid, ‘TheSidToTheGroupYouWantToAdd’)
}

var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://vsalm:8080/tfs/FabrikamFiberCollection"));

            var ims = tpc.GetService<IIdentityManagementService>();

            var tfsGroupIdentity = ims.ReadIdentity(IdentitySearchFactor.AccountName,
                                                    "[FabrikamFiber]\\Fabrikam Fiber Web Team",
                                                    MembershipQuery.None,
                                                    ReadIdentityOptions.IncludeReadFromSource);           

            var userIdentity = ims.ReadIdentity(IdentitySearchFactor.AccountName,
                                                    "VSALM\\Barry",
                                                    MembershipQuery.None,
                                                    ReadIdentityOptions.IncludeReadFromSource);

            ims.AddMemberToApplicationGroup(tfsGroupIdentity.Descriptor, userIdentity.Descriptor);

Sources:
http://stackoverflow.com/questions/16792995/get-members-of-tfs-group

http://stackoverflow.com/questions/7961727/how-to-grant-read-only-access-to-all-tfs-team-projects-to-a-group-of-users/7971731#7971731

http://blog.ronischuetz.com/2010/04/tfs-api-list-all-tfs-users.html

http://pauravlokesh.wordpress.com/2013/08/13/recursively-list-groups-users-tfsteamprojectcollection/

http://geekswithblogs.net/TarunArora/archive/2011/09/30/tfs-sdk-get-groups-users-permissions-using-tfs-api-with.aspx

Posted in .NET, PowerShell, Scripts, TFS | Etiquetado: , , | Leave a Comment »

Delete TestResults folder (Unit Testing Visual Studio)

Posted by kiquenet en 5 enero 2015

Cleaning up Visual Studio TestResults with PowerShell

If you write your unit tests using Visual Studio, then you know how quickly those pesky "TestResults" folders can eat up precious disk space over time.

Assuming all of your code is collocated in the same parent directory, replace "C:\TFS" with your parent directory.

(get-childitem C:\TFS\* -recurse) | where{$_.name -eq "TestResults"} |% {remove-item $_.fullname -recurse}

Improvements:

Error Handling when deleting folders and files.

Validating contents TestResults folder (subfolders In and Out, *.trx files, …)

$dir = "C:\TFS\"
(get-childitem $dir -recurse) | where { $_.name -eq "TestResults"} | foreach {

   $delete = $false;
   (get-childitem  $_.FullName -recurse) | where {$_.name -eq "Out"}  | foreach {
       
        $ParentS = ($_.Fullname).split("\")
        $Parent = $ParentS[@($ParentS.Length – 3)]
        if ($Parent -eq "TestResults") {$delete = $true;}

   }

   if ($delete)
   {
        Write-Host -ForegroundColor red ("Eliminando {0}" -f  $_.FullName )
        Remove-item $_.fullname -recurse
   }

}

Write-Host -ForegroundColor red ("Eliminado TestResults de {0}" -f  $dir )

Source:
http://captechconsulting.com/blog/mike-etheridge/cleaning-visual-studio-testresults-powershell

Posted in .NET, PowerShell, Productividad, Scripts, VisualStudio | Etiquetado: , , | Leave a Comment »

Change Owner Workspaces

Posted by kiquenet en 5 enero 2015

For example, maybe Domain is changed in a company.
We have workspaces with the older domain and older user.

Required change to new domain and new user (NEWDOMAIN\NEWUSER).

TFS 2008: The Team Foundation Server for this workspace does not support changing the owner of a workspace.

Using tf.exe command:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE

Workspace Command
http://msdn.microsoft.com/en-us/library/y901w7se(v=vs.100).aspx

Workspaces Command
http://msdn.microsoft.com/en-us/library/54dkh0y3(v=vs.100).aspx

Useful commands:

tf workspaces /collection:http://tfsServer:8080 /owner:* /computer:MYCOMPUTER /FORMAT:DETAILED

tf workspace /name:workspacename;workspaceowner /collection:tpcUrl
tf status /collection:tpcUrl /workspace:workspacename;workspaceowner
tf shelve /recursive name;owner *.* /move

tf workspace /new <name> /template:<oldname>;<olduser>

tf workspace /delete PC123;other-user /server:http://tfs:8080

A deleted workspace cannot be recovered.
Workspace ‘PC123′ on server ‘
http://tfs.8080′ has 0 pending change(s).

Are you sure you want to delete the workspace? (Yes/No)

Real usage:

tf workspace /new "MyTeamProject in MYCOMPUTER with owner NEWUSER;NEWDOMAIN\NEWUSER" /template:"MyTeamProject in MYCOMPUTER with owner OLDUSER;OLDERDOMAIN\OLDERUSER" /collection:http://tfsServer:8080

tf workspace /delete /server:http://tfsServer:8080 "MyTeamProject in MYCOMPUTER with owner OLDUSER;OLDERDOMAIN\OLDERUSER"

tf workspace /server:http://tfsServer:8080 "MyTeamProject in MYCOMPUTER with owner NEWUSER;NEWDOMAIN\NEWUSER"

Useful https://tfsworkspacescleaner.codeplex.com/

Sources:

http://www.colinsalmcorner.com/post/workspaces-updating-the-owner

http://willemduncan.github.io/2014-11-10/RemoveTFSWorkspaces/
https://grumpywookie.wordpress.com/2008/04/02/tfs-workspace-for-another-user/

http://roadtoalm.com/2012/09/03/tfs-source-control-2012workspaces-part-2/
http://roadtoalm.com/2012/08/16/tfs-source-control-2012workspaces-part-1/

http://blogs.msdn.com/b/phkelley/archive/2013/05/28/workspaces.aspx
http://davehope.co.uk/Blog/deleting-the-tfs-workspace-for-a-missing-account-fails-tf50605/

Posted in .NET, TFS | Etiquetado: , | Leave a Comment »

Manage Credentials programmatically using C#

Posted by kiquenet en 2 enero 2015

Credential Manager

CredentialManagement
http://nuget.org/packages/CredentialManagement/

http://credentialmanagement.codeplex.com/SourceControl/latest

CredMan.ps1
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Credentials-d44c3cde

        [TestMethod]
        public void Set_Credentials_for_older_domain_whe_migration_to_new_domain()
        {
            var accesos = new List<string> {
            "intranet",
            "intranet.xxxxx.net",
            "intranet.zzzzzzzz.com",
            "intranetescritorio.zzzzzzzz.net",
            "more…",
            };

            accesos.ForEach(acceso => SaveCredential(acceso));
        }

        private static Credential SaveCredential(string CredentialName)
        {
            var UserName = @"OLDERDOMAIN\user";
            var Password = "pass";

            var cm = new Credential { Target = CredentialName, Type = CredentialType.DomainPassword };
            if (cm.Exists())
            {
                cm.Load();
                Console.WriteLine("Credential " + cm.Target + ". Data: " + cm.Username + " " + cm.Password);

                //if (cm.Type == CredentialType.Generic)  cm.Delete();

                return cm;
            }

            cm = new Credential
            {
                Target = CredentialName,
                Type = CredentialType.DomainPassword,
                PersistanceType = PersistanceType.Enterprise,
                Username = UserName,
                Password = Password
            };
            cm.Save();
            return cm;
        }

Tools useful: PromptForCredentials Builder and Credential Set Manager by Kenny Kerr (Microsoft)

Windows 8 – New API Windows.Security
http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.aspx
https://code.msdn.microsoft.com/windowsapps/PasswordVault-f01be74a

[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
(new-object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % { $_.RetrievePassword(); $_ }

It only displays data from the Web Credentials store, not the Windows Credentials

The new api has no way to access the Windows Credentials

http://stackoverflow.com/questions/14813370/how-to-access-the-stored-credentials-passwordvault-on-win7-and-win8

Sources:

http://msdn.microsoft.com/en-us/library/aa480470.aspx#cred_topic5

http://stackoverflow.com/questions/9221245/how-do-i-store-and-retrieve-credentials-from-the-windows-vault-credential-manage

http://stackoverflow.com/questions/17741424/retrieve-credentials-from-windows-credentials-store-using-c-sharp

Posted in .NET, Security, Seguridad | Etiquetado: | Leave a Comment »