Monday, August 31, 2015

Powershell script to upload files recursively to FTP server

Uploading the files recursively here "D:\test" is source folder and destination is FTP server
$ftp_uri = "ftp://demo.azurewebsites.windows.net/"
$user = "domain\username"
$pass = "Password"
$path= "D;\test"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
 foreach($item in Get-ChildItem -recurse $path)
{
  $relpath =    [system.io.path]::GetFullPath($item.FullName).SubString([system.io.path]::GetFullPath($path).Length + 1)
        if ($item.Attributes -eq "Directory")
         {
            try
             {
                Write-Host Creating $item.Name
                $makeDirectory = [System.Net.WebRequest]::Create($ftp_uri+$relpath);
                $makeDirectory.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
                $makeDirectory.Method = [System.Net.WebRequestMethods+FTP]::MakeDirectory;
                $makeDirectory.GetResponse();
            }
            catch [Net.WebException]
             {
                Write-Host $item.Name Directory may be already exists.
            }
            continue;
        }
        "Uploading $item to :  $relpath"
        $uri = New-Object System.Uri($ftp_uri+$relpath)
        $webclient.UploadFile($uri, $item.FullName)
    }

Sunday, August 30, 2015

Powershell script to check in multiple files in TFS source control

param (
    [string]$tfsServer = "http://vsalm:8080/tfs/FabrikamFiberCollection",
    [string]$tfsLocation = "$/MPPDemo/Calculator/CalcTest",
    [string]$localFolder ="C:\test",
    [string]$file,
    [string]$checkInComments = "Checked in from PowerShell"
)
$clientDll = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Client.dll"
$versionControlClientDll = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.VersionControl.Client.dll"
$versionControlCommonDll = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Common.dll"
#Load the Assemblies
[Reflection.Assembly]::LoadFrom($clientDll)
[Reflection.Assembly]::LoadFrom($versionControlClientDll)
[Reflection.Assembly]::LoadFrom($versionControlCommonDll)
#Set up connection to TFS Server and get version control
$tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($tfsServer)
$versionControlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
$versionControlServer = $tfs.GetService($versionControlType)
#Create a "workspace" and map a local folder to a TFS location
$workspace = $versionControlServer.CreateWorkspace("PowerShell Workspace",$versionControlServer.AuthenticatedUser)
$workingfolder = New-Object Microsoft.TeamFoundation.VersionControl.Client.WorkingFolder($tfsLocation,$localFolder)
$workspace.CreateMapping($workingFolder)
Get-ChildItem $localFolder -recurse | Foreach-Object {
$file = $_.FullName
 $workspace.PendAdd($file)
} 
#Submit file as a Pending Change and submit the change
$pendingChanges = $workspace.GetPendingChanges()
$workspace.CheckIn($pendingChanges,$checkInComments)
#Delete the temp workspace
$workspace.Delete()

Create custom code analysis rule using FxCop and use it in visual studio 2013

1. Create a class library project in visual studio
2. Add the references FxCopSdk.dll and Microsoft.Cci.dll. The dll location is "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop"
3. Create the XML file and name it as RuleMetadata.xml   
<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="My Custom FxCop Rules">
  <Rule TypeName="EnforceHungarianNotation" Category="MyRules"CheckId="CR1000">
    <Name>Enforce Hungarian Notation</Name>
    <Description>Checks fields for compliance with Hungarian notation.</Description>
    <Resolution>Field {0} is not in Hungarian notation. Field name should be prefixed with '{1}'.              </Resolution>
    <MessageLevel Certainty="100">Warning</MessageLevel>
    <FixCategories>NonBreaking</FixCategories>
    <Url />
    <Owner />
    <Email />
  </Rule>
</Rules> 
4. Create the BaseFxCopRule.cs class
   Note: In below "MyCustomRules.RuleMetadata" MyCutomRules is name space and RuleMetadata is    xml file name which we created above.
using Microsoft.FxCop.Sdk;
namespace MyCustomRules
{
    internal abstract class BaseFxCopRule : BaseIntrospectionRule
    {
        protected BaseFxCopRule(string ruleName)
        : base(ruleName, "MyCustomRules.RuleMetadata"typeof(BaseFxCopRule).Assembly){ }
    }
}
5.Create a EnforceHungarianNotation.cs class which you can wright logic of custom rules.
  Here i we are wright the code for for every static variables should start with s_ and every non static variables should start with m_
