Monday, June 29, 2015

Merge records with automatic selection of all fields with data

When merging the records in GUI, you have the option of selecting the option which updates the master record with the values from the child record when the value is missing in the master record.

The below code does the same. If does a retrieve on the master and child record and then compares the columns from the child record with the master record and update the "UpdateContent" property of the merge request.

For merging custom entities, the first part of the code can be used and If we have a custom masterid created, the lookup value can be updated with the master record id and the child record can be inactivated/deleted.



Code:
public static bool MergeRecord(IOrganizationService _service, string entName, string srcId, string targetId)
        {
            bool result = false;
            MergeRequest mreq = new MergeRequest();
            Guid targetRecordID = new Guid(targetId);
            Guid tobemergedRecordID = new Guid(srcId);
            Entity srcEntity = _service.Retrieve(entName, tobemergedRecordID, new ColumnSet(true));
            Entity tgtEntity = _service.Retrieve(entName, tobemergedRecordID, new ColumnSet(true));
            Entity updContent = new Entity(entName);
            foreach (KeyValuePair<String, Object> attr in srcEntity.Attributes)
            {
                if (!tgtEntity.Attributes.Contains(attr.Key))
                { 
                    updContent.Attributes.Add(attr);
                }
            }

            mreq.Target = new EntityReference(entName, targetRecordID);  // Target Account ID , where other account will be mergered
            mreq.SubordinateId = tobemergedRecordID;
            mreq.PerformParentingChecks = false;
            mreq.UpdateContent = updContent;
            try
            {
                MergeResponse mresp = (MergeResponse)_service.Execute(mreq);
                result = true;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogMessage(message, true);
                result = false;
            }

            return result;
        }





Thursday, March 05, 2015

Import a solution from CRM 2011 to CRM 2015

If you keen on trying CRM 2015 and not willing to choose the upgrade path of CRM 2011-> CRM 2013 -> CRM 2015.... then you are not alone...

When you try to import the solution you will get an error saying the solution cannot be imported from CRM 2011...

Since the solution file is a mere XML, as a developer, I wanted to play around it..

This is what I did. I changes the customization.xml and updated the xml header like below.

<ImportExportXml version="7.0.0000.4013" SolutionPackageVersion="7.0" languagecode="1044" generatedBy="CrmLive" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'

And the import went fine. Now it's for me to just start modifying the UI and fixing the javascript part :)


Have fun with crm 2015

Wednesday, November 12, 2014

Create a followup activity for campaign response on the customer

It's a little tricky if you want to create a followup activity on the campaign response. As the campaign response is not linked to the customer directly it's impossible to do it via workflow.

There is a customer field in the campaign response which is in fact a row in the activityparty table with a reference to the customer. So this field is not available in the list of fields for workflow substitution. Here is a piece of code which can be run later or used in plugin to create a followup activity


Code:
//search for campaign responses created yesterday and create followup activity
                ConditionExpression cr_ce1 = new ConditionExpression("responsecode", ConditionOperator.Equal, 1); //Interested
                ConditionExpression cr_ce2 = new ConditionExpression("createdon", ConditionOperator.Yesterday); //Yesterday
                FilterExpression cr_fe = new FilterExpression(LogicalOperator.And); 
                cr_fe.AddCondition(cr_ce1);
                cr_fe.AddCondition(cr_ce2);
                QueryExpression cr_qe = new QueryExpression();
                cr_qe.EntityName = "campaignresponse";
                cr_qe.Criteria = cr_fe;
                cr_qe.ColumnSet = new ColumnSet("activityid", "subject", "customer","createdon");
                cr_qe.PageInfo.ReturnTotalRecordCount = true;
                EntityCollection cr_coll = _service.RetrieveMultiple(cr_qe);

                string fetchXML = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"">
                                      <entity name=""team"">
                                        <attribute name=""name"" />
                                        <attribute name=""teamid"" />
                                        <attribute name=""queueid"" />
                                        <order attribute=""name"" descending=""false"" />
                                        <filter type=""and"">
                                          <condition attribute=""name"" operator=""eq"" value=""Team Customerservice"" />
                                        </filter>
                                      </entity>
                                    </fetch>";

                Entity team = _service.RetrieveMultiple(new FetchExpression(fetchXML)).Entities[0];

                foreach (Entity ent in cr_coll.Entities)
                {
                    try
                    {
                        if (ent.Attributes.Contains("customer"))
                        {
                            EntityCollection actParty = (EntityCollection)ent["customer"];
                            //create new task
                            Entity task = new Entity();
                            task.LogicalName = "task";
                            task["description"] = @"Some description";
                            task["scheduledstart"] = DateTime.Now;
                            task["scheduledend"] = (DateTime.Parse(ent["createdon"].ToString())).AddDays(7);
                            task["regardingobjectid"] = (EntityReference)(actParty[0]["partyid"]);
                            task["ownerid"] = new EntityReference(team.LogicalName, team.Id);
                            task["subject"] = ent["subject"];
                            Guid _taskId = _service.Create(task);
                            // add to customer service queue
                            Entity qItem = new Entity();
                            qItem.LogicalName = "queueitem";
                            qItem["objectid"] = new EntityReference(task.LogicalName, _taskId);
                            qItem["queueid"] = (EntityReference)team["queueid"];
                            Guid _itemId = _service.Create(qItem);
                        }
                    }
                    catch (Exception ex)
                    {
                        Helper.Log("Problem while processing campaign response Record with ID : " + ent["activityid"].ToString() + "\n" + ex.Message, w, true);
                    }

Thursday, July 10, 2014

Get Optionset value from text

Here you go with the code


Code:
public static int GetOptionSetValueGivenText(IOrganizationService service, string entityName, string attributeName, string selectedValue)
        {
            try
            {
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true };
                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                int selectedOptionValue = 0;
                foreach (OptionMetadata oMD in optionList)
                {
                    if (oMD.Label.UserLocalizedLabel.Label == selectedValue)
                    {
                        selectedOptionValue = oMD.Value.Value;
                        break;
                    }
                }
                return selectedOptionValue;
            }
            catch (System.ServiceModelFaultException ex1)
            {
                string strEr = ex1.InnerException.Data.ToString();
                return 0;
            }

        }

Thursday, January 02, 2014

Strip HTML

Use this helper class for stirpping HTML. I am not the owner of this code. Got it from the web. But posting it here as it might be useful to many.

