Hi Folks,
This post will help you out in getting the complete list of metadata of Microsoft Dynamics CRM application.
That is all!! It is simple to get the metadata details of your CRM application.
Here comes my next and an interesting post. This post will help you out to send bulk emails from your CRM application through .Net code. And wait it is not just about sending emails and you can monitor the status of the operation as well in your application.
// Get a system user to use as the sender.
WhoAmIRequest emailSenderRequest = new WhoAmIRequest();
WhoAmIResponse emailSenderResponse =
_serviceProxy.Execute(emailSenderRequest) as WhoAmIResponse;
// Set trackingId for bulk mail request.
Guid trackingId = Guid.NewGuid();
SendBulkMailRequest bulkMailRequest = new SendBulkMailRequest()
{
// Create a query expression for the bulk operation to use to retrieve
// the contacts in the email list.
Query = new QueryExpression()
EntityName = Contact.EntityLogicalName,
ColumnSet = new ColumnSet(new String[] { "contactid" }),
Criteria = new FilterExpression()
Conditions =
new ConditionExpression("contactid",ConditionOperator.In, _contactsIds)
}
},
// Set the Sender.
Sender = new EntityReference(SystemUser.EntityLogicalName, emailSenderResponse.UserId),
// Set the RegardingId - this field is required.
RegardingId = Guid.Empty,
RegardingType = SystemUser.EntityLogicalName,
// Use a built-in Microsoft Dynamics CRM email template.
// NOTE: The email template's "template type" must match the type of
// customers in the email list. Our list contains contacts, so our
// template must be for contacts.
//Here modify the guid with your record.
TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),
RequestId = trackingId
};
// Execute the async bulk email request
SendBulkMailResponse resp = (SendBulkMailResponse)
_serviceProxy.Execute(bulkMailRequest);
// Now that we've executed the bulk operation, we need to retrieve it
// using our tracking Id.
QueryByAttribute bulkQuery = new QueryByAttribute()
EntityName = AsyncOperation.EntityLogicalName,
ColumnSet = new ColumnSet(new string[] { "requestid", "statecode" }),
Attributes = { "requestid" },
Values = { trackingId }
// Retrieve the bulk email async operation.
EntityCollection aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);
// Monitor the async operation via polling.
int secondsTicker = ARBITRARY_MAX_POLLING_TIME;
AsyncOperation createdBulkMailOperation = null;
while (secondsTicker > 0)
// Make sure the async operation was retrieved.
if (aResponse.Entities.Count > 0)
// Grab the one bulk operation that has been created.
createdBulkMailOperation = (AsyncOperation)aResponse.Entities[0];
// Check the operation's state.
if (createdBulkMailOperation.StateCode.Value !=
AsyncOperationState.Completed)
// The operation has not yet completed.
// Wait a second for the status to change.
System.Threading.Thread.Sleep(1000);
secondsTicker--;
// Retrieve a fresh version the bulk delete operation.
aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);
else
// Stop polling because the operation's state is now complete.
secondsTicker = 0;
// Wait a second for the async operation to activate.
// Retrieve the entity again
// When the bulk email operation has completed, all sent emails will
// have a status of "Pending Send" and will be picked up by your email
// router. Alternatively, you can then use BackgroundSendEmail to download
// all the emails created with the SendBulkEmail message.
#region Check success
// Validate async operation succeeded
if (createdBulkMailOperation.StateCode.Value == AsyncOperationState.Completed)
MessageBox.Show("Operation Completed."); }
MessageBox.Show("Operation not yet Completed."); }
#endregion
Hope this helps.
Happy coding!!
This is an extension of the post which I have written to connect to Microsoft Dynamics CRM 2013 programmatically from the following link: http://blogs.technet.com/b/tvishnun1/archive/2014/07/09/kick-start-with-connecting-to-microsoft-dynamics-crm-2013-programmatically.aspx.
In this example we will see how we can create a simple contact record which includes the following fields:
Schema Name
Display Name
Field Type
firstname
First Name
Single Line of Text
lastname
Last Name
gendercode
Gender Code
Option Set
birthdate
Birth Date
Date & Time
annualincome
Annual Income
Currency
preferredsystemuserid
Preferred User
Lookup
exchangerate
Exchange Rate
Decimal Number
In the above table all types of fields are given so that you can replicate that according to your business needs for your field.
Since we have already connected to CRM in our previous post and now have to create records into CRM with the above fields. This example shows some few fields with almost all types now if you have to create other fields of same type you can use similar approach.
Let us go back to the project we have created earlier and add a new button for creating contact in CRM.
Now let us get into some simple coding stuff.
On the button click event we are going to place the following code:
//Here we are getting the details of the connection string and placing in the context variable.
var context = new CrmOrganizationServiceContext(CrmConnection.Parse(connectionDialog.ConnectionString));
//We are instantiating object of Entity class. This is available in Microsot.Xrm.Sdk assembly.
Entity contact = new Entity("contact");
//Since First Name and last name are single line of texts we are passing string variable.
contact["firstname"] = "Vishnu";
contact["lastname"] = "Turlapati";
//Here we are giving the value of Male value avaialable in Microsoft CRM. So based on the option set that needs to be selected place the respective optionset value.
contact["gendercode"] = new OptionSetValue(1);
//Here we are placing the date in date time format.
contact["birthdate"] = new DateTime(1988, 01, 02);
//Annual income is a currency so we are giving it directly as money variable.
contact["annualincome"] = new Money((decimal)10000);
//Here we are setting the preferred System user to a specific user record. GUID of a record can be obtained from an individual record.
contact["preferredsystemuserid"] = new EntityReference("systemuser", new Guid("CF955D17-310B-E411-AB97-D89D6765A2D0"));
//This is another decimal value which we are placing.
contact["exchangerate"] = new decimal(60);
//Finally we are creating the contact record into CRM.
context.Create(contact);
Congratulations you have successfully created a record in CRM with different fields. In the next post we will see how this can be better streamlined for better operations.
I am redesigning this blog to get things interesting for people who want to kick start things in CRM 2013.
This post will help people who are new to Microsoft Dynamics CRM development and want to connect to Microsoft Dynamics CRM 2013 programmatically. You can connect to CRM 2013 in different ways well in this post I would tell you the easy way to get this rolling.
In this example I would like to show creating a simple .Net application which connects to Microsoft Dynamics CRM 2013. The prerequisite for this will be you need to download the Microsoft Dynamics CRM 2013 SDK.
Let us get started:
Step 1: Open your Visual Studio and click on new project and select Windows Forms Application as shown below:
Step 2: Now navigate to your designer area and add a button to the form. Let us name this as connect.
Step 3: Now add the following references into your project. a) Microsoft.Crm.Sdk.Proxy b) Microsoft.Xrm.Client c) Microsoft.Xrm.Sdk (these 3 assemblies are available in your bin folder of Microsoft Dynamics CRM SDK.) d) System.Xaml.dll (This assembly is available in .Net framework assemblies. (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Xaml.dll) e) PresentationFramework.dll (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\PresentationFramework.dll) f) PresentationCore (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\PresentationCore.dll) g) WindowsBase (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\WindowsBase.dll) h) System.Runtime.Serialization.dll (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Runtime.Serialization.dll) i) System.Data.Services.dll (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.Services.dll)
Step 4: Now it is time to write some simple code. Open your form designer double click on the button created to write some event handler. Place the following code in the event handler. Here connectCRM is the button ID.
Step 5: Well now you are almost there. Now hit on F5 or run the application from Visual Studio. Click on connect to CRM button which will open the below screen.
Step 6: Enter the discovery URL. This is available in Settings – Customizations --- Developer Resources. In this example I am connecting to online CRM:. Now click on GO.
Step 7: Enter the details of username and password:
Step 8: After successful authentication you can see the list of organizations you can connect. Now select the organization and get connected.
Step 9: Now we are successful in connecting to CRM. Let us try to make some operation with it. Stop debugging your application and let us go back to CS file to modify it. You can see the below image for the additional modifications that can be done in your code to create a new contact in CRM.
That is all!!! You have successfully connected to CRM and created a record!!
Hope you are enjoying reading my blog!! I want to add a new post which showcases the offline filters functionality of CRM outlook client.
You know the fact that Microsoft Dynamics CRM supports the offline capability with outlook client. Did you get a chance to look into the offline filters available with CRM outlook client?
Here is a chance to look into them.
String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='product'>
<attribute name='name' />
<attribute name='producttypecode' />
<attribute name='productnumber' />
<attribute name='subjectid' />
<attribute name='productid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='statecode' operator='eq' value='0' />
<condition attribute='name' operator='eq' value='1234' />
</filter>
</entity>
</fetch>";
SavedQuery filter = new SavedQuery();
filter.FetchXml = fetchXml;
filter.IsQuickFindQuery = false;
filter.QueryType = SavedQueryQueryType.OfflineFilters;
filter.ReturnedTypeCode = Product.EntityLogicalName;
filter.Name = "Product Sample filter";
filter.Description = "Sample offline filter for Product entity";
_offlineFilter = _serviceProxy.Create(filter);
This can be used to generate dynamic offline filters. You can use this similar stuff in plugins. Ex: If you want to create an offline filter when a new product is launched or created in your organization. You can automate this process.
Hope this helps!!
Cheers,
Vishnu
Hello folks,
Happy Holidays to everyone!! In this holiday season I would like to add one post to strengthen your skills.
Did you ever try debugging plugins in CRM online? I knew most of you must have done it. Still I feel this is an interesting article to publish!!
Following are the steps you need to follow for debugging a plugin in Dynamics CRM online:
Voila!!! This will trigger to the location where you have placed the breakpoint. In this way you can debug plugins for CRM online.
Cheers
Vishnu!!
Here is the scenario:
I remember the days we used to write lengthy code to get all the entities that are not associated with another entity.
Did not understand?? Ok… let me give you an example: I want to get all the cases that are not having tasks associated with them. This is a complex way of getting until CRM 2011. Now things have changed so are we!! Excited?? So let us look into how we can achieve this requirement:
string strFetch = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='incident'>
<attribute name='title' />
<link-entity name='task' from='regardingobjectid' to='incidentid' alias='ab' link-type='outer'>
<attribute name='regardingobjectid' />
</link-entity>
<condition entityname='ab' attribute='regardingobjectid' operator='null' />
In the above fetch xml you can see the link-type being shown as outer and we writing an alias for this entity. Eventually we are writing a condition mapping that alias name.
EntityCollection caseCollection = service.RetrieveMultiple(new FetchExpression(strFetch));
foreach (Entity caseEntity in caseCollection.Entities)
// Create a task activity to follow up with the account customer in 7 days.
Entity followup = new Entity("task");
followup["subject"] = "Send e-mail to the customer.";
followup["description"] =
"Follow up with the customer. Check if there are any new issues that need resolution.";
followup["scheduledstart"] = DateTime.Now;
followup["scheduledend"] = DateTime.Now.AddDays(7);
followup["category"] = context.PrimaryEntityName;
followup["regardingobjectid"] = new EntityReference("incident", caseEntity.Id);
service.Create(followup);
That is all!!You can relate this with several 1:n relationships that you have in CRM 2013.
Cheers!!
Scenario:
The social buzz is on!! Have you tried the latest Yammer integrated with Microsoft CRM 2013? Did you ever try configuring Yammer with CRM of two different domains? If you faced difficulties in this scenario this post will help you out to meet the requirement!!
Configuration Steps:
That is all!! Now you are good to configure Yammer and CRM with separate domains!!
Alright….. Let me tell you what you are going to get by reading this post.
Are you folks are aware of the fact that you can create Windows Azure active directory users? I would like to introduce how CRM online users can be synched with your Azure directory. Thanks to Siddharth for helping in this context.
Following is the step by step procedure to achieve this requirement:
1) Login to your Windows Azure portal from the following URL:
http://portal.windowsazure.com/
2) After logging into the portal you can see the following in the left hand side of the portal:
3) Now click on the Active Directory available at the bottom of the portal in the left hand pane. After clicking on Active Directory you can click on Add + symbol available at the bottom of the page to add a new or an existing user as shown below. Click on Use Existing Directory to add the office 365 users into this Windows Azure.
4) Now click on the check box “I am ready to be signed out now.” and hit on the tick mark shown below:
5) Now you will be prompted to enter username and password. This username and password can be the credentials which you enter to login Dynamics CRM online application. This can be your onmicrosoft.com account or your domain account. After logging into the portal you can see the following screen based on your organization name:
6) Click on continue in the above screen. This will make your account as global administrator of the domain account.
7) After that you get an option to Sign out now from the portal. Then go back to your url https://portal.windowsazure.com and login with your windows azure account credentials.
8) After logging in and navigating to Active Directory you can see all the new users being shown in the portal.
That is all!!! This is how simple it is to add the CRM online users to Windows Azure AD. I am also working on implementing single sign on by using these users. Hopefully you can that post very soon.
With the latest update of CRM 2011 we have compatibility with SQL 2012 server. I have got a chance to install CRM application on top of SQL 2012. If you are successful in installing CRM then trying to configure Reporting Extensions for CRM you might encounter the following error:
"Installation of Microsoft Visual C++ Runtime failed. Exit code: 5100"
After we get this error it is our usual understanding that Visual C++ Runtime is failed to install. If you can already see the Visual C++ runtime in the programs and features of your computer then that is the one which is installed by SQL server 2012. If your CRM setup which is running is an old one it doesn't support the latest version of C++ runtime.
To avoid this you can go download the latest CRM setup from the following location:
http://www.microsoft.com/en-us/download/details.aspx?id=27822
After downloading the file and extracting everything you will be able to see a folder named: "SrsDataConnector". This will help you in installing and configuring Reporting Extensions for CRM 2011 with SQL 2012.
Hope this helps!!!
Enjoy reporting with Dynamics CRM with SQL 2012.
Hello Folks,
After a long time I am coming up with a new post. I have been researching a lot on pushing a new post into my blog. Finally I have decided to write about the simplified connection to Microsoft Dynamics CRM 2011.
If you have downloaded the latest CRM sdk the connection to CRM application is simplified. Now you just have to pass your Connection String parameters in your configuration file. In your code we can leverage the connection string and connect to CRM application. Following are the steps which you need to leverage the simplified connection string.
1) Add a config file in your custom application with the following values:
<?xml version="1.0"?> <configuration> <connectionStrings> <!-- Online using Office 365 --> <!-- <add name="Server=CRM Online, organization=contoso, user=someone" connectionString="Url=https://contoso.crm.dynamics.com; Username=someone@contoso.onmicrosoft.com; Password=password;"/> --> <!-- Online using Windows Live ID --> <!-- <add name="Server=CRM Online, organization=contoso, user=someone@hotmail.com" connectionString="Url=https://contoso.crm.dynamics.com; Username=someone@hotmail.com; Password=password; DeviceID=11hfn41bbqrg580vyvoea05abc; DevicePassword=fuqNIlx%e$.l*+ax_#8O4abc;"/>--> <!-- On-premises with provided user credentials --> <!-- <add name="Server=myserver, organization=AdventureWorksCycle, user=administrator" connectionString="Url=http://myserver/AdventureWorksCycle; Domain=mydomain; Username=administrator; Password=password;"/> --> <!-- On-premises using Windows integrated security --> <!--<add name="Server=myserver, organization=AdventureWorksCycle" connectionString="Url=http://myserver/AdventureWorksCycle;"/>--> <!-- On-Premises (IFD) with claims --> <!--<add name="Server=litware.com, organization=contoso, user=someone@litware.com" connectionString="Url=https://contoso.litware.com; Username=someone@litware.com; Password=password;"/>--> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration>
2) This connection string can be leveraged either for all types of CRM connections. If you are connecting to CRM online, you need to get the Device ID and Device Password. They can be generated using the Device Registration tool available in your CRM SDK. This tool is available in the tools folder of CRM sdk named "Device Registration". To register your device and generate the Device credentials following is the command Prompt:
deviceregistration.exe /operation:Register
3) After passing all the configuration details in your application. You need to leverage them in your code as shown in the below code:
// Obtain connection configuration information for the Microsoft Dynamics // CRM organization web service. String connectionString = GetServiceConfiguration();
4) Now let us see the GetServiceConfiguration function definition:
/// <summary> /// Gets web service connection information from the app.config file. /// If there is more than one available, the user is prompted to select /// the desired connection configuration by name. /// </summary> /// <returns>A string containing web service connection configuration information.</returns> private static String GetServiceConfiguration() { // Get available connection strings from app.config. int count = ConfigurationManager.ConnectionStrings.Count; // Create a filter list of connection strings so that we have a list of valid // connection strings for Microsoft Dynamics CRM only. List<KeyValuePair<String, String>> filteredConnectionStrings = new List<KeyValuePair<String, String>>(); for (int a = 0; a < count; a++) { if (isValidConnectionString(ConfigurationManager.ConnectionStrings[a].ConnectionString)) filteredConnectionStrings.Add (new KeyValuePair<string, string> (ConfigurationManager.ConnectionStrings[a].Name, ConfigurationManager.ConnectionStrings[a].ConnectionString)); } // No valid connections strings found. Write out and error message. if (filteredConnectionStrings.Count == 0) { Console.WriteLine("An app.config file containing at least one valid Microsoft Dynamics CRM " + "connection string configuration must exist in the run-time folder."); Console.WriteLine("\nThere are several commented out example connection strings in " + "the provided app.config file. Uncomment one of them and modify the string according " + "to your Microsoft Dynamics CRM installation. Then re-run the sample."); return null; } // If one valid connection string is found, use that. if (filteredConnectionStrings.Count == 1) { return filteredConnectionStrings[0].Value; } // If more than one valid connection string is found, let the user decide which to use. if (filteredConnectionStrings.Count > 1) { Console.WriteLine("The following connections are available:"); Console.WriteLine("------------------------------------------------"); for (int i = 0; i < filteredConnectionStrings.Count; i++) { Console.Write("\n({0}) {1}\t", i + 1, filteredConnectionStrings[i].Key); } Console.WriteLine(); Console.Write("\nType the number of the connection to use (1-{0}) [{0}] : ", filteredConnectionStrings.Count); String input = Console.ReadLine(); int configNumber; if (input == String.Empty) input = filteredConnectionStrings.Count.ToString(); if (!Int32.TryParse(input, out configNumber) || configNumber > count || configNumber == 0) { Console.WriteLine("Option not valid."); return null; } return filteredConnectionStrings[configNumber - 1].Value; } return null; }
5) This connection string can be leveraged to connect to CRM application. Following is the code to leverage the connection string and establish a connection to CRM.
// Establish a connection to the organization web service using CrmConnection. Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse (connectionString);
6) Now as we have established the connection we can leverage it to create records into CRM application. Following is the code to achieve that:
private OrganizationService _orgService; // Obtain an organization service proxy. // The using statement assures that the service proxy will be properly disposed. using (_orgService = new OrganizationService(connection) ) { Entity account = new Entity("account"); account["name"] = "Contoso"; _orgService.Create(account); }
That is it!!! Now connecting to CRM is quite easy. Enjoy!!!
This post will help you guys to create records on behalf of another user in CRM 2011. Well are you thinking what is the advantage of doing this and how different is this from normal import?
Certainly there is an advantage if you want to create records on behalf of another user. The created by field will be updated by the name of the user whom you want to use instead of using your own name. This leads to the concept of impersonation in CRM 2011.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); // Retrieve the system user ID of the user to impersonate. OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); _userId = (from user in orgContext.CreateQuery<SystemUser>() where user.FullName == "FirstName LastName" select user.SystemUserId.Value).FirstOrDefault(); // To impersonate another user, set the OrganizationServiceProxy.CallerId // property to the ID of the other user. _serviceProxy.CallerId = _userId; Entity contact = new Entity("contact"); contact["firstname"] = "Vishnu"; contact["lastname"] = "Nandan"; Guid contactId = _serviceProxy.Create(contact); }
In this code we will update the callerid in the serviceProxy with the userid that you want to impersonate.
This will help you to create records on behalf of another user.
Cheers!!!
Trying to generate an early bound class in CRM 2011 online?? If yes is the answer this post will definitely help you out in meeting the requirement.
1) Before generating an early bound class you will have to make sure that the device is registered to connect to online CRM.
2) To make your device registered to connect to online CRM. You can just navigate to the Device Registration folder which is present in the tools folder of the SDK. In the Device registration folder just navigate to the bin/debug folder where you can find the deviceregistration.exe. Make sure you copy the path of the device registration application.
3) Now open the command prompt and paste the path to navigate to the location where DeviceRegistration.exe is present.
4) To register the device write the following command in the command prompt.
5) This will display the Device ID and Device Password which will be helpful for you to generate an early bound class in CRM online.
Note: If the device is already registered the application will throw an error saying the device is already registered.
6) After registering your device you can go ahead and generate an early bound class. To generate an early bound class you just have to navigate to the bin folder in the sdk. In the bin folder you have the crmsvcutil.exe file which will help you in generating the early bound class.
7) Now navigate to the crmsvcutil.exe folder location in the command prompt. In this location you can write the following code to generate the early bound class.
CrmSvcUtil.exe /url:https://dev.crm.dynamics.com/XRMServices/2011/Organization.svc /out: C:\GeneratedCode.cs /username:USERNAME /password: "********" / deviceid:”11mqqaku9s6usrnh52gn4fm75o” /devicepasswordXZo!O35,JF^/`n#tKO^iwj/B”)
8) In the above command url will be the url of the Organization.svc available in your developer resources in CRM. out will be the name of the output file name which is going to be generated. username and password will be the credentials which you will connect with CRM. DeviceId and DevicePassword will be the one which you have generated in our earlier step.
9) After running this command you will be able to see the code being generated.
Cheers!!!!
Are you not able to find the Windows Identity Foundation in your Windows 8 Operating System?? If yes is the answer this post will help you in locating the Windows Identity Foundation in your machine.
Following are the steps to get the Windows Identity Foundation
1) Navigate to Control Panel you will be able to find the window as shown in the below screen. 2) Now click on Programs and Features to Turn Windows Features on or off.
3) In the programs and features screen you will be able to Turn Windows Features on or off as shown in the below screenshot.
4) After clicking on the Windows Features on or off in the left navigation pane. You can see one new window being opened as shown in the below screenshot which will help you in adding the Windows Identity Foundation to your machine.
5) After clicking on OK you can see the status of the installation and after that you are done.
6) You are now done with adding Windows Identity Foundation in your machine.
Tired of the normal screensavers running in your machine?? Want to create your own screensaver?? If you are still thinking of how to do it. This post will help you in meeting the requirement.
Requirements:
Visual Studio 2010
Windows Operating System.
1) Open your visual studio and create a new project. In your installed templates look for Windows Form Application and click on OK.
2) Rename the form as per your need let us say screensaver
3) In the form designer you can go ahead and add the controls as per your requirement. In this sample we will just add one label, timer control.
4) In the main method you should ensure that we get parameters for the main function as shown in the below code.
static void Main(string[] args) { if (args.Length > 0) { if (args[0].ToLower().Trim().Substring(0,2) == "/c") { MessageBox.Show("No parameters are passed"); } else if (args[0].ToLower() == "/s") { for (int i = Screen.AllScreens.GetLowerBound(0); i <= Screen.AllScreens.GetUpperBound(0); i++) System.Windows.Forms.Application.Run(new ScreenSaverForm(i)); } } else { for (int i = Screen.AllScreens.GetLowerBound(0); i <= Screen.AllScreens.GetUpperBound(0); i++) System.Windows.Forms.Application.Run(new ScreenSaverForm(i)); } }
5) After making modification in the main method. We should copy the initialize component in the designer.cs file.
6) Now delete the designer.cs file and paste the initialize component method form1.cs/screensaver.cs file which you have used.
7) In the screensaver.cs/form1.cs file you can paste the following code.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace NewScreenSaver { public partial class ScreenSaver : Form { private System.ComponentModel.IContainer components; private Label label1; private Timer timer2; private Point MouseXY; private int ScreenNumber; private int xPos = 0, YPos = 0; private ImageList imageList1; private Button button1; public string mode = "LR"; public ScreenSaver(int i) { InitializeComponent(); ScreenNumber = i; } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private void ScreenSaver_Load(object sender, EventArgs e) { xPos = label1.Location.X; YPos = label1.Location.Y; mode = "LR"; timer2.Start(); this.Bounds = Screen.AllScreens[ScreenNumber].Bounds; Cursor.Hide(); TopMost = true; } private void OnMouseEvent(object sender, System.Windows.Forms.MouseEventArgs e) { if (!MouseXY.IsEmpty) { if (MouseXY != new Point(e.X, e.Y)) Close(); if (e.Clicks > 0) Close(); } MouseXY = new Point(e.X, e.Y); } private void ScreenSaver_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { Close(); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.label1 = new System.Windows.Forms.Label(); this.timer2 = new System.Windows.Forms.Timer(this.components); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Silver; this.label1.Font = new System.Drawing.Font("Vivaldi", 100F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.SystemColors.MenuHighlight; this.label1.Location = new System.Drawing.Point(31, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(894, 159); this.label1.TabIndex = 0; this.label1.Text = "My Screensaver."; // // timer2 // this.timer2.Tick += new System.EventHandler(this.timer2_Tick); // // imageList1 // this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.imageList1.ImageSize = new System.Drawing.Size(16, 16); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // button1 // this.button1.Location = new System.Drawing.Point(39, 17); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; // // ScreenSaver // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.HotPink; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(995, 551); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "ScreenSaver"; this.Text = "ScreenSaver"; this.TransparencyKey = System.Drawing.Color.Red; this.Load += new System.EventHandler(this.ScreenSaver_Load); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ScreenSaver_KeyDown); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.OnMouseEvent); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.OnMouseEvent); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void timer2_Tick(object sender, EventArgs e) { if (this.Width == xPos) { //repeat marquee this.label1.Location = new System.Drawing.Point(0, YPos); xPos = 0; } else { this.label1.Location = new System.Drawing.Point(xPos, YPos); xPos += 2; } } } }
8) In the above code the initialize component will be the same as the one which you have copied from your designer.cs file.
9) After making all the modifications build your application. After building your application you can go to the exe file located in the debug/release folder.
10) Rename the exe file to scr.
11) After renaming the file you can go ahead and right click the file and click on install.
Cheers!! now you will be able to see your screensaver file.
Note: This code is just for testing purpose and should be not be used in your normal working environment.
Ever tried adding a checkbox in the CRM ribbon form? This post will be helpful for that requirement.
Requirement:
a) Adding a checkbox in the contact entity in CRM form ribbon.
b) An action will be triggered when the checkbox is checked in the ribbon form.
Prerequisites:
a) Solution needs to have the a javascript web resource
i) The name of the javascript web resource is sample_Trigger which will trigger when the checkbox is checked. Following is the function which you can write in the javascript file.
Function trigger()
alert("Check box is checked");
Steps to achieve the requirement:
1) Navigate to Settings- Solutions and click on new solution which will open a new window as shown in the below figure
2) Click on the save button and add the existing contact entity which will add the contact entity. If you want to import the solution back into the same organization then you can include missing required components. Other component which you should add for this solution is a javascript file of name ‘sample_Trigger’ as shown in the below figure.
3) After adding the required entities into the solution export the solution to make modifications as per the requirement. This will open a compressed file which includes three xml files Content_Types.xml, customizations.xml, solution.xml and a webresources folder.
4) Our aim is to do some custom action in the form ribbon. In order to achieve that requirement we need to modify the customizations.xml file. Modify the ribbondiffxml tab by replacing it with the following code.
<RibbonDiffXml>
<CustomActions>
<CustomAction Id="MyISV.contact.grid.trigger.CustomAction" Location="Mscrm.HomepageGrid.contact.MainTab.Collaborate.Controls._children" Sequence="41">
<CommandUIDefinition>
<CheckBox Command="MyISV.contact.form.trigger.Command" Id="MyISV.contact.form.trigger.Button" LabelText="$LocLabels:MyISV.contact.trigger.LabelText" TemplateAlias="o2" ToolTipDescription="$LocLabels:MyISV.contact.trigger.ToolTip" ToolTipTitle="$LocLabels:MyISV.contact.trigger.LabelText" />
</CommandUIDefinition>
</CustomAction>
<CustomAction Id="MyISV.contact.form.trigger.CustomAction" Location="Mscrm.Form.contact.MainTab.Collaborate.Controls._children" Sequence="33">
</CustomActions>
<Templates>
<RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
</Templates>
<CommandDefinitions>
<CommandDefinition Id="MyISV.contact.grid.trigger.Command">
<EnableRules>
<EnableRule Id="MyISV.contact.WebClient.EnableRule" />
<EnableRule Id="MyISV.contact.grid.OneSelected.EnableRule" />
</EnableRules>
<DisplayRules>
<DisplayRule Id="MyISV.contact.WebClient.DisplayRule" />
</DisplayRules>
<Actions>
<JavaScriptFunction Library="$webresource:sample_Trigger" FunctionName="trigger" />
</Actions>
</CommandDefinition>
<CommandDefinition Id="MyISV.contact.form.trigger.Command">
<EnableRule Id="MyISV.contact.form.NotNew.EnableRule" />
<DisplayRule Id="MyISV.contact.form.FormStateNotNew.DisplayRule" />
</CommandDefinitions>
<RuleDefinitions>
<TabDisplayRules />
<DisplayRule Id="MyISV.contact.form.FormStateNotNew.DisplayRule">
<FormStateRule State="Create" InvertResult="true" />
</DisplayRule>
<DisplayRule Id="MyISV.contact.WebClient.DisplayRule">
<CrmClientTypeRule Type="Web" />
<EnableRule Id="MyISV.contact.WebClient.EnableRule">
</EnableRule>
<EnableRule Id="MyISV.contact.form.NotNew.EnableRule">
<EnableRule Id="MyISV.contact.grid.OneSelected.EnableRule">
<SelectionCountRule AppliesTo="SelectedEntity" Maximum="1" Minimum="1" />
</RuleDefinitions>
<LocLabels>
<LocLabel Id="MyISV.contact.trigger.LabelText">
<Titles>
<Title languagecode="1033" description="Trigger an action" />
</Titles>
</LocLabel>
<LocLabel Id="MyISV.contact.trigger.ToolTip">
</LocLabels>
</RibbonDiffXml>
5) After making modifications in the customizations.xml file compress the "Customizations.xml", "Solutions.xml", "Content-Types.xml" and the Webresources folder which includes the javascript file sample_trigger. Import the compressed zip file back into the CRM organization and publish all the customizations.
6) This will create a checkbox in the form ribbon and trigger an action when the checkbox is checked.
CRM 2011 has introduced a new concept called field level security. Whenever you create a secured field you will automatically get the secured key being shown just next to it. Can this be avoided?? Imagine a case where you do not want to show your employees that the field is a secured field. In that case this post will help to meet the requirement...
This post will help you to hide the secured key symbol for a secured field in the contact entity.
Following are the steps to be followed
1) Navigate to Settings - Customization - Customize the system. It will open a form as shown in the below figure.
2) Now expand the entities and click on the forms section as shown in the below figure.
3) Open the main form which will open the main form of the contact entity as shown in the below figure.
4) Now create a new field by clicking the on the New Field button at the bottom right as shown in the below figure.While creating the new field Enable the Field Security as shown in the below figure.
5) After creating the field place the field in the form as shown in the below figure.
6) Now our target is to hide the key symbol next to the Secured Field. This can be achieved by writing a code snippet in the form load. To achieve the same open the form and click on the form properties as shown in the below figure.
7) Now edit the library and place the following script in the form load function.
crmForm.all.sample_securedfield_c.innerText=”Custom Field”;
8) This will remove the key symbol and show the "Custom Field" label when the contact form loads.
Placing Dynamic Contact Image in CRM Form:This post explains you how to keep image for every contact. When you just use web resource to add contact image you have the problem of having the same image for each and every contact. To make a workaround for this we can have dynamic images for each contact. Let us say you have different contacts available for your organization and for each of them you have to add an image, this concept will be perfect to resolve the issue.Prerequisites:To achieve this requirement you should have a unique field in the contact entity. When you are creating a new contact, you should also create a new web resource of type image with name same as the unique field of the contact. This will help to dynamically generate images for each and every contact available in your organization. Step 1: Add an image web resource with the unique name of the contact record that is created as shown in the below figure. Web resources can be found when you click on Customizations - Customize the system as shown in the below figure.
Now click on the new button to add the web resource and select the type of the web resource as JPG as shown in the below figure. Also the remember the name of the web resource should be prefixed with the unique name of the contact record as shown in the below image.
For ex:You have a unique name of the contact field as "ContactId". The value of Contactid is "1234". The name of the web resource which should be created is new_1234 where "new" is the attribute prefix.Step 2: After entering all the values in the web resource save the record. As soon as you save the record the url of the web resource can be found as shown in the below image.
Step 3:Now add an iframe to contact form as shown in the below image and place the url of the iframe as "about:blank". This url will dynamically be changed to the web resource url in the next steps. In the iframe properties uncheck the checkbox "Restrict Cross Frame Scripting".
Step 4:Now navigate to the form properties of the contact entity and add the following script.var contactLogo = "https://orgname.crm.dynamics.com//WebResources/new_" + Xrm.Page.getAttribute("new_uniquefield").getValue();Xrm.Page.getControl("IFRAME_contactimage").setSrc(contactLogo);In this new_uniquefield will be the contact unique field which is created and IFRAME_contactimage will be the name of the iframe which you give while creating the iframe.