Thursday, 30 July 2015

multivalues to lookup in mscrm

if (SAPVACs.length > 0) {
                var query = "";
                for (var i = 0; i < SAPVACs.length; i++) {
                    if (SAPVACs[i].attributes["vaccodeid"] !== undefined) {
                     

                        query += "<value uitype='vacmaping'>{" + vacid + "}</value>";
                    }
                }

                var filter = "<filter type='and'>" +
                    "<condition attribute='vacmapingid' operator='in'>" + query + "</condition>" +
                       "</filter>";
                Xrm.Page.getControl("vacfmcid").addCustomFilter(filter);
            }

Saturday, 25 July 2015

Sample Plugins



public class Class1:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
             SamplePlugins handler1 = new SamplePlugins(service, tracing, context);
            handler1.createRecords();
        }
    }


///////////////////////////////////////////////////////////////

 class SamplePlugins
    {
        private IOrganizationService service;
        private ITracingService trace;
        private IPluginExecutionContext context;
      //DateTime dt=new DateTime()
     
        public SamplePlugins(IOrganizationService service,ITracingService trace, IPluginExecutionContext context)
        {
            this.context = context;
            this.trace = trace;
            this.service = service;
        }

        internal void createRecords()
         {
             Entity obj = new Entity("new_students");
             obj.Attributes["new_name"] = "ADBCD";
             obj.Attributes["new_rates"] = new Money(4555);
             DateTime adat = Handlers.GetLocalTime(trace, service, context, DateTime.Today);
//Fdate = string.Format("{0}-{1}-{2}", date.Year, date.Month, date.Day);
             service.Create(obj);
         }

    }


