Tuesday, 9 July 2013

Automating CRM 2011 Solution Backup - Programmatically (Import , Create, Retrieve Solution)



Recently i was working in CRM 2011 customizations, after completion of the customization , i have Exported the solution for my backup purpose. This i planned to automate daily. So i have created one Asp.net program to Automate this backup process.


The following sample shows how to export the solution from CRM online and save it in specified location.


Step 1 : Create a “Console Application” in Visual studio under Visual C# templates.
Step 2 : Give the Project and Solution Name, Make sure that .Net Framework must be 4.
Step 3 : Click “Ok”.

 


 



Step 4: Add the following References to the project from sdk\bin folder
             CRM References – Microsoft.Crm.Sdk.Proxy , Microsoft.Xrm.Sdk
             .Net References – System.ServiceModel, System.Runtime.Serialization,System.Security




Step 5 : Right Click the “ExportCRMonlineSolution” project and click “Add Existing Item”.
              Select “deviceidmanager.cs” from the sdk folder. (sdk\samplecode\cs\helpercode)



Your “Solution Explorer” should look like this.






Step 6 :  Add the following Namespace to the project.

using System.ServiceModel;
using System.IO;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Services.Utility;

 
Step 7 : Now Add the below code in the Main

       string userName = "<CRM online username>";
       string passWord = "<CRM online password>";
       string SolName = "<solution which is available in online CRM>";

       ClientCredentials credentials = new ClientCredentials();
       credentials.UserName.UserName = userName;
       credentials.UserName.Password = passWord;

       credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
       Uri organizationUri = new Uri("<crm online organization service url>");
       Uri homeRealmUri = null;
          
    # region Getting Current datetime information -- This is not mandatory we can skip
  
       string fileDate = DateTime.Now.Date.ToShortDateString();
       string formatedDate = fileDate.Replace("/", "-");
       string fileTime = DateTime.Now.ToShortTimeString().Replace(" ", "-");
       string formatedTime = fileTime.ToString().Replace(":", "-");
       string finalformat = formatedDate+"_"+formatedTime;

     #endregion
       
       using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, GetDeviceCredentials()))
            {
                 String outputDir = @"C:\temp\";

                 ExportSolutionRequest expsolreq = new ExportSolutionRequest();
                 expsolreq.Managed = false;
                 expsolreq.SolutionName = SolName;

                 ExportSolutionResponse expsolres = (ExportSolutionResponse)serviceProxy.Execute(expsolreq);

                 byte[] exportXml = expsolres.ExportSolutionFile;
                 string filename = SolName + "_" + finalformat + ".zip";
                 File.WriteAllBytes(outputDir + filename, exportXml);
              
                 Console.WriteLine("Solution Exported to {0}", outputDir + filename);

            }    

 
Step 8 :   Add the below method outside of the Main – This is to get the deviceid credentials for the particular running machine. This is required for CRM online.



        private static ClientCredentials GetDeviceCredentials()
        {
            return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
       


Step : 9 Your complete project looks likes the below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.IO;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Services.Utility;


namespace ExportSolution
{
    public class Program
    {              
    
        static public void Main(string[] args)
        {

     string userName = "<CRM online username>";
            string passWord = "<CRM online password>";
            string SolName = "<solution which is available in online CRM>";

            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = userName;
            credentials.UserName.Password = passWord;

            credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            Uri organizationUri = new Uri("<crm online organization service url>");
            Uri homeRealmUri = null;

            # region Getting Current datetime information -- This is not mandatory we can skip

            string fileDate = DateTime.Now.Date.ToShortDateString();
            string formatedDate = fileDate.Replace("/", "-");
            string fileTime = DateTime.Now.ToShortTimeString().Replace(" ", "-");
            string formatedTime = fileTime.ToString().Replace(":", "-");
            string finalformat = formatedDate+"_"+formatedTime;

            #endregion
           
                 using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, GetDeviceCredentials()))
                 {
                     String outputDir = @"C:\temp\";

                     ExportSolutionRequest expsolreq = new ExportSolutionRequest();
                     expsolreq.Managed = false;
                     expsolreq.SolutionName = SolName;

                     ExportSolutionResponse expsolres = (ExportSolutionResponse)serviceProxy.Execute(expsolreq);

                     byte[] exportXml = expsolres.ExportSolutionFile;
                     string filename = SolName + "_" + finalformat + ".zip";
                     File.WriteAllBytes(outputDir + filename, exportXml);
               
                     Console.WriteLine("Solution Exported to {0}", outputDir + filename);

                 }          
                
        }
        private static ClientCredentials GetDeviceCredentials()
        {
            return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
        }             
       
    }   
  
}



