Wednesday, 17 April 2013

Unit testing data annotations

There is little point of testing data annotations, if they are in code hard coded. but in case you have to:
my model definition:

    public class FilterModel
    {
        /// 
        /// Apply filter from date.
        /// 
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        [Display(Name = "From date")]
        public DateTime FromDate { get; set; }

        /// 
        /// Apply filter to date.
        /// 
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        [Display(Name = "To date")]
        public DateTime ToDate { get; set; }
        [Display(Name = "Branch")]
        public int BranchId { get; set; }
        [Display(Name = "Agent")]
        public int RsmId { get; set; }
        public List Branches { get; set; }
        public List Rsms { get; set; }
    }

as you can see I have some hard coded display names I would like to test.

 /// 
        /// Checks the filter contain correct data annotations.
        /// 
        [TestMethod]
        public void CheckFilterContainCorrectDataAnnotations()
        {
            var expectedDisplayName = "From date";
            var expectedToDate= "To date";
            var expectedBranchName = "Branch";
            var expectedAgentName = "Agent";

            var fromDateProperty = typeof(FilterModel).GetProperty("FromDate");
            var toDateProperty = typeof(FilterModel).GetProperty("ToDate");
            var branchProperty = typeof(FilterModel).GetProperty("BranchId");
            var agentProperty = typeof(FilterModel).GetProperty("RsmId");
            
            var fromDateActualName = GetDisplayName(fromDateProperty);
            var actualToDate = GetDisplayName(toDateProperty);
            var actualBranchName = GetDisplayName(branchProperty);
            var actualAgentName = GetDisplayName(agentProperty);
            
            Assert.AreEqual(expectedDisplayName,fromDateActualName);
            Assert.AreEqual(expectedToDate, actualToDate);
            Assert.AreEqual(expectedAgentName, actualAgentName);
            Assert.AreEqual(expectedBranchName, actualBranchName);
        }

Here is my test method to get data using data annotation.
        /// 
        /// Gets the display name.
        /// 
        /// The property.
        /// String of the property name
        public static string GetDisplayName(PropertyInfo property)
        {
            Object[] displayAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), true);
            if (displayAttributes.Length == 1)
                return ((DisplayAttribute)displayAttributes[0]).Name;
            
            return property.Name.ToString(CultureInfo.InvariantCulture);
        }

Wednesday, 10 April 2013

SalesForce Generation of APEX code


Creating an Apex Class from a WSDL

Available in: Unlimited, Developer, Enterprise, and Database.com Editions

User Permissions Needed
To define, edit, delete, set security, set version settings, show dependencies, and run tests for Apex classes:“Author Apex”
An Apex class can be automatically generated from a WSDL document that is stored on a local hard drive or network. Creating a class by consuming a WSDL document allows developers to make callouts to the external Web service in their Apex.
Note
Use Outbound Messaging to handle integration solutions when possible. Use callouts to third-party Web services only when necessary.
To access this functionality:
  1. In the application, click Your Name | Setup | Develop | Apex Classes.
  2. Click Generate from WSDL.
  3. Click Browse to navigate to a WSDL document on your local hard drive or network, or type in the full path. This WSDL document is the basis for the Apex class you are creating.
    Note
    The WSDL document that you specify might contain a SOAP endpoint location that references an outbound port.
    For security reasons, Salesforce restricts the outbound ports you may specify to one of the following:
    • 80: This port only accepts HTTP connections.
    • 443: This port only accepts HTTPS connections.
    • 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.
  4. Click Parse WSDL to verify the WSDL document contents. The application generates a default class name for each namespace in the WSDL document and reports any errors. Parsing will fail if the WSDL contains schema types or schema constructs that are not supported by Apex classes, or if the resulting classes exceed 1 million character limit on Apex classes. For example, the Salesforce SOAP API WSDL cannot be parsed.
  5. Modify the class names as desired. While you can save more than one WSDL namespace into a single class by using the same class name for each namespace, Apex classes can be no more than 1 million characters total.
  6. Click Generate Apex. The final page of the wizard shows which classes were successfully generated, along with any errors from other classes. The page also provides a link to view successfully generated code.
