Thursday, 31 March 2022

Java Script to add XRM web API on Form load

 function RetieveContact(executionContext)

{

 var formContext = executionContext.getFormContext();

        var recordId = formContext.data.entity.getId();

    Xrm.WebApi.retrieveMultipleRecords("contact", "?$select=firstname,lastname&$filter=_parentcustomerid_value eq '+recordId +'").then(

        function success(result){

            for (var i = 0; i < result.entities.length; i++)

            {

formContext.getAttribute("websiteurl").setValue("http://newvalue.com");

                alert(result.entities[i].firstname);

formContext.data.entity.save("saveandclose");

                break; // just for code demo

// Set value


            }

        },

        function (error)

        {

            alert("Error: " + error.message);

        }

    );

}


 //JavaScript source code


Thursday, 17 March 2022

MS Plugin Linq Query Using late Bound

 using System;JoyTaylor@zevn.onmicrosoft.com

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;


namespace AccountPluginOnPostCreate

{

    public class AccountPlugin : IPlugin

    {

        public void Execute(IServiceProvider serviceProvider)

        {

            // Obtain the tracing service

            ITracingService tracingService =

            (ITracingService)serviceProvider.GetService(typeof(ITracingService));


            // Obtain the execution context from the service provider.  

            IPluginExecutionContext context = (IPluginExecutionContext)

                serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.  

            if (context.InputParameters.Contains("Target") &&

                context.InputParameters["Target"] is Entity && context.MessageName.ToLower() == "update")

            {

                // Obtain the target entity from the input parameters.  

                Entity entity = (Entity)context.InputParameters["Target"];


                // Obtain the organization service reference which you will need for  

                // web service calls.  

                IOrganizationServiceFactory serviceFactory =

                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                OrganizationServiceContext orgContext = new OrganizationServiceContext(service);

                try

                {

                    var Contact = from a in orgContext.CreateQuery("contact")

                                  where (Guid)a["parentcustomerid"] == (Guid)entity.Id

                                  select a;


                    foreach (var con in Contact)

                    {

                        entity["telephone1"] = (string)con.Attributes["mobilephone"];

                    }


                    // Plug-in business logic goes here.  

                }


                catch (FaultException<OrganizationServiceFault> ex)

                {

                    throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);

                }


                catch (Exception ex)

                {

                    tracingService.Trace("Account Craete Plugin : {0}", ex.ToString());

                    throw;

                }

            }

        }

    }

}


Friday, 21 May 2021

Power App and SharePoint Connection Patch Update Query

 Create Data in SharePoint from Canvass APP 


Patch(
'SharePoint Data', //Data base 
Defaults('SharePoint Data'),
{
Title: TextInput1_1.Text,
'Last Name': TextInput2_1.Text,
Email: TextInput3_1.Text,
'Candidate ID': Value(TextInput4_1.Text),
'Reason for Late Submission': TextInput5_1.Text,
'Detailed Work Description': TextInput6_1.Text,
'Work Request Justification': TextInput7.Text
},


{//for Drop Down 
'Work Description': {
'@odata.type': "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
Id: Dropdown1.SelectedText.ID,
Value: Dropdown1.SelectedText.Title
},
'Project Approver':{
'@odata.type': "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
Id: Dropdown2.Selected.ID,
Value: Dropdown2.Selected.Value
}
}

);


Update 

UpdateIf('SharePoint Data', 'Candidate ID'= Value(TextInput4_2.Text),{
Title:TextInput1_2.Text,
'Last Name':TextInput2_2.Text,
Email:TextInput3_2.Text,
'Candidate ID':Value(TextInput4_2.Text),
'Reason for Late Submission':TextInput5_2.Text,
'Detailed Work Description':TextInput6_2.Text,
'Work Request Justification':TextInput2_2.Text,
'Work Description': {
'@odata.type':"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
Id:Dropdown1_1.SelectedText.ID,
Value:Dropdown1_1.SelectedText.Title}
});
Navigate(Screen2,ScreenTransition.Fade)


Thursday, 15 April 2021

Connect Dynamic CRM 365 using console with Mutli Factor Authentication