Code:
public static string StripHTML(string source)
        {
            try
            {
                string result;

                // Remove HTML Development formatting
                // Replace line breaks with space
                // because browsers inserts space
                result = source.Replace("\r", " ");
                // Replace line breaks with space
                // because browsers inserts space
                result = result.Replace("\n", " ");
                // Remove step-formatting
                result = result.Replace("\t", string.Empty);
                // Remove repeating spaces because browsers ignore them
                result = System.Text.RegularExpressions.Regex.Replace(result,
                                                                      @"( )+", " ");

                // Remove the header (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*head([^>])*>", "<head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*head( )*>)", "</head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<head>).*(</head>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // remove all scripts (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*script([^>])*>", "<script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*script( )*>)", "</script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                //result = System.Text.RegularExpressions.Regex.Replace(result,
                //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
                //         string.Empty,
                //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<script>).*(</script>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // remove all styles (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*style([^>])*>", "<style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*style( )*>)", "</style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<style>).*(</style>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert tabs in spaces of <td> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*td([^>])*>", "\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line breaks in places of <BR> and <LI> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*br( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*li( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line paragraphs (double line breaks) in place
                // if <P>, <DIV> and <TR> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*div([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*tr([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*p([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // Remove remaining tags like <a>, links, images,
                // comments etc - anything that's enclosed inside < >
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<[^>]*>", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // replace special characters:
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @" ", " ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&bull;", " * ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lsaquo;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&rsaquo;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&trade;", "(tm)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&frasl;", "/",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lt;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&gt;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&copy;", "(c)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&reg;", "(r)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove all others. More can be added, see
                // http://hotwired.lycos.com/webmonkey/reference/special_characters/
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&(.{2,6});", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // for testing
                //System.Text.RegularExpressions.Regex.Replace(result,
                //       this.txtRegex.Text,string.Empty,
                //       System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // make line breaking consistent
                result = result.Replace("\n", "\r");

                // Remove extra line breaks and tabs:
                // replace over 2 breaks with 2 and over 4 tabs with 4.
                // Prepare first to remove any whitespaces in between
                // the escaped characters and remove redundant tabs in between line breaks
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\t)", "\t\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\r)", "\t\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\t)", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove redundant tabs
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove multiple tabs following a line break with just one tab
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Initial replacement target string for line breaks
                string breaks = "\r\r\r";
                // Initial replacement target string for tabs
                string tabs = "\t\t\t\t\t";
                for (int index = 0; index < result.Length; index++)
                {
                    result = result.Replace(breaks, "\r\r");
                    result = result.Replace(tabs, "\t\t\t\t");
                    breaks = breaks + "\r";
                    tabs = tabs + "\t";
                }

                // That's it.
                return result.Trim();
            }
            catch (Exception e)
            {
                //MessageBox.Show("Error");
                throw e;
            }
        }

Update email properties

I had a client requirement to update few of the attributes of incoming email.

The incoming email was tracked on customers based on the from email address. Customer did not want the auto-resolution of emails to customers as many of the customers had the same email ( family members tend to have the same email for all of them). So they want to remove the customer name from the auto resolution.

The response from me was @£$€£€@$€{]}[$£

yeah it's possible. but HOW? We remove the activity party from the sender list... sounds simple :)

Go through the code to find yourself

For example they wanted to have a list view of email with the body of the email (a quick preview of the email).

This was not possible using the standard description field of the email as it contained HTML codes. The alternative is to create a new column to hold the plain text email. So I went ahead and created a new multiline text field with 2000 char limit.

I added a plugin on post activity create to update the description of the email. optionally the same plugin is to be added on email update for the description field.

Here you go with the code. target is the email entity

Entity target = context.InputParameters["Target"] as Entity;

Code:
Entity _email = service.Retrieve("email", target.Id, new ColumnSet("from","to", "description", "directioncode"));

                    if (!((bool)_email["directioncode"])) //Incoming
                    {
                        EntityCollection from = (EntityCollection)_email["from"];

                        if (from.Entities.Count > 0)
                        {
                            foreach (Entity actParty in from.Entities)
                            {
                                if (actParty.Contains("partyid"))
                                {
                                    actParty["partyid"] = null;
                                }
                                else
                                {
                                    actParty.Attributes.Add("partyid", null);
                                }
                            }
                        }
                        _email["from"] = from;
                    }
                    else //outgoing
                    {
                        EntityCollection to = (EntityCollection)_email["to"];

                        if (to.Entities.Count > 0)
                        {
                            foreach (Entity actParty in to.Entities)
                            {
                                if (actParty.Contains("partyid"))
                                {
                                    actParty["partyid"] = null;
                                }
                                else
                                {
                                    actParty.Attributes.Add("partyid", null);
                                }
                            }
                        }
                        _email["to"] = to;
                    }
                    if (_email.Contains("description"))
                    {
                        string desc = _email["description"].ToString();
                        string descStrip = PluginHelper.StripHTML(desc);
                        descStrip = descStrip.Trim();
                        string desc4 = "";
                        string prevLine = "";
                        foreach (string currLine in descStrip.Split('\r'))
                        {
                            if (currLine != prevLine)
                            {
                                prevLine = currLine.Trim();
                                desc4 += currLine.Trim();
                                if (currLine != "")
                                {
                                    desc4 += "\n";
                                }
                            }
                        }

                        if (desc4.Length > 2000)
                            desc4 = desc4.Substring(1, 2000);

                        if (_email.Contains("ssb_mail_text"))
                        {
                            _email["ssb_mail_text"] = desc4;
                        }
                        else
                        {
                            _email.Attributes.Add("ssb_mail_text", desc4);
                        }
                        _email.Attributes.Remove("description");
                    }
                    service.Update(_email);

Close queueitem

Use the code template from here

If you need to close the queueitem after creating a case from an email, here you go with the code

target is of type entity "email"
Code:
        if (target.Contains("regardingobjectid"))
        {
            EntityReference _object = (EntityReference)target["regardingobjectid"];

            if (_object.LogicalName == "incident")
            {
                CloseQueueItem(_object.Id, service);
            }
        }
Code:
public static bool CloseQueueItem(Guid _sourceId, IOrganizationService service)
    {

        Guid _queueItemId = Guid.Empty;
        bool _queueItemClosed = false;

        ConditionExpression ent_ce1 = new ConditionExpression("objectid", ConditionOperator.Equal, _sourceId);
        ConditionExpression ent_ce2 = new ConditionExpression("statecode", ConditionOperator.Equal, 0);
        FilterExpression ent_fe = new FilterExpression(LogicalOperator.And);
        ent_fe.AddCondition(ent_ce1);
        ent_fe.AddCondition(ent_ce2);

        QueryExpression ent_qe = new QueryExpression();
        ent_qe.EntityName = "queueitem";
        ent_qe.Criteria = ent_fe;
        ent_qe.ColumnSet = new ColumnSet("queueitemid", "queueid", "objectid");
        ent_qe.PageInfo.ReturnTotalRecordCount = true;
        EntityCollection ent_coll = service.RetrieveMultiple(ent_qe);

        if (ent_coll.Entities.Count > 0)
        {
            foreach (Entity _queueItem in ent_coll.Entities)
            {
                EntityReference enRef = (EntityReference)_queueItem["objectid"];
                PluginHelper.SetState(_queueItem.LogicalName, _queueItem.Id, 1, 2, service);
            }
            _queueItemClosed = true;
        }

        return _queueItemClosed;
    }

Thursday, November 07, 2013

Code snippet to increase Aggregate Query Record Limit


Use the code template from here

Code:
DeploymentServiceClient service = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(new Uri("http://crmtest/XRMDeployment/2011/Deployment.svc"));

                RetrieveAdvancedSettingsRequest request3 = new RetrieveAdvancedSettingsRequest()
                {
                    ConfigurationEntityName = "Deployment", ColumnSet = new ColumnSet(false)
                };
                RetrieveAdvancedSettingsResponse response3 = (RetrieveAdvancedSettingsResponse)service.Execute(request3);
                ConfigurationEntity configEntity = response3.Entity;

                ConfigurationEntity entity = new ConfigurationEntity();
                entity.LogicalName = "Deployment";
                entity.Attributes = new Microsoft.Xrm.Sdk.DeploymentAttributeCollection();
                entity.Attributes.Add(new KeyValuePair<string, object>("AggregateQueryRecordLimit", 50000));
                     
                UpdateAdvancedSettingsRequest request2 = new UpdateAdvancedSettingsRequest();
                request2.Entity = entity;
                service.Execute(request2);



Update the deployment service URL 

Code snippet to increase max records exported to excel


Use the code template from here

In the example below I am updating max records exported to excel.

Code:
QueryExpression qe = new QueryExpression("organization");
                qe.ColumnSet = new ColumnSet("maxrecordsforexporttoexcel");
                EntityCollection entColl = _service.RetrieveMultiple(qe);
                if (entColl.Entities.Count > 0)
                {
                    Entity ent = entColl.Entities[0];
                    ent["maxrecordsforexporttoexcel"] = 500000;
                    _service.Update(ent);
                }


Wednesday, October 02, 2013

Template for code snippet

Paste the code snippet in the try loop and execute the code snippets
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk.Client;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using System.IO;
using SSB.Xrm;
using Microsoft.Xrm.Sdk.Deployment;


namespace DynamicsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string dest = "prod";
            string prod = "http://crm/prod/XRMServices/2011/Organization.svc";
            string test = "http://crm/Test/XRMServices/2011/Organization.svc";
            string test2 = "http://crm/Testt/XRMServices/2011/Organization.svc";
            string dev = "http://crm/Dev/XRMServices/2011/Organization.svc";
            string server = "";
            switch (dest)
            {
                case "prod":
                    server = prod;
                    break;
                case "test2":
                    server = test2;
                    break;
                case "test":
                    server = test;
                    break;
                default:
                    server = dev;
                    break;
            }
            Uri organizationUri = new Uri(server);
            Uri homeRealmUri = null;
            ClientCredentials credentials = new ClientCredentials();
            credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
            OrganizationServiceProxy _serviceProxy  = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
            _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
            IOrganizationService _service = (IOrganizationService)_serviceProxy;

            if (!Directory.Exists("Logs"))
            {
                Directory.CreateDirectory("Logs");
            }
            StreamWriter w = new StreamWriter(".\\Logs\\DynamicsTest" + DateTime.Now.ToString("_yyyyMMdd") + ".log", true);

            try
            {
                //Code snippet goes here
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Helper.Log(ex.Message, w, true);
            }
            finally
            {
                if (w != null)
                    w.Close();
            }
        }

        

    }
}