Handler class for common Methodes
public static class Handlers
    {
      public static Entity GetCurrentEntityFromContext(IPluginExecutionContext context)
      {

          if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
          {
              return (Entity)context.InputParameters["Target"];
          }
          else
          {
              throw new Exception("Error: the context input parameter didn't return the target entity");
          }

      }
          public static int GetUserTimeZoneCode(ITracingService tracing, IOrganizationService service, IPluginExecutionContext context)
{
tracing.Trace("In GetUserTimeZoneCode method");
            int timeZoneCode = 0;

            try
            {
                string fetchXmls = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                <entity name='usersettings'>
                    <attribute name='timezonecode' />
                    <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='ad'>
                        <filter type='and'>
                            <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='{0}' />
                        </filter>
                    </link-entity>
                </entity>
            </fetch>";

                EntityCollection userSettings = service.RetrieveMultiple(new FetchExpression(string.Format(fetchXmls, context.UserId)));

                if (userSettings.Entities.Count > 0)
                {
                    timeZoneCode = GetValueFromContextOrImage<int>(userSettings.Entities.FirstOrDefault(), "timezonecode");
                    tracing.Trace("TimeZoneCode: " + timeZoneCode);
                }
            }
            catch (Exception ex)
            {
                tracing.Trace("Error in GetUserTimeZoneCode method: " + ex.Message);
            }

            return timeZoneCode;
}
      public static T GetValueFromContextOrImage<T>(Entity contextRecord, string fieldName, Entity image = null)
{
if (contextRecord != null && contextRecord.Contains(fieldName))
{
return contextRecord.GetAttributeValue<T>(fieldName);
}
else if (image != null && image.Contains(fieldName))
{
return image.GetAttributeValue<T>(fieldName);
}

return new Entity().GetAttributeValue<T>("dummyValue");
}
      public static void SetValueToContextOrImage(Entity contextRecord, string fieldName, object value)
      {
          if (contextRecord != null)
          {
              if (contextRecord.Contains(fieldName))
                  contextRecord.Attributes[fieldName] = value;
              else
                  contextRecord.Attributes.Add(fieldName, value);
          }
          else
          {
              throw new Exception("Record is null");
          }
      }

/// <summary>
/// Return the Local time for the time provided
/// </summary>
/// <param name="UTCTime">The DateTime of UTC Time</param>
/// <returns>The DateTime of local time</returns>
public static DateTime GetLocalTime(ITracingService tracing, IOrganizationService service, IPluginExecutionContext context, DateTime UTCTime)
{
tracing.Trace("In GetLocalTime method");
            LocalTimeFromUtcTimeResponse timeResp = new LocalTimeFromUtcTimeResponse();
            try
            {
                // If UTCTime is null the return UTCTime
                if (UTCTime.Equals(DateTime.MinValue))
                    return UTCTime;

                // Create LocalTimeFromUtcTimeRequest instance and set the UtcTime and TimeZoneCode
                LocalTimeFromUtcTimeRequest timeReq = new LocalTimeFromUtcTimeRequest();
                timeReq.UtcTime = UTCTime.ToUniversalTime();
                timeReq.TimeZoneCode = GetUserTimeZoneCode(tracing, service, context);

                // Execute the LocalTimeFromUtcTimeRequest
                timeResp = (LocalTimeFromUtcTimeResponse)service.Execute(timeReq);

            }
            catch (Exception ex)
            {
                tracing.Trace("Error in GetLocalTime method: "+ex.Message);
            }

return timeResp.LocalTime;
}


Get Local Time From UTC in MSCRM

public static int GetUserTimeZoneCode(ITracingService tracing, IOrganizationService service, IPluginExecutionContext context)
{
tracing.Trace("In GetUserTimeZoneCode method");
            int timeZoneCode = 0;

            try
            {
                string fetchXmls = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                <entity name='usersettings'>
                    <attribute name='timezonecode' />
                    <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='ad'>
                        <filter type='and'>
                            <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='{0}' />
                        </filter>
                    </link-entity>
                </entity>
            </fetch>";

                EntityCollection userSettings = service.RetrieveMultiple(new FetchExpression(string.Format(fetchXmls, context.UserId)));

                if (userSettings.Entities.Count > 0)
                {
                    timeZoneCode = GetValueFromContextOrImage<int>(userSettings.Entities.FirstOrDefault(), "timezonecode");
                    tracing.Trace("TimeZoneCode: " + timeZoneCode);
                }
            }
            catch (Exception ex)
            {
                tracing.Trace("Error in GetUserTimeZoneCode method: " + ex.Message);
            }

            return timeZoneCode;
}

/// <summary>
/// Return the Local time for the time provided
/// </summary>
/// <param name="UTCTime">The DateTime of UTC Time</param>
/// <returns>The DateTime of local time</returns>
public static DateTime GetLocalTime(ITracingService tracing, IOrganizationService service, IPluginExecutionContext context, DateTime UTCTime)
{
tracing.Trace("In GetLocalTime method");
            LocalTimeFromUtcTimeResponse timeResp = new LocalTimeFromUtcTimeResponse();
            try
            {
                // If UTCTime is null the return UTCTime
                if (UTCTime.Equals(DateTime.MinValue))
                    return UTCTime;

                // Create LocalTimeFromUtcTimeRequest instance and set the UtcTime and TimeZoneCode
                LocalTimeFromUtcTimeRequest timeReq = new LocalTimeFromUtcTimeRequest();
                timeReq.UtcTime = UTCTime.ToUniversalTime();
                timeReq.TimeZoneCode = GetUserTimeZoneCode(tracing, service, context);

                // Execute the LocalTimeFromUtcTimeRequest
                timeResp = (LocalTimeFromUtcTimeResponse)service.Execute(timeReq);

            }
            catch (Exception ex)
            {
                tracing.Trace("Error in GetLocalTime method: "+ex.Message);
            }

return timeResp.LocalTime;
}

public static void SetValueToContextOrImage(Entity contextRecord, string fieldName, object value)
{
if (contextRecord != null)
{
if (contextRecord.Contains(fieldName))
contextRecord.Attributes[fieldName] = value;
else
contextRecord.Attributes.Add(fieldName, value);
}
else
{
throw new Exception("Record is null");
}
}

/// <summary>
/// A generic method to check if a field exist in the context record and return its value. Otherwise will use the image record instead.
/// </summary>
/// <typeparam name="T">The type of the attribute</typeparam>
/// <param name="contextRecord">The current record in context or a retrieved record (must not be null)</param>
/// <param name="fieldName">The field name</param>
/// <param name="image">Optional. PreImage or PostImage record to get the value from if the context record doesn't have it</param>
/// <returns></returns>
public static T GetValueFromContextOrImage<T>(Entity contextRecord, string fieldName, Entity image = null)
{
if (contextRecord != null && contextRecord.Contains(fieldName))
{
return contextRecord.GetAttributeValue<T>(fieldName);
}
else if (image != null && image.Contains(fieldName))
{
return image.GetAttributeValue<T>(fieldName);
}

return new Entity().GetAttributeValue<T>("dummyValue");
}



Thursday, 23 July 2015

WCF Selft hosting

class Program
    {
        static void Main(string[] args)
        {

            ServiceHost svcHost = new ServiceHost(typeof(WCFLibrary2.WCFService1));
            Uri uri1 = new Uri("http://localhost:8888/WCFService1");
            BasicHttpBinding bhb = new BasicHttpBinding();
            svcHost.AddServiceEndpoint(typeof(WCFLibrary2.IWCFService1), bhb, uri1);
            
            //Add MEX Endpoint
            Uri uri2 = new Uri("http://localhost:8888/WCFService1/MEX");
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetUrl = new Uri("http://localhost:8888/WCFService1");
            smb.HttpGetEnabled = true;
            svcHost.Description.Behaviors.Add(smb);
            svcHost.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), uri2);
            //MEX END
            svcHost.Open();
            Console.WriteLine("Service is ready...");
            Console.WriteLine("Press Enter key to end..");
            Console.ReadLine();
            svcHost.Close();

        }
    }


///
 class Program
    {
        static void Main(string[] args)
        {
            ServiceHost svcHost = new ServiceHost(typeof(WCFLibrary1.WCFService1));
            svcHost.Open();
            Console.WriteLine("Service Started...");
            Console.WriteLine("Press Enter key to end service..");
            Console.ReadLine();
            svcHost.Close();
        }
    }



namespace WCFLibrary1
{
    [ServiceContract]
    public interface IWCFService1
    {
        [OperationContract]
        string Hello(string s);

    }
    public class WCFService1 : IWCFService1
    {
        public String Hello(String s)
        {
            return "Hello " + s;
        }

    }
}