Step 10 : Now Build the solution, also check that Framework should be in 4.

Step 11 : Press F5 to run the program. Solution zip file must be saved in the mentioned output directory.


Also we can do

  • Create a publisher.
  • Retrieve the default publisher.
  • Create a solution.
  • Retrieve a solution.
  • Add an existing solution component.
  • Remove a solution component.
  • Install or upgrade a solution.
  • Delete a solution.
To do this points please go through this complete post.

Try this out and Post your comments......     Thanks.........!!!!!!!!!!!!!






Friday, 5 July 2013

Windows Azure Integration with Microsoft Dynamics CRM 2011 - Overview


Windows Azure

Windows Azure is Microsoft's cloud application platform. Windows Azure can be used to build a web application that runs and stores its data in Microsoft datacenters. It can connect on-premises applications with each other or map between different sets of identity information.
The Windows Azure Platform provides an API built on REST, HTTP, and XML that allows a developer to interact with the services provided by Windows Azure. Microsoft also provides a client-side managed class library which encapsulates the functions of interacting with the services. It also integrates with Microsoft Visual Studio, Git, and Eclipse.
Windows Azure uses a specialized operating system, called Windows Azure, to run its "fabric layer" — a cluster hosted at Microsoft's datacenters that manages computing and storage resources of the computers and provisions the resources (or a subset of them) to applications running on top of Windows Azure. Windows Azure has been described as a "cloud layer" on top of a number of Windows Server systems, which use Windows Server 2008 and a customized version of Hyper-V, known as the Windows Azure Hypervisor to provide virtualization of services. Scaling and reliability are controlled by the Windows Azure Fabric Controller so the services and environment do not crash if one of the servers crashes within the Microsoft datacenter and provides the management of the user's web application like memory resources and load balancing.
Windows Azure Services
  • Web sites
  • Virtual machines
  • Cloud services
  • Data management
  • Business Analytics
  • Identity 
  • Messaging
  • Media Services
  • Mobile Services
 Get More Information about Windows Azure Here



Windows Azure Integration with Microsoft Dynamics CRM

Microsoft Dynamics CRM 2011 has been integrated with the Windows Azure platform by coupling the Microsoft Dynamics CRM event execution pipeline to the Windows Azure Service Bus in the cloud. In essence, the Microsoft Dynamics CRM pipeline connects to the Windows Azure Service Bus enabling the data that has been processed as part of the current Microsoft Dynamics CRM operation to be posted to the bus. Windows Azure Service Bus solutions that are “CRM aware” can listen for and read the data that is posted on the service bus by Microsoft Dynamics CRM. The posted data is stored in a RemoteExecutionContext class instance that is an extended version of IExecutionContext passed at run time to Microsoft Dynamics CRM asynchronous plug-ins.
This integration between Microsoft Dynamics CRM 2011 and the Windows Azure platform provides a secure channel for communicating Microsoft Dynamics CRM run-time data to external cloud based line of business applications. This capability is especially useful in keeping disparate CRM systems or other database servers synchronized with Microsoft Dynamics CRM Online business data changes.
 
Key Elements of the Integration:
·         Asynchronous Service
·         Plug-ins
·         Custom Workflow Activities
·         Windows Azure Service Bus
·         Windows Azure Solution