The successfully-generated Apex class includes stub and type classes for calling the third-party Web service represented by the WSDL document. These classes allow you to call the external Web service from Apex. For an example, see the Force.com Apex Code Developer's Guide.
Note the following about the generated Apex:
  • If a WSDL document contains an Apex reserved word, the word is appended with _x when the Apex class is generated. For example, limit in a WSDL document converts to limit_x in the generated Apex class. For a list of reserved words, see the Force.com Apex Code Developer's Guide.
  • If an operation in the WSDL has an output message with more than one element, the generated Apex wraps the elements in an inner class. The Apex method that represents the WSDL operation returns the inner class instead of the individual elements.

Monday, 8 April 2013

SOQL queries salesforce.com

SOQL & SalesForce.com




Get all records for id:

List<id> listaToTrue=newList<id>();
for(Account a : [select id from Account where ParentId in:addAccountsActivate]){
    listaParaActivar.add(a.id);
}
 
 
    private SforceService binding;

        public SalesForceTest()
        {
            ProcessConnection();

        }

        public bool ProcessConnection()
        {
            Boolean success = false;
            // Create a service object
            binding = new SforceService();
            LoginResult lr;
            try
            {
                Console.WriteLine("\nLogging in...\n");
                lr = binding.login(LoginUserName, LoginUserPassword + LoginSecurityToken);
                /**
                * The login results contain the endpoint of the virtual server instance
                * that is servicing your organization. Set the URL of the binding
                * to this endpoint.
                */
                // Save old authentication end point URL
                String authEndPoint = binding.Url;
                // Set returned service endpoint URL
                binding.Url = lr.serverUrl;
                /** Get the session ID from the login result and set it for the
                * session header that will be used for all subsequent calls.
                */
                binding.SessionHeaderValue = new SessionHeader();
                binding.SessionHeaderValue.sessionId = lr.sessionId;
                // Print user and session info
                GetUserInfoResult userInfo = lr.userInfo;
                Console.WriteLine("UserID: " + userInfo.userId);
                Console.WriteLine("User Full Name: " +
                                  userInfo.userFullName);
                Console.WriteLine("User Email: " +
                                  userInfo.userEmail);
                Console.WriteLine();
                Console.WriteLine("SessionID: " +
                                  lr.sessionId);
                Console.WriteLine("Auth End Point: " +
                                  authEndPoint);
                Console.WriteLine("Service End Point: " +
                                  lr.serverUrl);
                Console.WriteLine();
                // Return true to indicate that we are logged in, pointed
                // at the right URL and have our security token in place.
                success = true;
            }
            catch (SoapException e)
            {
                Console.WriteLine("An unexpected error has occurred: " +
                                  e.Message + "\n" + e.StackTrace);
            }
            return success;
        }

        public void CloseConnection()
        {
            binding.invalidateSessions(new[] {binding.SessionHeaderValue.sessionId});
            Console.WriteLine("Closed connection");
        }


        public void GetQuery()
        {
            QueryResult qResult = null;

            String soqlQuery = "SELECT ID, FirstName, LastName FROM Contact";
            qResult = binding.query(soqlQuery);
            Boolean done = false;
            if (qResult.size > 0)
            {
                Console.WriteLine("Logged-in user can see a total of "
                                  + qResult.size + " contact records.");
                while (!done)
                {
                    sObject[] records = qResult.records;
                    for (int i = 0; i < records.Length; ++i)
                    {
                        Contact con = (Contact) records[i];
                        String fName = con.FirstName;
                        String lName = con.LastName;
            
                        Console.WriteLine("Contact " + (i + 1) + ": ID:" + con.Id +" "+fName +" " + lName);
                        
                    }
                    if (qResult.done)
                    {
                        done = true;
                    }
                    else
                    {
                        qResult = binding.queryMore(qResult.queryLocator);
                    }
                }
            }
            else
            {
                Console.WriteLine("No records found.");
            }
            Console.WriteLine("\nQuery succesfully executed.");
            
        }

        public List<string> CustomSelect()
        {
            var list= new List<string>();
            QueryResult qResult = null;

            String soqlQuery = "SELECT ID,firstName__c,LastName__c FROM ContactPerson__c";
            qResult = binding.query(soqlQuery);
            Boolean done = false;
            if (qResult.size > 0)
            {
                Console.WriteLine("Logged-in user can see a total of "
                                  + qResult.size + " contact records.");
                while (!done)
                {
                    sObject[] records = qResult.records;
                    for (int i = 0; i < records.Length; ++i)
                    {
                        var con = (ContactPerson__c) records[i];
                        String fName = con.FirstName__c;
                        String lName = con.LastName__c;
                        list.Add(con.Id);
                        Console.WriteLine("Contact " + (i + 1) + ": ID:" + con.Id +" "+fName +" " + lName);
                        
                    }
                    if (qResult.done)
                    {
                        done = true;
                    }
                    else
                    {
                        qResult = binding.queryMore(qResult.queryLocator);
                    }
                }
            }
            else
            {
                Console.WriteLine("No records found.");
            }
            Console.WriteLine("\nQuery succesfully executed.");
            return list;
        }

        public void Insert()
        {
            var contactPerson = new ContactPerson__c();
            contactPerson.FirstName__c = string.Format("{0}{1}", "testFirstName", DateTime.Now.ToShortTimeString());
            contactPerson.LastName__c = string.Format("{0}{1}", "testLastName", DateTime.Now.ToShortTimeString());
            contactPerson.Email__c = string.Format("{0}{1}", DateTime.Now.ToString("ddMMhhmm"), "@gmail.com");
            contactPerson.LandLine__c = string.Format("{0}{1}", "01225", DateTime.Now.ToShortTimeString());
            contactPerson.CreatedDate = DateTime.Now;

            var saveResult = binding.create(new[] {contactPerson});
            if (saveResult.Length == 0)
            {
                Console.WriteLine("Failed to save");
            }
            foreach (var result in saveResult)
            {
                Console.WriteLine("id:{0} success:{1} errors:{2}", result.id, result.success,
                                  (result.errors != null) ? result.errors.Length : 0);
                if (result.errors != null)
                    foreach (var error in result.errors)
                    {
                        Console.WriteLine("Error: {0} Field: {1}", error.message, error.fields);
                    }
            }
        }

        public bool UpdateRecord(string recordId)
        {
            try
            {
                sObject[] sObjects = binding.retrieve("ID, FirstName__c,LastName__c,Email__c,LandLine__c", "ContactPerson__c",new[] { recordId });
                // Verify that some objects were returned.
                // Even though we began with valid object IDs,
                // someone else might have deleted them in the meantime.

                // Cast the SObject into an ContactPerson__c object
                ContactPerson__c contactPerson = (ContactPerson__c)sObjects.First();
                if (contactPerson != null)
                {
                    Console.WriteLine("contact person found");

                    ContactPerson__c con = (ContactPerson__c) contactPerson;
                    con.FirstName__c = DateTime.Today.ToShortDateString();

                    var saveResult = binding.update(new[] { con });
                    if (saveResult.Length == 0)
                    {
                        Console.WriteLine("Failed to save");
                    }
                    foreach (var result in saveResult)
                    {
                        Console.WriteLine("id:{0} success:{1} errors:{2}", result.id, result.success,
                                          (result.errors != null) ? result.errors.Length : 0);
                        if (result.errors != null)
                            foreach (var error in result.errors)
                            {
                                Console.WriteLine("Error: {0} Field: {1}", error.message, error.fields);
                            }
                    }
                }
                else
                {
                    Console.WriteLine("Nof Found contact person");
                }
            }
            catch (SoapException e)
            {
                Console.WriteLine("An unexpected error has occurred: " +
                                  e.Message + "\n" + e.StackTrace);
            }
            return false;
        }


        /// <summary>
        /// Deletes the record.
        /// </summary>
        /// <param name="recordId">The record id.</param>
        public void DeleteRecord(string recordId)
        {
            try
            {
                DeleteResult[] deleteResults = binding.delete(new[] { recordId });
                for (int i = 0; i < deleteResults.Length; i++)
                {
                    DeleteResult deleteResult = deleteResults[i];
                    if (deleteResult.success)
                    {
                        Console.WriteLine("Deleted Record ID: " + deleteResult.id);
                    }
                    else
                    {
                        // Handle the errors.
                        // We just print the first error out for sample purposes.
                        Error[] errors = deleteResult.errors;
                        if (errors.Length > 0)
                        {
                            Console.WriteLine("Error: could not delete " + "Record ID "
                                  + deleteResult.id + ".");
                            Console.WriteLine("   The error reported was: ("
                                  + errors[0].statusCode + ") "
                                  + errors[0].message + "\n");
                        }
                    }
                }
            }
            catch (SoapException e)
            {
                Console.WriteLine("An unexpected error has occurred: " +
                                        e.Message + "\n" + e.StackTrace);
            }
        } 