Get Client Id and Secret from APP registration in azure portal    

  string connectionString = "AuthType=ClientSecret; url=https://org55ced39c.crm.dynamics.com/;ClientId=ClientID ClientSecret=Secret";


            CrmServiceClient crmServiceClient = new CrmServiceClient(connectionString); //Connecting to the D-365 CE instance


            if (crmServiceClient != null && crmServiceClient.IsReady)


            {

                OrganizationServiceContext orgContext = new OrganizationServiceContext(crmServiceClient);


               var contact = from c in orgContext.CreateQuery("contact")

                             select c;


                Console.ForegroundColor = ConsoleColor.Green;


                Console.WriteLine("\nConnected Successfully!");


Monday, 29 July 2019

Refresh Look up Field

 public void CalculateRollupFieldRequest(EntityReference target, string fieldName)
        {
            if (this.organizationService != null)
            {
                CalculateRollupFieldRequest calculateRollUpFieldRequest = new CalculateRollupFieldRequest
                {
                    Target = target,
                    FieldName = fieldName
                };
                this.organizationService.Execute(calculateRollUpFieldRequest);
            }
        }

/ <summary>
        /// Gets or sets a Input Argument - Opportunity Entity Reference
        /// </summary>
        [RequiredArgument]
        [Input("OpportunityEntityReference")]
        [ReferenceTarget(Opportunity.EntityLogicalName)]
        public InArgument<EntityReference> OpportunityEntityReference { get; set; }
 
        /// <summary>
        /// Gets or sets a Input Argument - Field Name
        /// </summary>
        [RequiredArgument]
        [Input("OpportunityRollUpFieldName")]
        public InArgument<string> OpportunityRollUpFieldName { get; set; }

Monday, 22 July 2019

Move New Stage in Buisness Process Flow Praogramitcally

pdateSalesProcessStage(IOrganizationService service)
        {
            Guid oppId = new Guid("2b685c81-4f1c-e511-80d3-3863bb347ba8");
            Entity opportunity = service.Retrieve("opportunity", oppId, new ColumnSet(true));
            //Entity entity = this.Opportunity;
            //var source = opportunity.GetAttributeValue<OptionSetValue>("lvo_source").Value;
            var source = 100000000;
            string fetch = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='opportunitysalesprocess'>
                                <attribute name='businessprocessflowinstanceid' />
                                <attribute name='name' />
                                <attribute name='createdon' />
                                <attribute name='opportunityid' />
                                <attribute name='activestageid' />
                                <attribute name='statecode' />
                                <attribute name='statuscode' />
                                <attribute name='processid' />
                                <order attribute='opportunityid' descending='false' />
                                <filter type='and'>
                                  <condition attribute='opportunityid' operator='eq' uiname='4' uitype='opportunity' value='{0}' />
                                </filter>
                              </entity>
                            </fetch>";
            fetch = string.Format(fetch, oppId);
            EntityCollection ec = service.RetrieveMultiple(new FetchExpression(fetch));
            QueryExpression qe = new QueryExpression("processstage");
            qe.ColumnSet = new ColumnSet(true);
            qe.Criteria.AddCondition(new ConditionExpression("processid", ConditionOperator.Equal, ec.Entities[0].GetAttributeValue<EntityReference>("processid").Id));
            EntityCollection pc = service.RetrieveMultiple(qe);
            Dictionary<string, Guid> dict = new Dictionary<string, Guid>();
            foreach (var p in pc.Entities)
            {
                dict.Add(p.GetAttributeValue<string>("stagename"), p.GetAttributeValue<Guid>("processstageid"));
            }
            Guid processStageId = RetrieveProcessStageId(dict, source);
            //if (dict.ContainsKey("Qualify"))
            //{
            //    dict.TryGetValue("Qualify",out processStageId);
            //}
            Entity pro = new Entity(ec.Entities[0].LogicalName);
            pro.Id = ec.Entities[0].Id;
            pro.Attributes["activestageid"] = new EntityReference("processstage", processStageId);
            service.Update(pro);
            Console.WriteLine("done");
        }
   
        private static Guid RetrieveProcessStageId(Dictionary<string, Guid> dict, int sourceValue)
        {
            Guid processId = Guid.Empty;
            if (sourceValue == 100000000)
                processId = dict.ContainsKey("Qualify") ? dict["Qualify"] : Guid.Empty;
            else if (sourceValue == 100000002)
                processId = dict.ContainsKey("Qualify") ? dict["Qualify"] : Guid.Empty;
            else if (sourceValue == 100000003)
                processId = dict.ContainsKey("Propose") ? dict["Propose"] : Guid.Empty;
            else if (sourceValue == 100000001)
                processId = dict.ContainsKey("Develop") ? dict["Develop"] : Guid.Empty;
            return processId;
        }
    }
}

Tuesday, 2 July 2019

