Menu Close

Author: uk365guy

PLUGIN STEP BY STEP MS CRM 2O13

For the scope of this article, I assume that you are familiar with C# OOP concepts and C# projects.
  • We will create a plug-in in the C# Class library, you can also use a portable class library.
  • Add a class library project into the C# solution and name your class “MyDynamicPlugin”. 


  • Now add references to the 2 DLLs. 

    • Microsoft.Crm.Sdk.Proxy.dll
    • Microsoft.Xrm.Sdk.dll
  • And you will find both of the DLLs in the SDK/bin folder of your Microsoft SDK. 
  • And inherit the IPlugin interface. 

    create IPlugin
  • Implement the IPlugin Interface and you will get an Execute method with the IserviceProvider interface object as a parameter.
  • Execute method: This method runs as an entry point for any plugin in Microsoft Dynamic CRM.
  • IserviceProvider interface: This interface provides access to various services of dynamic, this interface has a method called GetService() that uses the reflection feature of .NET and allows us to get any type of service we want. 

    cs code
  • This Execute method is all the code you need to fire before or after any event occurred.
Let’s see how 
For this article I will create a default Contact whenever anyone creates an account.

For example, If an employee of an organization creates an account then a default contact with basic details should be added to that account automatically (using a plug-In).

Procedure

Step 1
Since we need to trigger our plug-in when an event is executed, we need to get the service of IPluginExecutionContext using the IServiceProvider object.
  1. IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));  
And the GetService method returns an object of the specified type. We need to type caste that object. 

Step 2
Plugin execution is an object with a property called InputParameter. 
  • Using this Inputparamter we can get the entity and other types of dynamic CRM. 
  • Target is one of the main parameters of this IPluginExecutionContext object.
  • All the plug-in events are first stored in this variable called “Target”.
  • So when any events occur we need to check if this variable is there in our current context execution.
  • And if so then we need to check if it’s an entity. Because for this article we will trigger a plug-in if a new account (Entity) is created.
Entity

Step 3
Now when you know, we have a value in the target and it’s an Entity. 

We can typecast it into an Entity and using its logicalname property we can determine if the current executing event is for an account Entity or not.

And if it’s an account entity we can write our creation of contact code here and associate that contact with the currently executing account.

executing account

Step 4: The last step is to create an Organizationservicefactory instance and we need to create a new plug-in, add a pluginexecutioncontext object ID to create an Organization service and based on that service client we can create our custom Event. 
  1. IOrganizationServiceFactory servicefactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));  
  2. IOrganizationService client = servicefactory.CreateOrganizationService(context.UserId);   
  3. client.Create(createcontact);  

Your Microsoft Dynamic CRM plug-in is created. 

This is the sample code, you can find the attachment of this code with my article. 

code

Build your Project. 

Important Step 
Once you build your project, you need to generate a key that will act as certificate for your plug-in. Without this key you cannot deploy a plug-in onto a server. 

To create a key, go to project property (ALT+ Enter) and go to the signing tab and check sign the assembly. 

Select new in the drop down and add a key name and your dynamic CRM Password. And select save (CTRL+ S).

If you have done this then it will add a pfx encrypted key for your current project. 

Rebuild your project 
Procedure to deploy this assembly using SDkToolsPluginRegistrationPluginRegistration.exe.

Step 1 

  • Run it and Click Create New connection,
  • Enter your Login Credentials for Connection with Dynamic CRM.
  • The first time you login, you need to pass all the details of your CRM Account.
Step 2
After logging in successfully, click Register > Register New Assembly.

Register New Assembly

Browse to the DLL you just created and click OK. 

Step 3
  • Now we need to add steps of this DLL execution.
  • So select the assembly and again click Register > Register new Steps.
  • Or just right-click the assembly you just added and select Register new Steps.

    Register New
This Window includes an option for how and when you want to execute or fire your assembly or plug-in. 

Message: It defines on which event you want to run the plug-in.

Example: Create.

Primary Entity: It define on which Entity execution you want to run the plug-in.

Example: account.

Event pipeline stage of Execution: It defines when you want to run the DLL, before the core operations or after the core operations.

Execution Mode:
 Execution can be synchronous by default or can be asynchronous (that will be handled further by the Dynamic CRM Queue manager).

Deployment: Server where every plug-in is deployed.

Offline where you can deploy it on Outlook for offline use. 

Click Register New Step and whoo, it’s done.

Your assembly or plug-in is deployed on the server. Now go to Dynamic CRM and create an account, an automated contact will be added by default in that account without any manual entry from employees. 
Share this:

MALWARE CLICKEU.TRACTIONIZE.COM

Remove Clickeu.tractionize.com pop-up ads (Removal Guide)

If you are seeing random pop-up ads from Clickeu.tractionize.com within Internet Explorer, Firefox and Google Chrome, then your computer is infected with an adware or a potentially unwanted program.
Clickeu.tractionize.com pop-up virus
Clickeu.tractionize.com virus
The Clickeu.tractionize.com pop-up ad happens regardless of the web browser or search engine, and if you are seeing ads from Clickeu.tractionize.com whenever you are doing a Google search or clicking on a link, then your computer may be infected with adware or a potentially unwanted program. This infection is designed specifically to make money. It generates web traffic, collects sales leads for other dubious sites, and will display advertisements and sponsored links within your web browser.
The Clickeu.tractionize.com advertisments are caused by an ad-supported (users may see additional banner, search, pop-up, pop-under, interstitial and in-text link advertisements) cross web browser plugin for Internet Explorer, Firefox and Chrome, which is distributed through various monetization platforms during installation. The malicious browser extensions is typically added when you install another free software (video recording/streaming, download-managers or PDF creators) that had bundled into their installation this adware program.
When an adware extension is installed on your computer, whenever you will open a new tab within Internet Explorer, Firefox and Google Chrome, an ad from Clickeu.tractionize.com will pop-up. This infection will also display advertising banners on the web pages that you are visiting, and as you browse Internet, it will show coupons and other deals available on different websites.
Clickeu.tractionize.com is not a malicious domain itself, however cyber criminals are using an adware program to display ads from this domain, thus getting pay-per-click revenue.
You should always pay attention when installing software because often, a software installer includes optional installs, such as this program that is causing the Clickeu.tractionize.com redirect. Be very careful what you agree to install.
Always opt for the custom installation and deselect anything that is not familiar, especially optional software that you never wanted to download and install in the first place. It goes without saying that you should not install software that you don’t trust.

How to remove Clickeu.tractionize.com pop-up ads (Virus Removal Guide)

This page is a comprehensive guide, which will remove Clickeu.tractionize.com pop-ups from your computer, and any other adware program that may have been installed during the the setup process.
Please perform all the steps in the correct order. If you have any questions or doubt at any point,STOP and ask for our assistance.
STEP 1: Uninstall the adware program that is responsible for the Clickeu.tractionize.com pop-up ads
STEP 2: Remove “Clickeu.tractionize.com” pop-up ads from Internet Explorer, Firefox and Google Chrome
STEP 3: Remove “Clickeu.tractionize.com” adware with AdwCleaner
STEP 4: Remove “Clickeu.tractionize.com” pop-up virus with Malwarebytes Anti-Malware Free
STEP 5: Double-check for the “Clickeu.tractionize.com” infection with HitmanPro

STEP 1: Uninstall the adware program that is responsible for the Clickeu.tractionize.com pop-up ads

