Wednesday 19 June 2019

Get the attachments from CRM 4.0 Onpremise Using Console

Today I have tried with getting all the attachments present inside CRM system through console application. So below is the code I used :

Before run this code create a folder where you want to keep the attachments files, An ex : D:\\attachments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.IO;
using System.Web.Services.Protocols;

namespace ConsoleApplication1
{
    class Program
    {
        // private Guid _annotationId;
        //   private String _fileName;

        static void Main(string[] args)
        {

            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.AuthenticationType = 0;
            token.OrganizationName = "OrgName";
            CrmService service = new CrmService();
            service.Url = "http://<servername:port>/MSCRMServices/2007/CrmService.asmx";
            service.CrmAuthenticationTokenValue = token;
            service.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Console.WriteLine("Connected to CRM......");
            Console.ReadLine();
            try
            {
                BusinessEntityCollection notes = new BusinessEntityCollection();
                //ICrmService service = context.CreateCrmService(true);
             //   if (context.MessageName == _DELETE)
            //    {
              //      entity = context.PreEntityImages["AnnotationDeleteImage"] as DynamicEntity;
           //     }
               // Lookup objLookup = new Lookup();
             //   objLookup = entity.Properties["objectid"] as Lookup;
             //   EntityNameReference enr = new EntityNameReference();
              //  enr = entity.Properties["objecttypecode"] as EntityNameReference;
                ColumnSet cols = new ColumnSet();
                cols.Attributes.Add("isdocument");
                cols.Attributes.Add("filename");
                cols.Attributes.Add("documentbody");
             //   ConditionExpression caseCondition = new ConditionExpression();
                //caseCondition.AttributeName = "objectid";
                //caseCondition.Operator = ConditionOperator.Equal;
                //caseCondition.Values = new object[] { objLookup.Value };
                // Build a search filter based on the above conditions.
                //FilterExpression filter = new FilterExpression();
                //filter.FilterOperator = LogicalOperator.And;
                //filter.Conditions.Add(caseCondition);
                QueryExpression query = new QueryExpression();
                query.EntityName = EntityName.annotation.ToString();
                query.ColumnSet = cols;
               // query.Criteria = filter;
                // Create the Web service request object.
                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
                retrieve.Query = query;
                RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);
                notes = retrieved.BusinessEntityCollection;
                bool HasAttachment = false;
                if (notes.BusinessEntities.Count > 0)
                {
                    foreach (annotation item in notes.BusinessEntities)
                    {
                        if (item.isdocument.Value)
                        {
                            HasAttachment = true;
                            // Download the attachment in the current execution folder.
                            using (FileStream fileStream = new FileStream("D:\\attachments\\" + item.filename, FileMode.Append))
                            {
                                byte[] fileContent = Convert.FromBase64String(item.documentbody);
                                fileStream.Write(fileContent, 0, fileContent.Length);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

      //  public static string _AnnotationAttachmentPath { get; set; }
    }
}


Note : The above code will work only where the crm has been installed means for Active directory users.So this one worked for my local crm need to check for dev crm currently am getting issue with 
The request failed with HTTP status 401: Unauthorized. Need to check for this to make it work.

Hope the above one will help someone...Enjoyyy

An error occurred when the workflow was being created. Try to save the workflow again in CRM 4.0

Suddenly got experienced with the below error while publishing workflow in crm onpremise 4.0 version :


After searching on it I got few lines need to add in web.config file in crm server & other solution is try to check with tracing by enabling it using Crm Dialog Tool, get the trace logs & analyse the logs using Crm trace log viewer in server itself where the crm has been installed.Please follow the below link:
https://danielcventer.wordpress.com/mscrm-4-0/troubleshooting-crm-4-0/running-crm-4-0-trace-diagnostic-tool/

The below lines I have added in web.config file, but before adding this take backup first :

<authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.Activities.Rules" TypeName="RuleSetReference" Authorized="True" />
     <authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.Activities.Rules" TypeName="RuleConditionReference" Authorized="True" />
     <authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.Activities.Rules" TypeName="RuleDefinitions" Authorized="True" />
     <authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.Activities.Rules" TypeName="RuleSet" Authorized="True" />
     <authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.Activities.Rules" TypeName="Rule" Authorized="True" />
     <authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.Activities.Rules" TypeName="RuleStatementAction" Authorized="True" />
     <authorizedType Assembly="System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.Activities.Rules" TypeName="RuleExpressionCondition" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeAssignStatement" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeExpressionStatement" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodePrimitiveExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeMethodInvokeExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodePropertyReferenceExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeThisReferenceExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeFieldReferenceExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeMethodReferenceExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeBinaryOperatorExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeTypeReferenceExpression" Authorized="True" />
     <authorizedType Assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Namespace="System.CodeDom" TypeName="CodeCastExpression" Authorized="True" />

     <authorizedType Assembly="System.Workflow.ComponentModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Workflow.ComponentModel.Serialization" TypeName="TypeExtension" Authorized="True" />

And finally, it get worked. Hope this will help someone.
Happy CRMing...!


                                                                                 








Tuesday 5 February 2019

“Invalid Action. The selected action was not valid” in Microsoft Dynamics CRM4.0

Suddenly got with error “Invalid Action. The selected action was not valid” while I was trying to login to Test crm.



So what I did just checked with the Microsoft CRM Asynchronous Processing Service through Run->Services.msc & it was stopped some how.So I started this servcie, then it got worked.

Tuesday 27 February 2018

Display CRM Records & perform CRUD Operations Using Web Template in Portal CRM

Today I am going to share, how we can display crm records in portal crm.
Here i am using Kendo Grid, we can use any client side script grid over here.

Below methods I have tried :
1. Create a Web Template with following code: But before that Download KendoJs.js file & KendoCss.css file, keep in web files & Create Entity List with Odata Feed as enabled & give ur Entity Type Name,Entity Set Name & view So that you can use for odataUri in template.

<!DOCTYPE html>
<html>
<head>
    <title></title>
   <script src="/KendoJs.js"></script>
   <link rel="stylesheet" href="/KendoCss.css" />
</head>
<body>
<div id="tableDiv">
    <div id="grid"></div>
    <script>
    </script>
</div>
<script>
$(document).ready(function() {
    var odataUri = "https://kitiportal38.microsoftcrmportals.com/_odata/Cricos";
    var list;
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        datatype: 'json',
        url: odataUri,
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader('Accept', 'application/json');
        },
        async: false,
        success: function(data, textStatus, xhr) {
            // Getting the company (Account) name that he belongs to
            var myData = data.value;     
         
       alert(myData);
        debugger;
            $("#grid").kendoGrid({
                dataSource: {
                    type: "json",
                    data:myData                 
                },
                height: 550,
                selectable: "multiple, row",
                groupable: true,
                sortable: true,
                pageable: {
                    refresh: true,
                    pageSizes: true,
                    buttonCount: 2
                },
                columns: [{               
                    field: "ags_name",
                    title: "Name",
                    width: 240,
                   template: "<a href='/CricosRedirectPage/?id=#= ags_cricosid #'>#= ags_name #</a>"
                }, {
                    field: "ags_fullname",
                    title: "FullName",
                    //template: "<a href='/CricosRedirectPage/?id=#= ags_fullname #'>#= ags_fullname #</a>"
                }, {
                    field: "ags_address",
                    title: "Address"
                }, {
                    field: "ags_dob",
                    title: "DOB"
                },  {
                    field: "createdon",
                    title: "Created On"
                },
                {
                command: ["edit", "destroy"], title: "&nbsp;", width: "250px"
               }
                ],
                editable: {
            update: true,
            destroy: true,
            confirmation: false,
            mode: "inline"
        },
            });
     
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(textStatus + ' ' + errorThrown);
        }
    });
});
</script>
</body>
</html>

2. Create Page Template & take here your web template file,then create web page along with Page template.












3. Create a Entity Form for edit & delete purpose & create another Web Page for redirect to different page for update & delete records & here what Partial Url we are giving it should be mention in your above Web Template.

























4. So Final Grid will be something like this in below :











I hope it will help to someone !!

Tuesday 13 February 2018

Display Power BI Reports in Dynamics CRM Online Dashboards

Hello All Today I am going to tell how we can display database table records in CRM Dashboard using Power BI Desktop.

1. Install Power BI Desktop for designing the reports & Sign Up with your CRM Credentials.

2. Get the data from Sql DB & design the reports in Power BI Desktop then Publish it .



3. Now configure the Power BI on CRM.



4. Create New Dashboard in CRM & add a Power BI tile to the dashboard.



5. Below reports added in CRM Dashboard , if you want to do any modification, then we can do by open in Power BI.







Hope it will helps!!

Friday 19 January 2018

Clone Opportunity Record Using Action in CRM Online 365

I came up with a task of cloning opportunity records on click of a button in Opportunity Form.
Below procedures I have followed :
1. Added button in Opportunity form using Ribbon Workbench.
2.Create an action in CRM with input parameter & output parameter like below:
2. Below Scripts, I kept on the button :

function executeCustomActionSynchronous(entityId, entityCollectionName, actionName, parameters, isGlobalAction) {
    debugger;
    var query = "";
    var req = "";
    var response = {};
    stringParameterCheck(actionName, "XrmUtilities.webAPI.executeCustomActionSynchronous requires the actionName parameter is a string.");
    if (!isNullOrUndefined(isGlobalAction) && isGlobalAction !== true) {
        entityId = entityId.replace("{", "").replace("}", "");
        stringParameterCheck(entityId, "XrmUtilities.webAPI.executeCustomAction requires the e entityId parameter is a string.");
        stringParameterCheck(entityCollectionName, "XrmUtilities.webAPI.executeCustomAction requires the entityCollectionName parameter is a string.");
        query = entityCollectionName + "(" + entityId + ")/Microsoft.Dynamics.CRM." + actionName;
    }
    else {
        query = actionName;
    }
    req = new XMLHttpRequest();
    req.open("POST", getWebAPIPath() + query, false);
    setRequestHeaders(req, false);
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            switch (this.status) {
                case 200:
                    response.status = true;
                    response.results = JSON.parse(this.response);
                    break;
                case 204:
                    response.status = true;
                    break;
                case 1223:
                    response.status = true;
                    break;
                default:
                    response.status = false;
                    response.error = JSON.parse(this.response).error;
            }
        }
    };
    req.send((!isNullOrUndefined(parameters)) ? JSON.stringify(parameters) : null);
    return response;
};
function isNullOrUndefined(value) {
    return (typeof (value) === "undefined" || value === null);
};
function getWebAPIPath() {
    return getClientUrl() + "/api/data/v8.1/";
};
function getClientUrl() {
    var clientUrl = context().getClientUrl();
    return clientUrl;
};
function context() {
    ///<summary>
    /// Private function to the context object.
    ///</summary>
    ///<returns>Context</returns>
    var oContext = null;
    if (!isNullOrUndefined(window.parent.Xrm)) {
        oContext = window.parent.Xrm.Page.context;
    }
    else if (!isNullOrUndefined(window.GetGlobalContext)) {
        oContext = window.GetGlobalContext();
    }
    else if (!isNullOrUndefined(Xrm)) {
        oContext = Xrm.Page.context;
    }
    else {
        throw new Error("Context is not available.");
    }
    return oContext;
};
function stringParameterCheck(parameter, message) {
    if (typeof parameter !== "string") {
        throw new Error(message);
    }
};
function setRequestHeaders(req, includeFormattedValues, customHeaders) {
    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");
    if (!(!isNullOrUndefined(includeFormattedValues) && includeFormattedValues === false)) {
        req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
    }
    var arrayName = [];
    if (!(customHeaders && customHeaders.constructor === arrayName.constructor)) {
        customHeaders = [];
    }
    customHeaders.forEach(function (h) {
        switch (h.key) {
            case "Accept":
            case "Content-Type":
            case "OData-MaxVersion":
            case "OData-Version":
            case "Prefer":
                break;
            default:
                req.setRequestHeader(h.key, h.value);
        }
    });
};
function copyOpportunityRecord() {
    debugger;
    var opportunityId = Xrm.Page.data.entity.getId();
    var parameters =
    {
        ActionType: opportunityId.toString()
    };
    var Result = executeCustomActionSynchronous(opportunityId, "opportunities", "ags_CopyOpportunityAction", parameters, false)
    var id = Result.results.OppId;
    var options = { openInNewWindow: true };
    Xrm.Utility.openEntityForm("opportunity", id,null,options);
}