Read Files from Web Reources , Add to Excel

  WebResourceList = GetAllWebResourceFilesfromSolution(ConfigurationManager.AppSettings["SolutionName"].ToString());
            Dictionary<string, string> keyValueText = null;
            if (WebResourceList != null)
            {
                foreach (string file in WebResourceList.Values)
                {
                    keyValueText = ReadWebResourceContent(file);

                    AddToExcelFile(keyValueText, file);

                }
                ReadFromExcelandTranslate();
                Console.WriteLine("Translation Completed!! Press Any key to exit..!");
                Console.ReadKey();
                Environment.Exit(0);
            }

 public static void AddToExcelFile(Dictionary<string, string> resourcedictionary, string filename)
        {
            try
            {
                bool sheet_avail = false;
                string newfilePath = Environment.CurrentDirectory + @"\Transalation.xlsx";
                Excel.Application xlApp = new Excel.Application();
                Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(newfilePath);
                int sheetCount = xlWorkBook.Worksheets.Count;
                Excel.Sheets sheets = xlWorkBook.Worksheets;
                // Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets;
                Excel.Range xlRange;
                Excel.Worksheet excelWorkSheet;
                int index1 = filename.IndexOf('_') + 1;
                int index2 = filename.IndexOf('.');
                string languagecode = filename.Substring(index2 + 1, 4);

                for (int k = 1; k <= sheetCount; k++)
                {

                    Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(k);
                    string name = worksheet.Name;

                    if (filename.Contains(name))
                    {
                        sheet_avail = true;
                        excelWorkSheet = (Excel.Worksheet)sheets.Item[k];
                        xlRange = excelWorkSheet.UsedRange;
                        int totalColumns = xlRange.Columns.Count;
                        string[] colnames = new string[totalColumns + 1];
                        for (int q = 1; q <= totalColumns; q++)
                            colnames[q] = xlRange.Cells[1, q].Value.ToString();
                        int i = 2, j = 1;
                        if (languagecode == "1033")
                        {
                            foreach (KeyValuePair<string, string> entry in resourcedictionary)
                            {
                                excelWorkSheet.Cells[i, j] = entry.Key;
                                excelWorkSheet.Cells[i, j + 1] = entry.Value;
                                i++;
                            }
                        }
                        else
                        {
                            bool col_avail = false;
                            for (int m = 1; m < colnames.Length; m++)
                            {
                                if (colnames[m] == languagecode)
                                {
                                    col_avail = true;
                                    foreach (KeyValuePair<string, string> entry in resourcedictionary)
                                    {
                                        if (excelWorkSheet.Cells[i, j].Value.ToString() == entry.Key)
                                            excelWorkSheet.Cells[i, m] = entry.Value;
                                        i++;
                                    }
                                    break;
                                }
                            }
                            if (col_avail == false)
                            {
                                excelWorkSheet.Cells[1, totalColumns + 1] = languagecode;
                                foreach (KeyValuePair<string, string> entry in resourcedictionary)
                                {
                                    if (excelWorkSheet.Cells[i, j].Value.ToString() == entry.Key)
                                        excelWorkSheet.Cells[i, totalColumns + 1] = entry.Value;
                                    i++;
                                }
                            }

                        }
                        break;
                    }
                }

                if (sheet_avail == false)
                {
                    var xlNewSheet = (Excel.Worksheet)sheets.Add(Type.Missing, sheets[1], Type.Missing, Type.Missing);
                    //wSheet.Move(Missing.Value, workbook.Sheets[workbook.Sheets.Count]);
                    //var xlNewSheet=xlWorkBook.Worksheets.Add();
                    //xlWorkBook.Sheets.Move(After: xlWorkBook.Sheets.Count);
                    filename.Substring(index1, index2 - index1);
                    xlNewSheet.Name = filename.Substring(index1, index2 - index1);

                    int NewCount = xlWorkBook.Worksheets.Count;
                    excelWorkSheet = (Excel.Worksheet)sheets.Item[NewCount];
                    excelWorkSheet.Cells[1, 1] = "Key";
                    excelWorkSheet.Cells[1, 2] = "1033";
                    int i = 2, j = 1;
                    foreach (KeyValuePair<string, string> entry in resourcedictionary)
                    {
                        excelWorkSheet.Cells[i, j] = entry.Key;
                        excelWorkSheet.Cells[i, j + 1] = entry.Value;
                        i++;
                    }
                }

                xlApp.Visible = false;
                xlApp.UserControl = false;
                xlWorkBook.Save();
                xlWorkBook.Close();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }

 public static void ReadFromExcelandTranslate()
        {
            try
            {
                string excelPath = Environment.CurrentDirectory + @"\Transalation.xlsx";
                Excel.Application xlApp = new Excel.Application();
                Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(excelPath);
                int totalSheets = xlWorkBook.Worksheets.Count;
                for (int sheet = 1; sheet <= totalSheets; sheet++)
                {
                    Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(sheet);
                    Excel.Range xlRange = xlWorkSheet.UsedRange;
                    int totalRows = xlRange.Rows.Count;
                    int totalColumns = xlRange.Columns.Count;
                    string[] languageTobeConverted = null;
                    string combinedLanguages = ConfigurationManager.AppSettings["languagesTranslation"];
                    languageTobeConverted = combinedLanguages.Split(',');
                    List<int> integerList = new List<int>();
                    string[] languageLables = null;
                    languageLables = new string[languageTobeConverted.Count()];
                    //foreach (var langCode in languageTobeConverted)
                    for (int u = 0; u < languageTobeConverted.Count(); u++)
                    {
                        integerList.Add(int.Parse(languageTobeConverted[u]));
                        languageLables[u] = languageTobeConverted[u];
                    }

                    totalColumns = 2 + integerList.Count;

                    for (int colCount = 3; colCount <= totalColumns; colCount++)
                    {
                        int languageID = 0;
                        string colNullValue = (xlRange.Cells[1, colCount] as Excel.Range).Text;

                        if (string.IsNullOrEmpty(colNullValue))
                        {
                            for (int d = 0; d < integerList.Count; d++)
                            {
                                xlWorkSheet.Cells[1, colCount + d] = integerList[d];
                            }
                            languageID = Convert.ToInt32((xlRange.Cells[1, colCount] as Excel.Range).Text);
                        }

                        if (!string.IsNullOrEmpty(colNullValue) && languageID == 0)
                        {
                            languageID = Convert.ToInt32((xlRange.Cells[1, colCount] as Excel.Range).Text);
                        }

                        for (int rowCount = 2; rowCount <= totalRows; rowCount++)
                        {
                            originalText = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);
                            translatedText = Convert.ToString((xlRange.Cells[rowCount, colCount] as Excel.Range).Text);
                            if (translatedText == null || translatedText == "")
                            {
                                List<TranslationHelper> translatedTextList = Translation.TranslateText(originalText, LanguageCodes.languageID[languageID]);
                                xlWorkSheet.Cells[rowCount, colCount] = translatedTextList.Where(x => x.to == LanguageCodes.languageID[languageID]).Select(x => x.text).ToList().FirstOrDefault();
                            }
                        }
                        integerList.Remove(languageID);
                    }
                }
                xlApp.DisplayAlerts = false;
                xlWorkBook.Save();
                xlWorkBook.Close();
                xlApp.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }

        static void ReadFromExcelToImport()
        {
            try
            {
                string excelPath = Environment.CurrentDirectory + @"\Transalation.xlsx";
                //XmlDocument doc = new XmlDocument();           
                //doc.Load(@"..\..\sampleResource.resx");
                //string xmlcontents = doc.InnerXml;
                //XDocument xmlDocument = XDocument.Parse(xmlcontents);           
                Excel.Application xlApp = new Excel.Application();
                Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(excelPath);

             
                int sheetcount = xlWorkBook.Worksheets.Count;
                for (int k = 1; k <= sheetcount; k++)
                {
                    Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(k);
                    Excel.Range xlRange = xlWorkSheet.UsedRange;
                    int totalRows = xlRange.Rows.Count;
                    int totalColumns = xlRange.Columns.Count;
                    for (int c = 1; c < totalColumns; c++)
                    {
                        var xmlDocument = new XDocument();
                        var declartion = new XDeclaration("1.0", "UTF-8", null);
                        xmlDocument.Declaration = declartion;
                        var rootElement = new XElement("root");
                        xmlDocument.Add(rootElement);

                        for (int row = 1; row < totalRows; row++)
                        {
                            var data = new XElement("data");
                            data.SetAttributeValue("name", "test");
                            data.SetAttributeValue(XNamespace.Xml + "space", "preserve");
                            var value = new XElement("value", "test");
                            data.Add(value);
                            rootElement.Add(data);
                        }
                            int i = 2, j = 1;
                        var dataelements = xmlDocument.Descendants("data").ToList();
                        //for (int n = 1; n < totalRows - 8; n++)
                        //{
                        //    dataelements.Add(new XElement("data", new XAttribute("name", "test"), new XAttribute(XNamespace.Xml + "space", "preserve"), new XElement("value", "test")));
                        //}
                   
                        foreach (var dataelement in dataelements)
                        {
                            if (xlRange.Cells[i, j] != null)
                                dataelement.Attribute("name").Value = xlRange.Cells[i, j].Value.ToString();
                            if (xlRange.Cells[i, j + c] != null)
                                dataelement.Element("value").Value = xlRange.Cells[i, j + c].Value.ToString();
                            i++;
                        }
                     
                        //dataelements=xmlDocument.Descendants("data").ToList();
                        string ws_name = xlWorkSheet.Name;
                        string c_name = xlRange.Cells[1, j + c].Value.ToString();
                        string filename = ws_name + "." + c_name;
                        CreateResourcefile(xmlDocument, filename);

                    }
                }


                xlApp.DisplayAlerts = false;
                xlWorkBook.Close();
                xlApp.Quit();

            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("File not Found");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();

            }

        }

    }
}