In this first step, we will try to identify and remove any malicious program that might be installed on your computer.
  1. To uninstall a program from Windows XP, Windows Vista or Windows 7, click the “Start” button, then click on the “Control Panel” menu option.
    [Image: Control Panel in Windows Start Menu]
    If you are using Windows 8, simply drag your mouse pointer to the right edge of the screen, select Search from the list and search for “control panel” .Or you can right-click on a bottom left hot corner (formerly known as the Start button) and select Control Panel from there.
    [Image: Type Control Panel in Windows 8 search box]
  2. When the “Control Panel” window opens click on the “Uninstall a program” option under “Programs” category. This option is shown by the arrow in the image below. If you are using the “Classic View” of the Control Panel, then you would double-click on the “Programs and Features” icon instead.
    [Image: Uninstall a program]
  3. When the “Programs and Features” or the “Uninstall a Program” screen is displayed, scroll through the list of currently installed programs and uninstall Discount Cow, V-bates, PriceMeter,Supra Savings, weDownload Manager, PureLead, Search Assist, Re-Markable, Zombie Alert,Wajam, Coupon Server, Lollipop, HD-Total-Plus, BlockAndSurf, Safe Saver, SupTab, Search Protect, Lollipop, Software Updated Version, DP1815, Video Player, Convert Files for Free, Plus-HD 1.3, BetterSurf, Trusted Web, PassShow, LyricsBuddy-1, PureLeads, Media Player 1.1,RRSavings, Feven Pro 1.2, Websteroids, Savings Bull, TidyNetwork, Search Snacks, MyPC BackupRe-markit and any other recently installed unknown program from your computer.To view the most recently installed programs, you can click on the “Installed On” column to sort your program by the installation date. Scroll though the list, and uninstall any unwanted or unknown programs.
    [Image: Uninstall Clickeu.tractionize.com from Windows]
    Depending on what program has installed the Clickeu.tractionize.com adware infection, the above program may have a different name or not be installed on your computer. If you cannot find any unwanted or unknown programs on your machine, then you can proceed with the next step.
If you are having issues while trying to uninstall the Clickeu.tractionize.com program, you can useRevo Uninstaller to completely remove this unwanted program from your machine.

STEP 2: Remove “Clickeu.tractionize.com” pop-up ads from Internet Explorer, Firefox and Google Chrome

Remove Clickeu.tractionize.com pop-up ads from Internet Explorer

You can reset Internet Explorer settings to return them to the state they were in when Internet Explorer was first installed on your PC.
  1. Open Internet Explorer, click on the “gear icon [Image: icongear.jpg] in the upper right part of your browser, then click again on Internet Options.
    [Image: Internet Options in Internet Explorer]
  2. In the “Internet Options” dialog box, click on the “Advanced” tab, then click on the “Reset” button.
    [Image: Reset Internet Explorer]
  3. In the “Reset Internet Explorer settings” section, select the “Delete personal settings” check box, then click on “Reset” button.
    [Image: Reset Internet Explorer to its default settings to remove Clickeu.tractionize.com popup]
  4. When Internet Explorer has completed its task, click on the “Close” button in the confirmation dialogue box. You will now  need to close your browser, and then you can open Internet Explorer again.
    [Image Reset Internet Explorer settings]

Remove Clickeu.tractionize.com pop-up ads from Mozilla Firefox

If you’re having problems with Firefox, resetting it can help. The reset feature fixes many issues by restoring Firefox to its factory default state while saving your essential information like bookmarks, passwords, web form auto-fill information, browsing history and open tabs.
  1. In the upper-right corner of the Firefox window, click the Firefox menu button ([Image: Firefox Menu button]), then click on the “Help” ([Image: Firefox Help button]) button.
    [Image: Click on the Menu button then Help]
  2. From the Help menu, choose Troubleshooting Information.
    If you’re unable to access the Help menu, type about:support in your address bar to bring up the Troubleshooting information page.
    [Image: Troubleshooting Information in Firefox]
  3. Click the “Reset Firefox” button in the upper-right corner of the “Troubleshooting Information” page.
    [Image: Reset Firefox to its default settings]
  4. To continue, click on the “Reset Firefox” button in the new confirmation window that opens.
    [Image: Click on the Reset Firefox button]
  5. Firefox will close itself and will revert to its default settings. When it’s done, a window will list the information that was imported. Click on the “Finish“.
Note: Your old Firefox profile will be placed on your desktop in a folder named “Old Firefox Data“. If the reset didn’t fix your problem you can restore some of the information not saved by copying files to the new profile that was created. If you don’t need this folder any longer, you should delete it as it contains sensitive information.

Remove Clickeu.tractionize.com pop-up ads from Google Chrome

  1. Click on the “Chrome menu button” (Chrome menu)  on the browser toolbar, select “Tools“, and then click on “Extensions“.
    [Image: Extensions menu in Chrome]
  2. In the “Extensions” tab, remove the HD-Total-Plus, SafeSaver, DP1815, Video Player, Convert Files for Free, Plus-HD 1.3, BetterSurf, Media Player 1.1, PassShow, LyricsBuddy-1,YClickeu.tractionize.com 1.2, Media Player 1.1, Savings Bull, Feven Pro 1.1, Websteroids,Savings Bull, HD-Plus 3.5 any other unknown extensions by clicking the trash can [Image: Remove an extension from Chrome] icon.
    Basically, if you have not installed an extensions then you should remove it from your web browser.
    If you cannot remove the Clickeu.tractionize.com extension, and under the trash can you can see the “Installed by enterprise policy” text, then you will need to follow our “Remove Installed by enterprise policy extension from Chrome” guide.
    [Image: Remove Clickeu.tractionize.com Chrome extensions]

STEP 3: Remove “Clickeu.tractionize.com” adware with AdwCleaner

The AdwCleaner utility will scan your computer and web browser for malicious files, adware browser extensions and registry keys, that may have been installed on your computer without your knowledge.
  1. You can download AdwCleaner utility from the below link.
    ADWCLEANER DOWNLOAD LINK (This link will open a new web page from where you can download “AdwCleaner”)
  2. Before starting AdwCleaner, close all open programs and internet browsers, then double-click on the AdwCleaner icon.
    AdwCleaner Icon
    If Windows prompts you as to whether or not you wish to run AdwCleaner, please allow it to run.
  3. When the AdwCleaner program will open, click on the “Scan” button as shown below.
    Click on Scan button to find Clickeu.tractionize.com virus
    AdwCleaner will now start to search for the “Clickeu.tractionize.com” malicious files that may be installed on your computer.
  4. To remove the “Clickeu.tractionize.com” malicious files that were detected in the previous step, please click on the “Clean” button.
    Remove Clickeu.tractionize.com virus with AdwCleaner
  5. AdwCleaner will now prompt you to save any open files or documents, as the program will need to reboot the computer. Please do so and then click on the OK button.
    AdwCleaner removing Clickeu.tractionize.com virus

STEP 4: Remove “Clickeu.tractionize.com” popup virus with Malwarebytes Anti-Malware Free