Get More Information about Windows Azure Integration With Microsoft Dynamics CRM 2011 Here

Thursday, 4 July 2013

MS CRM 2011 Integration With SilverLight 4


I was going through some blogs and found some basic integration about MSCRM 2011 with Silverlight 4.
Just thought to replace CRM standard contact page with Silverlight page. Here s the look.



So Now i m showing the demo of Creating contact form in SilverLight and hosting the same in CRM Contact form.
Open Visual Studio (Right click-> Run as Administrator)
1) Select -> File->New->Project
2) Choose “Silverlight” from the left side Visual C# “Templates” and choose “Silverlight Application”. (Make sure that you have installed Silverlight 4 prior to this sample).
Else you will receive the download message, Please click the link and install the required.








3) Make Sure you have selected “.Net Framework 4”.
4) Give Solution name as “SampleCRMSilverlight_Integration” and click “Ok”.


















5) Then you will see one dialog box with the project name and Silverlight version details. Click Ok.



















Some time you may receive some error “Object reference not set to an instance” after clicking “Ok”. For that I have given solution at the end of this post.
Once opened , you can find this design page. Else, In solution Explorer, Select “MainPage.xaml” Right click and choose “View designer”.



















Before adding controls to the page, i am going to add background image.
To do that, Right click the designer and click properties. Move your cursor to “Background” property as mentioned in the below screenshot.
1)      Click  - > Select Image - > Add-> select any image from your local desktop-> Ok.Now you can see this designer with your background image/color.












2)      Now add controls to the page.
My requirement is to fill “Firstname” and “Lastname” and click save in silver light page. So that it will create a record in CRM Contact.
I am gonna show only two controls. You can add the controls as per your need.
You can find the Tool Box from the left side and drag two label , two text box and one button to the designer. Refer below screenshot. (Give the Textbox and Label name as per you need).












3)      Add one more label after “save” button to show the confirmation message after successful save. In Label 3 properties, remove the “Content” value.
Now our design part is over. So you can Build the solution and make sure there is no errors.


 
Adding XRM script to update/retrieve value from CRM.
1)      Right click the “SampleCRMSilverlight_Integration” project and click “Add Reference”.
2)      Check for .Net Reference and select “Microsoft.CSharp”.
3)      Click “Ok” and add to your project. Add this namespace using System.Windows.Browser in MainPage.xaml.cs             
4)      Doube click the “Save” button and write the below code.

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            dynamic xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
            xrm.Page.data.entity.attributes.get("firstname").setValue(textBox1.Text);
            xrm.Page.data.entity.attributes.get("lastname").setValue(textBox2.Text);
            xrm.Page.data.entity.save();

            label3.Content = "Record Saved";

        }

5)      Next add the below script in public Mainpage(). (After Initialize Component)

          dynamic xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");

          if (xrm.Page.data.entity.attributes.get("firstname").getValue() != null)
          {
            textBox1.Text = xrm.Page.data.entity.attributes.get("firstname").getValue();
          textBox2.Text = xrm.Page.data.entity.attributes.get("lastname").getValue();
          }

6)      So you are almost done with Silver light part. Only action left is to Rebuild the Complete solution.
7)      So your final code look like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
namespace SampleCRMSilverlight_Integration
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            dynamic xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");

            if (xrm.Page.data.entity.attributes.get("firstname").getValue() != null)
            {
                textBox1.Text = xrm.Page.data.entity.attributes.get("firstname").getValue();              
                textBox2.Text = xrm.Page.data.entity.attributes.get("lastname").getValue();
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            dynamic xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
            xrm.Page.data.entity.attributes.get("firstname").setValue(textBox1.Text);
            xrm.Page.data.entity.attributes.get("lastname").setValue(textBox2.Text);
            xrm.Page.data.entity.save();

            label3.Content = "Record Saved";
        }
    }
}