Import data using Excel MSCRM programitacally

   public static void ImportToCRMPluginErrorCodes()
        {
            //string filePath = Environment.CurrentDirectory + @"\Active sheetname.xlsx";
            Entity import = new Entity("import");
            import["modecode"] = new OptionSetValue(1);
            import["name"] = "Active sheet Name";
            import["sendnotification"] = false;
            Guid importId = organizationService.Create(import);

            OrganizationServiceContext servicecontext = new OrganizationServiceContext(organizationService);

            var importMap = (from a in servicecontext.CreateQuery("importmap") where a.GetAttributeValue<string>("name") == "DataFinal" select new { a.Id }).FirstOrDefault();

            Entity impmap = new Entity("importmap");
            Guid importMapId = importMap.Id;
            var importEntityMap = (from cl in servicecontext.CreateQuery("columnmapping")
                                   where (Guid)cl["importmapid"] == importMap.Id && cl["sourceentityname"] != null
                                   select cl).FirstOrDefault();

            // Create the ImportFile class
            Entity importFile = new Entity("importfile");
            importFile["content"] = getEncodedFileContents(filePath);
            importFile["name"] = "File Name";
            importFile["filetypecode"] = new OptionSetValue(3);
            importFile["isfirstrowheader"] = true;
            importFile["source"] = "lenovo.xlsx";
            importFile["sourceentityname"] = (string)importEntityMap["sourceentityname"];
            // Schema name of the Target entity
            importFile["targetentityname"] = "lvo_languageresource";
            importFile["importmapid"] = new EntityReference(impmap.LogicalName, importMapId);
            importFile["importid"] = new EntityReference(import.LogicalName, importId);
            //importFile["Size"] = importFile.Content.Length.ToString();
            importFile["size"] = importFile.FormattedValues.Count.ToString();
            importFile["processcode"] = new OptionSetValue(1);
            importFile["datadelimitercode"] = new OptionSetValue(1);
            importFile["fielddelimitercode"] = new OptionSetValue(2);
            importFile["usesystemmap"] = false;
            importFile["enableduplicatedetection"] = true;
            organizationService.Create(importFile);

            ParseImportRequest parseRequest = new ParseImportRequest();
            parseRequest.ImportId = importId;
            organizationService.Execute(parseRequest);

            TransformImportRequest transRequest = new TransformImportRequest();
            transRequest.ImportId = importId;
            TransformImportResponse transResponse = (TransformImportResponse)organizationService.Execute(transRequest);

            ImportRecordsImportRequest request = new ImportRecordsImportRequest();
            request.ImportId = importId;

            ImportRecordsImportResponse response = (ImportRecordsImportResponse)organizationService.Execute(request);
        }

        static public string getEncodedFileContents(String pathToFile)
        {
            FileStream fs = new FileStream(pathToFile, FileMode.Open, FileAccess.Read);
            byte[] binaryData = new byte[fs.Length];
            long bytesRead = fs.Read(binaryData, 0, (int)fs.Length);
            fs.Close();
            return System.Convert.ToBase64String(binaryData, 0, binaryData.Length);
        }