Malwarebytes Anti-Malware Free uses industry-leading technology to detect and remove all traces of malware, including worms, Trojans, rootkits, rogues, dialers, spyware, and more.
It is important to note that Malwarebytes Anti-Malware works well and should run alongside antivirus software without conflicts.
  1. You can download download Malwarebytes Anti-Malware from the below link.
    MALWAREBYTES ANTI-MALWARE DOWNLOAD LINK (This link will open a new web page from where you can download “Malwarebytes Anti-Malware”)
  2. Once downloaded, close all programs, then double-click on the icon on your desktop named “mbam-setup-consumer-2.00.xx” to start the installation of Malwarebytes Anti-Malware.
    [Image: Malwarebytes Anti-Malware setup program]
    Picture of User Account Control You may be presented with a User Account Control dialog asking you if you want to run this file. If this happens, you should click “Yes” to continue with the installation.
  3. When the installation begins, you will see the Malwarebytes Anti-Malware Setup Wizard which will guide you through the installation process.
    [Image: Malwarebytes Anti-Malware Setup Wizard]
    To install Malwarebytes Anti-Malware on your machine, keep following the prompts by clicking the “Next” button.
    [Image: Malwarebytes Anti-Malware Final Setup Screen]
  4. Once installed, Malwarebytes Anti-Malware will automatically start and you will see a message stating that you should update the program, and that a scan has never been run on your system. To start a system scan you can click on the “Fix Now” button.
    [Image: Click on the Fix Now button to start a scan]
    Alternatively, you can click on the “Scan” tab and select “Threat Scan“, then click on the “Scan Now” button.
    [Image: Malwarebytes Anti-Malware Threat Scan]
  5. Malwarebytes Anti-Malware will now check for updates, and if there are any, you will need to click on the “Update Now” button.
    [Image: Click on Update Now to update Malwarebytes Anti-Malware]
  6. Malwarebytes Anti-Malware will now start scanning your computer for the Clickeu.tractionize.com virus. When Malwarebytes Anti-Malware is scanning it will look like the image below.
    [Image: Malwarebytes Anti-Malware while performing a scan]
  7. When the scan has completed, you will now be presented with a screen showing you the malware infections that Malwarebytes’ Anti-Malware has detected. To remove the malicious programs that Malwarebytes Anti-malware has found, click on the “Quarantine All” button, and then click on the “Apply Now” button.
    [Image: Remove the malware that Malwarebytes Anti-Malware has found]
    Please note that the infections found may be different than what is shown in the image.
  8. Malwarebytes Anti-Malware will now quarantine all the malicious files and registry keys that it has found. When removing the files, Malwarebytes Anti-Malware may require a reboot in order to remove some of them. If it displays a message stating that it needs to reboot your computer, please allow it to do so.
    [Image: Malwarebytes Anti-Malware while removing Clickeu.tractionize.com popup virus]
    After your computer will restart, you should open Malwarebytes Anti-Malware and perform another “Threat Scan” scan to verify that there are no remaining threats

STEP 5: Double-check for the “Clickeu.tractionize.com” infection with HitmanPro

HitmanPro is a second opinion scanner, designed to rescue your computer from malware (viruses, trojans, rootkits, etc.) that have infected your computer despite all the security measures you have taken (such as anti-virus software, firewalls, etc.). HitmanPro is designed to work alongside existing security programs without any conflicts. It scans the computer quickly (less than 5 minutes) and does not slow down the computer.
  1. You can download HitmanPro from the below link:
    HITMANPRO DOWNLOAD LINK (This link will open a new web page from where you can download “HitmanPro”)
  2. Double-click on the file named “HitmanPro.exe” (for 32-bit versions of Windows) or “HitmanPro_x64.exe” (for 64-bit versions of Windows). When the program starts you will be presented with the start screen as shown below.
    [Image: HitmanPro start-up screen]
    Click on the “Next” button, to install HitmanPro on your computer.
    [Image: HitmanPro setup options]
  3. HitmanPro will now begin to scan your computer for Clickeu.tractionize.com malicious files.
    [Image: HitmanPro scanning for Clickeu.tractionize.com virus]
  4. When it has finished it will display a list of all the malware that the program found as shown in the image below. Click on the “Next” button, to remove Clickeu.tractionize.com virus.
    [Image: HitmanPro scan results]
  5. Click on the “Activate free license” button to begin the free 30 days trial, and remove all the malicious files from your computer.
    [Image: HitmanPro Activate Free License]

Your computer should now be free of the “Clickeu.tractionize.com” pop-up ads. If your current anti-virus solution let this infection through, you may want to consider purchasing the Premium version of Malwarebytes Anti-Malware to protect against these types of threats in the future, and perform regular computer scans with HitmanPro.
If you are still experiencing problems while trying to remove “Clickeu.tractionize.com” pop-up virus from your machine, please start a new thread in our Malware Removal Assistance forum
Share this:

BASIC PLUGIN STEPS IN MS CRM 2013

