Sunday, 19 April 2015

Silverlight grid in mscrm

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.CSharp;
using System.Threading;
using SilverlightApplication2.ServiceReference1;
using System.Data.Services.Client;
namespace SilverlightApplication2
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;
            InitializeCRMServiceContext();
            LoadForecast();

        }
        private SynchronizationContext _syncContext;
        private CRM2013VanillaContext _context;
        private String _serverURL;

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            InitializeCRMServiceContext();
            LoadForecast();

        }

        private void InitializeCRMServiceContext()
        {
            // Get the ServerUrl (ServerUrl is formatted differently OnPremise than
            // OnLine).
            _serverURL = ServerUtility.GetServerUrl();

            if (!String.IsNullOrEmpty(_serverURL))
            {

                // Setup context.
                _context = new CRM2013VanillaContext(
                    new Uri(String.Format("{0}/xrmservices/2011/organizationdata.svc/",
                        _serverURL), UriKind.Absolute));

                //This is important because if the entity has new
                //attributes added the code will fail.
                _context.IgnoreMissingProperties = true;
                _context.MergeOption = MergeOption.PreserveChanges;
                //Set defaults;

            }
            else
            {
                //lblError.Content = "unable to connect to crm server.";
            }
        }

        private void LoadForecast()
        {

            //Get Engagement Record ID
            string recordID = ((string)HtmlPage.Window.Eval("Xrm.Page.data.entity.getId()")).Replace("{", "").Replace("}", "");
            //
            MessageBox.Show(recordID);
         
            DataServiceQuery<new_test> query = (DataServiceQuery<new_test>)_context.new_testSet.AddQueryOption("$select", "new_name,new_Age");

            // DataServiceQuery<new_test> query = (DataServiceQuery<new_test>)_context.new_testSet.AddQueryOption("$select", "new_name eq 'ddddddd'");
            //DataServiceQuery<new_forecast> query = (DataServiceQuery<new_forecast>)_context.new_forecastSet;

            /// DataServiceQuery<new_test> query = (DataServiceQuery<new_test>)_context.new_testSet.Where(a => a.new_testId == new Guid(recordID)

            //).Select(a=>new{rt=a.new_Age,tf=a.new_name});

            // DataServiceQuery<new_test> query = (DataServiceQuery<new_test>)_context.new_testSet.AddQueryOption("$select", "new_name,new_name");

            //           DataServiceQuery<new_test> query = (DataServiceQuery<new_test>)
            //_context.new_testSet.AddQueryOption("$filter", "new_testId eq guid'" + recordID + "'");
            //          // queryContact.BeginExecute(RetrieveContactHandler, queryContact);


           query.BeginExecute(this.LoadForecastCallback, query);
        }

        #region Callbacks
        private void LoadForecastCallback(IAsyncResult asyncResult)
        {
            // DataServiceQuery<new_test> query1 = (DataServiceQuery<new_test>)_context.new_testSet.AddQueryOption("$select", "new_name,new_Age").Where<new_test>(a => (a.new_name == "ddddddd"));
            //Label.Content = "Message: successful call back";
            DataServiceQuery<new_test> query = asyncResult.AsyncState as DataServiceQuery<new_test>;
            List<new_test> r = new DataServiceCollection<new_test>(query.EndExecute(asyncResult)).ToList();

            // MessageBox.Show(r.Count.ToString());



            //var list = (query.EndExecute(asyncResult)).ToList();
            demo.ItemsSource = (from e in r select new { name = e.new_name, age = e.new_Age }).ToList();

            //r.Select(p=>p.new_name,new_ag);
            // silvergrid.DataContext = list;


        }
        private void SaveChangesCallback(IAsyncResult asyncResult)
        {
            _context = asyncResult.AsyncState as CRM2013VanillaContext;
            var response = _context.EndSaveChanges(asyncResult);
        }
        #endregion

        private void demo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }




    }
}
/////////////////////////////////////////


using System;
using System.Windows.Browser;


    public static class ServerUtility
    {
        /// <summary>
        /// Returns the ServerUrl from Microsoft Dynamics CRM
        /// </summary>
        /// <returns>String representing the ServerUrl or String.Empty if not found.</returns>
        public static String GetServerUrl()
        {
            String serverUrl = String.Empty;

            //Try to get the ServerUrl from the Xrm.Page object
            serverUrl = GetServerUrlFromContext();            

            return serverUrl;
        }

        /// <summary>
        /// Attempts to retrieve the ServerUrl from the Xrm.Page object
        /// </summary>
        /// <returns></returns>
        private static String GetServerUrlFromContext()
        {
            try
            {
                // Silverlight hosted within HTML, this will get the server url
                ScriptObject parent = (ScriptObject)HtmlPage.Window.GetProperty("parent");

                ScriptObject xrm = (ScriptObject)parent.GetProperty("Xrm");
                ScriptObject page = (ScriptObject)xrm.GetProperty("Page");
                ScriptObject pageContext = (ScriptObject)page.GetProperty("context");

                String serverUrl = (String)pageContext.Invoke("getServerUrl");

                //The trailing forward slash character from CRM Online needs to be removed.
                if (serverUrl.EndsWith("/"))
                {
                    serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
                }

                return serverUrl;
            }
            catch
            {
                return String.Empty;
            }
        }
    }

