Monday, 9 February 2015

Convert date time to UTC zone



Hi Folks,




Just another post which will help you to convert your date and time to UTC and give you the response


LocalTimeFromUtcTimeRequest timeReq = new LocalTimeFromUtcTimeRequest();
//app_date is date field value which you want to update.                       
timeReq.UtcTime = app_date;
timeReq.TimeZoneCode = timezone;
                        // Execute the LocalTimeFromUtcTimeRequest
                        LocalTimeFromUtcTimeResponse timeResp = (LocalTimeFromUtcTimeResponse)service.Execute(timeReq);
                        DateTime actualdate= timeResp.LocalTime;




Thanks

Thursday, 5 February 2015

MSCRM 2013 Workhours (Creation of Schedule from 9 - 5 from Plugin) and (Updation of time for one day based on Date selection)

Hi Folks ,
 
After long break I am writing this blog which may help in some of your customer requirement.
MSCRM has strong feature in UR3 called Scheduling holidays and Scheduling workhours for users and Facilities.
In my Scenario , I am using Facility/Equipment entity to store my resource attendance. My functionality flow is:
Step 1: User creates a record in Custom entity which is called "Resource" a plugin will create a record in "Facilities" which by default will have calendar created for whole day(OOB)
Step2: My next step in Plugin will update the calendar created by MSCRM form full day schedule to schedule of(9AM - 6PM).
Step3: Resource will update in his "resource" record stating for one day he has worked only for 4 hours. My Plugin would again update Time for that specific date.
 
This blog will help you to achieve below 2 functionalities:
  • Creation of Workhour calendar.
  • Updating  Workhour calendar.
First of all to understand how Workhours for User and Facilities/Equipment works .Please follow below link:


http://www.microsoft.com/en-us/dynamics/crm-customer-center/set-work-hours-of-a-resource.aspx


http://crmbook.powerobjects.com/basics/service-scheduling/work-hours/




And Thanks for Nishanth Ranas blog which helped me to achieve my Functionalities:


http://nishantrana.me/2013/04/16/sample-code-to-update-users-calendar-programmatically-work-hours-in-crm-2011/


Holiday Schedule will be available only in UR3. Please find below link to know what it is and how it works:
http://inogic.com/blog/2014/07/calendars-holiday-and-customer-service-scheduling-in-microsoft-dynamics-crm-2013-sp1/




Please find code below to create WorkHour calendar for Specific Hours for Specific Date Range:


