Tuesday 21 May 2013

SalesForce - Tips

Sales force


 Errors I have encountered while trying to connect without much reading

   LOGIN_MUST_USE_SECURITY_TOKEN: Invalid username, password, security token; or user locked out. Are you at a new location? When accessing Salesforce--either via a desktop client or the API--from outside of your company’s trusted networks, you must add a security token to your password to log in.To receive a new security token, log in to salesforce.com at http://login.salesforce.com and click Setup | My Personal Information | Reset Security Token.
       
  Resolution
      Update password field of your log in with merged password and security token
      var response = sforce.login(LoginUserName, LoginUserPassword + LoginSecurityToken);
       

       


Creating custom fields

 I have used designer to generate custom fields in my object and generated WSDL but my custom field is not present in generated XML.

Solution:

 Go to: Account => Setup =>App Setup=>Objects

Open object you want to edit. Click on field you want to make visible.

 Click on highlighted "Set Field-Level Security"
 

Set appropriate visibility read only levels.











Used references:

reference book
Creating custom fields

Detect access rights to directory

 
Just have been playing on my lunch and wondered how can 
I detect from my C# code whether I have access right for reading/writing to
specific folder.
 
 
I come up after bit of trial and error to code as follows:
 

 

 


string path = @"c:\temp";
string NtAccountName = @"group\userName";

var di = new DirectoryInfo(path);
var acl = di.GetAccessControl(AccessControlSections.Access);
var rules = acl.GetAccessRules(true, true, typeof(NTAccount));

//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
    //If we find one that matches the identity we are looking for
    if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase))
    {
        //Cast to a FileSystemAccessRule to check for access rights
        if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
        {
            Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path));
        }
        else
        {
            Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path));
        }

        if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.Read) > 0)
        {
            Console.WriteLine(string.Format("{0} does not have read access to {1}", NtAccountName, path));
        }
        else
        {
            Console.WriteLine(string.Format("{0} does not have read access to {1}", NtAccountName, path));
        }
    }
}

original code that i used is of course from StackOverflow

 
 
 
 

Thursday 16 May 2013

Continuous Integration - TFS Build web deploy

I have been working on web development for a while no wand using TFS 2010 and 2012.
For a while I am using "web deployment" functionality.

In this article I make the assumption that:
  1. You know how to setup TFS build.
  2. You have setup MS Deploy on your IIS application.
  3. Your are using IIS 7 or higher

To create next step in CI is to have build server deploy your latest version of code to the website.

I am using default build template for this deployment.

Make sure that Web deploy is installed on the server (TFS and deployment)
Note: I am using version Web Deploy 3.0




From the picture you can see default build configuration.

I am using MSBuild arguments in order to realize my deployment.

Now the arguments you need to provide to be able to create deployment.
 
/p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:MSDeployPublishMethod=InProc /p:CreatePackageOnPublish=True /p:MSDeployServiceUrl=localhost /p:DeployIisAppPath="Your Project App Name" /p:UserName=domain\user /p:Password=userPassword

I have had few attempts to do this right, but the most important issue I have had is:
  1. Too long output drop folder in build configuration ( file path exceeded 248 characters)
  2. Insufficient write permissions. This was due to account that is running build did not had write access to folder. Do not let it fool you, account that does the publishing has to have access rights to write into the folder.  Alternative is web deploy service has to run under account that has write privilege to write into target folder. 





Wednesday 15 May 2013

CodeSnippet - Copy stream

/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}
 
 
http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file
 
 

public void DoFileDeletingLogic(){         
   string file = _dataPath + "\\file.txt";
            string fileTemp = _dataPath + "\\fileTemp.txt";
            
            if (!File.Exists(file))
            {
                throw new Exception("File does not exists");
            }

            FileStream fileStream = File.OpenRead(file);
            
   // copy file into new file
   using (Stream newfile = File.OpenWrite(fileTemp))
            {
                CopyStream(fileStream, newfile);
            }
            // and dispose of the stream, as now its locked for access.
   fileStream.Dispose();

            // do your logic here that deletes file
   
   
            if (File.Exists(file))
            {
                throw new Exception("File should be deleted");
            }
            else
            {
                // replace existing file
                File.Move(fileTemp, file);
            }
        }

        /// <summary>
        /// Copies the contents of input to output. Doesn't close either stream.
        /// </summary>
        public static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, len);
            }
        }

Interesting links


Deploy to multiple web-apps in TFS Build

http://stackoverflow.com/questions/6457108/how-to-tell-tfs-to-deploy-multiple-webapps-containing-in-one-solution

Facebook SDK

https://github.com/barans/FacebookCsharpSdk 

Guide for faking DBSet in EF

http://refactorthis.wordpress.com/2011/05/31/mock-faking-dbcontext-in-entity-framework-4-1-with-a-generic-repository/

Ninject logging

http://www.eyecatch.no/blog/2012/08/logging-with-log4net-in-c-sharp/
http://stackoverflow.com/questions/4680303/log-ninject-resolved-dependencies-application-start-up


Dapper 

orm mapping  to data
http://www.contentedcoder.com/2012/12/creating-data-repository-using-dapper.html

Render partial view into string in controller



I have run into a situation where I would like to render a partial view to a string and then return it as part of a JSON response like so:

return Json(new {
 personHtml = RenderPartialViewToString("Person", person)
});
The ability to do something like this would open up a ton of amazing possibilities, so I really scoured the internet looking for a solution. Unfortunately, no one seems to have come up with a clean solution for it, so I dug into the MVC code and came up one…and because I’m such a nice guy, you get to copy it for free. ;)


public abstract class MyBaseController : Controller {

    protected string RenderPartialViewToString()
    {
        return RenderPartialViewToString(null, null);
    }

    protected string RenderPartialViewToString(string viewName)
    {
        return RenderPartialViewToString(viewName, null);
    }

    protected string RenderPartialViewToString(object model)
    {
        return RenderPartialViewToString(null, model);
    }

    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter()) {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

Now you can simply do this:

public class MyController : MyBaseController {

    public ActionResult CreatePerson(Person p) {     
            return Json(new {
                    statusCode = 1,
                    statusMessage = "The person has been added!",
                    personHtml = RenderPartialViewToString("Person", p)
                });
    }
}
Also note that you can modify these functions to render a View (rather than a PartialView) with this small change:

ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName);
Enjoy!

My final implementation is:

  /// <summary>
        /// Renders the partial view to string.
        /// </summary>
        /// <param name="viewName">Name of the view.</param>
        /// <param name="model">The model.</param>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="viewData">The view data.</param>
        /// <param name="tempData">The temp data.</param>
        /// <returns>Returns parsed view as string.</returns>
        /// <remarks>
        /// Used from page: http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
        /// </remarks>
        public static string RenderPartialViewToString(string viewName, object model, ControllerContext controllerContext, ViewDataDictionary viewData, TempDataDictionary tempData)
        {
            viewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
                ViewContext viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        } 
My code is based on :
http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string 

Locking thread singleton example

Example of implementing singleton.


 public class Settings
    {
        /// <summary>
        /// Private lock used while loading
        /// </summary>
        private Object setupLock = new Object();

        /// <summary>
        /// Container for settings loaded from web.config.
        /// </summary>
        private Dictionary<string, object> _settings { get; set; }

        /// <summary>
        /// While class is getting loading information from app.config, the object is locked.
        /// </summary>
        public Settings()
        {
            // Check if settings is null, othewise do not carry on with constructing settings.
            if (_settings == null)
            {
                // Add lock on the process inside
                lock (setupLock)
                {
                    // if this has been hit by 2 processes after each other, make sure that the value is still before start processing.
                    if (_settings == null)
                    {
                        var settings = new Dictionary<string, object>();
                        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
                        {
                            settings.Add(key, ConfigurationManager.AppSettings[key].ToString(CultureInfo.InvariantCulture));
                        }
                        _settings = settings;
                    }
                }
            }
        }

    }
}

Thursday 9 May 2013

Generate class from xml

Using XML Schema Definition Tool (Xsd.exe)

I needed to write code that maps data in xml to my cs file.
I know that that xsd can generate this.

Lets do it step by step.

Generate definition file


C:\test\1>xsd AttachFileHandler.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\test\1\AttachFileHandler.xsd'.




Generate class: 

c:\test\1>xsd /classes /language:CS AttachFileHandler.xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'c:\test\1\AttachFileHandler.cs'.


Generate dataset

C:\test\1>xsd /dataset /language:CS AttachFileHandler.xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\test\1\AttachFileHandler.cs'.


 Final result



C:\test\1>dir

 Directory of C:\test\1

09/05/2013  12:11    <DIR>          .
09/05/2013  12:11    <DIR>          ..
09/05/2013  12:11           468,262 AttachFileHandler.cs
09/05/2013  12:05             2,746 AttachFileHandler.xml
09/05/2013  12:11             8,374 AttachFileHandler.xsd


Result => just extract of generated data

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18034
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.0.30319.17929.

//


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Statistics {
    }



For more help see following location:

http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx tool


Tuesday 7 May 2013

TFS History command


Command to retrieve tfs history


Get me all things what we have worked on within last month.
I know that there is a command: "TF HISTORY"  with basic implementation below

tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/
Where:
1.      $/Project/development – Project against which you want to run report
2.      /collection:http://tfs01:8080/tfs/DevelopmentServices/ -  Tfs collection

Finally add options:

/noprompt
This option:
·         Suppresses the display of windows and dialog boxes (such as the History window) and redirects output data to the command prompt. See Team Foundation Version Control Command Reference.
·         Does not display the history of revisions that occurred before an item was moved, renamed, branched, or merged.

 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt
This had disabled popups
  /user:username
Filters the historical data to show changes made by the specified user. An asterisk (*) symbol includes data on changes from all users (the default).
 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt /user:*

This selected all users for history
/recursive
Recursively retrieves historical data on items in the specified directory and any sub directories.
 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt /user:* /recursive
Suddenly I have all changesets
/format
Specifies how much detail to display about each changeset when the /noprompt option is specified:
·         Brief (default): Displays one line about each changeset that includes: ID number, changes made, user who made the changes, date, and comment. Some of the data may be truncated.
·         Detailed: Displays a full description of each changeset. In addition to the above information, this option displays additional data such as date with time, items changed, check-in notes, and check-in policy warnings.

 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt /user:* /recursive /format:brief
This gets level of detail displayed about changesets

Final Command

tf history /noprompt $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /format:brief /v:D"01/05/2013"~D"05/08/2013" /user:*  /recursive

Resource for this article is of course MSDN