//</snippetServerUtility>

Sunday, 5 April 2015

exception in mscrm

internal static void ThrowException(Exception exception, ITracingService trace, string pluginName)
        {
            exception = exception.InnerException != null ? exception.InnerException : exception;

            trace.Trace("Error message: {0}", exception.Message);
            trace.Trace("Error StackTrace: {0}", exception.StackTrace);
            trace.Trace("Error Source: {0}", exception.Source);
            trace.Trace("Error TargetSite: {0}", exception.TargetSite);
            throw new InvalidPluginExecutionException(string.Format("An error has occured in the {0} plugin. Please download the error trace and contact the system administrator. Message: {1}", pluginName, exception.Message), exception);
        }

exception inmscrm

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

public static Entity GetCurrentEntityForRetrieve(IPluginExecutionContext context, IOrganizationService service, params string[] columns)
        {
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
            {
                return service.Retrieve(((EntityReference)context.InputParameters["Target"]).LogicalName, ((EntityReference)context.InputParameters["Target"]).Id, new ColumnSet(columns));
            }
            else
            {
                throw new Exception("Error: the context input parameter didn't return the target EntityReference");
            }
        }////////////////////
internal static void ThrowException(Exception exception, ITracingService trace, string pluginName)
        {
            exception = exception.InnerException != null ? exception.InnerException : exception;

            trace.Trace("Error message: {0}", exception.Message);
            trace.Trace("Error StackTrace: {0}", exception.StackTrace);
            trace.Trace("Error Source: {0}", exception.Source);
            trace.Trace("Error TargetSite: {0}", exception.TargetSite);
            throw new InvalidPluginExecutionException(string.Format("An error has occured in the {0} plugin. Please download the error trace and contact the system administrator. Message: {1}", pluginName, exception.Message), exception);
        }



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

 public static void CreateErrorLog(string functionalityName, Exception ex, IOrganizationService service, ITracingService tracing, IPluginExecutionContext context)
        {
            tracing.Trace("In CreateErrorLog method.");
            tracing.Trace(ex.Message);

            Entity errorLog = new Entity("hppscm_errorlog");
            Hand.SetValueToContextOrImage(errorLog, "hvvv_name", functionalityName);
            Hand.SetValueToContextOrImage(errorLog, "hvvv_errordatetime", Handler.GetLocalTime(tracing, service, context, DateTime.UtcNow));
            Hand.SetValueToContextOrImage(errorLog, "hvvv_message", ex.Message);
            Hand.SetValueToContextOrImage(errorLog, "hvvv_stacktrace", ex.StackTrace);
            Guid errorLogId = service.Create(errorLog);

            tracing.Trace("Error Log ID: " + errorLogId);
        }

GetValueFromContextOrImage in mscrm

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

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

 DateTime date = demoexample.GetLocalTime(tracing, service, context, demoexample.GetValueFromContextOrImage<DateTime>(ImportedData, "hrrrrrr_date"));
               string Fdate = string.Format("{0}-{1}-{2}", date.Year, date.Month, date.Day);

GetLocalTime in mscrm

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

GetUserTimeZoneCode

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

Friday, 3 April 2015

Trigger workfow using javascripts

function RunWorkflow() {
   
        var url = Xrm.Page.context.getServerUrl();
        var entityId = Xrm.Page.data.entity.getId();
        var workflowId = '82BFCEA3-3C09-4E85-A83C-5081A78CFBF2';
        var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
        url = url + OrgServicePath;
        var request;
        request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                      "<s:Body>" +
                        "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                          "<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">" +
                            "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">" +
                              "<a:KeyValuePairOfstringanyType>" +
                                "<c:key>EntityId</c:key>" +
                                "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + entityId + "</c:value>" +
                              "</a:KeyValuePairOfstringanyType>" +
                              "<a:KeyValuePairOfstringanyType>" +
                                "<c:key>WorkflowId</c:key>" +
                                "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + workflowId + "</c:value>" +
                              "</a:KeyValuePairOfstringanyType>" +
                            "</a:Parameters>" +
                            "<a:RequestId i:nil=\"true\" />" +
                            "<a:RequestName>ExecuteWorkflow</a:RequestName>" +
                          "</request>" +
                        "</Execute>" +
                      "</s:Body>" +
                    "</s:Envelope>";

        var req = new XMLHttpRequest();
        req.open("POST", url, true)
        // Responses will return XML. It isn't possible to return JSON.
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        req.onreadystatechange = function () { assignResponse(req); };
        req.send(request);
    }


function assignResponse(req) {
    debugger;
    if (req.readyState == 4) {
        if (req.status == 200) {
            alert('successfully executed the workflow');
        }
    }
}