Wednesday 25 June 2014

How to Create Log File in MSCRM using c#

Sometimes you might have the requirement to create log file while writing code either in Plugin or Custom Workflow or in web service etc to trace and keep the generated error.There might be a other option as well to keep it but here i am going to show Error Log in Text file.

In this blog I have described how to create log file in C#. Log file can be simple text fileXML document or we can also use tables in database to create log. Here I have used.txt file. In this file we have stored information about generated exception of application. Using this log file we have easily find out error list. In this file we have stored information according our requirement. For example in log file we have stored file nameexception namedate and timeerror line numberevent name, Controls name etc.

Now let’s to implementation

using System;
using System.IO;
using context = System.Web.HttpContext;

namespace LogText
{
    public class Logger
    {

        public Logger(string ErrorCode, string ErrorMsg)
        {
            try
            {

                string path = context.Current.Server.MapPath("~/ErrorLogging/");
                // check if directory exists
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = path + DateTime.Today.ToString("dd-MMM-yy") + ".log";
                // check if file exist
                if (!File.Exists(path))
                {
                    File.Create(path).Dispose();
                }
                // log the error now
                using (StreamWriter writer = File.AppendText(path))
                {
                    string error = "\r\nLog written at        : " + DateTime.Now.ToString() +
                    "\r\n\r\nError occured on page : " + context.Current.Request.Url.ToString() +
                    "\r\n\r\nError Code            : " + ErrorCode +
                    "\r\n\r\nError Message         : " + ErrorMsg;
                    writer.WriteLine(error);
                    writer.WriteLine("=======================================");
                    writer.Flush();
                    writer.Close();
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}


Where i would see the Error Log Text file ?

A folder will be created inside your Project/Solution named 'ErrorLogging'. All error log test file will be created inside this Folder with named as 'Log Creation Date.log' for example- '04-Jul-13.log'.
















Error Log File will look like as below:





Monday 23 June 2014

XML Parser to get List of All Elements, Attribute Name & Attribute Value

Function to Get Element List of XML :

 public List<string> getElements(string xmlfile)
        {

            List<string> ElementList = new List<string>();

            XmlReader reader = XmlReader.Create(new StringReader(xmlfile));
            while (reader.Read())
            {
                if (reader.NodeType.Equals(XmlNodeType.Element))
                {
                    ElementList.Add(reader.Name);
                }

            }
            return ElementList;
        }

Function to Get List of Attribute Name XML :

 public List<String> getAttributeName(string xmlfile)
        {
            List<string> AttributeNameList = new List<string>();

            XmlReader reader = XmlReader.Create(new StringReader(xmlfile));
            while (reader.Read())
            {
                if (reader.NodeType.Equals(XmlNodeType.Element))
                {

                    if (reader.HasAttributes)
                    {
                        for (int attInd = 0; attInd < reader.AttributeCount; attInd++)
                        {
                            reader.MoveToAttribute(attInd);

                            AttributeNameList.Add(reader.Name);
                        }
                    }
                }

            }
            return AttributeNameList;
        }


Function to Get List of Attribute Value XML :

 public List<String> getAttributeValue(string xmlfile)
        {
            List<string> AttributeValueList = new List<string>();

            XmlReader reader = XmlReader.Create(new StringReader(xmlfile));
            while (reader.Read())
            {
                if (reader.NodeType.Equals(XmlNodeType.Element))
                {

                    if (reader.HasAttributes)
                    {
                        for (int attInd = 0; attInd < reader.AttributeCount; attInd++)
                        {
                            reader.MoveToAttribute(attInd);
                            AttributeValueList.Add(reader.Value);
                        }
                    }
                }

            }
            return AttributeValueList;

        }













Wednesday 4 June 2014

Entity Logical Name and Entity Schema Name in MSCRM 2011

When we create an Entity, What is the difference between Entity Schema Name and Entity Logical Name ?



When we are creating an entity, at that time, the Name we give is its schema name. When we save this entity the schema name also becomes the logical name. So entities have two names; logical name and schema name. The values are same but with one difference, the casing.
For example, if I create an entity with the Name “new_TestField”. Here “new_” is the customization prefix set to maintain uniqueness in naming of components. When I save this entity, the name new_TestField will be set as schema name and “new_testfield” will be set as logical name.



As we see, the entity schema name = entity logical name. The difference is schema name retains the casing but logical name will always be lowercase. In other words we can say logical name is lower case conversion of the schema name. The same goes for attributes and relationships for an entity.

Where do we use the schema Name and when do we use the 

Logical Name of an Entity ?


  • In CRM 2011 Early bound programming model, we always use schema names.We also use schema names in “Rest/o Data” programming. 
  • Logical names are used in CRM 2011 Late bound programming model. In CRM 2011 JavaScript web resources, we use logical names.


So in this blog we saw that schema names and logical names are same except the casing but they have different usage. In plugins and custom workflow activities, if we use early bound programming model, then we have to use schema names. In plugins and custom workflow activities, if we use late bound programming model, then we have to use logical names.
I hope this blog about ‘Microsoft Dynamics CRM 2011 – Entity Logical Name and Entity Schema Name’ was informative. 

Please feel free to leave your comments.

Association and DeAssociation of Records in MSCRM

Recently, I got one requirement to Associate a Contact Record with Three Account Records.

Below is the code to Associate a Record with Multiple Records


// Associate the accounts to the contact record.

// Create a collection of the entities that will be 
// associated to the contact.

EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account1Id));
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account2Id));
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account3Id));

// Create an object that defines the relationship between the contact and account.
Relationship relationship = new Relationship("account_primary_contact");

//Associate the contact with the 3 accounts.

_service.Associate(Contact.EntityLogicalName, _contactId, relationship,
    relatedEntities);

Console.WriteLine("The entities have been associated.");

//Disassociate the records.
_service.Disassociate(Contact.EntityLogicalName, _contactId, relationship,
    relatedEntities);

Difference between Asynchronous Plugin and Workflows in MSCRM

So many times I have been asked a question from my colleagues, 
What is the difference between Async Plugin and Workflow, Since both are Asynchronous But What is the actual difference between them and When should i use Workflow and When should I use Async Plugin ?

Answer :
My Answer is always "Depends", the right approach is determined by the Characteristics of the task that you are trying to accomplish.


 Following Matrix show the difference between the same :



          Requirement

Use Plug-in

Use Workflow

Needs a synchronous action to happen before or after an event occurs
Or
Need to perform a task that has to completed within 2 Sec




Yes


              No

 The logic needs to be executed while offline

Yes

No
Needs elevation of privileges (impersonation)
Or
Perform data operations on behalf of another system user



Yes


No
Needs to execute on events other than assign, create, update, set state

Yes

No
The process/logic may take a long time to complete or will be a persistent process (multiple long running steps)

No

Yes

End users will need to modify the process logic

            No

Yes
                                         Child sub processes will be triggered

No

Yes


Blogger Widgets