Sunday, September 30, 2012

The security timestamp is invalid because its creation time ('2012-10-01T03:55:05.847Z') is in the future. Current time is '2012-10-01T03:45:30.851Z' and allowed clock skew is '00:05:00'.

While connecting to the CRM by the Plugin Registration tool from other System(beside the CRM server) on of the client machine suppose.
I got the error and while clicked show details i got the below error.
So this clearly said that there is a time gap in between the MS CRM server and the client machine from where we are connecting using the Plugin tool.
as per my observation, the client time can be in a range of +- 5 mnts respect to the MS CRM Server time.

if it is very less than 5 mnts frm the server time , it will throw the below error and the next if its earlier...
Unhandled Exception: System.ServiceModel.Security.MessageSecurityException: The security timestamp is invalid because its creation time ('2012-10-01T03:55:05.847Z') is in the future. Current time is '2012-10-01T03:45:30.851Z' and allowed clock skew is '00:05:00'.
 
Server stack trace:
   at System.ServiceModel.Security.SecurityTimestamp.ValidateFreshness(TimeSpan timeToLive, TimeSpan allowedClockSkew)
   at System.ServiceModel.Security.SecurityTimestamp.ValidateRangeAndFreshness(TimeSpan timeToLive, TimeSpan allowedClockSkew)
   at System.ServiceModel.Security.ReceiveSecurityHeader.ReadTimestamp(XmlDictionaryReader reader)
   at System.ServiceModel.Security.ReceiveSecurityHeader.ExecuteFullPass(XmlDictionaryReader reader)
   at System.ServiceModel.Security.ReceiveSecurityHeader.Process(TimeSpan timeout, ChannelBinding channelBinding, ExtendedProtectionPolicy extendedProtectionPolicy)
   at System.ServiceModel.Security.MessageSecurityProtocol.ProcessSecurityHeader(ReceiveSecurityHeader securityHeader, Message& message, SecurityToken requiredSigningToken, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
   at System.ServiceModel.Security.SymmetricSecurityProtocol.VerifyIncomingMessageCore(Message& message, String actor, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
   at System.ServiceModel.Security.MessageSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
 
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Xrm.Sdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
   at Microsoft.Xrm.Sdk.Client.DiscoveryServiceProxy.Execute(DiscoveryRequest request)
   at PluginRegistrationTool.CrmConnection.RetrieveOrganizations() in C:\Users\Administrator\Desktop\MSCRM2011_SDK\tools\pluginregistration\CrmConnection.cs:line 315
   at PluginRegistrationTool.ConnectionsForm.OpenConnection(CrmConnection con) in C:\Users\Administrator\Desktop\MSCRM2011_SDK\tools\pluginregistration\ConnectionsForm.cs:line 940

also the below error if the client machine from where you are connecting using the PLugin tool is ahead of time that the crm server you will get the below error...

Unhandled Exception: System.ServiceModel.Security.MessageSecurityException: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
 
Server stack trace:
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
 
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Xrm.Sdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
   at Microsoft.Xrm.Sdk.Client.DiscoveryServiceProxy.Execute(DiscoveryRequest request)
   at PluginRegistrationTool.CrmConnection.RetrieveOrganizations() in C:\Users\Administrator\Desktop\MSCRM2011_SDK\tools\pluginregistration\CrmConnection.cs:line 315
   at PluginRegistrationTool.ConnectionsForm.OpenConnection(CrmConnection con) in C:\Users\Administrator\Desktop\MSCRM2011_SDK\tools\pluginregistration\ConnectionsForm.cs:line 940
Inner Exception: System.ServiceModel.FaultException: An error occurred when verifying security for the message.

Hope this will help someone to find it...
 
Regards,
yes.sudhanshu

Thursday, September 27, 2012

How to get the OptionSet attributes and values from SM CRM 2011 , by SQL query

the below is the query to get OptionSets and the Values from the whole organization of MS CRM 2011 DB.


SELECT DISTINCT sm.attributeName, e.name, SM.Value AS Option_Value
FROM   StringMap AS SM INNER JOIN
       MetadataSchema.Entity AS E ON E.ObjectTypeCode = SM.ObjectTypeCode
--and e.name like 'new_%' – can use this if you want only the Custom Attributes
order by 1,2,3

result will be like as follows...


accessmode     SystemUser     Administrative
accessmode     SystemUser     Non-interactive
accessmode     SystemUser     Read
accessmode     SystemUser     Read-Write
accessmode     SystemUser     Support User
accountcategorycode  Account          Preferred Customer
accountcategorycode  Account          Standard

 
Regards,
yes.sudhanshu

Refesh Grid in Out Look , MS CRM 2011

If you have integrated Outllok with MS CRM 2011. then how to refesh the grids inside outlook?

inside MS CRM 2011, if its main grid or association grid, or subgrid, we will get a refresh button in the top right corner on the grid as in the below figures....
Main Grid


Association Grid
Sub Grid in form

then how to do in the outlook?
there is no direct refersh button as in MS CRM browser screens as in the Main Grid is fitted inside the Outlook main body...
so the refresh button some where in the extreme right in the View tab as below figure...
Outlook

its not vey difficult but can take time to find it ... :P
regards,
yes.sudhanshu

Sunday, September 23, 2012

the caller was not authenticated by the service MS crm 2011 C#

while writing a batch job by using the MS CRM 2011 SDK, i got the below exception
"the caller was not authenticated by the service".

but the same was working in my VPC, but while deployed in my Dev Server, i got the exception.
what i was missing the the domain name while getting the credential.
after added the domain name , it has resolved... (but make sure about the two servers time, if the batch job and CRM servers are different).
initially i was using the below code...

ClientCredentials creds = new ClientCredentials();
                // Credentials
                creds.UserName.UserName = userName;
                creds.UserName.Password = password;
                OrganizationServiceProxy service = new OrganizationServiceProxy(new Uri(orgURL), null, creds, null);
                service.Timeout = new TimeSpan(0, 5, 0);
                //service.EnableProxyTypes();
                return (IOrganizationService)service;

then changed to the below and it works fine... :)

ClientCredentials creds = new ClientCredentials();
                // Credentials
                creds.Windows.ClientCredential = new System.Net.NetworkCredential(userName, password, domain);
                OrganizationServiceProxy service = new OrganizationServiceProxy(new Uri(orgURL), null, creds, null);
                service.Timeout = new TimeSpan(0, 5, 0);
                //service.EnableProxyTypes();
                return (IOrganizationService)service;

Regards,
yes.sudhanshu

Friday, September 21, 2012

Integrate Bing Map in MS CRM 2011

we need to integrate the map to make life easier in now a days...
like we use mobile not to lost ourself anywhere,...
same in ms crm e can use to make productivity and easy to find a location etc...
here is a very well described link
http://blogs.msdn.com/b/crm/archive/2011/05/27/title-integrating-mapping-with-microsoft-dynamics-crm-2011.aspx

but how integrate it in MS CRM, i will just follow step by step here how to integrate.
before that you need to get the Bing key (license key) to use the bing map and from where you are trying to use that, it must be connected to internet...

1. to get the key please follow the link here...
https://www.bingmapsportal.com/application/Index/142233?status=Created
you can use ur live id to log in, if you have else register to get an id

2.Create an HTML file and upload as Webresource
in the file put the below code...

3. now add the weresource in the Account form ...
then create a record by entering the address1_city value.
once it will be loaded, it will render the address properly...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html>
 
   <head>
 
      <title></title>
 
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript">
          var Bingmap = null;
          function GetBingMap() {
              // Initialize the Bingmap
              Bingmap = new Microsoft.Maps.Map(document.getElementById("BingmapDiv"), { credentials: "Use the key you got after registration", mapTypeId: Microsoft.Maps.MapTypeId.road });
          }
          function ClickGeocode(credentials) {
              Bingmap.getCredentials(MakeGeocodeRequest);
          }
          function MakeGeocodeRequest(credentials) {
            //Get City value from MS CRM account,s form
              //var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + window.parent.Xrm.Page.getAttribute("address1_city").getValue() + "?output=json&jsonp=GeocodeCallback&key=" + credentials; //make sure to replace field name if you are using custom field.
              //here i have used the hardcode value for Singapore
              var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + "Singapore" + "?output=json&jsonp=GeocodeCallback&key=" + credentials;
              CallRestService(geocodeRequest);
          }
          function GeocodeCallback(result) {
                   if (result &&
                   result.resourceSets &&
                   result.resourceSets.length > 0 &&
                   result.resourceSets[0].resources &&
                   result.resourceSets[0].resources.length > 0) {
                  // Set the Bingmap view using the returned bounding box
                  var bbox = result.resourceSets[0].resources[0].bbox;
                  var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
                  Bingmap.setView({ bounds: viewBoundaries });
                  var location = new Microsoft.Maps.Location(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1]);
                  var pushpin = new Microsoft.Maps.Pushpin(location);
                  Bingmap.entities.push(pushpin);
              }
          }
          function CallRestService(request) {
             var script = document.createElement("script");
              script.setAttribute("type", "text/javascript");
              script.setAttribute("src", request);
              document.body.appendChild(script);
          }
      </script>
   </head>
 
   <body onload="GetBingMap();ClickGeocode();">
      <div id="BingmapDiv" style="position:relative; width:400px; height:400px;"></div>
   </body>