Thursday, 28 March 2013

TFS 2012 Update work item template

Exporting work item definition fromTFS 2012

This guide is specific to TF2012 and VS2012.
All commands you will need to run from Developer Command Prompt for VS2012.

Get list all all items existing


First lets check what work items do we have in our project collection:

Command example

witadmin listwitd  /collection:http://TfsServer:8080/tfs/DefaultServices /p:ProjectName


where
  1. listwitd - list of work items
  2. /collection: select tfs server and your Team Project Collection
  3. /p:Project Name  Work item for project

Export the work item

Exporting template to xml file. This file you can modify using your Visual Studio


This one will fail
witadmin exportwitd  /collection:http://TfsServer:8080/tfs/DefaultServices /p:ProjectName /f:UserStory.xml /n:User Story

The reason for fail is user story has to be surrounded in double quotes
TF212000: Story is not a valid argument for this command. Type 'witadmin exportwitd /?' or 'witadmin help exportwitd' and press Enter for more information.


Update command as follows:

witadmin exportwitd  /collection:http://TfsServer:8080/tfs/DefaultServices /p:ProjectName /f:UserStory.xml /n:"User Story"

Update your work item template

When creating new fields into work item template make sure that you use name starting with unique prefix (for example: CompanyName.MyFieldName) and it is not only name of the field. This is to distinguish between custom fields and default build ones.


Validate your work item

To validate your updated template you can run command:
 
witadmin importwitd /collection:http://AdventureWorksServer:8080/tfs/DefaultCollection /f:WorkItemFileName.xml /p:ProjectName /v
 
The result should be for valid collection.

The work item type is valid.



Import work item to project

 To add new work item to tfs you can run command:

witadmin importwitd  /collection:http://TfsServer:8080/tfs/DefaultServices /f:WorkItemFile.xml
The work item type import has completed.

Destroy work  item

 Delete work item
itemwitadmin destroywitd /collection:http://TfsServer:8080/tfs/DefaultServices /p:ProjectName /n:WorkItemName

Are you sure you want to destroy the NewBug work item type as well as its 0 wo
rk item(s)?  This action is not recoverable. (Yes/No) y
The work item type was destroyed.

Article is written thanks to following resources

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

Monday, 25 March 2013

c# generate class from wsdl definition

How to generate cs file from wsdl

  1. Save file to place where you can read and write
  2. open Developer command prompt for VS 2010/2012
  3. Execute command (update where you need)

wsdl yourWsdlDefinition.wsdl /out:MyProxyClass.cs