9AM - 6PM

                    //Create workHour calendar for attendance




                    // Get the calendar id of the facilities
                    Entity facilityEntity = service.Retrieve("equipment", attendance, new ColumnSet(new String[] { "calendarid" }));


                    // Retrieve the calendar of the Facilities
                    Entity facilityCalendarEntity = service.Retrieve("calendar", ((Microsoft.Xrm.Sdk.EntityReference)(facilityEntity.Attributes["calendarid"])).Id, new ColumnSet(true));

                    // Retrieve the calendar rules defined in the calendar
                    EntityCollection calendarRules = (EntityCollection)facilityCalendarEntity.Attributes["calendarrules"];

                    // Create a new inner calendar
                    Entity newInnerCalendar = new Entity("calendar");
                    newInnerCalendar.Attributes["businessunitid"] = new EntityReference("businessunit", ((Microsoft.Xrm.Sdk.EntityReference)(facilityCalendarEntity["businessunitid"])).Id);
                    Guid innerCalendarId = service.Create(newInnerCalendar);

                   
                    // Create a new calendar rule and assign the inner calendar id to it
                    Entity calendarRule = new Entity("calendarrule");
                    calendarRule.Attributes["duration"] = 1440;
                    calendarRule.Attributes["extentcode"] = 1;
                    calendarRule.Attributes["pattern"] = "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR";
                    calendarRule.Attributes["rank"] = 0;
                    calendarRule.Attributes["timezonecode"] = 190;
                    calendarRule.Attributes["innercalendarid"] = new EntityReference("calendar", innerCalendarId);
                    calendarRule.Attributes["starttime"] = new DateTime(2015, 2, 3,9, 0, 0, DateTimeKind.Utc);
                   // calendarRule.Attributes["endtime"] = new DateTime(9999, 12, 30, 23, 59, 59, DateTimeKind.Utc);
                    calendarRules.Entities.Add(calendarRule);

                    // assign all the calendar rule back to the user calendar
                    facilityCalendarEntity.Attributes["calendarrules"] = calendarRules;
                    // update the user calendar entity that has the new rule
                    service.Update(facilityCalendarEntity);

                    Entity calendarRule1 = new Entity("calendarrule");
                    // duration of 5 hours
                    calendarRule1.Attributes["issimple"] = true;
                   // calendarRule1.Attributes["isselected"] = false;
                    calendarRule1.Attributes["duration"] = 540;
                    calendarRule1.Attributes["offset"] = 0;
                   // calendarRule1.Attributes["isselected"] = true;
                    calendarRule1.Attributes["rank"] = 0;
                    calendarRule1.Attributes["subcode"] = 1;
                    calendarRule1.Attributes["timecode"] = 0;
                    calendarRule1.Attributes["timezonecode"] = 190;
                    calendarRule1.Attributes["calendarid"] = new EntityReference("calendar", innerCalendarId);

                    EntityCollection innerCalendarRules = new EntityCollection();
                    innerCalendarRules.EntityName = "calendarrule";
                    innerCalendarRules.Entities.Add(calendarRule1);

                    newInnerCalendar.Attributes["calendarrules"] = innerCalendarRules;
                    newInnerCalendar.Attributes["calendarid"] = innerCalendarId;
                    service.Update(newInnerCalendar);

                    //Create second inner calendar
                    Entity newInnerCalendar1 = new Entity("calendar");
                    newInnerCalendar1.Attributes["businessunitid"] = new EntityReference("businessunit", ((Microsoft.Xrm.Sdk.EntityReference)(facilityCalendarEntity["businessunitid"])).Id);
                    Guid innerCalendarId1 = service.Create(newInnerCalendar1);

                    // Create a 2nd calendar rule and assign the inner calendar id to it
                    Entity calendarRuleWeekend = new Entity("calendarrule");
                    calendarRuleWeekend.Attributes["duration"] = 525600;
                    calendarRuleWeekend.Attributes["extentcode"] = 1;
                    calendarRuleWeekend.Attributes["pattern"] = "FREQ=YEARLY;INTERVAL=1";
                    calendarRuleWeekend.Attributes["rank"] = 0;
                    calendarRuleWeekend.Attributes["timezonecode"] = 190;
                    calendarRuleWeekend.Attributes["innercalendarid"] = new EntityReference("calendar", innerCalendarId1);
                    calendarRuleWeekend.Attributes["starttime"] = new DateTime(2015, 2, 3, 9, 0, 0, DateTimeKind.Utc);
                   // calendarRuleWeekend.Attributes["endtime"] = new DateTime(9999, 12, 30, 23, 59, 59, DateTimeKind.Utc);
                    calendarRules.Entities.Add(calendarRuleWeekend);
                    // assign all the calendar rule back to the user calendar
                    facilityCalendarEntity.Attributes["calendarrules"] = calendarRules;
                    // update the user calendar entity that has the new rule
                    service.Update(facilityCalendarEntity);
                   

                    Entity calendarRule2 = new Entity("calendarrule");
                    calendarRule2.Attributes["issimple"] = true;
                    calendarRule2.Attributes["duration"] = 0;
                    calendarRule2.Attributes["offset"] = 0;
                    calendarRule2.Attributes["rank"] = 1;
                    calendarRule2.Attributes["subcode"] = 0;
                    calendarRule2.Attributes["timecode"] = 0;
                    calendarRule2.Attributes["timezonecode"] = 190;
                    calendarRule2.Attributes["calendarid"] = new EntityReference("calendar", innerCalendarId1);

                    EntityCollection innerCalendarRules1 = new EntityCollection();
                    innerCalendarRules1.EntityName = "calendarrule";
                    innerCalendarRules1.Entities.Add(calendarRule2);

                    newInnerCalendar1.Attributes["calendarrules"] = innerCalendarRules1;
                    newInnerCalendar1.Attributes["calendarid"] = innerCalendarId1;
                    service.Update(newInnerCalendar1);





In Above Code I have created 2 Inner Calendar, one to add standard schedule and one to state leav on Saturday and Sunday.