</html>

 
more on this also you can render, like take the full address and pass to Bing...
 
Regards,
Sudhanshu

Thursday, September 20, 2012

Microsoft Dynamics CRM 4.0 , 2011 IPv6 Supportability

as we know the world is moving to IPv6 from IPv4.
so the applications and servers should support it.
so how about MS CRM 4.0 and 2011.

here are few links which describes it support and issues and work aorunds to the issues...
http://support.microsoft.com/kb/2700059

error for MS CRM 4.0 (IPv6 for 4.0 does not work alone, but with IPv4 it works.)
http://support.microsoft.com/kb/954313

MS CRM 2011
http://technet.microsoft.com/en-us/library/gg554883.aspx

Sunday, September 16, 2012

How to hide some system/cuctom views MS CRM 2011 and 4.0

sometimes we get requirements/demands from users that they do not want to see the extra view list.
so we can manage the view list to hide the unnecessary views.

in 4.0 this can be done by using pluing code...
1. follow the link below...
http://blogs.c5insight.com/Home/tabid/40/entryid/23/MS-CRM-4-0-How-to-Hide-System-Views.aspx

2. i got the below code from internet but lost the link, thanks to the author..

a. plugin code

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
 
namespace Excitation.PluginHideSystemViews
{
    public class CheckView : IPlugin
    {
        Dictionary<int, StringCollection> _hideViews;
        public CheckView(string Config)                     // Constructor takes Configuration data from registration
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(Config);
                _hideViews = new Dictionary<int, StringCollection>();
                foreach (XmlElement entityNode in doc.SelectNodes("/entities/entity"))
                {
                    StringCollection sc = new StringCollection();
                    foreach (XmlNode viewNode in entityNode.ChildNodes)
                        sc.Add(viewNode.InnerText);
                    string sOTC = entityNode.GetAttribute("otc");
                    if (!String.IsNullOrEmpty(sOTC))
                    {
                        int otc = 0;
                        int.TryParse(sOTC, out otc);
                        if (otc != 0)
                            _hideViews.Add(otc, sc);
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    System.Diagnostics.EventLog.WriteEntry("MSCRMWebService", "Excitation.PluginHideSystemViews.CheckView Constructor: " + ex.Message);
                    _hideViews = new Dictionary<int, StringCollection>();
                }
                catch { }
            }
 
        }
 