using Microsoft.FxCop.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
namespace MyCustomRules
{
    internal sealed class EnforceHungarianNotation : BaseFxCopRule
    {
        public EnforceHungarianNotation()base("EnforceHungarianNotation"){ }
        // Only fire on non-externally visible code elements.
        public override TargetVisibilities TargetVisibility
        {
            get{return TargetVisibilities.NotExternallyVisible;}
        }
        public override ProblemCollection Check(Member member)
        {
            Field field = member as Field;
            if (field == null)
            {
                // This rule only applies to fields.
                // Return a null ProblemCollection so no violations are reported for this member.
                return null;
            }
             if (field.IsStatic){ CheckFieldName(field, s_staticFieldPrefix); }
            else { CheckFieldName(field, s_nonStaticFieldPrefix);}
            // By default the Problems collection is empty so no violations will be reported
            // unless CheckFieldName found and added a problem.
            return Problems;
        }
        private const string s_staticFieldPrefix = "s_";
        private const string s_nonStaticFieldPrefix = "m_";
        static int a;
        private void CheckFieldName(Field field, string expectedPrefix)
        {
            if (!field.Name.Name.StartsWith(expectedPrefix, StringComparison.Ordinal))
            {
                Resolution resolution = GetResolution(
                  field,  // Field {0} is not in Hungarian notation.
                  expectedPrefix  // Field name should be prefixed with {1}.
                  );
                Problem problem = new Problem(resolution);
                Problems.Add(problem);
            }
        }
    }
} 
6. After completing above steps build your application. Goto Solution Explore-->right click on solution and build it.
7. copy the dll from the bin folder  to "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop\Rules " 
8. Now test the rules for same project. Now goto EnforceHungarianNotation.cs class create a static variable
9. run the code analysis on solution we can see the warning CR1000 which we created.


Tuesday, August 04, 2015

TFS Build Failed for Exception Message: TF270015 Or TF42097


Solution for TFS Build Failed Due to Below Errors
Release | Any CPU
7 error(s), 1 warning(s)
$/TailsPin Toys/TeamBuildTypes/BuildAutomation_Aug/TFSBuild.proj ('CompileConfiguration' target(s)) - 7 error(s), 1 warning(s), View Log File
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1146): Could not write lines to file "E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToys Framework\FrameworkComponents\TailsPinToys.FrameWorkComponents.sln.Release.vsprops". Could not find a part of the path 'E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToys Framework\FrameworkComponents\TailsPinToys.FrameWorkComponents.sln.Release.vsprops'.
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1162): The project file "E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\MW\TailsPinToys.MW.sln" was not found.
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1146): Could not write lines to file "E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\MW\Approval\TailsPinToys.MW.Approval.sln.Release.vsprops". Could not find a part of the path 'E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\MW\Approval\TailsPinToys.MW.Approval.sln.Release.vsprops'.
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1146): Could not write lines to file "E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\MW\InterfaceIntegration\InterfaceIntegration.sln.Release.vsprops". Could not find a part of the path 'E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\MW\InterfaceIntegration\InterfaceIntegration.sln.Release.vsprops'.
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1146): Could not write lines to file "E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\MW\InterfaceIntegration\TailsPinToys.Interface.Services\TailsPinToys.Interface.Services.sln.Release.vsprops". Could not find a part of the path 'E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\MW\InterfaceIntegration\TailsPinToys.Interface.Services\TailsPinToys.Interface.Services.sln.Release.vsprops'.
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1146): Could not write lines to file "E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\Services\TailsPinToys.Service.sln.Release.vsprops". Could not find a part of the path 'E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\Services\TailsPinToys.Service.sln.Release.vsprops'.
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1162): The project file "E:\Builds\1040\TailsPin Toys\TailsPinToysBuild\src\SourceCode\Dev & Release\TailsPinToysBuild\Presentation\TailsPinToys.Presentation.sln" was not found.
 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets (1745): TF42097: A work item could not be saved due to a field error. The following fields have incorrect values: Field: 'PhaseDetected' Value: ''
1 projects/solutions compiled
No Test Results
No Code Coverage Results
Other Errors and Warnings
1 error(s), 0 warning(s)
 Exception Message: TF270015: 'MSBuild.exe' returned an unexpected exit code. Expected '0'; actual '1'. See the build logs for more details. (type UnexpectedExitCodeException)Exception Stack Trace:    at System.Activities.Statements.Throw.Execute(CodeActivityContext context)   at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)   at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

Solution for above errors
  1.    Restarted the build agents.
  2.  Create the new build definition.
  3.  Clear the TFS cache form the client machine ” C:\Users\ %user%\AppData\Local\Microsoft\Team Foundation\5.0\Cache”
  4. Clean the Build Directory Path in the build server.
If all the above process is not worked do the below step and check..
  1. Changed the local workspace for that branchs or Team Project.