Please find Code below to Update time for Resource for specified Date:


                    //Retrieve workHours from resource
                    Entity resourceschedule = service.Retrieve("contact", resource.Id, new ColumnSet(true));
                    switch ((datetoUpdate.AddDays(1)).ToString("dddd"))
                    {
                        case "Sunday":
                            duration = (int) resourceschedule.Attributes["usmc_sunday"];
                            break;
                        case "Saturday":
                            duration = (int) resourceschedule.Attributes["usmc_saturday"];
                            break;
                        case "Monday":
                            duration = (int)resourceschedule.Attributes["usmc_monday"];
                            break;
                        case "Tuesday":
                            duration = (int)resourceschedule.Attributes["usmc_tuesday"];
                            break;
                        case "Wednesday":
                            duration = (int)resourceschedule.Attributes["usmc_wednesday"];
                            break;
                        case "Thursday":
                            duration = (int)resourceschedule.Attributes["usmc_thursday"];
                            break;
                        case "Friday":
                            duration = (int)resourceschedule.Attributes["usmc_friday"];
                            break;
                    }

                    TimeSpan time1 = new TimeSpan(0,9,0,0);
                    datetoUpdate = datetoUpdate.AddDays(1).Date.Add(time1);
                    //Retrieve Facilities for Specific Leav Record
                    QueryExpression Qe = new QueryExpression();
                    Qe.EntityName = "equipment";
                    Qe.ColumnSet = new ColumnSet(true);
                    ConditionExpression ce = new ConditionExpression();
                    ce.AttributeName = "usmc_resource";
                    ce.Operator = ConditionOperator.Equal;
                    ce.Values.Add(resource.Id);
                    Qe.Criteria.AddCondition(ce);
                    EntityCollection facility = service.RetrieveMultiple(Qe);
                    foreach (Entity FC in facility.Entities)
                    {
                        faciltyID = FC.Id;
                    }
                   
                    //Update Time for Specific Faciltiy/Attendance for selected date
                    // Get the calendar id of the facilities
                    Entity FaciltiyEntity = service.Retrieve("equipment", faciltyID, new ColumnSet(new String[] { "calendarid" }));


                    // Retrieve the calendar of the Facilities
                    Entity FaciltiyCalendarEntity= service.Retrieve("calendar", ((Microsoft.Xrm.Sdk.EntityReference)(FaciltiyEntity.Attributes["calendarid"])).Id, new ColumnSet(true));



                    // Retrieve the calendar rules defined in the calendar
                    EntityCollection calendarRules = (EntityCollection)userCalendarEntity.Attributes["calendarrules"];

                    //Create a new inner calendar
                    Entity newInnerCalendar = new Entity("calendar");
                    newInnerCalendar.Attributes["businessunitid"] = new EntityReference("businessunit", ((Microsoft.Xrm.Sdk.EntityReference)(userCalendarEntity["businessunitid"])).Id);
                    Guid innerCalendarId = service.Create(newInnerCalendar);

                     //Create a new calendar rule and assign the inner calendar id to it
                     Entity calendarRule = new Entity("calendarrule");
                     calendarRule.Attributes["duration"] = 1440;
                     calendarRule.Attributes["extentcode"] = 1;
                     calendarRule.Attributes["pattern"] = "FREQ=DAILY;COUNT=1";
                     calendarRule.Attributes["rank"] = 0;
                     calendarRule.Attributes["timezonecode"] = 190;
                     calendarRule.Attributes["innercalendarid"] = new EntityReference("calendar", innerCalendarId);
                     calendarRule.Attributes["starttime"] = datetoUpdate;
                     calendarRules.Entities.Add(calendarRule);

                     // assign all the calendar rule back to the Faacility calendar
                     userCalendarEntity.Attributes["calendarrules"] = calendarRules;
                     // update the Facility calendar entity that has the new rule
                     service.Update(userCalendarEntity);

                     Entity calendarRule1 = new Entity("calendarrule");
                     calendarRule1.Attributes["duration"] = duration*60;
                     calendarRule1.Attributes["effort"] = 0.0;
                    calendarRule1.Attributes["extentcode"] = 1;
                    calendarRule1.Attributes["issimple"] = true;
                     calendarRule1.Attributes["offset"] = 0;
                     calendarRule1.Attributes["rank"] = 0;
                     calendarRule1.Attributes["subcode"] = 1;
                     calendarRule1.Attributes["timecode"] = 0;
                     calendarRule1.Attributes["timezonecode"] = 190;
                     calendarRule1.Attributes["calendarid"] = new EntityReference("calendar", innerCalendarId);

                    EntityCollection innerCalendarRules = new EntityCollection();
                    innerCalendarRules.EntityName = "calendarrule";
                    innerCalendarRules.Entities.Add(calendarRule1);

                    newInnerCalendar.Attributes["calendarrules"] = innerCalendarRules;
                    newInnerCalendar.Attributes["calendarid"] = innerCalendarId;
                    service.Update(newInnerCalendar);