Export using Code Programitically MSCRM

 var exportToExcelRequest = new OrganizationRequest("ExportToExcel");
                exportToExcelRequest.Parameters = new ParameterCollection();
                //Has to be a savedquery aka "System View" or userquery aka "Saved View"
                //The view has to exist, otherwise will error out
                //Guid of the view has to be passed
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("View",
                    new EntityReference("savedquery", new Guid(ConfigurationManager.AppSettings["SavedViewId"]))));
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("FetchXml", @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                          <entity name='entity name'>
                   ' descending='false' />
                            <filter type='and'>
                              <condition attribute='statecode' operator='eq' value='0' />
                            </filter>
                        </entity>
                    </fetch>"));
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("LayoutXml", @"
                    <grid name='resultset' object='2' jump='lvo_name' select='1' icon='1' preview='1'>
                        <row name='result' id='primary key'>
                        </row>
                    </grid>"));
                //need these params to keep org service happy
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("QueryApi", ""));
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("QueryParameters",
                    new InputArgumentCollection()));
                var exportToExcelResponse = organizationService.Execute(exportToExcelRequest);
                if (exportToExcelResponse.Results.Any())
                {
                    File.WriteAllBytes(filePath, exportToExcelResponse.Results["ExcelFile"] as byte[]);
                }

Tuesday, 14 March 2017

MSCRM Plugin using early binding

1) Generate CRM proxy class using CSV UTIL using following config detail

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="url" value="https:///XRMServices/2011/Organization.svc"/>
    <add key="out" value="class.cs"/>
    <add key="namespace" value="MscrmOnlinePlugin"/>
    <add key="serviceContextName" value="XrmServiceContext"/>
    <add key="username" value="username"/>
    <add key="password" value="password "/>
  </appSettings>
</configuration>


2) Adding the generated proxy file in project

3) Create plugins.cs to project inheriting Iplugin interface