        #region IPlugin Members
 
        public void Execute(IPluginExecutionContext context)
        {
            try
            {
                if (!(context.MessageName == MessageName.RetrieveMultiple && context.PrimaryEntityName == EntityName.savedquery.ToString() && context.InputParameters.Contains(ParameterName.Query) && context.OutputParameters.Contains(ParameterName.BusinessEntityCollection)))
                    return;
                QueryExpression qe = context.InputParameters[ParameterName.Query] as QueryExpression;
                if (qe == null)         // Check it's a QueryExpression
                    return;
                ConditionExpression cond = GetCondition(qe.Criteria, "returnedtypecode");
                if (!(cond != null && cond.Operator == ConditionOperator.Equal && cond.Values.Length == 1 && cond.Values[0] is int))       // Check there is an equiality condition on returnedtypecode for an integer value
                    return;
                int otc = (int)cond.Values[0];
                if (!_hideViews.ContainsKey(otc))       // Check that we want to exclude views for this entity
                    return;
                BusinessEntityCollection becViews = (BusinessEntityCollection)context.OutputParameters[ParameterName.BusinessEntityCollection];
                if (!(becViews != null && becViews.EntityName == EntityName.savedquery.ToString()))  // Check there are some views, and they are the right type
                    return;
                StringCollection scHide = _hideViews[otc];
                for (int i = becViews.BusinessEntities.Count - 1; i >= 0; i--)      // Iterate backwards, as items may be removed
                {
                    DynamicEntity de = (DynamicEntity)becViews.BusinessEntities[i]; // BusinessEntityCollection is of type DynamicEntity
                    if (de.Properties.Contains("name") && scHide.Contains((string)de.Properties["name"]))   // Hide this view - i.e. remove it from the collection of returned views
                        becViews.BusinessEntities.RemoveAt(i);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    System.Diagnostics.EventLog.WriteEntry("MSCRMWebService", "Excitation.PluginHideSystemViews.Execute: " + ex.Message);
                }
                catch { }
            }
        }
        private ConditionExpression GetCondition(FilterExpression Filter, string Attribute)
        {
            ConditionExpression ret = null;
            if (Filter != null && Filter.Conditions != null)
                for(int i=0; i<Filter.Conditions.Count;i++)
                {
                    ConditionExpression cond = (ConditionExpression) Filter.Conditions[i];
                    if (cond.AttributeName == Attribute)
                    {
                        ret = cond;
                        break;
                    }
                }
            return ret;
        }
        #endregion
    }
}
b. the unsecured xml