Hope it help you to achieve ur requirments.


Thank you












Tuesday, 17 September 2013

Retrieve selected value from Option Set - MSCRM 2011 - C#


    string selectedCategory = (string)scanEntity.FormattedValues["field name"]; 

Monday, 16 September 2013

MSCRM 2011 Paging Queries

As u all Know CRM "RetireveMultiple" fetches all the records . In  a Scenario where you want to restrict it to retrieve the count of records according to the business rule, the below query would be used to restrict the count

public Guid retrievesite(int count)
{
       

        QueryExpression qe = new QueryExpression("new_scans");
        qe.PageInfo = new PagingInfo();
        qe.PageInfo.Count = count;// pass number to which it should be restricted
        qe.ColumnSet = new ColumnSet(true);
        qe.Criteria.AddCondition("statuscode", ConditionOperator.Equal,100000003);
        EntityCollection scans = _xrm.RetrieveMultiple(qe);
        if (scans.Entities.Count > 0)
  {
   foreach (Entity site in scans.Entities)
    {
     string  _sitename = site.Attributes["new_name"].ToString();
    }
  }

}

Thanks

Friday, 13 September 2013

To Create and Remove Connections in MSCRM 2011 Programatically

Hi CRM Dynamites,


In Microsoft Dynamics CRM 2011, a new feature called Connections adds a layer to records organization, allowing users to connect records in an intuitive manner. Connections gives users insight into their company’s records in Dynamics CRM 2011 at a glance. A user can open any record and quickly identify relationships or a hierarchy by looking at that record’s Connections with other records.

Scenario: Suppose u have a Account entity and Contact Entity and u want to create a connection for Account with Contact Entity.

To Create this Connections Programmatically below code can be used :


public void Create_Accc_Contact_Connection(Guid accountid, int objectTypeCode) //Account Entity Obeject Typecode
        {
          
                Guid Contact = ContactGUID;
 Connection newConnection = new Connection
                    {
                        Record1Id = new EntityReference(ContactEntityLogicalName,
                                                Contact),
                        Record1RoleId = new EntityReference(ConnectionRole.EntityLogicalName,
                                                ContactConnectionRoleId),
                        Record2RoleId = new EntityReference(ConnectionRole.EntityLogicalName,
                                                AccountConnectionRoleId),
                        Record2Id = new EntityReference(AccountEntityLogicalName,
                                                accountid)
                    };

                    service.Execute(newConnection);
              
      
          
        }





To Remove Connection Programmatically between entity below code can be used :


 
public void Remove_Accc_Contact_Connection(Guid accountid, int objectTypeCode) //Account Entity Obeject Typecode
        {
          
                Guid Contact = ContactGUID;
                QueryExpression query = new QueryExpression
                {
                    EntityName = Connection.EntityLogicalName,
                    Criteria =
                    {
                        Conditions =
                        {
                            new ConditionExpression("record1id", ConditionOperator.Equal, accountid),
                            new ConditionExpression("record2objecttypecode", ConditionOperator.Equal, objectTypeCode),
                            new ConditionExpression("record2roleid", ConditionOperator.Equal, Contact)
                        }
                    },
                };
                    service.Delete(Connection.EntityLogicalName, ent.Id);
              
      
          
        }



Hope this post helps for your requirement

Thanks

 

Associate Request MSCRM 2011