public class Plugins : IPlugin
 {
 protected class LocalPluginContext

 {
 internal IServiceProvider ServiceProvider

 {
 get;


private set;

 }
 internal IOrganizationService OrganizationService



 {
 get;


private set;
 }
 internal IPluginExecutionContext PluginExecutionContext

 {
 get;

private set;
 }
 internal ITracingService TracingService


 {
 get;
private set;

 }
 private LocalPluginContext()

 {
 }
 internal LocalPluginContext(IServiceProvider serviceProvider)

 {
 if (serviceProvider == null)

 {
 throw new ArgumentNullException("serviceProvider");

 }
 // Obtain the execution context service from the service provider.

this.PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

// Obtain the tracing service from the service provider.

this.TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

// Obtain the Organization Service factory service from the service provider
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
// Use the factory to generate the Organization Service.

this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);

 }
 internal void Trace(string message)

 {
 if (string.IsNullOrWhiteSpace(message) || this.TracingService == null)

 {
 return;


 }
 if (this.PluginExecutionContext == null)

 {
 this.TracingService.Trace(message);

 }
 else

 {
 this.TracingService.Trace(

"{0}, Correlation Id: {1}, Initiating User: {2}",

 message,
 this.PluginExecutionContext.CorrelationId,

this.PluginExecutionContext.InitiatingUserId);

 }

 }

 }
 private Collection<Tuple<int, string, string, Action<LocalPluginContext>>> registeredEvents;

/// <summary>



/// Gets the List of events that the plug-in should fire for. Each List



/// Item is a <see cref="System.Tuple"/> containing the Pipeline Stage, Message and (optionally) the Primary Entity.



/// In addition, the fourth parameter provide the delegate to invoke on a matching registration.



/// </summary>



protected Collection<Tuple<int, string, string, Action<LocalPluginContext>>> RegisteredEvents

 {
 get


 {
 if (this.registeredEvents == null)

 {
 this.registeredEvents = new Collection<Tuple<int, string, string, Action<LocalPluginContext>>>();
 }
 return this.registeredEvents;

 }

 }
 /// <summary>

/// Gets or sets the name of the child class.



/// </summary>



/// <value>The name of the child class.</value>

protected string ChildClassName




 {
 get;


private set;

 }
 /// <summary>


/// Initializes a new instance of the <see cref="Plugin"/> class.

/// </summary>

/// <param name="childClassName">The <see cref=" cred="Type"/> of the derived class.</param>

internal Plugin(Type childClassName)

 {
 this.ChildClassName = childClassName.ToString();



 }
 /// <summary>



/// Executes the plug-in.



/// </summary>



/// <param name="serviceProvider">The service provider.</param>



/// <remarks>



/// For improved performance, Microsoft Dynamics CRM caches plug-in instances.



/// The plug-in's Execute method should be written to be stateless as the constructor



/// is not called for every invocation of the plug-in. Also, multiple system threads



/// could execute the plug-in at the same time. All per invocation state information



/// is stored in the context. This means that you should not use global variables in plug-ins.



/// </remarks>



public void Execute(IServiceProvider serviceProvider)


 {
 if (serviceProvider == null)

 {
 throw new ArgumentNullException("serviceProvider");
 }
 // Construct the Local plug-in context.


LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);

localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));


try

 {
 // Iterate over all of the expected registered events to ensure that the plugin


// has been invoked by an expected event

// For any given plug-in event at an instance in time, we would expect at most 1 result to match.
Action<LocalPluginContext> entityAction =
 (from a in this.RegisteredEvents


where (

 a.Item1 == localcontext.PluginExecutionContext.Stage &&

 a.Item2 == localcontext.PluginExecutionContext.MessageName &&
 (string.IsNullOrWhiteSpace(a.Item3) ? true : a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
 )
 select a.Item4).FirstOrDefault();

if (entityAction != null)

 {
 localcontext.Trace(string.Format(


CultureInfo.InvariantCulture,


"{0} is firing for Entity: {1}, Message: {2}",


this.ChildClassName,


localcontext.PluginExecutionContext.PrimaryEntityName,

localcontext.PluginExecutionContext.MessageName));

entityAction.Invoke(localcontext);
 // now exit - if the derived plug-in has incorrectly registered overlapping event registrations,



// guard against multiple executions.



return;

 }

 }
 catch (FaultException<OrganizationServiceFault> e)


 {
 localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));


// Handle the exception.

throw;


 }
 finally


 {
 localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));



 }

 }

 }
4) Create pluginsbase  abstract  class


public abstract class PluginsBase : IPlugin



 {
 public IPluginExecutionContext Context;


public IOrganizationServiceFactory Factory;


// public CrmOrganizationServiceContext CrmOrgService;



public XrmServiceContext ServiceContext;


public IOrganizationService _service;


protected abstract void OnExecute();


public void Execute(IServiceProvider serviceProvider)

 {
 // Obtain the execution context from the service provider.



 Context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));


