Angular Interceptor for Converting UTC date time into Local date time

Angular Interceptor for Converting UTC date time into Local date time

Hi Everyone recently I have a requirement in which we have to convert every date time attributes of  AJAX response into local date time because response date time attributes in UTC but we wanted in local date time.

It is always good to save all our date time information into UTC format on server because using of UTC format we can calculate local date time easily with just knowing user timezone.

E.g. In our database we saved date in UTC format that is 2016-05-29 00:00:00(UTC) but we want to show this according to user timezone like for India timezone user that is 2016-05-29 05:30:00(GMT+5:30).

For achieving this I wrote a angular interceptor that runs on every AJAX request and check every AJAX response that have a valid date time attributes then converted  into local.

Let’s start with creating a new angular factory and use into our app.js config section.

1.Add a new JavaScript namespace that contains important function

//Namespace
var dateUTC = {};
dateUTC.checkNested = function (prop, val1) {
//check for string
if (typeof (val1[prop]) == “string”) {
if (isNaN(val1[prop])) {
if (dateUTC.checkISOdate(val1[prop])) {
val1[prop] = moment(moment.utc(val1[prop]).toDate()).format();
}
}
}
//check for object
if (typeof (val1[prop]) == “object”) {
//start loop for array
for (var prp in val1[prop]) {
if (typeof (val1[prop][prp]) == “string”) {
if (dateUTC.checkISOdate(val1[prop][prp])) {
val1[prop][prp] = moment(moment.utc(val1[prop][prp]).toDate()).format();
}
}
if (typeof (val1[prop][prp]) == “object”) {
//start loop for nested object
for (var pr in val1[prop][prp]) {
if (typeof (val1[prop][prp][pr]) == “string”) {
if (isNaN(val1[prop][prp][pr])) {
if (dateUTC.checkISOdate(val1[prop][prp][pr])) {
val1[prop][prp][pr] = moment(moment.utc(val1[prop][prp][pr]).toDate()).format();
}
}
}
if (typeof (val1[prop][prp][pr]) == “object”) {
for (var p in val1[prop][prp][pr]) {
dateUTC.checkNested(p, val1[prop][prp][pr]);
}
}
}
}
}
}
};
dateUTC.checkISOdate = function (date) {
if (moment(date, “YYYY-MM-DDTHH:mm:ss.SSS”, true).isValid()
|| moment(date, “YYYY-MM-DDTHH:mm:ss.SS”, true).isValid()
|| moment(date, “YYYY-MM-DDTHH:mm:ss.S”, true).isValid()
|| moment(date, “YYYY-MM-DDTHH:mm:ss”, true).isValid()) {
return true;
}
return false;
}

2.Create a new factory that intercept on every AJAX request

Myservice.factory(‘dateinterceptor’, function () {
return {
request: function (config) {
return config;
},

requestError: function (config) {
return config;
},

response: function (res) {
if (typeof (res.data) == “object”) {
if (res.data) {
if (res.data.length) {
angular.forEach(res.data, function (val, key) {
if (typeof (val) == “object”) {
if (val) {
if (val.length) {
angular.forEach(val, function (val1, key1) {
for (var prop in val1) {
dateUTC.checkNested(prop, val1);
}
})
}
else {
for (var prop in val) {
dateUTC.checkNested(prop, val);
}
}
}
}
})
}
else {
for (var prop in res.data) {
dateUTC.checkNested(prop, res.data);
}
}
}
}
return res;
},

responseError: function (res) {
return res;
},

}
});

3.Add our date interceptor factory appModule.config section

appModule.config([‘$httpProvider’, function ( $httpProvider) {
$httpProvider.interceptors.push(‘dateintercepter’);
}]);

Thanks for vising my blog.

Hope it’ll help someone.

 

 

Advertisements
Response type ‘token’ is not enabled for the application

Response type ‘token’ is not enabled for the application


