Microsoft Dynamics CRM Deployment Automation and Scheduling Automated Deployments using MSBuild scripts, batch files and other tools

Automated Deployment during the development of Dynamics CRM projects implementation is a time, effort and cost saving approach. A combination of MSBuild (MS Build) scripts, batch files and custom built console applications can provide a fully automated Dynamics CRM deployment and development life cycle.

Additionally, Microsoft Developer Toolkit which is released as a free tool part of the Dynamics CRM SDK provides an excellent deployment functionality (amongst many other useful features) but this is the subject of another post about automated deployment using Dynamics CRM SDK developer toolkit : http://www.mohamedibrahim.net/blog/2012/08/09/dynamics-crm-automated-deployment-using-dynamics-crm-developer-toolkit-from-the-sdk/ .

Examples of the most common deployment automation requirements in Dynamics CRM development projects:

1) Automated Deployment by getting the latest code from Visual Studio (via TFS – Team Foundaion Server) and deploying into a Dynamics CRM organisation on a server (local VM or a development/test server).

2) Export of Dynamics CRM default solution or a specific CRM solution package and importing the solution into another environment or Dynamics CRM server (or organisation). This is also known as Promotion: Promoting a CRM solution from one environemnt (such as Development environemtn) to another environment (such as test).

3) Export a CRM Solution from a CRM Server and then check in this exported solution file (the solution zip file) into TFS for backup or reusage.

These are the most commmon automated deployments used in projects but there could be many more based on projects requirements.

To achieve each on of these deployment automation setup there are a number of approaches and methods. I’ll try now to give some samples on how to do these automated deployments mentioned before:

You will need to create a batch file that calls an MSBuild file which in turn can do the operaton. The reason for using a batch file is that you can then setup a windows scheduled task to run the batch file at your chosen time for running the build. You can also add an auto numbering to the batch file if you want to increment the build number after every build. In this case, you will need to store the last build number in a separate text file.

The minimum that you will need in the batch file:

:: Check if Visual Studio command line is available. If not, then go to missing and end of file

if not exist “C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat” goto missing

:: Otherwise, call the Visual Studion Command shell.

call “C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat”

:: Call the msbuild file

msbuild myprojectbuild.msbuild /property:BuildVersion=%ver% /property:BuildDate=%builddate%>log\log_%builddate%_%ver%.txt

goto :eof

:missing

echo Visual Studio command prompt is missing

pause

goto :eof

 

Your MSBuild file that will get the latest code Visual Studio code from TFS can be too long but I’ll try to give you below the main commands that you will need to perform:

 <?xml version=”1.0″ encoding=”utf-8″ ?>

<!– All rights reserved for Mohamed Ibrahim Mostafa. www.mohamedibrahim.net Please leave this copyright notice if you use this file. –>

<Project xmlns=”http://schemas.microsoft.com/developer/msbuild/2003” InitialTargets=”Release”>

<PropertyGroup>

<!– Build version – alternatively these vallues can be passed from the batch file–>

<BuildVersion>1.1.0.0</BuildVersion>

<BuildDate>20120101</BuildDate>

<TFSUser>mytfsusername</TFSUser>

<TFSPassword>mytfspassword</TFSPassword>

<BuildConfiguration>Release</BuildConfiguration>

</PropertyGroup>

<Target Name=”Get”>

<!– get latest source code from tfs –>

<Exec Command=”tf get Clinet.Name/MySolutionName /force /recursive /noprompt /login:$(TFSUser),$(TFSPassword)” />

</Target>

<!– Build my visual studio CRM solution output binaries

<Target Name=”Build” DependsOnTargets=”Clean”>

<Message Text=”Building CRM solution code…” />

<!– Build all CRM-related outputs including plugins, scheduled tasks and user interface components –>

<MSBuild Projects=”Clinet.Name\MySolutionName\MyVisualStudio.sln” Properties=”Configuration=$(BuildConfiguration)”/>

</Target>

<!– now you have the visual studio solution built. use a console application to deploy it into CRM server as follows –>

<!– Use plugin registeration developer console application (available in SDK) to deploy plugins and workflows –>

<!– or alternatively use the deploy command of the microsoft dynamics crm developer toolkit (from the SDK) to deploy the whole solution into your CRM server organisation–>

<!– using the deploy command of the developer toolkit will be covered in a separate post –>

<!– The following command uses a custom console application that I have built to export Dynamics CRM solutions –>

<Target Name=”Package” DependsOnTargets=”Build”>