BASIC PLUGIN STEPS IN MS CRM 2011/2013/2015/2016

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace LeadRecordw
{
    public class Class1
    {

        public static void Read()
        {
            Entity account = new Entity(“account”);
            Entity cass = new Entity(“incident”);
            Entity account2 = new Entity();
            account2.LogicalName = “account”;



            // read the values from the entity (any entity which is defined)
            // read means, retrieve the entity’s fields name values from the entity is called as “reading” the values 
            account.Attributes.ContainsKey(“name”);
            string accname = account[“name”].ToString();

            DateTime date = (DateTime)account[“createdon”];
            DateTime date2 = Convert.ToDateTime(account2[“createdon”]);

            string accname1 = account2[“name”].ToString();
            //optionset
            OptionSetValue optname = (OptionSetValue)account[“new_accounttype”];
            //lookup
            EntityReference Parentaccount = (EntityReference)account[“parentaccountid”];
            string parentname = Parentaccount.LogicalName;
            Guid parentid = Parentaccount.Id;

            int age = (int)account[“new_age”];

            int age2 = Convert.ToInt32(account[“new_age”]);

        }

        public static void Write()
        {

            Entity contact = new Entity(“contact”);
            contact[“name”] = “abc”;
            contact[“new_age”] = 68;
            DateTime aa = new DateTime(1999, 12, 09);
            contact[“createdon”] = aa;

            contact[“createdon”] = new DateTime(1999, 12, 09);

            OptionSetValue ad = new OptionSetValue(12);
            contact[“new_accounttype”] = ad;
        }


        public static void Main()
        {
            Entity account = new Entity(“account”);

            string accname = account[“accountname”].ToString();

            Entity csd = new Entity(“incident”);
            csd[“incidentname”] = accname;

        }



        public static void read1()
        {
            Entity lead = new Entity(“lead”);
            Entity lead1 = new Entity();
            lead1.LogicalName = “lead”;

            string sub = lead1[“subject”].ToString();
            string name = lead1[“fullname”].ToString();
            string jobtitle = lead1[“jobtitle”].ToString();
            int businessphone = Convert.ToInt32(lead1[“telephone1”]);
            int mobilephone = Convert.ToInt32(lead1[“mobilephone”]);

            EntityReference parentaccountoflead = (EntityReference)lead1[“parentaccountid”];
            string parentaccount = lead1.LogicalName;
            Guid parentid = lead1.Id;

            string email = lead1[“email”].ToString();

            EntityReference parentcontact = (EntityReference)lead1[“parentcontactid”];
            string parentcont = lead1.LogicalName;
            Guid parentsid = lead1.Id;

            string companyname = lead1[“companyname”].ToString();
            string websiteurl = lead1[“websiteurl”].ToString();
            string address = lead1[“address1_composite”].ToString();
            string description = lead1[“description”].ToString();

            int annualrevenue = Convert.ToInt32(lead1[“revenue”]);
            int numbofemployyee = Convert.ToInt32(lead1[“numberofemployees”]);
            OptionSetValue industry = (OptionSetValue)lead1[“industrycode”];
            string SIC = lead1[“SIC”].ToString();

            EntityReference currency = (EntityReference)lead1[“transcationcurrencyid”];
            string curren = lead1.LogicalName;
            Guid currenid = lead1.Id;
        }


        public static void Write2()
        {
            Entity contact = new Entity(“contact”);
            contact[“fullname”] = “malla”;
            contact[“jobtitle”] = “MANAGER”;

            // here retrieve values from account entity then assign to contact entity fields.

            Entity account = new Entity(“account”);
            string accname = account[“name”].ToString();

            Entity contat = new Entity(“contact”);
            contat[“name”] = accname;
            //contact[“fullname”] = accname;

            DateTime date = new DateTime(2001, 12, 12);
            contat[“new_date”] = date;

            OptionSetValue acctype = new OptionSetValue(2);
            account[“new_accounttype”] = acctype;
        }


        public static void Main1()
        {
            // here iam assigning the contact field name companyname = lead field name parent account for lead 
            Entity contact = new Entity(“contact”);
            EntityReference compname = (EntityReference)contact[“parentcustomerid”];
            string companyname = contact.LogicalName;
            Guid companyid = contact.Id;

            Entity lead = new Entity(“lead”);
            lead[“parentaccountid”] = contact.Id;
        }

        public static void Read1()
        {
            Entity annotation = new Entity(“annotation”);
            // annotation[“createdby”] = “mallareddy”;

            Entity cad = new Entity();
            cad.LogicalName = “incident”;

            DateTime date = (DateTime)cad[“new_date”];

            Entity cad1 = new Entity(“incident”);
            int casid = Convert.ToInt32(cad1[“caseid”]);
            string casename = cad1[“casename”].ToString();

            OptionSetValue caseoption = (OptionSetValue)cad1[“caseoption”];

            EntityReference caserefer = (EntityReference)cad1[“casereference”];
            string casefer = cad1.LogicalName;
            Guid caseferid = cad1.Id;

        }

        public static void Write3()
        {
            Entity account = new Entity(“account”);
            account[“name”] = “kashmir”;
            account[“address1”] = “london”;

            OptionSetValue ad = new OptionSetValue(2);
            account[“new_accountype”] = ad;

            DateTime dat = new DateTime(2011, 12, 11);
            account[“createdon”] = dat;

        }

        public static void Main3()
        {
            Entity contact = new Entity(“contact”);
            string companyname = contact[“companyname”].ToString();

            Entity cass = new Entity(“incident”);
            cass[“casename”] = companyname;

        }
        public static void Read4()
        {
            Entity contact = new Entity(“contact”);
            Entity csd = new Entity();
            csd.LogicalName = “incident”;

            Entity activity = new Entity();
            activity.LogicalName = “activity”;


            Entity account = new Entity();
            string accname = account[“accountname”].ToString();
            int accno = Convert.ToInt32(account[“accountnumber”]);
            DateTime date = (DateTime)account[“new_date”];
            EntityReference companyname = (EntityReference)account[“companynameid”];
            OptionSetValue region = (OptionSetValue)account[“new_region”];
            bool gender = (bool)account[“new_gender”];

            EntityReference parentaccount = (EntityReference)account[“parentaccountid”];
            string parentaccountname = account.LogicalName;
            Guid parentaccountid = account.Id;
        }

        public static void Write6()
        {
            Entity acc = new Entity(“account”);
            acc[“accountname”] = “Malla reddy”;
            acc[“phone”] = 1234555;
            acc[“new_weburl”] = “www.excitech.co.uk”;

            Guid parentcusromerid = new Guid();
            EntityReference accparentid = new EntityReference();
            accparentid.Id = parentcusromerid;
            accparentid.LogicalName = “account”;
            acc[“parentaccountid”] = accparentid;




            OptionSetValue region = new OptionSetValue(5);
            acc[“new_region”] = region;

            DateTime dat = new DateTime(2001, 12, 03);
            acc[“new_date”] = dat;

        }

        public static void Main5()
        {
            Entity account1 = new Entity(“account”);
            DateTime createdon = (DateTime)account1[“createdon”];

            Entity lead = new Entity(“lead”);
            lead[“datecreatedlead”] = createdon;


            string accname = account1[“accountname”].ToString();
            lead[“leadname”] = accname;

            int accountnumber = Convert.ToInt32(account1[“accountnumber”]);
            lead[“leadnumber”] = accountnumber;
            //or
            lead[“leadnumber”] = Convert.ToInt32(account1[“accountnumber”]);

        }
        public static void Retrieve(Guid id, IOrganizationService service)
        {
            Entity account = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“accountname”));
            string accname = account[“accountname”].ToString();

            Entity account1 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“telephone1”));
            int phone = Convert.ToInt32(account[“telephone1”]);

            Entity account2 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“fax”));
            int fax1 = Convert.ToInt32(account[“fax”]);

            Entity account3 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“address1_addresstypecode”));
            OptionSetValue address = (OptionSetValue)account[“address1_addresstypecode”];

            Entity account4 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“createdon”));
            DateTime createdon1 = (DateTime)account[“createdon”];

            Entity account5 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“parentaccountid”));

            EntityReference parentaccount = (EntityReference)account[“parentaccountid”];
            string parentacc = account.LogicalName;
            Guid parentaccid = account.Id;

            Entity account6 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“new_employeesworking”));
            OptionSetValue employeeworking = (OptionSetValue)account[“new_employeesworking”];

            //————————————————————————————————–

            Entity account7 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“new_name”, “new_age”, “emailaddress1”));
            string accountname = account7[“new_name”].ToString();
            int accage = Convert.ToInt32(account7[“new_age”]);
            string email = account7[“emailaddress1”].ToString();


            Entity account8 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“new_age”, “new_bitfield”, “new_existingcustomer”));
            int accountage = Convert.ToInt32(account8[“new_age”]);
            OptionSetValue bitfield = (OptionSetValue)account8[“new_bitfield”];
            OptionSetValue existingcustomer = (OptionSetValue)account8[“new_existingcustomer”];


            Entity account9 = service.Retrieve(“account”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(“new_accounttype”, “address1_line1”, “new_employeesworking”, “new_lastmodifiedby”));
            OptionSetValue acctype = (OptionSetValue)account9[“new_accounttype”];
            string addressline = account9[“address1_line1”].ToString();
            OptionSetValue employeeworking1 = (OptionSetValue)account9[“new_employeesworking”];
            DateTime lastmodifiedby = (DateTime)account9[“new_lastmodifiedby”];


        }

        public static void read3()
        {
            Entity lead1 = new Entity(“lead”);

            Entity lead = new Entity();
            lead.LogicalName = “lead”;

            string subject = lead[“subject”].ToString();
            string fullname = lead[“fullname”].ToString();
            string jobtitle = lead[“jobtitle”].ToString();
            int businessphone = Convert.ToInt32(lead[“telephone1”]);

            int mobilephone = Convert.ToInt32(lead[“mobilephone”]);
            EntityReference parentaccountforlead = (EntityReference)lead[“parentaccountid”];
            string email = lead[“email”].ToString();

            EntityReference parentcontactforlead = (EntityReference)lead[“parentcontactid”];
            string parentcontactname = lead.LogicalName;
            Guid parentcontactid = lead.Id;

            string company = lead[“companyname”].ToString();
            string website = lead[“websiteurl”].ToString();
            string Address1 = lead[“address1_composite”].ToString();

            string description = lead[“description”].ToString();

            OptionSetValue industry = (OptionSetValue)lead[“industrycode”];
            int annualrevenue = Convert.ToInt32(lead[“revenue”]);// currency data type??
            int noofemployees = Convert.ToInt32(lead[“numberofemployees”]);

            string SIC = lead[“sic”].ToString();

            EntityReference currency = (EntityReference)lead[“transcationcurrencyid”];
        }

        public static void Write3()
        {
            Entity contract = new Entity(“contract”);
            contract[“contractnumber”] = 12333333;
            contract[“title”] = “BSSYSTEMS”;

            //EntityReference accparentid = new EntityReference();
            //accparentid.Id = parentcusromerid;
            //accparentid.LogicalName = “account”;
            //acc[“parentaccountid”] = accparentid;

            EntityReference customer = new EntityReference();
            customer.LogicalName = “contract”;
            contract[“customerid”] = customer;  // doubt how to assign values of entity reference

            EntityReference contractaddress = new EntityReference();
            contract.LogicalName = “contract”;
            contract[“serviceaddress”] = contractaddress; // ??

            DateTime contractstartdate = new DateTime(1988, 12, 09);
            contract[“activeon”] = contractstartdate;


            DateTime contractenddate = new DateTime(1999, 12, 12);
            contract[“expireson”] = contractenddate;

            contract[“duration”] = 12;
        }

        public static void Main5()
        {
            Entity account = new Entity(“account”);
            string accountnames = account[“accountname”].ToString();

            Entity contract = new Entity(“contract”);
            contract[“title”] = accountnames;

        }

        public static void Retreive(Guid id, IOrganizationService service)
        {
            Entity leaddetails = service.Retrieve(“leaddetails”, id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
        }

        public static void RetreiveMuliple(IOrganizationService service)
        {
            QueryExpression query = new QueryExpression();

            query.EntityName = “lead”;
            query.ColumnSet = new ColumnSet(true);
            query.Criteria.Conditions.Add(new ConditionExpression(“emailaddress1”, ConditionOperator.Equal, “malla@gmail.com”));
            query.Criteria.Conditions.Add(new ConditionExpression(“fullname”, ConditionOperator.Equal, “malla”));

            EntityCollection leadrecords = service.RetrieveMultiple(query);

            foreach (Entity lead in leadrecords.Entities)
            {
                string email = lead[“subject”].ToString();
                Console.WriteLine(email);
            }
        }

        public static void RetreiveMultiple(IOrganizationService service)
        {
            QueryExpression query1 = new QueryExpression();

            query1.EntityName = “contact”;
            query1.ColumnSet = new ColumnSet(true);
            query1.Criteria.Conditions.Add(new ConditionExpression(“fullname”, ConditionOperator.EndsWith, “das”));
            query1.Criteria.Conditions.Add(new ConditionExpression(“telephone1”, ConditionOperator.EndsWith, “22”));

            EntityCollection contactrecords = service.RetrieveMultiple(query1);

            foreach (Entity contact in contactrecords.Entities)
            {
                string fullname = contact[“fullname”].ToString();
                Console.WriteLine(fullname);
            }
        }

        public static void RetreiveMultiple(IOrganizationService service)
        {
            QueryExpression query2 = new QueryExpression();
            
            query2.EntityName = “account”;
            query2.ColumnSet = new ColumnSet(true);
            query2.Criteria.Conditions.Add(new ConditionExpression(“name”, ConditionOperator.DoesNotEndWith, “hsjs”));
            query2.Criteria.Conditions.Add(new ConditionExpression(“telephone1”, ConditionOperator.DoesNotEndWith, “3222”));

            EntityCollection accountrecord = service.RetrieveMultiple(query2);
            foreach (Entity account in accountrecord.Entities)
            {
                string name = account[“name”].ToString();
                Console.WriteLine(name);
            }

        }

        public static void RetreiveMultiplesss(IOrganizationService service)
        {
            QueryExpression query3 = new QueryExpression();
            query3.EntityName = “new_leaddetails”;
            query3.ColumnSet = new ColumnSet(true);
            query3.Criteria.Conditions.Add(new ConditionExpression(“new_name”, ConditionOperator.DoesNotContain, “his”));
            query3.Criteria.Conditions.Add(new ConditionExpression(“new_age”, ConditionOperator.DoesNotContain, “12”));
            query3.Criteria.Conditions.Add(new ConditionExpression(“new_email”, ConditionOperator.DoesNotContain, “mll@gmail.com”));
            query3.Criteria.Conditions.Add(new ConditionExpression(“new_dob”, ConditionOperator.DoesNotContain, “23”));
            query3.Criteria.Conditions.Add(new ConditionExpression(“new_rating”, ConditionOperator.DoesNotContain, “coolest”));
            query3.Criteria.Conditions.Add(new ConditionExpression(“new_connection”, ConditionOperator.DoesNotContain, “sample”));
            query3.Criteria.Conditions.Add(new ConditionExpression(“new_account”, ConditionOperator.DoesNotContain, “simple”));

            EntityCollection leaddetailsrecord = service.RetrieveMultiple(query3);
            foreach (Entity leaddetail in leaddetailsrecord.Entities)
            {
                int name = Convert.ToInt32(leaddetail[“new_age”]);
                Console.WriteLine(name);
            }

        }

        public static void RetreiveMultipleA(IOrganizationService service)
        {
            QueryExpression query4 = new QueryExpression();
            query4.EntityName = “opportunity”;
            query4.ColumnSet = new ColumnSet(“purchaseprocess”);
            query4.Criteria.Conditions.Add(new ConditionExpression(“purchaseprocess”, ConditionOperator.DoesNotContain, “kls”));

            EntityCollection Opportunity = service.RetrieveMultiple(query4);
            foreach (Entity opportunity in Opportunity.Entities)
            {
                OptionSetValue purchaseprocess = (OptionSetValue)opportunity[“purchaseprocess”];
                Console.WriteLine(purchaseprocess);
            }
        }
    }
}
