<?xml version="1.0" encoding="utf-8" ?>
<entities>
            <!-- Sample configuration data. Entities are identified by the otc attribute, and views by name-->
            <entity otc="1">
                        <view>Inactive Accounts</view>
                        <view>Accounts: No Orders in Last 6 Months</view>
            </entity>
            <entity otc="4">
                        <view>Leads Opened Last Week</view>
                        <view>Leads Opened This Week</view>
    <Sec_Role>POM Role</Sec_Role>
            </entity>
</entities>
here make sure the entity oct are the object type code for the entities...
c. registed as below...

 

 in MS CRM 2011, we can manage the views by just "Activate" and "deactivate" option as below...
go to settings->entityname->views, then see the below image to find the activate and deactivate options from Action...
 
the above will help to hide the views from all the users all over the business units who ever have acces to the entity.
if we can manage it by security roles...
let us take example, the view from the account should not be visible to other division, as its a custom view for that division.
so we can manage it by Plugin as we did in MS CRM 4.0.
we need to get the security role from the userID of context.
then we can execute our logic...
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
 
namespace Excitation.PluginHideSystemViews
{
    public class CheckView : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                // Obtain the execution context from the service provider.
                Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
                // Obtain the organization service reference.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
 
                // The InputParameters collection contains all the data passed in the message request.
if(CheckRole(context.UserId, "User Role",  service)){
                if (context.InputParameters.Contains("Query") == true && context.InputParameters["Query"] is QueryExpression)
                {
                    QueryExpression qe = (QueryExpression)context.InputParameters["Query"];
                    if (qe.EntityName == "savedquery")
                    {
                        if (qe.Criteria != null)
                        {
                            if (qe.Criteria.Conditions != null)
                            {
                                /*The query is edited to look at views not starting with "My" at the begining of the View Name*/
                                ConditionExpression queryCondition = new ConditionExpression("name", ConditionOperator.NotLike, "My%");
                                qe.Criteria.Conditions.Add(queryCondition);
                                //context.InputParameters.Properties[ParameterName.Query] = qe;
                                context.InputParameters["Query"] = qe;
                            }
                        }
                    }
 
                }
              }
            }
            catch (Exception e)
            {
            }
        }
 
//check if the user belongs to the specified role....
        private static bool CheckRole(Guid UserGuid, string SecurityRole, IOrganizationService CrmService)
        {
            #region Retrieve records from an intersect table via QueryExpression
 
 
            //Create Query Expression to fetch Role Entity
            QueryExpression Query = new QueryExpression()
            {
                //Setting the link entity condition and filter condition criteria/
                LinkEntities = 
                        {                            
                            new LinkEntity
                            {
                                LinkFromEntityName = "role",
                                LinkFromAttributeName = "roleid",
                                LinkToEntityName = "systemuserroles",
                                LinkToAttributeName = "roleid",
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions = 
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "systemuserid",
                                            Operator = ConditionOperator.Equal,
                                            Values = { UserGuid }
                                        }
                                    }
                                }
                            }
                        }
            };
            Query.EntityName = "role";
 
            Query.ColumnSet = new ColumnSet(true);
 
 
            // Obtain results from the query expression.
            EntityCollection UserRoles = CrmService.RetrieveMultiple(Query);
 
 
            // Searching for a specified Security Role into the list
            Entity UserSecurityRole = UserRoles.Entities.ToList<Entity>().Find(delegate(Entity RoleEntity)
            {
                return (string)RoleEntity.Attributes["name"] == SecurityRole;
            });
 
            if (UserSecurityRole == null)
            {
                //return false as the role does not present
                return false;
            }
            else
            {
                return true;
            }
 
 
            #endregion
 
        }
    }
}
 
register it as follows...
 
Regards,
yes.sudhanshu