Recently I faced problem when I was trying to build client-side app with CRM and Azure.

I was able to login to my APP and adal.js successfully acquired a token for my webApi and injected it into a request.

Then token acquisition for webApi stopped working with error:

“response_type ‘token’ is not enabled for the application”

Here is the steps that resolved my problem.

Note: If we’re building client-side app, so we need to enable Implicit flow from the application manifest.

How?

1. Select the Configure tab of your application’s entry in the Azure Management Portal.

2. Using the Manage Manifest button in the drawer, download the manifest file for the application and save it to your computer.

2

3. Open the manifest file with a text editor. Search for the oauth2AllowImplicitFlow property. By default it is set to false; change it to true and save the file.

3

4.Using the Manage Manifest button, upload the updated manifest file.

4

Logout and Login with again with you app and it’ll work like a charm.

For more info about OAuth Flow please refer below links

Looking at the Different OAuth2 Flows Supported in AzureAD for Office 365 APIs

v2.0 Protocols – SPAs using the implicit flow

An Introduction to OAuth 2

Hope it’ll help someone.

Thanks for visiting my blog.

Update FetchXml and Grid layout of Entity View using C# in CRM

Update FetchXml and Grid layout of Entity View using C# in CRM

In this post, I am going to tell you how we can update Entity view programmatically using c#.

Before starting let’s cover entity view and their query types.

What is Entity View ?

Entity views are special SavedQuery that retrieve data by using a specific filter. They also contain information about how the data in the view should be displayed in the application.

An Entity view is different from a UserQuery. A user query, called a Saved view in the application, is owned by an individual user, can be assigned and shared with other users, and can be viewed by other users depending on the query’s access privileges.

Let’s create a new view in account entity i.e. My Custom Accounts

1

4

Here is default Grid Layout and FetchXml of this view

2

5.PNG

Now we write some code for getting fetchXml and layoutXml for this view.

 

QueryExpression qe = new QueryExpression(“savedquery“);
qe.Criteria.AddCondition(“returnedtypecode”, ConditionOperator.Equal, “account“);
qe.Criteria.AddCondition(“name”, ConditionOperator.Equal, “My Custom Accounts“);
qe.ColumnSet = new ColumnSet(true);
var viewData= _service.RetrieveMultiple(qe);

 

For our demo purpose we’re trying to add Account Number in FetchXml.

You can also add filter or some complex query which we want to add but can’t add using Advanced find.

 