Share this:

JAVASCRIPT SCENARIO IN MS CRM 2013

Requirement Overview
The Client Budgets entity requires expansion to provide additional budgeting details to be specified optionally alongside a single annual Client Target value.  Individual target values for the 3 main  revenue categories (Hardware, Graphics & Modular)must be optionally available for input against a client record.
The 3 main revenue categories will be combined with the Business Adjustment value to determine the overall annual client target for the give budget year.  The target value shall then be split by month as per the appropriate Budget Phasing record template and entered alongside the existing target value in the Client Stats entity record for each month.
 Solution Brief
1.      Add additional fields to the Client Budgets entity:
Field
Type
Usage/Values
Hardware Target
Money
Holds the budget target value for Hardware sales to the client
Graphics Target
Money
Holds the budget target value for Graphics sales to the client
Modular Target
Money
Holds the budget target value for Modular sales to the client
Categorised Targets
Boolean
Determines whether the annual target is calculated from the 3 categorised targets or entered manually
2.      Amend entry form of the Client Budgets entity to include the new fields
3.      Apply logical flow to the Categorised Targets value
a.       If True:
                                                               i.      Disable “Budgeted Revenue” field
                                                             ii.      Enable “Hardware Target”, “Graphics Target”, “Modular Target”
                                                           iii.      On Save the value of Hardware, Graphics, Modular to be combined and recorded in the “Budgeted Revenue” field
                                                           iv.      On Save the value of the Budgeted Revenue field (post any calculation), to be combined with the “Business adjustment” field and recorded in the “Target” field.
b.      If False
                                                               i.      Enable “Budgeted Revenue” field
                                                             ii.      Disable “Hardware Target”, “Graphics Target”, “Modular Target”
                                                           iii.      On Save the value of Hardware, Graphics, Modular fields to be set to 0.00
                                                           iv.      On Save the value of the Budgeted Revenue field (post any calculation), to be combined with the “Business adjustment” field and recorded in the “Target” field.
4.      Add additional fields to the Client Stats entity:
Field
Type
Usage/Values
Hardware Target
Money
Holds the budget target value for Hardware sales to the client
Graphics Target
Money
Holds the budget target value for Graphic sales to the client
Modular Target
Money
Holds the budget target value for Modular sales to the client
5.      On Save (Create or Update) of the relevant Client Budget record the values of the Hardware Target, Graphics Target and Modular Target fields on the Client Budget record must be assessed. 
The value in these fields must be split using the appropriate Budget Phasing record and each monthly entry in the Client Stats entity updated with the appropriate target value.
e.g.       Client Budget entity –> Hardware Target = £100,000
            Budget Phasing for January = 10%
            Client Stats entity –> Hardware Target for January = £10,000
