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




Monday, 25 February 2013

MackBook Pro bootcamp right button


On my work mack book I am using BootCamp software to switch between Mac and Windows

The biggest problem I have had so far was right button in windows because I thing I am using right click on windows more than anything else.

This is
  1. Go to "Control Panel".  2. Click on the phrase "System and Security"
  3. Then "Boot Camp".
  4. Click on the "Trackpad" tab.




 








  5. In the "One Finger" area, enable the check box next to "Secondary Click" and select your click option to get right click..















  6. Click OK.

This will let you simulate a right click by depressing the bottom-right corner of the trackpad.


Friday, 15 February 2013

TFS build using testing files

TFS build using testing files

Desired result

I want to run test that are using test files on server.
I am targeting VS and TFS 2012

Solution

My test solution layout.


Add all your files into folder which is part of your solution.
Set property all files you need for tests to content and copy always.
This will ensure that files are always the latest ones.




Now create test class

    [TestClass]
    [DeploymentItem(@"TestData", @"TestData")]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.IsTrue(File.Exists(@"TestData\TextFile1.txt"));
        }
    }

and test result

You need to use in, out directory for Deployment Item, this will copy only existing item from your solution. I have not managed to create only empty directory.

Check if your directory has been created in location: ClassLibrary1.Tests\bin\Debug.

You can read up about DeploymentItem