8)      Once you see the Succeed Build, Go to CRM -> Settings->Customization->Customize the system
9)      Then Click “New”->Web Resource.
10)  Give the Web Resource name as “silverLightContact”, Type - > SilverLight(XAP), Language->English.
11)  Click “Browse” from Upload File, route to “ur solution folder/ SampleCRMSilverlight_Integration.Web/ClientBin/ SampleCRMSilverlight_Integration.xap.
12)  Save and Publish the Webresource
13)  Next, Go back to Contact Form Customization- Choose “General” Tab and insert “Webresource”.

14)  Browse the “Webresource” lookup and select the “silverLightContact” Webresource which was created at last step.















15)      Save and publish the contact form.

For testing, you can open any already created contact and see the values automatically flowing to the Silverlight page from CRM page.












For testing purpose, i m keeping the CRM fields visible. You can hide that field and start creating new contact records.
Also you can add some more fields to the Silverlight page and host again.
This is my final screen.

This is the Error message you may receive while creating new project.

Details:
System.NullReferenceException Object reference not set to an instance of an object. at Microsoft.Windows.Design.Platform.SilverlightMetadataContext.SilverlightXamlExtensionImplementations.d__8.MoveNext() at MS.Internal.Design.Metadata.ReflectionProjectNode.BuildSubsumption()
at MS.Internal.Design.Metadata.ReflectionProjectNode.SubsumingNamespace(Identifier identifier) at MS.Internal.Design.Markup.XmlElement.BuildScope(PrefixScope parentScope, IParseContext context) at MS.Internal.Design.Markup.XmlElement.ConvertToXaml(XamlElement parent, PrefixScope parentScope, IParseContext context, IMarkupSourceProvider provider) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.FullParse(Boolean convertToXamlWithErrors) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.get_RootItem() at Microsoft.Windows.Design.DocumentModel.Trees.ModifiableDocumentTree.get_ModifiableRootItem() at Microsoft.Windows.Design.DocumentModel.MarkupDocumentManagerBase.get_LoadState() at MS.Internal.Host.PersistenceSubsystem.Load() at MS.Internal.Host.Designer.Load() at MS.Internal.Designer.VSDesigner.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.Load() at MS.Internal.Designer.DesignerPane.LoadDesignerView()


This is because of silver light 5. Please uninstall and install silver light 4 for silver sdk 4 http://www.microsoft.com/download/en/details.aspx?id=18149

Try this and post your comments.....

Thanks ...............................................................

 
 

Microsoft Dynamics CRM 2013 makes business personal

 

Microsoft Corp. today announced that it plans to make the next version of Microsoft Dynamics CRM available in the fall of 2013. Designed to redefine how businesses engage with their customers, the new version represents the approach Microsoft Dynamics is taking to developing and delivering business solutions that put people at the center.

Available both online as Microsoft Dynamics CRM Online Fall '13 and on-premises as Microsoft Dynamics CRM 2013, this major release will deliver more personal experiences to sales, marketing and customer care professionals. The new release gives people the ability to access their information on a variety of devices;* introduces a new user experience that is fast and fluid, enabling people to access information that is relevant to their jobs; and delivers richer contextual information that helps people have deeper insights into customers and their needs. Microsoft Dynamics CRM also offers enhanced social collaboration capabilities, so users can connect with the right people, and the right resources, at the right time.

“Customers don’t want to be sold to anymore. They are knowledgeable and are interacting with their social and professional networks to make their buying decisions. They expect businesses to help them make the most informed choice,” said Bob Stutz, corporate vice president, Microsoft Dynamics CRM. “Microsoft Dynamics CRM helps people connect with these customers in a way that is personal — giving them the information they need to choose the right solutions, engage to drive sales and nurture relationships to deliver amazing experiences.”

 

See the complete post here.

Wednesday, 3 July 2013

Microsoft CRM 2011 - Interfaces - IOrganization, IWorkflowContext, IDiscovery, IExecutionContext


Today we will see some of the basic information about Microsoft Dynamics CRM 2011 Interfaces which is the key part of developing Custom services, Plugin, Custom Workflow etc.