Code snippet to add to marketing list


Use the code template from here
Code:
string[] cust_str = {"000000XXXXX"};
                     ConditionExpression con_ce1 = new ConditionExpression("efs_sourcecustomernumber", ConditionOperator.In, cust_str);
                     FilterExpression con_fe = new FilterExpression(LogicalOperator.And);
                     con_fe.AddCondition(con_ce1);
                     QueryExpression con_qe = new QueryExpression();
                     con_qe.EntityName = "contact";
                     con_qe.Criteria = con_fe;
                     con_qe.ColumnSet = new ColumnSet("contactid", "efs_sourcecustomernumber");
                     con_qe.PageInfo.ReturnTotalRecordCount = true;
                     EntityCollection con_coll = _service.RetrieveMultiple(con_qe);

                     foreach (Entity ent in con_coll.Entities)
                     {
                         AddMemberListRequest req = new AddMemberListRequest();
                         //we will add an account to our marketing list
                         //entity type must be an account, contact, or lead
                         req.EntityId = ent.Id;
                         //we will add the account to this existing marketing list
                         //Morgenmøte NL
                         req.ListId = new Guid("22F69F49-360A-E311-8620-0050568E0699");
                         AddMemberListResponse resp = (AddMemberListResponse)_service.Execute(req);
                     }

Code snippet to copy a particular record from test to prod or vice versa


Use the code template from here

In the example below I am copying a particular task and related notes/attachments.
Code:
 Entity entity = _service.Retrieve("task", new Guid("F6213B56-61A7-E211-A560-0050568E0699"), new ColumnSet(true));
                    organizationUri = new Uri(prod);
                    OrganizationServiceProxy _prodProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
                    _prodProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                    IOrganizationService _Prodservice = (IOrganizationService)_prodProxy;

                    _prodProxy.Create(entity);
         
                //ConditionExpression con_ce1 = new ConditionExpression("isdocument", ConditionOperator.Equal, true);
                ConditionExpression con_ce2 = new ConditionExpression("objectid", ConditionOperator.Equal, new Guid("F6213B56-61A7-E211-A560-0050568E0699"));
                FilterExpression con_fe = new FilterExpression(LogicalOperator.And);
                //con_fe.AddCondition(con_ce1);
                con_fe.AddCondition(con_ce2);
                QueryExpression con_qe = new QueryExpression();
                con_qe.EntityName = "annotation";
                con_qe.Criteria = con_fe;
                con_qe.ColumnSet = new ColumnSet("annotationid");
                con_qe.PageInfo.ReturnTotalRecordCount = true;
                EntityCollection con_coll = _service.RetrieveMultiple(con_qe);
                MessageBox.Show("Record Count: " + con_coll.Entities.Count);

                foreach(Entity note in con_coll.Entities)
                {

                    Entity entity = _service.Retrieve(note.LogicalName,note.Id, new ColumnSet(true));
                    organizationUri = new Uri(prod);
                    OrganizationServiceProxy _prodProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
                    _prodProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                    IOrganizationService _Prodservice = (IOrganizationService)_prodProxy;

                    _prodProxy.Create(entity);
                }
         

Code snippet to copy saved outlook filters from one user to all users


Use the code template from here