Hardware target-200 – jan -2
Graphics target- 300-jan – 3
Modular target -400- jan -4
Target revenue -9
The above scenario can be achieved through javascript

OnSave_ClientBudgets = function () {
    
    var categorisedValue = Xrm.Page.data.entity.attributes.get(‘new_categorisedtargets’).getValue();
    if (categorisedValue == true) {
        var totalValue = Xrm.Page.data.entity.attributes.get(“new_hardwaretarget”).getValue() + Xrm.Page.data.entity.attributes.get(“new_graphicstarget”).getValue() + Xrm.Page.data.entity.attributes.get(“new_modulartarget”).getValue();
        Xrm.Page.data.entity.attributes.get(“new_budgetedrevenue”).setValue(totalValue);
        Xrm.Page.data.entity.attributes.get(“new_budgetedrevenue”).setSubmitMode(“always”);
    } else {
        Xrm.Page.getAttribute(“new_hardwaretarget”).setValue(0);
        Xrm.Page.getAttribute(“new_graphicstarget”).setValue(0);
        Xrm.Page.getAttribute(“new_modulartarget”).setValue(0);
        Xrm.Page.data.entity.attributes.get(“new_hardwaretarget”).setSubmitMode(“always”);
        Xrm.Page.data.entity.attributes.get(“new_graphicstarget”).setSubmitMode(“always”);
        Xrm.Page.data.entity.attributes.get(“new_modulartarget”).setSubmitMode(“always”);
    }
}
OnLoad_ClientBudgets = function () {
    CommonDisableEnableField();
}
OnChange_Categorised_Targets = function () {
    
    var categorisedValue = Xrm.Page.data.entity.attributes.get(‘new_categorisedtargets’).getValue();
    if (categorisedValue == true) {
        Xrm.Page.getAttribute(“p3dev_budgetedrevenue”).setValue(null);
        Xrm.Page.data.entity.attributes.get(“p3dev_budgetedrevenue”).setSubmitMode(“always”);
    } else {
        Xrm.Page.getAttribute(“new_hardwaretarget”).setValue(null);
        Xrm.Page.getAttribute(“new_graphicstarget”).setValue(null);
        Xrm.Page.getAttribute(“new_modulartarget”).setValue(null);
        Xrm.Page.data.entity.attributes.get(“new_hardwaretarget”).setSubmitMode(“always”);
        Xrm.Page.data.entity.attributes.get(“new_graphicstarget”).setSubmitMode(“always”);
        Xrm.Page.data.entity.attributes.get(“new_modulartarget”).setSubmitMode(“always”);
    }
    CommonDisableEnableField();
}
CommonDisableEnableField = function () {
    var categorisedValue = Xrm.Page.data.entity.attributes.get(‘new_categorisedtargets’).getValue();
    if (categorisedValue == true) {
        Xrm.Page.getControl(“new_budgetedrevenue”).setDisabled(true);
        Xrm.Page.getAttribute(“new_budgetedrevenue”).setRequiredLevel(“none”);
        Xrm.Page.getControl(“new_hardwaretarget”).setDisabled(false);
        Xrm.Page.getAttribute(“new_hardwaretarget”).setRequiredLevel(“required”);
        Xrm.Page.getControl(“new_graphicstarget”).setDisabled(false);
        Xrm.Page.getAttribute(“new_graphicstarget”).setRequiredLevel(“required”);
        Xrm.Page.getControl(“new_modulartarget”).setDisabled(false);
        Xrm.Page.getAttribute(“new_modulartarget”).setRequiredLevel(“required”);
    } else {
        Xrm.Page.getControl(“new_budgetedrevenue”).setDisabled(false);
        Xrm.Page.getAttribute(“new_budgetedrevenue”).setRequiredLevel(“required”);
        Xrm.Page.getControl(“new_hardwaretarget”).setDisabled(true);
        Xrm.Page.getAttribute(“new_hardwaretarget”).setRequiredLevel(“none”);
        Xrm.Page.getControl(“new_graphicstarget”).setDisabled(true);
        Xrm.Page.getAttribute(“new_graphicstarget”).setRequiredLevel(“none”);
        Xrm.Page.getControl(“new_modulartarget”).setDisabled(true);
        Xrm.Page.getAttribute(“new_modulartarget”).setRequiredLevel(“none”);
    }
}
Share this:

PLUGIN SCENARIO IN MS CRM 2013

Requirement Overview
Solution needed to track the individual financial target of personnel within the CRM.  This financial target will be combined with total of all related account targets to form the overall financial target for the business, a territory and or individual.
The target entered shall be an overall annual target per individual based on expected new business revenue.  The target will be in the currency of the related Business Unit.  E.g.  UK = GBP, 
NORWAY = EUR.
The target will be split into monthly targets based on the corresponding budget phasing record for the Business Unit, Budget Year & related Territory (optional).
 Solution Brief
1.      Create new CRM Entity called New Bus. Budgets
Field
Type
Usage/Values
Lookup to user entity
Relate record to specific user
Budget Year
Text (4 Characters)
Lookup to Currency entity
Currency of the Financial Target
Target
Money
Version
Whole Number
Budget Phasing
Lookup to Budget Phasing entity
Business Unit
Lookup to Business Unit entity
Lookup to Territory entity
Status/Reason Configuration
Active              –           Active
Inactive           –           Revised


2.      Create New Entity call New Bus. Stats
Field
Type
Usage/Values
Lookup to New Bus. Budgets entity
Text (4 Characters)
Lookup to Currency entity
Money
Date
Logical Flow
1.      Create New Business Budget entity Record for user with target
o   Create Plugin uses the related budget phasing entity record to calculate the target for each month.
o   Jan=250*(3/100)
o   Feb=250*(5/100)
o  
o   Dec=250*(1/100)
o   New Bus. Stats entity record create for every month of the year based on calculation.
2.      If New Business Budget record is amended.  Version number field is incremented and all New Bus. Stats entity records are recalculated.
3.      If New Business Budget entity is deleted, all related New Bus. Stats are also deleted.
 ————————————————————————————————————————-using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