//Update fetchxml of view
XmlDocument xml1 = new XmlDocument();
xml1.LoadXml(viewData.Entities[0][“fetchxml”].ToString());
XmlNode entityNode= xml1.SelectSingleNode(“//entity”);
var newAttrnode= xml1.CreateElement(“attribute”);
var nameAttribute = xml1.CreateAttribute(“name”);
nameAttribute.Value = “accountnumber”;
newAttrnode.Attributes.Append(nameAttribute);
entityNode.AppendChild(newAttrnode);
dar.Entities[0][“fetchxml”] = xml1.OuterXml;

 

Using below code ,we’re trying to add accountnumber column in our view grid.

 

//Update Gridxml of view
XmlDocument gridxml = new XmlDocument();
gridxml.LoadXml(viewData.Entities[0][“layoutxml”].ToString());
XmlNode rowNode = gridxml.SelectSingleNode(“//row”);
var newrowAttrnode = gridxml.CreateElement(“cell”);
var accountname = gridxml.CreateAttribute(“name”);
accountname.Value = “accountnumber”;
newrowAttrnode.Attributes.Append(accountname);
var width = gridxml.CreateAttribute(“width”);
width.Value = “150”;
newrowAttrnode.Attributes.Append(width);
rowNode.AppendChild(newrowAttrnode);
dar.Entities[0][“layoutxml”] = gridxml.OuterXml;
_service.Update(dar.Entities[0]);

 

//Publish Account Entity
PublishXmlRequest puxml = new PublishXmlRequest()
{
ParameterXml = “<importexportxml><entities><entity>account</entity></entities></importexportxml>”
};
_service.Execute(puxml);

 

That’s it, our custom view successfully updated with Account Number Column. 🙂

7

6

Thanks for visiting my blog.

Do some creative stuff in CRM  !!!  🙂

 

 

 

 

QueryExpression with a paging cookie

QueryExpression with a paging cookie

Query expressions are used in methods that retrieve more than one record, such as the IOrganizationService.RetrieveMultiple method, in messages that perform an operation on a result set specified by a query expression, such as BulkDeleteRequest and when the ID for a specific record is not known.

You can use the paging cookie feature to make paging in an application faster for large datasets. The feature is available in both FetchXML and QueryExpression queries. When you use the paging cookie feature when querying a set of records, the result contains a value for the paging cookie. To improve system performance, you can then pass that value when you retrieve the next set of records.

QueryExpression and FetchXML use different formats for their paging cookies. If you convert from one query format to the other by using theQueryExpressionToFetchXmlRequest message or the FetchXmlToQueryExpressionRequest message, the paging cookie value is ignored. In addition, if you request nonconsecutive pages, the paging cookie value is ignored.

 // Query using the paging cookie.
 // Define the paging attributes.
 // The number of records per page to retrieve.
 int queryCount = 3;
 
 // Initialize the page number.
 int pageNumber = 1;
 
 // Initialize the number of records.
 int recordCount = 0;
 
 // Define the condition expression for retrieving records.
 ConditionExpression pagecondition = new ConditionExpression();
 pagecondition.AttributeName = "parentaccountid";
 pagecondition.Operator = ConditionOperator.Equal;
 pagecondition.Values.Add(_parentAccountId);

 // Define the order expression to retrieve the records.
 OrderExpression order = new OrderExpression();
 order.AttributeName = "name";
 order.OrderType = OrderType.Ascending;

 // Create the query expression and add condition.
 QueryExpression pagequery = new QueryExpression();
 pagequery.EntityName = "account";
 pagequery.Criteria.AddCondition(pagecondition);
 pagequery.Orders.Add(order);
 pagequery.ColumnSet.AddColumns("name", "emailaddress1"); 

 // Assign the pageinfo properties to the query expression.
 pagequery.PageInfo = new PagingInfo();
 pagequery.PageInfo.Count = queryCount;
 pagequery.PageInfo.PageNumber = pageNumber;

 // The current paging cookie. When retrieving the first page, 
 // pagingCookie should be null.
 pagequery.PageInfo.PagingCookie = null;
 Console.WriteLine("Retrieving sample account records in pages...\n");
 Console.WriteLine("#\tAccount Name\t\tEmail Address"); 
 
 while (true)
 {
 // Retrieve the page.
 EntityCollection results = _serviceProxy.RetrieveMultiple(pagequery);
 if (results.Entities != null)
 {
 // Retrieve all records from the result set.
 foreach (Account acct in results.Entities)
 {
 Console.WriteLine("{0}.\t{1}\t{2}", ++recordCount, acct.Name,
 acct.EMailAddress1);
 }
 }

 // Check for more records, if it returns true.
 if (results.MoreRecords)
 {
 Console.WriteLine("\n****************\nPage number {0}\n****************", pagequery.PageInfo.PageNumber);
 Console.WriteLine("#\tAccount Name\t\tEmail Address");

 // Increment the page number to retrieve the next page.
 pagequery.PageInfo.PageNumber++;
 
 // Set the paging cookie to the paging cookie returned from current results.
 pagequery.PageInfo.PagingCookie = results.PagingCookie;
 }
 else
 {
 // If no more records are in the result nodes, exit the loop.
 break;
 }
 }
Create log in Plug-in using Custom Entity

Create log in Plug-in using Custom Entity

Sometime we want to know what is going on in our plugin code. When the plugin code is very large then we need to write the code for every step which is executed successfully or not.

For Debugging a Plugin we can –

  • Use ITracingService
  • Attach Plugin Registration Tool with VS and debug it.

For more info please refer the below links.

To review more options for external logging, you can also go through the below link.

Author by Salim Adamon

Error Logging Options in CRM

https://community.dynamics.com/crm/b/salimadamondynamicscrm/archive/2013/08/14/error-logging-options-in-crm

In this Blog, we’ll talk about creating log in plug-in using custom entity.

Let’s create an entity i.e. am_log in our CRM.

1

and create attributes which are required for this entity like

am_status ,  am_errordescription.

2

As we all know that creating a record in CRM is very easy but If you are writing logs in a failing transaction of Plugin, then the entire transaction will be rolled back including creation of logging records.

To avoid this roll back of logging records we can use ExecuteMultipleRequest.

For more info about ExecuteMultipleRequest refer to below link

https://msdn.microsoft.com/en-in/library/jj863631.aspx

In this process first we create a plugin, here named as LoggingUsingCustomEntity.

First we need to Create object for ExcuteMultipleRequest and assign settings that define execution behavior  i.e.

ContinueOnError =false,

ReturnResponse=true

ex

exmultiple

Lets say before creating a new account we need to count all Accounts(or any other business requirement) that already present in CRM that create success log in our Log Entity.

success

Now we write invalid expression for creating new account that generate error log in our Log entity.error

According above code log records will create two times,  one for getting all accounts successfully and other for error that is Account doesn’t contain “Name” attribute.

Let’s we deployed this plugin code on Account Create Message and see what will be generates in Log entity.

last.PNG

It created successfully what we expected 🙂

It won’t be created and also roll backed if we use normal create request here.

here is the link of  Plugin complete code.

http://1drv.ms/1MZBBzi

 

Thanks for visiting my blog.

Do some creative stuff in CRM  !!!  🙂

 

 

 

MS CRM dynamics with Firebase(using c#)

MS CRM dynamics with Firebase(using c#)

In my previous blog I wrote about how we can use firebase with CRM Dynamics in client side.
Here is the link MS CRM dynamics with Firebase (Using JS)

Today I am going to explain, how we can use Firebase with Plugin or Custom workflow in CRM using C#.

Let’s create a class library and add a class FirebaseWithCRM.cs

For communicate from CRM plugin to Firebase, we use FireSharp. It is a .net library for Firebase Rest Api.

c1

Next we add CRM core assemblies in our Class library project.

c2

We register this plugin on pre-operation event of Account Entity and on create Message ,so whenever new Account is create it ‘ll modify/add Account data in Firebase.

c3

Add new file as FirebaseHelper.cs that contain Push function

c4

c5

But our code is depends on some other DLL like Firesharp, Newtonsoft.Json , System.Net.Http , Microsoft.Threading.Task etc.

So Need to Merge all Dll’s into single one.

c6

What is ILMerge ?

ILMerge is a utility for merging multiple .NET assemblies into a single .NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output.

For info refer this link

http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx

 

For Merging Dll’s there is a Nuget Package MSBuild.ILMerge.Task so using this package we can merge all DLL’s.

You can also refer this article for more understanding about DLL’s Merge by Nicolas Niwonski.

 

c7

 

c8

After Merging we can deployed this DLL using Plugin Registration tool on pre-operation event for Account Entity and on Create Message.

You can also register on Post-operation event by this we get Guid of account entity and store it in Firebase.

c11.PNG

That’s it Now we can test. 🙂

c9

C10

Now when we create New account it created in Firebase under Accounts Node.

For more synchronous and asynchronous function for Firesharp, please refer below link

https://github.com/ziyasal/FireSharp/wiki/v1-Docs

 

 

Thanks for visiting my blog.

Do some creative stuff in CRM  !!!  🙂