Code:
QueryExpression ownerQe = new QueryExpression("systemuser");
                ownerQe.Criteria.AddCondition("domainname", ConditionOperator.Equal, "domain\\c260xxx");
                ownerQe.ColumnSet.AddColumn("systemuserid");
                EntityCollection ownerColl =  _service.RetrieveMultiple(ownerQe);
                if (ownerColl.Entities.Count == 1)
                {
                    Entity owner = ownerColl.Entities[0];
                    Guid _OwnerId = owner.Id;//new Guid("79934B9F-065B-E211-AA02-0050568E0699");//Ganesh Sivakumar
                    ConditionExpression query_ce1 = new ConditionExpression("querytype", ConditionOperator.Equal, 256);
                    ConditionExpression query_ce2 = new ConditionExpression("ownerid", ConditionOperator.Equal, _OwnerId);
                    FilterExpression query_fe = new FilterExpression(LogicalOperator.And);
                    query_fe.AddCondition(query_ce1);
                    query_fe.AddCondition(query_ce2);
                    QueryExpression query_qe = new QueryExpression();
                    query_qe.EntityName = "userquery";
                    query_qe.Criteria = query_fe;
                    query_qe.ColumnSet = new ColumnSet("userqueryid", "fetchxml", "returnedtypecode");
                    query_qe.PageInfo.ReturnTotalRecordCount = true;
                    EntityCollection query_coll = _service.RetrieveMultiple(query_qe);

                    string _appointmentFetchXml = "", _recurringFetchXml = "";

                    foreach (Entity query in query_coll.Entities)
                    {
                        if ((string)query["returnedtypecode"] == "appointment")
                            _appointmentFetchXml = (string)query["fetchxml"];
                        if ((string)query["returnedtypecode"] == "recurringappointmentmaster")
                            _recurringFetchXml = (string)query["fetchxml"];
                    }

                    ConditionExpression con_ce1 = new ConditionExpression("domainname", ConditionOperator.NotNull);
                    FilterExpression con_fe = new FilterExpression(LogicalOperator.And);
                    con_fe.AddCondition(con_ce1);
                    QueryExpression con_qe = new QueryExpression();
                    con_qe.EntityName = "systemuser";
                    con_qe.Criteria = con_fe;
                    con_qe.ColumnSet = new ColumnSet("systemuserid", "ssb_delete_flag", "isdisabled");
                    con_qe.PageInfo.ReturnTotalRecordCount = true;
                    EntityCollection con_coll = _service.RetrieveMultiple(con_qe);

                    foreach (Entity user in con_coll.Entities)
                    {
                        Guid _userId = user.Id;
                        ConditionExpression ent_ce1 = new ConditionExpression("querytype", ConditionOperator.Equal, 256);
                        ConditionExpression ent_ce2 = new ConditionExpression("ownerid", ConditionOperator.Equal, _userId);
                        //ConditionExpression ent_ce3 = new ConditionExpression("returnedtypecode", ConditionOperator.Equal, 2);
                        FilterExpression ent_fe = new FilterExpression(LogicalOperator.And);
                        ent_fe.AddCondition(ent_ce1);
                        ent_fe.AddCondition(ent_ce2);
                        //ent_fe.AddCondition(ent_ce3);
                        QueryExpression ent_qe = new QueryExpression();
                        ent_qe.EntityName = "userquery";
                        ent_qe.Criteria = ent_fe;
                        ent_qe.ColumnSet = new ColumnSet("userqueryid", "returnedtypecode", "fetchxml", "statecode");
                        ent_qe.PageInfo.ReturnTotalRecordCount = true;
                        EntityCollection ent_coll = _service.RetrieveMultiple(ent_qe);

                        foreach (Entity ent in ent_coll.Entities)
                        {
                            if ((string)ent["returnedtypecode"] == "contact")
                            {
                                OptionSetValue stateCode = (OptionSetValue)ent["statecode"];
                                if (stateCode.Value == 0)
                                {
                                    Backup.SetState(ent.LogicalName, ent.Id, 1, 2, _service);
                                    Helper.Log("QueryId " + ent.Id.ToString() + " is disabled", w);
                                }
                            }

                            if ((string)ent["returnedtypecode"] == "recurringappointmentmaster")
                            {
                                if ((string)ent["fetchxml"] != _recurringFetchXml)
                                {
                                    ent["fetchxml"] = _recurringFetchXml;
                                    _service.Update(ent);
                                    Helper.Log("QueryId " + ent.Id.ToString() + " is updated", w);
                                }
                            }

                            if ((string)ent["returnedtypecode"] == "appointment")
                            {
                                if ((string)ent["fetchxml"] != _appointmentFetchXml)
                                {
                                    ent["fetchxml"] = _appointmentFetchXml;
                                    _service.Update(ent);
                                    Helper.Log("QueryId " + ent.Id.ToString() + " is updated", w);
                                }
                            }
                        }
                    }

Code snippet to execute workflow crm 2011


Use the code template from here

Code:
ExecuteWorkflowRequest request = new ExecuteWorkflowRequest();
                //Assign the ID of the workflow you want to execute to the request.        
                request.WorkflowId = new Guid("129112BD-A601-43DB-97DA-59AD13743069");

                string[] cust_str = {"000000XXXXX"};
                foreach (string cust in cust_str)
                {
                    ConditionExpression con_ce1 = new ConditionExpression("accountnumber", ConditionOperator.Equal, cust);
                    FilterExpression con_fe = new FilterExpression(LogicalOperator.And);
                    con_fe.AddCondition(con_ce1);
                    QueryExpression con_qe = new QueryExpression();
                    con_qe.EntityName = "account";
                    con_qe.Criteria = con_fe;
                    con_qe.ColumnSet = new ColumnSet("accountid", "accountnumber");
                    con_qe.PageInfo.ReturnTotalRecordCount = true;
                    EntityCollection con_coll = _service.RetrieveMultiple(con_qe);

                    foreach (Entity ent in con_coll.Entities)
                    {
                        request.EntityId = ent.Id;
                        ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_service.Execute(request);
                    }
                }

Code snippet to convert fetch xml to query expression crm 2011


Use the code template from here

Code:
string fetchExp = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"">
                                      <entity name=""task"">
                                        <attribute name=""activityid"" />
                                        <attribute name=""ownerid"" />
                                        <order attribute=""subject"" descending=""false"" />
                                        <filter type=""and"">
                                          <condition attribute=""ssb_type"" operator=""eq"" value=""867700004"" />
                                          <condition attribute=""statuscode"" operator=""in"">
                                            <value>2</value>
                                            <value>3</value>
                                            <value>4</value>
                                            <value>7</value>
                                          </condition>
                                          <condition attribute=""description"" operator=""like"" value=""%MÃ¥nedlig risikovurdering%"" />
                                          <condition attribute=""createdon"" operator=""last-x-days"" value=""365"" />
                                        </filter>
                                        <link-entity name=""account"" from=""accountid"" to=""regardingobjectid"" alias=""accountOwner"">
                                          <attribute name=""efs_kundeansvarligid"" />
                                          <filter type=""and"">
                                            <condition attribute=""efs_kundeansvarligid"" operator=""not-null"" />
                                          </filter>
                                        </link-entity>
                                      </entity>
                                    </fetch>";
                FetchExpression fe = new FetchExpression(fetchExp);

                FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest();
                req.FetchXml = fetchExp;
                FetchXmlToQueryExpressionResponse resp = (FetchXmlToQueryExpressionResponse)_service.Execute(req);

                QueryExpression con_qe = resp.Query;
                EntityCollection con_coll = _service.RetrieveMultiple(con_qe);

Helper class in CRM 2011

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.IO;
using System.Xml;

namespace DynamicsTest
{
    class Helper
    {
        

        public static string CreateXml(string xml, string cookie, int page, int count)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);

            // Load document
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            return CreateXml(doc, cookie, page, count);
        }

        public static string CreateXml(XmlDocument doc, string cookie, int page, int count)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

            if (cookie != null)
            {
                XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                pagingAttr.Value = cookie;
                attrs.Append(pagingAttr);
            }

            XmlAttribute pageAttr = doc.CreateAttribute("page");
            pageAttr.Value = System.Convert.ToString(page);
            attrs.Append(pageAttr);

            XmlAttribute countAttr = doc.CreateAttribute("count");
            countAttr.Value = System.Convert.ToString(count);
            attrs.Append(countAttr);

            StringBuilder sb = new StringBuilder(1024);
            StringWriter stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            doc.WriteTo(writer);
            writer.Close();

            return sb.ToString();
        }


        private static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {

        #region Big freaking list of mime types
        // combination of values from Windows 7 Registry and 
        // from C:\Windows\System32\inetsrv\config\applicationHost.config
        // some added, including .7z and .dat
        {".323", "text/h323"},
        {".3g2", "video/3gpp2"},
        {".3gp", "video/3gpp"},
        {".3gp2", "video/3gpp2"},
        {".3gpp", "video/3gpp"},
        {".7z", "application/x-7z-compressed"},
        {".aa", "audio/audible"},
        {".AAC", "audio/aac"},
        {".aaf", "application/octet-stream"},
        {".aax", "audio/vnd.audible.aax"},
        {".ac3", "audio/ac3"},
        {".aca", "application/octet-stream"},
        {".accda", "application/msaccess.addin"},
        {".accdb", "application/msaccess"},
        {".accdc", "application/msaccess.cab"},
        {".accde", "application/msaccess"},
        {".accdr", "application/msaccess.runtime"},
        {".accdt", "application/msaccess"},
        {".accdw", "application/msaccess.webapplication"},
        {".accft", "application/msaccess.ftemplate"},
        {".acx", "application/internet-property-stream"},
        {".AddIn", "text/xml"},
        {".ade", "application/msaccess"},
        {".adobebridge", "application/x-bridge-url"},
        {".adp", "application/msaccess"},
        {".ADT", "audio/vnd.dlna.adts"},
        {".ADTS", "audio/aac"},
        {".afm", "application/octet-stream"},
        {".ai", "application/postscript"},
        {".aif", "audio/x-aiff"},
        {".aifc", "audio/aiff"},
        {".aiff", "audio/aiff"},
        {".air", "application/vnd.adobe.air-application-installer-package+zip"},
        {".amc", "application/x-mpeg"},
        {".application", "application/x-ms-application"},
        {".art", "image/x-jg"},
        {".asa", "application/xml"},
        {".asax", "application/xml"},
        {".ascx", "application/xml"},
        {".asd", "application/octet-stream"},
        {".asf", "video/x-ms-asf"},
        {".ashx", "application/xml"},
        {".asi", "application/octet-stream"},
        {".asm", "text/plain"},
        {".asmx", "application/xml"},
        {".aspx", "application/xml"},
        {".asr", "video/x-ms-asf"},
        {".asx", "video/x-ms-asf"},
        {".atom", "application/atom+xml"},
        {".au", "audio/basic"},
        {".avi", "video/x-msvideo"},
        {".axs", "application/olescript"},
        {".bas", "text/plain"},
        {".bcpio", "application/x-bcpio"},
        {".bin", "application/octet-stream"},
        {".bmp", "image/bmp"},
        {".c", "text/plain"},
        {".cab", "application/octet-stream"},
        {".caf", "audio/x-caf"},
        {".calx", "application/vnd.ms-office.calx"},
        {".cat", "application/vnd.ms-pki.seccat"},
        {".cc", "text/plain"},
        {".cd", "text/plain"},
        {".cdda", "audio/aiff"},
        {".cdf", "application/x-cdf"},
        {".cer", "application/x-x509-ca-cert"},
        {".chm", "application/octet-stream"},
        {".class", "application/x-java-applet"},
        {".clp", "application/x-msclip"},
        {".cmx", "image/x-cmx"},
        {".cnf", "text/plain"},
        {".cod", "image/cis-cod"},
        {".config", "application/xml"},
        {".contact", "text/x-ms-contact"},
        {".coverage", "application/xml"},
        {".cpio", "application/x-cpio"},
        {".cpp", "text/plain"},
        {".crd", "application/x-mscardfile"},
        {".crl", "application/pkix-crl"},
        {".crt", "application/x-x509-ca-cert"},
        {".cs", "text/plain"},
        {".csdproj", "text/plain"},
        {".csh", "application/x-csh"},
        {".csproj", "text/plain"},
        {".css", "text/css"},
        {".csv", "application/octet-stream"},
        {".cur", "application/octet-stream"},
        {".cxx", "text/plain"},
        {".dat", "application/octet-stream"},
        {".datasource", "application/xml"},
        {".dbproj", "text/plain"},
        {".dcr", "application/x-director"},
        {".def", "text/plain"},
        {".deploy", "application/octet-stream"},
        {".der", "application/x-x509-ca-cert"},
        {".dgml", "application/xml"},
        {".dib", "image/bmp"},
        {".dif", "video/x-dv"},
        {".dir", "application/x-director"},
        {".disco", "text/xml"},
        {".dll", "application/x-msdownload"},
        {".dll.config", "text/xml"},
        {".dlm", "text/dlm"},
        {".doc", "application/msword"},
        {".docm", "application/vnd.ms-word.document.macroEnabled.12"},
        {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".dot", "application/msword"},
        {".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
        {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
        {".dsp", "application/octet-stream"},
        {".dsw", "text/plain"},
        {".dtd", "text/xml"},
        {".dtsConfig", "text/xml"},
        {".dv", "video/x-dv"},
        {".dvi", "application/x-dvi"},
        {".dwf", "drawing/x-dwf"},
        {".dwp", "application/octet-stream"},
        {".dxr", "application/x-director"},
        {".eml", "message/rfc822"},
        {".emz", "application/octet-stream"},
        {".eot", "application/octet-stream"},
        {".eps", "application/postscript"},
        {".etl", "application/etl"},
        {".etx", "text/x-setext"},
        {".evy", "application/envoy"},
        {".exe", "application/octet-stream"},
        {".exe.config", "text/xml"},
        {".fdf", "application/vnd.fdf"},
        {".fif", "application/fractals"},
        {".filters", "Application/xml"},
        {".fla", "application/octet-stream"},
        {".flr", "x-world/x-vrml"},
        {".flv", "video/x-flv"},
        {".fsscript", "application/fsharp-script"},
        {".fsx", "application/fsharp-script"},
        {".generictest", "application/xml"},
        {".gif", "image/gif"},
        {".group", "text/x-ms-group"},
        {".gsm", "audio/x-gsm"},
        {".gtar", "application/x-gtar"},
        {".gz", "application/x-gzip"},
        {".h", "text/plain"},
        {".hdf", "application/x-hdf"},
        {".hdml", "text/x-hdml"},
        {".hhc", "application/x-oleobject"},
        {".hhk", "application/octet-stream"},
        {".hhp", "application/octet-stream"},
        {".hlp", "application/winhlp"},
        {".hpp", "text/plain"},
        {".hqx", "application/mac-binhex40"},
        {".hta", "application/hta"},
        {".htc", "text/x-component"},
        {".htm", "text/html"},
        {".html", "text/html"},
        {".htt", "text/webviewhtml"},
        {".hxa", "application/xml"},
        {".hxc", "application/xml"},
        {".hxd", "application/octet-stream"},
        {".hxe", "application/xml"},
        {".hxf", "application/xml"},
        {".hxh", "application/octet-stream"},
        {".hxi", "application/octet-stream"},
        {".hxk", "application/xml"},
        {".hxq", "application/octet-stream"},
        {".hxr", "application/octet-stream"},
        {".hxs", "application/octet-stream"},
        {".hxt", "text/html"},
        {".hxv", "application/xml"},
        {".hxw", "application/octet-stream"},
        {".hxx", "text/plain"},
        {".i", "text/plain"},
        {".ico", "image/x-icon"},
        {".ics", "application/octet-stream"},
        {".idl", "text/plain"},
        {".ief", "image/ief"},
        {".iii", "application/x-iphone"},
        {".inc", "text/plain"},
        {".inf", "application/octet-stream"},
        {".inl", "text/plain"},
        {".ins", "application/x-internet-signup"},
        {".ipa", "application/x-itunes-ipa"},
        {".ipg", "application/x-itunes-ipg"},
        {".ipproj", "text/plain"},
        {".ipsw", "application/x-itunes-ipsw"},
        {".iqy", "text/x-ms-iqy"},
        {".isp", "application/x-internet-signup"},
        {".ite", "application/x-itunes-ite"},
        {".itlp", "application/x-itunes-itlp"},
        {".itms", "application/x-itunes-itms"},
        {".itpc", "application/x-itunes-itpc"},
        {".IVF", "video/x-ivf"},
        {".jar", "application/java-archive"},
        {".java", "application/octet-stream"},
        {".jck", "application/liquidmotion"},
        {".jcz", "application/liquidmotion"},
        {".jfif", "image/pjpeg"},
        {".jnlp", "application/x-java-jnlp-file"},
        {".jpb", "application/octet-stream"},
        {".jpe", "image/jpeg"},
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg"},
        {".js", "application/x-javascript"},
        {".jsx", "text/jscript"},
        {".jsxbin", "text/plain"},
        {".latex", "application/x-latex"},
        {".library-ms", "application/windows-library+xml"},
        {".lit", "application/x-ms-reader"},
        {".loadtest", "application/xml"},
        {".lpk", "application/octet-stream"},
        {".lsf", "video/x-la-asf"},
        {".lst", "text/plain"},
        {".lsx", "video/x-la-asf"},
        {".lzh", "application/octet-stream"},
        {".m13", "application/x-msmediaview"},
        {".m14", "application/x-msmediaview"},
        {".m1v", "video/mpeg"},
        {".m2t", "video/vnd.dlna.mpeg-tts"},
        {".m2ts", "video/vnd.dlna.mpeg-tts"},
        {".m2v", "video/mpeg"},
        {".m3u", "audio/x-mpegurl"},
        {".m3u8", "audio/x-mpegurl"},
        {".m4a", "audio/m4a"},
        {".m4b", "audio/m4b"},
        {".m4p", "audio/m4p"},
        {".m4r", "audio/x-m4r"},
        {".m4v", "video/x-m4v"},
        {".mac", "image/x-macpaint"},
        {".mak", "text/plain"},
        {".man", "application/x-troff-man"},
        {".manifest", "application/x-ms-manifest"},
        {".map", "text/plain"},
        {".master", "application/xml"},
        {".mda", "application/msaccess"},
        {".mdb", "application/x-msaccess"},
        {".mde", "application/msaccess"},
        {".mdp", "application/octet-stream"},
        {".me", "application/x-troff-me"},
        {".mfp", "application/x-shockwave-flash"},
        {".mht", "message/rfc822"},
        {".mhtml", "message/rfc822"},
        {".mid", "audio/mid"},
        {".midi", "audio/mid"},
        {".mix", "application/octet-stream"},
        {".mk", "text/plain"},
        {".mmf", "application/x-smaf"},
        {".mno", "text/xml"},
        {".mny", "application/x-msmoney"},
        {".mod", "video/mpeg"},
        {".mov", "video/quicktime"},
        {".movie", "video/x-sgi-movie"},
        {".mp2", "video/mpeg"},
        {".mp2v", "video/mpeg"},
        {".mp3", "audio/mpeg"},
        {".mp4", "video/mp4"},
        {".mp4v", "video/mp4"},
        {".mpa", "video/mpeg"},
        {".mpe", "video/mpeg"},
        {".mpeg", "video/mpeg"},
        {".mpf", "application/vnd.ms-mediapackage"},
        {".mpg", "video/mpeg"},
        {".mpp", "application/vnd.ms-project"},
        {".mpv2", "video/mpeg"},
        {".mqv", "video/quicktime"},
        {".ms", "application/x-troff-ms"},
        {".msi", "application/octet-stream"},
        {".mso", "application/octet-stream"},
        {".mts", "video/vnd.dlna.mpeg-tts"},
        {".mtx", "application/xml"},
        {".mvb", "application/x-msmediaview"},
        {".mvc", "application/x-miva-compiled"},
        {".mxp", "application/x-mmxp"},
        {".nc", "application/x-netcdf"},
        {".nsc", "video/x-ms-asf"},
        {".nws", "message/rfc822"},
        {".ocx", "application/octet-stream"},
        {".oda", "application/oda"},
        {".odc", "text/x-ms-odc"},
        {".odh", "text/plain"},
        {".odl", "text/plain"},
        {".odp", "application/vnd.oasis.opendocument.presentation"},
        {".ods", "application/oleobject"},
        {".odt", "application/vnd.oasis.opendocument.text"},
        {".one", "application/onenote"},
        {".onea", "application/onenote"},
        {".onepkg", "application/onenote"},
        {".onetmp", "application/onenote"},
        {".onetoc", "application/onenote"},
        {".onetoc2", "application/onenote"},
        {".orderedtest", "application/xml"},
        {".osdx", "application/opensearchdescription+xml"},
        {".p10", "application/pkcs10"},
        {".p12", "application/x-pkcs12"},
        {".p7b", "application/x-pkcs7-certificates"},
        {".p7c", "application/pkcs7-mime"},
        {".p7m", "application/pkcs7-mime"},
        {".p7r", "application/x-pkcs7-certreqresp"},
        {".p7s", "application/pkcs7-signature"},
        {".pbm", "image/x-portable-bitmap"},
        {".pcast", "application/x-podcast"},
        {".pct", "image/pict"},
        {".pcx", "application/octet-stream"},
        {".pcz", "application/octet-stream"},
        {".pdf", "application/pdf"},
        {".pfb", "application/octet-stream"},
        {".pfm", "application/octet-stream"},
        {".pfx", "application/x-pkcs12"},
        {".pgm", "image/x-portable-graymap"},
        {".pic", "image/pict"},
        {".pict", "image/pict"},
        {".pkgdef", "text/plain"},
        {".pkgundef", "text/plain"},
        {".pko", "application/vnd.ms-pki.pko"},
        {".pls", "audio/scpls"},
        {".pma", "application/x-perfmon"},
        {".pmc", "application/x-perfmon"},
        {".pml", "application/x-perfmon"},
        {".pmr", "application/x-perfmon"},
        {".pmw", "application/x-perfmon"},
        {".png", "image/png"},
        {".pnm", "image/x-portable-anymap"},
        {".pnt", "image/x-macpaint"},
        {".pntg", "image/x-macpaint"},
        {".pnz", "image/png"},
        {".pot", "application/vnd.ms-powerpoint"},
        {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
        {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
        {".ppa", "application/vnd.ms-powerpoint"},
        {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
        {".ppm", "image/x-portable-pixmap"},
        {".pps", "application/vnd.ms-powerpoint"},
        {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
        {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
        {".ppt", "application/vnd.ms-powerpoint"},
        {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
        {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".prf", "application/pics-rules"},
        {".prm", "application/octet-stream"},
        {".prx", "application/octet-stream"},
        {".ps", "application/postscript"},
        {".psc1", "application/PowerShell"},
        {".psd", "application/octet-stream"},
        {".psess", "application/xml"},
        {".psm", "application/octet-stream"},
        {".psp", "application/octet-stream"},
        {".pub", "application/x-mspublisher"},
        {".pwz", "application/vnd.ms-powerpoint"},
        {".qht", "text/x-html-insertion"},
        {".qhtm", "text/x-html-insertion"},
        {".qt", "video/quicktime"},
        {".qti", "image/x-quicktime"},
        {".qtif", "image/x-quicktime"},
        {".qtl", "application/x-quicktimeplayer"},
        {".qxd", "application/octet-stream"},
        {".ra", "audio/x-pn-realaudio"},
        {".ram", "audio/x-pn-realaudio"},
        {".rar", "application/octet-stream"},
        {".ras", "image/x-cmu-raster"},
        {".rat", "application/rat-file"},
        {".rc", "text/plain"},
        {".rc2", "text/plain"},
        {".rct", "text/plain"},
        {".rdlc", "application/xml"},
        {".resx", "application/xml"},
        {".rf", "image/vnd.rn-realflash"},
        {".rgb", "image/x-rgb"},
        {".rgs", "text/plain"},
        {".rm", "application/vnd.rn-realmedia"},
        {".rmi", "audio/mid"},
        {".rmp", "application/vnd.rn-rn_music_package"},
        {".roff", "application/x-troff"},
        {".rpm", "audio/x-pn-realaudio-plugin"},
        {".rqy", "text/x-ms-rqy"},
        {".rtf", "application/rtf"},
        {".rtx", "text/richtext"},
        {".ruleset", "application/xml"},
        {".s", "text/plain"},
        {".safariextz", "application/x-safari-safariextz"},
        {".scd", "application/x-msschedule"},
        {".sct", "text/scriptlet"},
        {".sd2", "audio/x-sd2"},
        {".sdp", "application/sdp"},
        {".sea", "application/octet-stream"},
        {".searchConnector-ms", "application/windows-search-connector+xml"},
        {".setpay", "application/set-payment-initiation"},
        {".setreg", "application/set-registration-initiation"},
        {".settings", "application/xml"},
        {".sgimb", "application/x-sgimb"},
        {".sgml", "text/sgml"},
        {".sh", "application/x-sh"},
        {".shar", "application/x-shar"},
        {".shtml", "text/html"},
        {".sit", "application/x-stuffit"},
        {".sitemap", "application/xml"},
        {".skin", "application/xml"},
        {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
        {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
        {".slk", "application/vnd.ms-excel"},
        {".sln", "text/plain"},
        {".slupkg-ms", "application/x-ms-license"},
        {".smd", "audio/x-smd"},
        {".smi", "application/octet-stream"},
        {".smx", "audio/x-smd"},
        {".smz", "audio/x-smd"},
        {".snd", "audio/basic"},
        {".snippet", "application/xml"},
        {".snp", "application/octet-stream"},
        {".sol", "text/plain"},
        {".sor", "text/plain"},
        {".spc", "application/x-pkcs7-certificates"},
        {".spl", "application/futuresplash"},
        {".src", "application/x-wais-source"},
        {".srf", "text/plain"},
        {".SSISDeploymentManifest", "text/xml"},
        {".ssm", "application/streamingmedia"},
        {".sst", "application/vnd.ms-pki.certstore"},
        {".stl", "application/vnd.ms-pki.stl"},
        {".sv4cpio", "application/x-sv4cpio"},
        {".sv4crc", "application/x-sv4crc"},
        {".svc", "application/xml"},
        {".swf", "application/x-shockwave-flash"},
        {".t", "application/x-troff"},
        {".tar", "application/x-tar"},
        {".tcl", "application/x-tcl"},
        {".testrunconfig", "application/xml"},
        {".testsettings", "application/xml"},
        {".tex", "application/x-tex"},
        {".texi", "application/x-texinfo"},
        {".texinfo", "application/x-texinfo"},
        {".tgz", "application/x-compressed"},
        {".thmx", "application/vnd.ms-officetheme"},
        {".thn", "application/octet-stream"},
        {".tif", "image/tiff"},
        {".tiff", "image/tiff"},
        {".tlh", "text/plain"},
        {".tli", "text/plain"},
        {".toc", "application/octet-stream"},
        {".tr", "application/x-troff"},
        {".trm", "application/x-msterminal"},
        {".trx", "application/xml"},
        {".ts", "video/vnd.dlna.mpeg-tts"},
        {".tsv", "text/tab-separated-values"},
        {".ttf", "application/octet-stream"},
        {".tts", "video/vnd.dlna.mpeg-tts"},
        {".txt", "text/plain"},
        {".u32", "application/octet-stream"},
        {".uls", "text/iuls"},
        {".user", "text/plain"},
        {".ustar", "application/x-ustar"},
        {".vb", "text/plain"},
        {".vbdproj", "text/plain"},
        {".vbk", "video/mpeg"},
        {".vbproj", "text/plain"},
        {".vbs", "text/vbscript"},
        {".vcf", "text/x-vcard"},
        {".vcproj", "Application/xml"},
        {".vcs", "text/plain"},
        {".vcxproj", "Application/xml"},
        {".vddproj", "text/plain"},
        {".vdp", "text/plain"},
        {".vdproj", "text/plain"},
        {".vdx", "application/vnd.ms-visio.viewer"},
        {".vml", "text/xml"},
        {".vscontent", "application/xml"},
        {".vsct", "text/xml"},
        {".vsd", "application/vnd.visio"},
        {".vsi", "application/ms-vsi"},
        {".vsix", "application/vsix"},
        {".vsixlangpack", "text/xml"},
        {".vsixmanifest", "text/xml"},
        {".vsmdi", "application/xml"},
        {".vspscc", "text/plain"},
        {".vss", "application/vnd.visio"},
        {".vsscc", "text/plain"},
        {".vssettings", "text/xml"},
        {".vssscc", "text/plain"},
        {".vst", "application/vnd.visio"},
        {".vstemplate", "text/xml"},
        {".vsto", "application/x-ms-vsto"},
        {".vsw", "application/vnd.visio"},
        {".vsx", "application/vnd.visio"},
        {".vtx", "application/vnd.visio"},
        {".wav", "audio/wav"},
        {".wave", "audio/wav"},
        {".wax", "audio/x-ms-wax"},
        {".wbk", "application/msword"},
        {".wbmp", "image/vnd.wap.wbmp"},
        {".wcm", "application/vnd.ms-works"},
        {".wdb", "application/vnd.ms-works"},
        {".wdp", "image/vnd.ms-photo"},
        {".webarchive", "application/x-safari-webarchive"},
        {".webtest", "application/xml"},
        {".wiq", "application/xml"},
        {".wiz", "application/msword"},
        {".wks", "application/vnd.ms-works"},
        {".WLMP", "application/wlmoviemaker"},
        {".wlpginstall", "application/x-wlpg-detect"},
        {".wlpginstall3", "application/x-wlpg3-detect"},
        {".wm", "video/x-ms-wm"},
        {".wma", "audio/x-ms-wma"},
        {".wmd", "application/x-ms-wmd"},
        {".wmf", "application/x-msmetafile"},
        {".wml", "text/vnd.wap.wml"},
        {".wmlc", "application/vnd.wap.wmlc"},
        {".wmls", "text/vnd.wap.wmlscript"},
        {".wmlsc", "application/vnd.wap.wmlscriptc"},
        {".wmp", "video/x-ms-wmp"},
        {".wmv", "video/x-ms-wmv"},
        {".wmx", "video/x-ms-wmx"},
        {".wmz", "application/x-ms-wmz"},
        {".wpl", "application/vnd.ms-wpl"},
        {".wps", "application/vnd.ms-works"},
        {".wri", "application/x-mswrite"},
        {".wrl", "x-world/x-vrml"},
        {".wrz", "x-world/x-vrml"},
        {".wsc", "text/scriptlet"},
        {".wsdl", "text/xml"},
        {".wvx", "video/x-ms-wvx"},
        {".x", "application/directx"},
        {".xaf", "x-world/x-vrml"},
        {".xaml", "application/xaml+xml"},
        {".xap", "application/x-silverlight-app"},
        {".xbap", "application/x-ms-xbap"},
        {".xbm", "image/x-xbitmap"},
        {".xdr", "text/plain"},
        {".xht", "application/xhtml+xml"},
        {".xhtml", "application/xhtml+xml"},
        {".xla", "application/vnd.ms-excel"},
        {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
        {".xlc", "application/vnd.ms-excel"},
        {".xld", "application/vnd.ms-excel"},
        {".xlk", "application/vnd.ms-excel"},
        {".xll", "application/vnd.ms-excel"},
        {".xlm", "application/vnd.ms-excel"},
        {".xls", "application/vnd.ms-excel"},
        {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
        {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".xlt", "application/vnd.ms-excel"},
        {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
        {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
        {".xlw", "application/vnd.ms-excel"},
        {".xml", "text/xml"},
        {".xmta", "application/xml"},
        {".xof", "x-world/x-vrml"},
        {".XOML", "text/plain"},
        {".xpm", "image/x-xpixmap"},
        {".xps", "application/vnd.ms-xpsdocument"},
        {".xrm-ms", "text/xml"},
        {".xsc", "application/xml"},
        {".xsd", "text/xml"},
        {".xsf", "text/xml"},
        {".xsl", "text/xml"},
        {".xslt", "text/xml"},
        {".xsn", "application/octet-stream"},
        {".xss", "application/xml"},
        {".xtp", "application/octet-stream"},
        {".xwd", "image/x-xwindowdump"},
        {".z", "application/x-compress"},
        {".zip", "application/x-zip-compressed"},
        #endregion

        };

        public static void Log(string logMessage, TextWriter w)
        {
            Log(logMessage, w, false);
        }
        public static void Log(string logMessage, TextWriter w, bool error)
        {
            if (error)
                w.WriteLine("Error {0} : {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), logMessage);
            else
                w.WriteLine("Log   {0} : {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), logMessage);
        }

        public static string GetMimeType(string extension)
        {
            if (extension == null)
            {
                //throw new ArgumentNullException("extension");
                return "application/unknown";
            }

            if (!extension.StartsWith("."))
            {
                extension = "." + extension;
            }

            string mime;

            return _mappings.TryGetValue(extension, out mime) ? mime : "application/octet-stream";
        }
    }
}