<Exec Command=”MyCustomDeploymentTool.exe export solution=Default outputdir=myfolder\CRM discoveryurl=$(DiscoveryUrl) orgname=$(OrganizationName)” />

<!– parameteres discovery url and organisation name are parameters in the property group –>

</Target>

<!–Now check in TFS and label your code using MSBuild commands –>

<Target Name=”Versioning” DependsOnTargets=”Package”>

<Exec Command=”tf add  /login:$(TFSUser),$(TFSPassword)” />

<Exec Command=”tf checkin MyProjectName\CRM_SolutionName_$(BuildDate)_$(BuildVersion).zip /login:$(TFSUser),$(TFSPassword)” />

<!– label TFS with the build number –>

<Exec Command=”tf label $(BuildVersion) MyProjectName/* /recursive /comment:&quot;Automatically labelled by Mohamed Mostafa build script.&quot; /login:$(TFSUser),$(TFSPassword)” />

</Target>

<Target Name=”Release” DependsOnTargets=”Versioning”>

<Message Text=”Completed..”/>    </Target>

</Project>

<!– All rights reserved for Mohamed Ibrahim Mostafa: www.mohamedibrahim.net –>

The console application that you can use to import or export a CRM solution will be the subject of another post. I think this post is too long already and I have spent good few hours writing it.

I hope this helps. If you have any questions, ideas or feedback please write them in a comment below.

If you want the various MSBuild files, batch files, etc then please comment below and I’ll email them to you (I tend to collect requests and send the files to a whole group in bulk).

New Features in Microsoft dynamics CRM 2011. Introduction to CRM 2011 new Customizations & Productivity functionality, Web Client & development enhancements

What’s new in Microsoft Dynamics CRM 2011, Microsoft Dynamics CRM Online 2011 & International worldwide Europe and United Kingdom (UK) CRM Dynamics Online launch. This post tries to answer these questions. The post is the next one in the series and collection of posts that discuss Microsoft dynamics CRM 2011 new features, changes, additions, add-ons and improvements. We discussed in our previous post CRM Outlook client for Microsoft Dynamics CRM 2011 New features, changes, additions and improvements & gave a fairly quick introduction to the CRM Outlook client  (you can read the previous post here). This post is focusing on what’s new in Dynamics CRM 2011 Web Client (IE) and CRM 2011 Customizations, configuration and development o f the new Microsoft CRM 2011 version.

The number of additions, enhancements, improvements in CRM 2011 are estimated to be over 500 new features at least. Some new features are fundamental and others are minor changes that are aimed at making the lives of Microsoft CRM Architects, consultants and developers easier, much easier I would say.

Let’s now go through some of the enhancements in CRM 2011 without too much details and I will aim to do more detailed posts in the future on how to work on each main new feature.

  • Dashboards: CRM 2011 now has the big, major change which is the Dashboards. You can now build out of the box standard dashboards, graphical dashboards, charts, etc in CRM 2011. Building dashboards has been made easy enough so that business users can build dashboards for themselves without the need of CRM consultants or developers to build them unless they are advanced dashboards. Gone are the days (or at least I hope so) when CRM Consultants had to build dashboards for clients using Asp.net page, user controls a.k. widgets, etc. We can now very easily configure (can’t really call it develop) a dashboard in quick few steps. I think I will have to do a separate blog post to go through CRM 2011 Dashboards in detail.

Dashboards in CRM 2011

  • Records Navigation: CRM 2011 now has full records navigation in the web clients, so CRM users can just click on the next record or previous record buttons to navigate easily between CRM records especially in case they want to do a specific task on all records one by one. They no longer now need to double click a record, edit it, save it, close and then go back and open the next one. There is simply one button to get you to the next one.

CRM 2011 new Records Navigation feature snapshot

  • Headers & Footers: Every form for every entity record in Microsoft Dynamics CRM 2011 now can have footers and headers. Here is a screenshot:

CRM 2011 Headers & Footers screenshot

  • Sub Grids:You can now build sub grids in CRM web client for drilling further into CRM data.
  • Customise Tab: To customise (or customize for my American friends!), you now have a tab on ever entity that allows you to customise it without having to go to the settings –> customisations area as in Dynamics CRM 4.0. Obviously only users who have the relative security roles that allows them to customize entities can see this tab. Normal CRM users will not see this tab if they do not have the related security role.
  • Form editor: Forms customisation and editors are now much much simpler really. No more going between several screens to add fields and then go back to the main form to add the field. It is now as simple as drag and drop fields on the form, and as easy as creating a new field while customising the form, there and then. This will definitely lower down the time required for customisations as everything is handled from one screen.
  • Multiple Forms per entity: Every CRM 2011 entity now can have one or more forms. Each form can have different security roles associated, so you can basically have a form for each security role or in other words each group of users. So if you want not to display certain data to specific CRM user, you can just create a form that only has the data they need to see. Don’t confuse this with field level security which is also a new feature in CRM 2011. You can also add parameters to be passed to the Form from within the Form properties. This data from the parameters can be accessed in scripts for form and field event handlers.
  • Global Picklist – Option set: CRM 2011 now has a new field type which is Option set. An option set is in effect a picklist (or dropdown) field type but which is global to all CRM entities. So any entity form can add the same option set. This is quite useful when you have something like countries list or job types, etc. You can now create one global option set and then all entities can reference this option set.
  • Entity Forms left navigation: You can now edit every entity’s left navigation graphically (no JavaScript is needed). You can move (drag and drop) left nav items up and down, from one group to another group (for example from sales to marketing, etc) for each form. You can also remove specific left navigation links on any form. You can even hide all left nav items for a specific form for a specific entity. You can also rename any section (such as sales, etc..) and you can rename every left nav item using their properties dialog window. Again, no scripting required. You can add a new navigation item which can be pointing to a URL or to any web resource and you can choose an icon for it.
  • Publish within the customisation screen: Do all your customisation changes then click Publish button without the need to close or open any windows (horrayyy).
  • Auditing: CRM 2011 now comes with an auditing module included. You can enable and disable auditing for every entity. If auditing is enabled on an entity, all its fields become audited as well. You can then go through each field in this entity and disable auditing for it if required.
  • Field Level Security: You can now enable and disable field level security for every custom field (not customizable ones). If a field security is enabled, you can then go to Settings –> Administration –> Field security profiles and change the field level security for each field for as many profiles as you want. For example you can create a profile for temp employees and set certain fields as: Read, Update and/or Create. If you don’t tick any of these 3 options, Teams and users in this profile will not see this profile’s fields on the related entities’ forms. You can add teams and users for each field level security profile.
  • Form level Security: Every CRM 2011 form now can be secured against each security role. When you edit every form in CRM 2011, you will have an option on the CRM 2011 ribbon at the top that allows you to assign security roles to this form. So, you can either choose the option to display this form to everyone or you can select what security roles can see this form. Anyone who does not have the security roles assigned to this form, will not be able to view it.
  • Excel Import and Export CRM Data: CRM 2011 allows for the import and export of data to and from CRM and an Excel sheet. You can now add information in the excel sheet and import to CRM and vice versa. When you open excel spreadsheets with CRM data exported from CRM, you will be able to see all values for each picklist to change the values in the excel sheet and then import back to CRM. This is excellent for Sales and field employees who can work disconnectedly on excel sheets and then import to CRM at the end of the day. This is also very useful for data cleansing where you can export data, do a data cleansing exercise (wash it thoroughly) and then import back.

 

That’s it for this post. More blog posts are coming with more CRM 2011 features and capabilities. Next blog post will be a continuation of the productivity enhancements that Microsoft Dynamics CRM 2011 has.

The next post will be published very soon so, please watch this space.

// Update 1 November 2010——————————————

The new post, in continuation of this series can has been published and can be viewed by clicking here.

Hope this post was helpful. Please feel free to comment with your feedback and input.

Thanks,

Mohamed Mostafa

—————————————————-
Disclaimer: No Warranty or Liability on this post:
As always, this post, like all other posts on this blog are presented as is without any guarantee or warranty and I’m not responsible for any inaccurate or incorrect information mentioned in this blog nor decisions made based on this post. Myself, Microsoft and my employer can not be held responsible for any of this post content or information.

What’s new in Microsoft Dynamics CRM 2011? Introduction to CRM Outlook client for Microsoft Dynamics CRM 2011 New features, changes, additons and improvements

This post and the following collection of posts will be discussing Microsoft dynamics CRM 2011 new features, changes, additions, add-ons and improvements. The post is based on a collection of quick notes that I have taken from a recent Microsoft Dynamics CRM partners event called Microsoft Dynamics CRM 2011 Global Readiness Tour event that happened just 2 days before Microsoft Dynamics Convergence event in London. I attended this GRT and took these notes which might I must warn that the may potentially be not fully accurate, wrong or contains incorrect information. Further checks are advised in regards to the content of this post, related posts and all posts on the blog (you know I have to say that!)

Introduction:

The speaker on the technical session was Reuben Kippner and with all honesty, I think it was a brilliant session(s), straight to the point and most event delegates I spoke with liked his presentation and the way he puts information across. So well done Reuben.

One more thing before we delve into the details: I always try not to put my opinion or views in my blog posts as I prefer to put facts and straight forward information, so I’ll try to do this in this post as well but apologies in advance if I end up putting my views in some cases.

What’s new in Microsoft Dynamics CRM 2011 Outlook client:

  • Now in CRM 2011, you can go and create a new email and then you will have the option of inserting resources from CRM records such as: Templates, Sales literature and Articles.
  • You can now have more than one organisation added to your Outlook. So you will have one organisation that you can set to synchronise with, and as many more as you want where you can view and access their CRM data in Outlook but do not synchronise with. Obviously you will only be able to synchronise with one of them only as you can sync with more than one and end up with data such as contacts and appointments from multiple organisations in your outlook.
  • CRM 2011 outlook client has been fully re-written and is not based on CRM 4 outlook client.
  • CRM 2011 outlook client is now native to Outlook which means you can do all your usual outlook configuration and settings to your CRM data in outlook.
  • For example you can now use outlook categories for your CRM records, etc.
  • Go to the View tab in outlook –> View settings –> Conditional formatting -> then all your Outlook formatting there can be applied to your CRM records in Outlook.
  • You also have reading pane for CRM 2011 data similar to how outlook emails are displayed. It is no longer a window to CRM data in outlook, it is actually displaying and using CRM data in Outlook based on Outlook native features and display settings.
  • You can now have multiple views in Outlook. So you can see all CRM views in your Outlook.
  • Please see below a screen shot of a CRM 2011 contact in outlook with the available views

The next post will be available soon, so watch this space.

Please comment below to let me know your views on the new additions in CRM Outlook client for CRM 2011 and all new features in Microsoft Dynamics CRM 2011 in general.

Please also comment with any corrections to this post or any features that I haven’t listed (which I’m sure they are many).

Hope you like it!

Thanks

//———————–Update on 21 October 2010—————-

The next post is now live. It discusses Microsoft Dynamics CRM 2011 & Online development and customisation enhancements and productivity functionlity in CRM 2011. Click here to go to the new Post

—————————————————-
No Warranty or Liability on this post:
As always, this post, like all other posts on this blog are presented as is without any guarantee or warranty and I’m not responsible for any inaccurate or incorrect information mentioned in this blog nor decisions made based on this post. Myself, Microsoft and my employer can not be held responsible for any of this post content or information.

Microsoft Dynamics CRM 4.0 Demonstration Tool Review: Edit Microsoft Dynamics CRM SiteMap using a Graphical User Interface (GUI) tool & utility, CRM data tool & other useful features

This is a quick post to direct people to Microsoft Dynamics CRM tool or utility developed by Microsoft and available free that can be used to quickly edit Microsoft Dynamics CRM SiteMap via a Graphical Interface (GUI) where you can easily change, amend & publish the site map file: sitemap.xml.

I’m sure many people already know that but I’m also sure there are some people who have not heard of Microsoft Dynamics CRM Demonstration Tool (for Microsoft Dynamics CRM 4.0). This tool is an excellent tool to help you do few things using a graphical interface.

Microsoft Dynamics CRM Demonstration Tool allow you to import the sitemap.xml file to edit your site map and left navigation links in each section area of your main Dynamics CRM application interface. You can edit each and every left nav link, move links up and down, re-order them the way you want it and add links to ISV applications (asp.net webpages or web applications, etc.) and again align this link wherever you want on the main CRM left navigation and in any section. This is all done via a user interface so no need to code or add any javascript to adjust that. Always remember to back up your sitemap and you customisations before using this tool. This utility also only works on On-Premise implementations only.

You can download the tool from the following URL:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=634508DC-1762-40D6-B745-B3BDE05D7012&displaylang=en

Just download it (1.8MB) and run the exe file and you do NOT need to install any files, it’s a self contained exe file.

The tool is also very useful for the following:

  • Automated Data generation, enter and edit data, populate and save your CRM data for future use in XML format.
  • You can move the date forward for all your data date fields (non-system dates only) so that you can have your demonstration data up to date and you can clearly show information such as opportunities pipeline and future sales data.
  • It also generates a code for you for dependant picklists where if you choose a value in the primary picklist the dependant picklist will have its list of values changed according to the primary picklist selection. The JavaScript Client side code is generated for you for this. You can also preview your picklists behaviour in the utility.
  • You can generate incoming emails from your existing Dynamics CRM contacts for demonstration.
  • You can edit, upload, change and handle your icons for all your Microsoft Dynamics CRM custom entities.
  • Site Map editor as we discussed above.
  • String editor is also another feature in this tool that allows you replace display text, form labels, view names and messages in CRM for all your entities.

Microsoft describes it as follows: “The Microsoft Dynamics CRM 4.0 Demonstration Tools provide a simple user interface that allows you to easily enter and edit data to populate or modify your instance of Microsoft Dynamics CRM. It also allows you to load and store your data in XML format, so that you can reuse your data in the future”

Hope you find this review useful. Please comment if you have anything to add that can help anyone.

Converting Microsoft Dynamics CRM 4 JavaScript to Microsoft Dynamics CRM 2011 Javascript code converter

I have just seen this javascript converter tool and I thought I’ll let everyone know about it as it could be quite beneficial when upgrading Microsoft Dynamics CRM 4.0 to Microsoft Dynamics CRM 2011 including Javascript upgrade and changes.

This is the link for the tool. I haven’t tested it thoroughly myself yet, so please write your comments and reviews below to let everyone know how good this tool is:
http://bingsoft.wordpress.com/2010/09/09/crm-4-to-crm-2011-javascript-converter-tool/
http://crm2011scriptconvert.codeplex.com/

Hope this helps!

Import & Export Microsoft Dynamics CRM Customizations as XML or as compressed file programatically (dynamically) using CRM API/Web Service

 

It is very common that you would need to import customizations from a file and upload it directly on CRM then publish thes customizations OR the opposite: where you import customisations from Dynamic CRM implementation and export to a file either XML file or a Zip file which you can then archive or add to your source control (TFS or Source Safe). The later is specially common when you need to have a regular backup of your customizations that is stored in TFS or your choses Source control.

To do this, MSDN provides several ways of importing and exporting files (see: http://msdn.microsoft.com/en-us/library/cc151164.aspx)

This is what you can do:

Message name Description
ExportAllXml Export all customizations to an XML file.
ExportCompressedAllXml Export all customizations to an XML file, which is then compressed into a zipped format.
ExportCompressedTranslationsXml Export all translations to an XML file, which is then compressed into a zipped format.
ExportCompressedXml Export the specified customizations to an XML file, which is then compressed into a zipped format.
ExportTranslationsXml Export all translations to an XML file.
ExportXml Export a list of entities to an XML file.
ImportAllXml Import all customizations from an XML file.
ImportCompressedAllXml Import all customizations from an XML file that has been compressed into a zipped format.
ImportCompressedXmlWithProgress Import all customizations with progress logging from an XML file that has been compressed into a zipped format.
ImportTranslationsXmlWithProgress Import all translations from an XML file with progress logging.
ImportXml Import a list of entities from an XML file.
ImportXmlWithProgress Import the specified set of entity customizations from an XML file with progress logging.
PublishAllXml Publish all customizations.
PublishXml Publish a list of entity customizations.

 

Export All XML customizations is usually the most popular one. Here is how you can do it (Code from MSDN):

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request.
ExportAllXmlRequest request = new ExportAllXmlRequest();

// Execute the request.
ExportAllXmlResponse response = (ExportAllXmlResponse)service.Execute(request);

// Load the results into an XML document.
XmlDocument entityXml = new XmlDocument();
entityXml.LoadXml(response.ExportXml);

 

As for Import All XML customization followed by a publish, here is the code for it:

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// This is a potentially long running operation. The default 90-second
// time-out might be too short.  Set the time-out to be 5 minutes.
// This property takes milliseconds.
service.Timeout = 300 * 1000; 

// Create the request.
ExportAllXmlRequest request = new ExportAllXmlRequest();

// Execute the request.
ExportAllXmlResponse exportResponse = (ExportAllXmlResponse)service.Execute((Request)request);

// Create the request.
ImportAllXmlRequest importRequest = new ImportAllXmlRequest();

// Tell the request where the temporary XML file is located.
importRequest.CustomizationXml = exportResponse.ExportXml;

// Execute the import.
ImportAllXmlResponse importResponse = (ImportAllXmlResponse)service.Execute(importRequest);

Finally to publish your customizations, this is what you need to do:

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request.
PublishAllXmlRequest request = new PublishAllXmlRequest();

// Execute the request.
PublishAllXmlResponse response = (PublishAllXmlResponse)service.Execute(request);

Creating, consuming and using Microsoft Dynamics CRM 4.0 Service, Using CRM API and CRM SDK to access CRM database via the webservice

  

Creating, consuming and using Microsoft Dynamics CRM 4.0 Service, Using CRM API and CRM SDK to access CRM database via the webservice. Custom .NET code to access CRM, create, update (edit), insert, delete, retrieve (return) and retrievemultiple records for system entities and custom entities using both entity objects and dynamic entities. 

This post is a collection of the main methods that you would frequently use in your .NET code (Plugin, Website) that is accessing a dynamics CRM 4.0 system and consuming its CRM services. 

The CrmService Web service provides a set of methods used to perform the most common operations on system and custom entities. 

This collection mainly comes from sevaral pages on MSDN. I just thought it will be useful to have them all together if we need one or more of them. 

  

The following code shows how to set up the Web service, and how to use the Create and Retrieve methods. 

  

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create an account entity and assign data to some attributes.
account newAccount = new account();
newAccount.name = "Greg Bike Store";
newAccount.accountnumber = "123456";
newAccount.address1_postalcode = "98052";
newAccount.address1_city = "Redmond";
 
// Call the Create method to create an account.
Guid accountId = service.Create(newAccount);
 
Guid contactId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");
 
// Call the Retrieve method to retrieve an existing contact.
ColumnSet myColumnSet = new ColumnSet();
myColumnSet.Attributes = new string[] { "firstname" };
contact myContact = (contact) service.Retrieve ("contact", contactId, myColumnSet)

  

 

 

—————————- 

The following example demonstrates the use of the Create method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 
// You can use enums.cs from the SDK\Helpers folder to get the enumeration 
//   for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the contact object.
contact contact = new contact();
 
// Create the properties for the contact object.
contact.firstname = "Jesper";
contact.lastname = "Aaberg";
contact.address1_line1 = "23 Market St.";
contact.address1_city = "Sammamish";
contact.address1_stateorprovince = "MT";
contact.address1_postalcode = "99999";
contact.donotbulkemail = new CrmBoolean();
contact.donotbulkemail.Value = true;
 
// Create the contact in Microsoft Dynamics CRM.
Guid contactGuid = service.Create(contact);

  

———————————- 

  

The following example demonstrates the use of the Retrieve method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the column set object that indicates the properties to be retrieved.
ColumnSet cols = new ColumnSet();
 
// Set the properties of the column set.
cols.Attributes = new string [] {"fullname"};
 
// contactGuid is the GUID of the record being retrieved.
Guid contactGuid = new Guid("4D507FFE-ED25-447B-80DE-00AE3EB18B84");
 
// Retrieve the contact.
// The EntityName indicates the EntityType of the object being retrieved.
contact contact = (contact)service.Retrieve(EntityName.contact.ToString(), 
                                             contactGuid, cols);

  

  

—————————- 

  

The following example demonstrates the use of the RetrieveMultiple method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the ColumnSet that indicates the properties to be retrieved.
ColumnSet cols = new ColumnSet();
 
// Set the properties of the ColumnSet.
cols.Attributes = new string [] {"fullname", "contactid"};
 
// Create the ConditionExpression.
ConditionExpression condition = new ConditionExpression();
 
// Set the condition for the retrieval to be when the 
//    contact's address' city is Sammamish.
condition.AttributeName = "address1_city";
condition.Operator = ConditionOperator.Like;
condition.Values = new string [] {"Sammamish"};
 
// Create the FilterExpression.
FilterExpression filter = new FilterExpression();
 
// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.Conditions = new ConditionExpression[] {condition};
 
// Create the QueryExpression object.
QueryExpression query = new QueryExpression();
 
// Set the properties of the QueryExpression object.
query.EntityName = EntityName.contact.ToString();
query.ColumnSet = cols;
query.Criteria = filter;
 
// Retrieve the contacts.
BusinessEntityCollection contacts = service.RetrieveMultiple(query);

  

—————————- 

  

  

The following example demonstrates the use of the Update method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// Create the contact object.
contact contact = new contact();
 
// Set the contact object properties to be updated.
contact.address1_line1 = "34 Market St.";
 
// The contactid is a key that references the ID of the contact to be updated.
contact.contactid = new Key();
// The contactid.Value is the GUID of the record to be changed.
contact.contactid.Value = new Guid("4D507FFE-ED25-447B-80DE-00AE3EB18B84");
 
// Update the contact.
service.Update(contact);

  

—————————- 

  

The following example demonstrates the use of the Delete method. 

  

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
 

// You can use enums.cs from the SDK\Helpers folder to get the enumeration
//   for Active Directory authentication

  

token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";
 
CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
// contactGuid is the GUID of the record being deleted.
Guid contactGuid = new Guid("4D507FFE-ED25-447B-80DE-00AE3EB18B84");
 
// Delete the contact.
// The EntityName indicates the EntityType of the object being deleted.
service.Delete(EntityName.contact.ToString(), contactGuid);

  

—————————- 

  

For Dynamic Entities: The following sample shows how to create a new entity instance by calling the CreateEntity method followed by the AddObject method. 

  

var contact = crm.CreateEntity("contact");
 
// Set the string properties.
contact.SetPropertyValue("firstname", "Allison");
contact.SetPropertyValue("lastname", "Brown");
contact.SetPropertyValue("emailaddress1", "allison.brown@contoso.com");
 
// Setting an explicit ID value is optional, it can be left unassigned, 
//    but here it is being explicitly assigned.
var id = Guid.NewGuid();
contact.SetPropertyValue("contactid", id);
 
// Pass the entity name of the entity being created as the first parameter.
crm.AddObject("contact", contact);
crm.SaveChanges();
 
// The ID value can be retrieved after you have called the SaveChanges method.
var id2 = contact.GetPropertyValue<Guid>("contactid");

  

  

  

These methods have been collected from MSDN mainly from these two locations:  http://msdn.microsoft.com/en-us/library/cc151016.aspx and http://msdn.microsoft.com/en-us/library/ff681571.aspx  

  

  

Get Current User Security Roles in Microsoft Dynamics CRM 4.0 on client side using JavaScript calls to CRM Service & API

In Microsoft Dynamics CRM 4.0, it is quite common that you want to call the CRM service from client side: i.e. Call the CRM service using JavaScript code that is located on the OnLoad, OnSave or OnChange events on a Dynamics CRM entity or field event.

The most common call is the call to CRM service to determine what roles the current user has.

The following function returns all roles of a specific user by creating a SOAP message request to the CRM Service:

//*********************
function GetCurrentUserRoles()
{
 var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
 " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>role</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +
 " <q1:Attribute>name</q1:Attribute>" +
 " </q1:Attributes>" +
 " </q1:ColumnSet>" +
 " <q1:Distinct>false</q1:Distinct>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkCriteria>" +
 " <q1:FilterOperator>And</q1:FilterOperator>" +
 " <q1:Conditions>" +
 " <q1:Condition>" +
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +
 " <q1:Operator>EqualUserId</q1:Operator>" +
 " </q1:Condition>" +
 " </q1:Conditions>" +
 " </q1:LinkCriteria>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </query>" +
 " </RetrieveMultiple>" +
 " </soap:Body>" +
 "</soap:Envelope>" +
 "";

 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
 xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
 xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
 xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
 xmlHttpRequest.send(xml);

 var resultXml = xmlHttpRequest.responseXML;
 return(resultXml);
}
//*********************

 The following function checks if the specified user has a specified user role:

//*********************
function UserHasRole(roleName) {
    //get Current User Roles, oXml is an object
    var oXml = GetCurrentUserRoles();
    if (oXml != null) {
        //select the node text
        var roles = oXml.selectNodes("//BusinessEntity/q1:name");
        if (roles != null) {
            for (i = 0; i < roles.length; i++) {
                if (roles[i].text == roleName) {
                    //return true if user has this role
                    return true;
                }
            }
        }
    }
    //otherwise return false
    return false;
}
//*********************

The following code block uses the above function to do some logic based on user’s security roles:

if(UserHasRole("System Administrator"))
{
  //do something
}
else
{
   //do something else
}

Embedding ISV web applications in Microsoft Dynamics CRM 4.0 through SiteMap (not as an IFrame) via a left navigation link. Application & link Access restriction through Site Map

There are (at least) two standard ways of implementing an external ISV web application (website, html, .NET, etc..) inside your dynamics CRM application.

The first way is by creating an IFrame inside the form of an entity. This is quite straight forward and can be achieved from the entity customisation section in CRM settings.

The second option is to create a link in the left navigation of your Microsoft Dynamics CRM 4.0 solution. This link can then point to your ISV webpage (aspx page for example) and you will have your web page implemented and embedded inside CRM. If you also do the application css (stylesheet file)  to be same colours and similar styles as CRM colours and styles, your application will be presented nicely inside CRM as if it is part of CRM. The permission and restriction of access to this web application and its left navigation link is also controlled to show/hide the applications to users.

This post is discussing the second option.

Embedding a webpage or web application in CRM and having  CRM’s left navigation linked to it can be done by editing the sitemap customisation file (xml). This left nav link can be shown or hidden to users based on their security roles and this is also controlled in the site map file. If the link is hidden, then obviously the web application will not be accessible and cannot be retrieved by unauthorised users.

The following is an example of a sitemap file that displays two links to two applications on the top of the left navigation menu of CRM 4.0. The privilage for accessing each link is also set in the following example:

<SiteMap>
    <SiteMap>
      <Area Id="Workplace" ResourceId="Area_Workplace" ShowGroups="true"
Icon="/_imgs/workplace_24x24.gif" DescriptionResourceId="Workplace_Description">
        <Group Id="MyWork" ResourceId="Group_MyWork" 
DescriptionResourceId="My_Work_Description">
          <SubArea Id="MyWebApplication" Icon="/_imgs/ico_18_servicecal.gif" 
Url="../../ISV/MyWebApplication/WebPage.aspx" AvailableOffline="false">
            <Titles>
              <Title LCID="1033" Title="My Web Application ONE" />
            </Titles>
            <Descriptions>
              <Description LCID="1033" Description="My Web Application ONE" />
            </Descriptions>
<!-- this is where you control displaying the 1st link-->
<!-- if the user has read and write access to entity Kbarticle (for ex)-->
<!-- then they should be able to view this link. Otherwise, its hidden-->
            <Privilege Entity="kbarticle" Privilege="Read,Write" /> 
          </SubArea><!--another example follows: -->
          <SubArea Id="WebPage2" Icon="/_imgs/ico_18_servicecal.gif"  
Url="../../ISV/WebApplication2/index.htm" AvailableOffline="false">
            <Titles>
              <Title LCID="1033" Title="Web Page 2" />
            </Titles>
            <Descriptions> 
<!-- if the user has create access to entity Kbarticle (for ex)-->
<!-- then they should be able to view this link. Otherwise, its hidden-->
              <Description LCID="1033" Description="Web Page 2" />
            </Descriptions>
            <Privilege Entity="kbarticle" Privilege="Create" />
          </SubArea>
<!-- The following is the standard activity left link for CRM-->
          <SubArea Id="nav_activities" Entity="activitypointer"  
DescriptionResourceId="Activities_SubArea_Description"  
Url="/Workplace/home_activities.aspx" />

This is how you can get site map to control your left navigation buttons and get them to link to ISV applications. Please mind that you might need to change the relative location of your application in the URL parameter.

Hope this helps.

 

Microsoft Dynamics CRM 4 field level validation using javascript regular expression on client side handling the onChange event to validate and check the value and text of a CRM 4.0 field

Please note that this post is aimed as showing how to use javascript regular expression field level validation in Microsoft Dynamics CRM. The post does not focus on the many ways of getting a regular expression. The example regular expression below is used for explanation only.

If you want to create validation at field level in Microsoft Dynamics CRM 4 to check the input value and text of a CRM field in an entity form, you can do this using regular expressions written in javascript code that handles the on change (onChange) event of this field at client side.

Below is an example of a regular expression but you might want to use your own regex value or search online for almost unlimited number of regular expressions that do just about anything.

For example, if you want to validate a CRM 4 field so that only a 4 digit year value starting from year 1980 is entered in the field text box, follow the following steps:

– Open the entity customisation form
– select the field you want to validate using javascript regular expression.
– Click on field properties, events tab and then open the onChange event.
– In the onChange event type the following javascript code (script) to handle the event and implement the field level validation:

//-----------------------------
//Regular expression ensuring a 4 digit year value is input starting from year 1980.
var reDate =/^(([1]{1}[9]{1}[8-9]{1}\d{1})|([2-9]{1}\d{3}))$/
//Check if the input value satisfies the regular expression condition
if (document.crmForm.all.new_yearfieldname.value.search(reDate)==-1)
{//if match failed
alert("Please enter a valid year value. Year value must be four digits starting from the year 1980")
crmForm.all.new_yearfieldname.value = '';
}
//-----------------

Another way of doing this is as follows;

//-----------------------------
var regexS = "^(([1]{1}[9]{1}[8-9]{1}\d{1})|([2-9]{1}\d{3}))$"; 
var regex = new RegExp( regexS ); 
var results = regex.exec( crmForm.all.new_yearfieldname.value);
if( results == null )   
{//if match failed
alert("Please enter a valid year value. Year value must be four digits starting from the year 1980")
crmForm.all.new_yearfieldname.value = '';
}
//-----------------------------

Hope this helps.