//If ILMerged used for plug in , we can remove the below line of code



//InitiliazeEntityType(();

// Get a reference to the organization service.



 Factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));


// _service = (IOrganizationService)serviceProvider.GetService(typeof(IOrganizationService));



//CrmOrgService = new CrmOrganizationServiceContext(Factory.CreateOrganizationService(Context.UserId));



ServiceContext = new XrmServiceContext(Factory.CreateOrganizationService(Context.UserId));


OnExecute();

 }
 public PluginBase()


 {

 }

 }

 5)Add Account Update and create plugin code

public class AccountUpdate : PluginBase

 {
 protected override void OnExecute()



 {

 {
 Entity entity = (Entity)Context.InputParameters["Target"];

 if (entity.LogicalName != "account" )
return;
try
 {
 if (Context.MessageName.ToLower() == "create")
 {
 Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");

 Account acc = entity.ToEntity<Account>();
  ServiceContext.ClearChanges();
 acc.WebSiteURL = "google@gmail.com";
 acc.ParentAccountId = new EntityReference(Account.EntityLogicalName, parentAcc); ;
 acc.Address1_AddressTypeCode = new OptionSetValue(1);

 }
 if (Context.MessageName.ToLower() == "update")

 {

 Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");
 Account account = new Account();

 account.Id = entity.Id;

 account.LogicalName = entity.LogicalName;
 account["websiteurl"] = "google.com";
 account["parentaccountid"] = new EntityReference("account", parentAcc);
 account["address1_addresstypecode"] = new OptionSetValue(2);

ServiceContext.ClearChanges();

ServiceContext.Attach(account);

ServiceContext.UpdateObject(account);

ServiceContext.SaveChanges();

 }


 }
 catch (FaultException<OrganizationServiceFault> ex)

 {

 }
 catch (Exception ex)





 {


 throw;

 }

 }

 }





Friday, 10 March 2017

Accessing WCF Web API

Create WCF with the following web invoke method:

1) In interface add web invoke
  [WebInvoke(Method = "GET", UriTemplate = "/Lead/{LeadId}",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle= WebMessageBodyStyle.Wrapped)]
        CompositeType GetLeadData(string LeadId);

2)Add in service
 [AspNetCompatibilityRequirements(RequirementsMode  = AspNetCompatibilityRequirementsMode.Allowed)]

Add following detail in web config for webHttpBinding
    <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information,
          set the values below to false before deployment -->
          <serviceMetadata  httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <!-- To receive exception details in faults for debugging purposes,
          set the value below to true.  Set to false before deployment
          to avoid disclosing exception information -->
          <!--<serviceDebug includeExceptionDetailInFaults="True"/>-->
        </behavior>
      </serviceBehaviors>
 <endpoint address="" binding="webHttpBinding"  contract=".IService1" behaviorConfiguration="EndpBehavior">

   <endpointBehaviors>
        <behavior name="basichttp">
          <clientVia />
        </behavior>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>

3) Access from console application
string url = "http://service/" + "488C7C54-0EFF-E611-80E4-005056A93809";
            WebRequest req = WebRequest.Create(@url);
            req.Method = "GET";
            req.ContentType = @"application/json; charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            string jsonResponse = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResponse = sr.ReadToEnd();
                Console.WriteLine(jsonResponse);
            }

Tuesday, 7 March 2017

Generating Early Bound and MS CRM Proxy for MSCRM Online

1) First please Generate MSCRM proxy file by using below CRMSVCUTIL.EXE

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="url" value="https://.crm8.dynamics.com/XRMServices/2011/Organization.svc"/>
    <add key="out" value="TestAppXrmProxy.cs"/>
    <add key="namespace" value="TestMsApp"/>
    <add key="serviceContextName" value="XrmServiceContext"/>
    <add key="username" value="username"/>
    <add key="password" value="password"/>
  </appSettings>
</configuration>

2) Add helper class
#region Assembly Needed
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk;
#endregion

namespace TestMsApp
{
    public static class ServiceHelper
    {
        private static IOrganizationService _service = null;
        private static OrganizationServiceProxy _serviceProxy = null;
        private static XrmServiceContext _ServiceContext = null;
        //Check error to be logged in CRM
        static bool isErrorLogged = false;

        /// <summary>
        /// InitializeCRMService
        /// </summary>
        /// <returns></returns>
        private static IOrganizationService InitializeCRMService()
        {
            try
            {
                string url = "https://r/XRMServices/2011/Organization.svc";
                ClientCredentials Credentials = new ClientCredentials();
                //Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
                //Not using default credentials since we need WCF Service for IFD deployment
                Credentials.UserName.UserName = "user name";
                Credentials.UserName.Password = "password";
                Uri organizationUri = new Uri(url);
                _serviceProxy = new OrganizationServiceProxy(organizationUri, null, Credentials, null);
                _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                _serviceProxy.EnableProxyTypes();
                _service = (IOrganizationService)_serviceProxy;
            }
            catch (Exception ex)
            {
           
                    throw ex;
            }
            return _service;
        }

