Monday 22 April 2013

Mime type table to use for office documents

Mime table for office

after while trying to find right format I have found gold mine: here. Below is reference copy


Ext
MIME Type
.doc
application/msword
.dot
application/msword
.docx
application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx
application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm
application/vnd.ms-word.document.macroEnabled.12
.dotm
application/vnd.ms-word.template.macroEnabled.12
.xls
application/vnd.ms-excel
.xlt
application/vnd.ms-excel
.xla
application/vnd.ms-excel
.xlsx
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx
application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm
application/vnd.ms-excel.sheet.macroEnabled.12
.xltm
application/vnd.ms-excel.template.macroEnabled.12
.xlam
application/vnd.ms-excel.addin.macroEnabled.12
.xlsb
application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt
application/vnd.ms-powerpoint
.pot
application/vnd.ms-powerpoint
.pps
application/vnd.ms-powerpoint
.ppa
application/vnd.ms-powerpoint
.pptx
application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx
application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx
application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam
application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm
application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm
application/vnd.ms-powerpoint.presentation.macroEnabled.12
.ppsm
application/vnd.ms-powerpoint.slideshow.macroEnabled.12

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);
            }
        }