Scenario: I have 2 Entity "Entity A" and Entity B", and there is a relationship 1:N between "Entity A"and "Entity B".Suppose you have create a new record for "Entity A"and since there is a relationship between "Entity A"and "Entity B", so you would like to relate this "Entity A" record to a specific or many records of "Entity B". I will use a class called “Associate Request”  which links records to each user assuming there is a relationship between the entities which records belong to . Below is the code snippet to achieve:



IOrganizationSericce service;  // instance of the organization serivce
AssociateRequest  contactToAccount = new AssociateRequest
 {

//Entity A Record
Target = new EntityReference(Entity A LogicalName, Entity A.GUID),
RelatedEntities = new EntityReferenceCollection
 {
 new EntityReference(Entity B LogicalName, Entity B.GUID)
 },

Relationship = new Relationship(“name of the relationship already existing”)
 };

              

Thanks.. :)
 

Bulk import functionality using Execcute Multiple Request UR12 -Not OOB feature

Hi folks, after long time adding something to my blog

This is a small feature which was requested by my client where they wanted to have bulk import functionality in there Web application but they never wanted to use OOB Bulk Import functionality in MSCRM 2011.
Scenario: Customer would upload a excel file from web application which consists (1000 Min) rows , for which the record should be created in MSCRM 2011

We Used normal create call but the time consumed to created record was very High . In a scenario time taken to create 25 records is (90 Sec Approx.) . Later we achieved the same using the new class in UR12 "ExecuteMultipleRequest" class. using which 25 records got created in (12 sec Approx.).Below code gives the demo of how to create a series of record using the new class.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.ServiceModel;
using MS.GetOnline.SiteInfo.code;
using MS.GetOnline.SiteInfo.CrmOrgServiceLib;
using Microsoft.Xrm.Sdk;
using System.Globalization;
using AjaxControlToolkit;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text.RegularExpressions;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using System.Configuration;
using System.Data;
using System.Diagnostics;
namespace MS.GetOnline.SiteInfo
{
    public partial class Bulk_Import : System.Web.UI.Page
   
{
 public void bulkimport(List<SiteInformation> objSiteInformation, string status)
        {
            try
            {
//Object which we create using the data imported in Excel sheet Count.
                int noOfRecs = objSiteInformation.Count();
                List<Guid> _createdSiteGuids = new List<Guid>();
                #region Site with ExecuteMultipleRequest

                ExecuteMultipleRequest SiteCreation = new ExecuteMultipleRequest()
                {
                    // Assign settings that define execution behavior: continue on error, return responses.
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    },
                    // Create an empty organization request collection.
                    Requests = new OrganizationRequestCollection()
                };
                for (int i = 0; i < noOfRecs; i++)
                {
                    Entity site = new Entity("Entity Logical Name");
                    site["new_name"] = objSiteInformation[i].SiteUrl;
                    Guid PrimaryContactIdStr = new Guid(Crm.Data.GetContactIdByFullName(objSiteInformation[i].PrimaryContactName));
                    site["new_primarycontactid"] = new EntityReference("contact", PrimaryContactIdStr);
                    site["new_username"] = objSiteInformation[i].UserID;
                    site["new_password"] = objSiteInformation[i].Password;
                
                    if (objSiteInformation[i].dataClass == "LBI")
                    {
                        site["new_dataclassification"] = new OptionSetValue(100000000);
                    }
                    else
                        if (objSiteInformation[i].dataClass == "MBI")
                        {
                            site["new_dataclassification"] = new OptionSetValue(100000001);
                        }
                        else
                        {
                            site["new_dataclassification"] = new OptionSetValue(100000002);
                        }
                   //  Create New request For ExecuteMutlipleRequest                  
                    CreateRequest createReq = new CreateRequest { Target = site };
                    SiteCreation.Requests.Add(createReq);
                }
                // Execute all the requests in the request collection using a single web method call.
                ExecuteMultipleResponse siteResults = (ExecuteMultipleResponse)_xrm.Execute(SiteCreation);
                // Display the results returned in the responses.
                foreach (var responseItem in siteResults.Responses)
                {
                    // A valid response.
                    if (responseItem.Response != null)
                    {
                        _createdSiteGuids.Add(new Guid(responseItem.Response.Results["id"].ToString()));
                    }
                }
               }


}
}


Hope this helps you in your scenario.....