IOrganizationService

This is an Interface which provides programmatic access to the metadata and data for an organization. This contains the methods that you must be used in order to write code that uses all the data and metadata in Microsoft Dynamics CRM.
To use this webservice, Microsoft.Xrm.Sdk.dll assembly needs to be added in Visual studio Project.
To work on other Non-core Xrm Messages, Microsoft.Crm.SdkProxy.dll needs to be added in VS project.

IDiscoveryService

This is an Interface which Provides programmatic access to organization and user information.
The IDiscoveryService Web service is used to determine the organizations that a user is a member of, and the endpoint address URL to access the IOrganizationService Web service for each of those organizations. This discovery service is necessary because Microsoft Dynamics CRM 2011 is a multi-tenant environment, a single Microsoft Dynamics CRM server can host multiple business organizations. By using the discovery Web service, your application can determine the endpoint address URL to access the target organization’s business data.

To use this webservice, Microsoft.Xrm.Sdk.Discovery assembly needs to be added in Visual studio Project along with Microsoft.Xrm.Sdk.

IWorkflowContext

This is an Interface which Provides access to the data associated with the process instance.
This IWorkflowContext is used to develop the Custom workflow process for both onpremise and online.
To use this webservice, Microsoft.Xrm.Sdk.Workflow assembly needs to be added in Visual studio Project.

IExecutionContext

Base interface that defines the contextual information passed to a plug-in or custom workflow activity at run-time.

IOrganizationServiceFactory

This is an Interface which Represents a factory for creating IOrganizationService instances.

 

  

Thanks .... Enojy !!!!!!!!!!!!!!!!

 

Feel free to post you comments if you need any help.


MSCRM 2011 - Disable fields based on Lookup Change - Retrieve Lookup Values using Javascript


Right now i am going to brief about retrieving value from MSCRM lookup field and disabling the other fields based on Lookup change.

Scenario :

I have a lookup, in which i want to disable other field whenever the lookup value is selected as "Country". Here the sample script.

//Code Starts
var lookupItem = new Array;

if (Xrm.Page.getAttribute("lookupfieldid").getValue())
{

    lookupItem = Xrm.Page.getAttribute("lookupfieldid ").getValue();

    if (lookupItem[0] != null)
    {
        if (lookupItem[0].name == "Country")
        {
            Xrm.Page.getControl("fieldname").setDisabled(true);
        }
        else
        {
            Xrm.Page.getControl("fieldname").setDisabled(false);
        }
    }


}

//Code end.

Add the above code on the Lookup field on change event.

To know about working on other CRM fields, please visit my previous post.

Feel free to post you comments if you need any help.

MSCRM 2011 Supported JavaScript - Part 3



Again I’m back with Some of the Javascript snippets which we are using around in many scenarios.


To retrieve the value of the CRM field.
Var fieldVal = Xrm.Page.getAttribute("fieldname ").getValue();
To assign value
Xrm.Page.getAttribute("fielname").setValue(“Test”);

To make field readonly /disable /enable
Xrm.Page.getControl("fieldname").setDisabled(true);  //Making Readonly/Disable
Xrm.Page.getControl("fieldname").setDisabled(false); //Enable

To update the disable field in CRM

Xrm.Page.getAttribute("fieldname ").setSubmitMode("always");

To Hide/show the field

Xrm.Page.ui.navigation.items.get("fieldname ").setVisible(false); //hide
Xrm.Page.ui.navigation.items.get("fieldname ").setVisible(true); //show

To get the current form type

Xrm.Page.ui.getFormType()

To get the current entity Id

Xrm.Page.data.entity.getId()

Making field mandatory

Xrm.Page.getAttribute(‘fieldname’).setRequiredLevel("required");

Making non-mandatory

Xrm.Page.getAttribute(‘fieldname’).setRequiredLevel("none");

Assigning URL to IFRAME

Xrm.Page.getControl("IFRAME_fieldname").setSrc(url);

Check my other blog for hiding/Showing sections