        /// <summary>
        /// GetXRMCRMServiceContext
        /// </summary>
        /// <returns></returns>
        public static XrmServiceContext GetXRMCRMServiceContext()
        {
            try
            {
                _service = InitializeCRMService();

                _ServiceContext = new XrmServiceContext(_service);
               
            }
            catch (Exception ex)
            {
               
                    throw ex;
            }
            return _ServiceContext;
        }
    }
}

3) Define proxy Object
   private static XrmServiceContext serviceContext;
   serviceContext = ServiceHelper.GetXRMCRMServiceContext();

Enjoy MSCRMING !


Monday, 6 March 2017

Web Api GET data using Java script MSCRM

// JavaScript source code


function WhoAmIRequest() {

    var qry = "accounts?$filter=startswith(name,'A') or startswith(name,'C')";
    var clientUrl = Xrm.Page.context.getClientUrl();

    var req = new XMLHttpRequest()

    req.open("GET", encodeURI(clientUrl + "/api/data/v8.0/" + qry  ), true);

    req.setRequestHeader("Accept", "application/json");

    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

    req.setRequestHeader("OData-MaxVersion", "4.0");

    req.setRequestHeader("OData-Version", "4.0");

    req.onreadystatechange = function () {

        if (this.readyState == 4 /* complete */) {

            req.onreadystatechange = null;

            if (this.status == 200) {

                var data = JSON.parse(this.response);
               
                for(var i = 0; i < data.value.length ; i++ )
                {
                    alert("Acc Num Id : "+ data.value[i].accountnumber);
                }
                }

            else {

                var error = JSON.parse(this.response).error;

                alert(error.message);

            }

        }

    };

    req.send();

}

sample plugin code MSCRM create and update

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.Crm.Sdk.Messages;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;

using System.ServiceModel.Description;

using Microsoft.Xrm.Sdk.Query;

using System.ServiceModel;

namespace MscrmOnlinePlugin



{

public class AccountUpdate : IPlugin



{

public void Execute(IServiceProvider serviceProvider)



{

// Extract the tracing service for use in debugging sandboxed plug-ins.

// If you are not registering the plug-in in the sandbox, then you do

// not have to add any tracing service related code.

ITracingService tracingService =

(ITracingService)serviceProvider.GetService(typeof(ITracingService));

// Obtain the execution context from the service provider.

IPluginExecutionContext context = (IPluginExecutionContext)

serviceProvider.GetService(typeof(IPluginExecutionContext));

// The InputParameters collection contains all the data passed in the message request.

if (context.InputParameters.Contains("Target") &&

context.InputParameters["Target"] is Entity)



{

// Obtain the target entity from the input parameters.

Entity entity = (Entity)context.InputParameters["Target"];

Entity entPost = (Entity)context.PostEntityImages["postImage"];

// Verify that the target entity represents an entity type you are expecting.

// For example, an account. If not, the plug-in was not registered correctly.

if (entity.LogicalName != "account" )

return;

// Obtain the organization service reference which you will need for

// web service calls.

IOrganizationServiceFactory serviceFactory =

(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

try



{

if (context.MessageName.ToLower() == "create")



{

Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");

entity["websiteurl"] = "google@gmail.com";

entity["parentaccountid"] = new EntityReference("account", parentAcc);

entity["address1_addresstypecode"] = new OptionSetValue(1);

// service.Update(entity);



}

if (context.MessageName.ToLower() == "update")



{

Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");

Entity account = new Entity();



account.Id = entity.Id;

account.LogicalName = entity.LogicalName;

account["websiteurl"] = "google@gmail.com";

account["parentaccountid"] = new EntityReference("account", parentAcc);

account["address1_addresstypecode"] = new OptionSetValue(1);



service.Update(account);

 

}

if (context.MessageName.ToLower() == "update")



{

if (entPost.Attributes.Contains("address1_addresstypecode"))



{

if (((OptionSetValue)entPost.Attributes["address1_addresstypecode"]).Value == 1)



{

Entity account = new Entity();



account.Id = entPost.Id;

account.LogicalName = entPost.LogicalName;

account["address1_addresstypecode"] = new OptionSetValue(2);



service.Update(account);

}

}

}

}

catch (FaultException<OrganizationServiceFault> ex)



{

throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);



}

catch (Exception ex)



{

tracingService.Trace("MyPlugin: {0}", ex.ToString());

throw;



}

}

}

}

}