3. Below plugin code, I wrote 

public void Execute(IServiceProvider serviceProvider)
      {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);
            try
            {
                tracingService.Trace("Checking plugin");
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
                {
                    EntityReference opportunity = (EntityReference)context.InputParameters["Target"];
                    string opportunityId = context.InputParameters["ActionType"].ToString();
                    tracingService.Trace("Check Action Parameter" + opportunityId);
                    Guid id = Guid.Parse(opportunityId);
                    Guid newOpportunityId = CreateOpportunityRecord(service, id);
                    //tracingService.Trace(id);
                    context.OutputParameters["OppId"] = newOpportunityId.ToString();
                    tracingService.Trace("Successfully Created");
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("An Error occurred in plugin.", ex);
            }
        }
          /// <summary>
          /// Create Opportunity Record
          /// </summary>
          /// <param name="service"></param>
          /// <param name="id"></param>
          /// <returns></returns>
        private Guid CreateOpportunityRecord (IOrganizationService service, Guid id)
        {
            Entity oppEntity = service.Retrieve("opportunity", id, new ColumnSet(true));
            oppEntity.Attributes.Remove("opportunityid");
            oppEntity.Attributes.Remove("createdon");
            oppEntity.Attributes.Remove("modifiedon");
            oppEntity.Attributes.Remove("modifiedby");
            Entity opportunity = new Entity("opportunity");
            opportunity.Attributes = oppEntity.Attributes;
            return service.Create(opportunity);
        }
4. Registered the dll file in plugin registration tool & here I took message as my action which i have created on opportunity.

Hope it will helps !!