namespace SampleSolution2016
{
    public class ClientStatisticsMonthlyTarget : IPlugin
    {
        /// <summary>
        ///     
        ///     Plugin registration steps :
        ///    
        /// Message : Create
        /// PrimaryEntityName : new_newbusinessbudgets
        /// Event : PostOperation
        /// </summary>
        /// <param name=”serviceProvider”></param>
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
      IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                if (context.MessageName != “Create” && context.PrimaryEntityName != “new_newbusinessbudgets”)
                {
                    return;
                }
                if ((context.InputParameters.Contains(“Target”)) && (context.InputParameters[“Target”] is Entity))
                {
                    Entity entity = (Entity)context.InputParameters[“Target”];
                    //new_budgetphasing —>budget
                    //new_budgetyer
                    //new_target
                    //new_territory
                   
                    Money target = (Money)entity[“new_target”];
                    Entity Phasing = new Entity(“p3dev_budgetphasing”);
                    //Get budget phasing – check year + territory first, than just budget year
                    EntityReference businessUnit = (EntityReference)entity[“new_businessunit”];
                    Entity bu = service.Retrieve(“businessunit”, businessUnit.Id, new ColumnSet(“name”));
                   
                    QueryExpression query = new QueryExpression(“new_budgetphasing”);
                    query.ColumnSet = new ColumnSet(true);
                    //
                    query.Criteria.AddCondition(new ConditionExpression(“new_businessunit”, ConditionOperator.Equal, bu.Id));
                    if (entity.Contains(“new_territory”))
                    {
                        EntityReference territory = (EntityReference)entity[“new_territory”];
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“new_territory”, ConditionOperator.Equal, territory.Id));
                    }
                    else
                    {
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“new_territory”, ConditionOperator.Null));
                    }
                    query.Criteria.AddFilter(LogicalOperator.And);
                    query.Criteria.AddCondition(new ConditionExpression(“new_year”, ConditionOperator.Equal, entity[“new_budgetyear”].ToString()));
                    query.Criteria.AddFilter(LogicalOperator.And);
                    query.Criteria.AddCondition(new ConditionExpression(“statuscode”, ConditionOperator.Equal, 1));
                    EntityCollection results = service.RetrieveMultiple(query);
                   
                    if (results.Entities.Count == 0)
                    {
                        query = new QueryExpression(“p3dev_budgetphasing”);
                        query.ColumnSet = new ColumnSet(true);
                        query.Criteria.AddCondition(new ConditionExpression(“new_territory”, ConditionOperator.Null));
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“new_year”, ConditionOperator.Equal, entity[“new_budgetyear”].ToString()));
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“statuscode”, ConditionOperator.Equal, 1));
                        results = service.RetrieveMultiple(query);
                    }
                    
                    if (results.Entities.Count > 0)
                    {
                        Phasing = results.Entities[0];
                        //Counter loop 1 to 12 (Jan to Dec) create Statistics record for every month based on budget phasing record for territory and/or year
                        int counter = 1;
                        Money TargetToDate = new Money(0);
                        while (counter <= 12)
                        {
                            //                            
                            //new_name
                            //new_budgetyear
                            //new_newbusbudgetid
                            //new_period
                            //new_currency
                            //new_target
                            Entity Stats = new Entity(“new_newbusinessstatistics”);
                            Stats[“new_name”] = entity[“new_name”].ToString() + “_” + Phasing[“p3dev_year”].ToString() + “_” + counter.ToString();
                            Stats[“new_newbusbudgetid”] = entity.ToEntityReference();
                            Stats[“new_budgetyear”] = Phasing[“new_year”].ToString();
                            decimal phasePercentage = 0;
                            DateTime y1 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 1);
                            DateTime y2 = new DateTime();
                            //Check Counter value to determine phasing month value to select & set last day of month parameter for later lookup
                            if (counter == 1)
                            {
                                phasePercentage = Convert.ToDecimal(Phasing[“new_january”].ToString());
                                y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 31);
                            }
                            else
                            {
                                if (counter == 2)
                                {
                                    phasePercentage = Convert.ToDecimal(Phasing[“new_february”].ToString());
                                    try
                                    {
                                        y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 29);
                                    }
                                    catch
                                    {
                                        y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 28);
                                    }
                                }
                                else
                                {
                                    if (counter == 3)
                                    {
                                        phasePercentage = Convert.ToDecimal(Phasing[“p3dev_march”].ToString());
                                        y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 31);
                                    }
                                    else
                                    {
                                        if (counter == 4)
                                        {
                                            phasePercentage = Convert.ToDecimal(Phasing[“new_april”].ToString());
                                            y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 30);
                                        }
                                        else
                                        {
                                            if (counter == 5)
                                            {
                                                phasePercentage = Convert.ToDecimal(Phasing[“new_may”].ToString());
                                                y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 31);
                                            }
                                            else
                                            {
                                                if (counter == 6)
                                                {
                                                    phasePercentage = Convert.ToDecimal(Phasing[“new_june”].ToString());
                                                    y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 30);
                                                }
                                                else
                                                {
                                                    if (counter == 7)
                                                    {
                                                        phasePercentage = Convert.ToDecimal(Phasing[“new_july”].ToString());
                                                        y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 31);
                                                    }
                                                    else
                                                    {
                                                        if (counter == 8)
                                                        {
                                                            phasePercentage = Convert.ToDecimal(Phasing[“new_august”].ToString());
                                                            y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 31);
                                                        }
                                                        else
                                                        {
                                                            if (counter == 9)
                                                            {
                                                                phasePercentage = Convert.ToDecimal(Phasing[“new_september”].ToString());
                                                                y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 30);
                                                            }
                                                            else
                                                            {
                                                                if (counter == 10)
                                                                {
                                                                    phasePercentage = Convert.ToDecimal(Phasing[“new_october”].ToString());
                                                                    y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 31);
                                                                }
                                                                else
                                                                {
                                                                    if (counter == 11)
                                                                    {
                                                                        phasePercentage = Convert.ToDecimal(Phasing[“new_november”].ToString());
                                                                        y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 30);
                                                                    }
                                                                    else
                                                                    {
                                                                        if (counter == 12)
                                                                        {
                                                                            phasePercentage = Convert.ToDecimal(Phasing[“new_december”].ToString());
                                                                            y2 = new DateTime(Convert.ToInt32(Phasing[“new_year”].ToString()), counter, 31);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                           
                            //Add basic attributes to new Statistics record
                            Stats[“new_period”] = y2;
                            phasePercentage = (phasePercentage / 100) * target.Value;
                            Money targetRevenue = new Money(phasePercentage);
                            Stats[“new_currency”] = entity[“new_currency”];
                            Stats[“new_target”] = targetRevenue;
                            //Stats[“p3dev_actualrevenue”] = new Money(0);
                            //DateTime analysisPeriod = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 1);
                            //Stats[“p3dev_analysisperiod”] = analysisPeriod;
                            service.Create(Stats);
                            counter++;
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            
        }
    }
}
———————————————————————————————————————
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace SampleSolution2016
{
 
    /// <summary>
    ///    Plugin registration steps :
    ///    
    /// Message : Update
    /// PrimaryEntityName : new_newbusinessbudgets
    /// Event : PreOperation
    /// Fitering Attributes : new_budgetphasing, new_budgetyear, new_businessunit, new_currency, new_name, new_target, new_territory, new_user
    /// 
    /// 
    /// Register On Image :
    /// Image Type : PreImage
    /// Name : PreImagenewbusinessbudgets
    /// Enitiy Alias : PreImagenewbusinessbudgets
    /// Parameters :new_budgetphasing, new_budgetyear, new_businessunit, new_currency, new_name, new_target, new_territory, new_user, new_version
    /// </summary>
 
    public class UpdateClientStatisticsMonthlyTarget : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName != “Update” && context.PrimaryEntityName != “new_newbusinessbudgets”)
                {
                    return;
                }
                if ((context.InputParameters.Contains(“Target”)) && (context.InputParameters[“Target”] is Entity))
                {
                    Entity entity = (Entity)context.InputParameters[“Target”];
                    Entity preImageNewBusinessBudges = (Entity)context.PreEntityImages[“PreImagenewbusinessbudgets”];

                    //  currency
                    //Business Unit
                    //Budget Year
                    //Target
                    //Budget Phasing

                    //Territory

                    Money target = new Money();
                    if (entity.Contains(“new_target”))
                    {
                        target = (Money)entity[“new_target”];
                    }
                    else
                    {
                        target = (Money)preImageNewBusinessBudges[“new_target”];
                    }
                    Entity Phasing = new Entity(“p3dev_budgetphasing”);
                    EntityReference businessUnit;
                    if (entity.Attributes.Contains(“new_businessunit”))
                    {
                        businessUnit = (EntityReference)entity[“new_businessunit”];
                    }
                    else
                    {
                        businessUnit = (EntityReference)preImageNewBusinessBudges[“new_businessunit”];
                    }

                    Entity bu = service.Retrieve(“businessunit”, businessUnit.Id, new ColumnSet(“name”));

                    QueryExpression query = new QueryExpression(“p3dev_budgetphasing”);
                    query.ColumnSet = new ColumnSet(true);
                    //
                    query.Criteria.AddCondition(new ConditionExpression(“p3dev_businessunit”, ConditionOperator.Equal, bu.Id));
                    EntityReference territory;
                    if (entity.Contains(“new_territory”))
                    {
                        territory = (EntityReference)entity[“new_territory”];
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“p3dev_territory”, ConditionOperator.Equal, territory.Id));
                    }
                    else if (preImageNewBusinessBudges.Contains(“new_territory”))
                    {

                        territory = (EntityReference)preImageNewBusinessBudges[“new_territory”];
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“p3dev_territory”, ConditionOperator.Equal, territory.Id));
                    }
                    else
                    {
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“p3dev_territory”, ConditionOperator.Null));
                    }
                    if (entity.Contains(“new_budgetyear”))
                    {
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“p3dev_year”, ConditionOperator.Equal, entity[“new_budgetyear”].ToString()));
                    }
                    else
                    {
                        query.Criteria.AddFilter(LogicalOperator.And);
                        query.Criteria.AddCondition(new ConditionExpression(“p3dev_year”, ConditionOperator.Equal, preImageNewBusinessBudges[“new_budgetyear”].ToString()));
                    }

                    query.Criteria.AddFilter(LogicalOperator.And);
                    query.Criteria.AddCondition(new ConditionExpression(“statuscode”, ConditionOperator.Equal, 1));

                    EntityCollection results = service.RetrieveMultiple(query);

                    if (results.Entities.Count == 0)
                    {
                        query = new QueryExpression(“p3dev_budgetphasing”);
                        query.ColumnSet = new ColumnSet(true);

                        query.Criteria.AddCondition(new ConditionExpression(“p3dev_territory”, ConditionOperator.Null));
                        query.Criteria.AddFilter(LogicalOperator.And);
                        if (entity.Contains(“new_budgetyear”))
                        {
                            query.Criteria.AddCondition(new ConditionExpression(“p3dev_year”, ConditionOperator.Equal, entity[“new_budgetyear”].ToString()));
                            query.Criteria.AddFilter(LogicalOperator.And);
                        }
                        else
                        {
                            query.Criteria.AddCondition(new ConditionExpression(“p3dev_year”, ConditionOperator.Equal, preImageNewBusinessBudges[“new_budgetyear”].ToString()));
                            query.Criteria.AddFilter(LogicalOperator.And);
                        }

                        query.Criteria.AddCondition(new ConditionExpression(“statuscode”, ConditionOperator.Equal, 1));

                        results = service.RetrieveMultiple(query);
                    }

                    if (results.Entities.Count > 0)
                    {
                        Phasing = results.Entities[0];

                        //Counter loop 1 to 12 (Jan to Dec) create Statistics record for every month based on budget phasing record for territory and/or year
                        int counter = 1;
                        QueryExpression bdgtPhasing = new QueryExpression(“new_newbusinessstatistics”);
                        bdgtPhasing.ColumnSet = new ColumnSet(true);
                        bdgtPhasing.Criteria.AddCondition(new ConditionExpression(“new_newbusbudgetid”, ConditionOperator.Equal, entity.Id));
                        bdgtPhasing.Criteria.AddFilter(LogicalOperator.And);
                        bdgtPhasing.Criteria.AddCondition(new ConditionExpression(“statuscode”, ConditionOperator.Equal, 1));
                        EntityCollection Stats = service.RetrieveMultiple(bdgtPhasing);
                     
                        Money TargetToDate = new Money(0);
                        while (counter <= 12)
                        {
                            Entity Sta = Stats.Entities[counter – 1];
                         
                            string name;

                            if (entity.Contains(“new_name”))
                            {
                                name = entity[“new_name”].ToString();
                            }
                            else
                            {
                                name = preImageNewBusinessBudges[“new_name”].ToString();
                            }

                            Sta[“new_name”] = name + “_” + Phasing[“p3dev_year”].ToString() + “_” + counter.ToString();
                            //Stats[“new_newbusbudgetid”] = entity.ToEntityReference();

                            Sta[“new_budgetyear”] = Phasing[“p3dev_year”].ToString();
                            decimal phasePercentage = 0;

                            DateTime y1 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 1);
                            DateTime y2 = new DateTime();

                            //Check Counter value to determine phasing month value to select & set last day of month parameter for later lookup
                            if (counter == 1)
                            {

                                phasePercentage = Convert.ToDecimal(Phasing[“p3dev_january”].ToString());
                                y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 31);
                            }
                            else
                            {

                                if (counter == 2)
                                {
                                    phasePercentage = Convert.ToDecimal(Phasing[“p3dev_february”].ToString());
                                    try
                                    {
                                        y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 29);
                                    }
                                    catch
                                    {
                                        y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 28);
                                    }
                                }
                                else
                                {
                                    if (counter == 3)
                                    {
                                        phasePercentage = Convert.ToDecimal(Phasing[“p3dev_march”].ToString());
                                        y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 31);
                                    }
                                    else
                                    {
                                        if (counter == 4)
                                        {
                                            phasePercentage = Convert.ToDecimal(Phasing[“p3dev_april”].ToString());
                                            y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 30);
                                        }
                                        else
                                        {
                                            if (counter == 5)
                                            {
                                                phasePercentage = Convert.ToDecimal(Phasing[“p3dev_may”].ToString());
                                                y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 31);
                                            }
                                            else
                                            {
                                                if (counter == 6)
                                                {
                                                    phasePercentage = Convert.ToDecimal(Phasing[“p3dev_june”].ToString());
                                                    y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 30);
                                                }
                                                else
                                                {
                                                    if (counter == 7)
                                                    {
                                                        phasePercentage = Convert.ToDecimal(Phasing[“p3dev_july”].ToString());
                                                        y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 31);
                                                    }
                                                    else
                                                    {
                                                        if (counter == 8)
                                                        {
                                                            phasePercentage = Convert.ToDecimal(Phasing[“p3dev_august”].ToString());
                                                            y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 31);
                                                        }
                                                        else
                                                        {
                                                            if (counter == 9)
                                                            {
                                                                phasePercentage = Convert.ToDecimal(Phasing[“p3dev_september”].ToString());
                                                                y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 30);
                                                            }
                                                            else
                                                            {
                                                                if (counter == 10)
                                                                {
                                                                    phasePercentage = Convert.ToDecimal(Phasing[“p3dev_october”].ToString());
                                                                    y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 31);
                                                                }
                                                                else
                                                                {
                                                                    if (counter == 11)
                                                                    {
                                                                        phasePercentage = Convert.ToDecimal(Phasing[“p3dev_november”].ToString());
                                                                        y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 30);
                                                                    }
                                                                    else
                                                                    {
                                                                        if (counter == 12)
                                                                        {
                                                                            phasePercentage = Convert.ToDecimal(Phasing[“p3dev_december”].ToString());
                                                                            y2 = new DateTime(Convert.ToInt32(Phasing[“p3dev_year”].ToString()), counter, 31);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //Add basic attributes to new Statistics record
                            Sta[“new_period”] = y2;

                            phasePercentage = (phasePercentage / 100) * target.Value;

                            Money targetRevenue = new Money(phasePercentage);
                            if (entity.Contains(“new_currency”))
                            {
                                Sta[“new_currency”] = entity[“new_currency”];
                            }
                            else
                            {
                                Sta[“new_currency”] = preImageNewBusinessBudges[“new_currency”];
                            }

                            Sta[“new_target”] = targetRevenue;
                         
                            service.Update(Sta);
                            counter++;
                        }

                    }

                    int counterValue = (int)preImageNewBusinessBudges[“new_version”];
                    preImageNewBusinessBudges[“new_version”] = counterValue + 1;

                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}


Share this: