Tuesday, 2 December 2025

Secure and Unsecure configuration in Dynamics CRM 365.

Overview: In Dynamics CRM, when we create a plugin, we sometimes need to pass data to that plugin, instead of writing this data inside the plugin code. We can pass it using Secure and Unsecure configurations. 

Advantge  

Security - Protect sensitive information like API Key.

Flexibility -Easily change configuration values without modifying the Plugin code.

Reusability - Use the same plugin in different environments with different configuration values. 

Sample Code 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Text;

using System.Text.Json.Serialization;

using System.Threading.Tasks;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

using Newtonsoft.Json;

namespace SendCustomerData

{

    public class SendCustomerDataUnSecureAndSecureConfig : IPlugin

    {

        private readonly string _unsecureString;

        private readonly string _secureString;

        public SendCustomerDataUnSecureAndSecureConfig(string unsecureString, string secureString)

        {

            _unsecureString = unsecureString;

            _secureString = secureString;

        }

        public void Execute(IServiceProvider serviceProvider)

        {

            IPluginExecutionContext context =

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

            IOrganizationServiceFactory serviceFactory =

                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));


            ITracingService tracingService =

                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            tracingService.Trace("Unsecure Config: {0}", _unsecureString);

            tracingService.Trace("Secure Config: {0}", _secureString);

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


            //Ensure that the plugin is trigger on Create Mesage .

            if (context.MessageName != "Create" || context.PrimaryEntityName.ToLower() != "contact")

            {

                return;


            }

            //Get the contact details from the input parameters

            Entity contact = (Entity)context.InputParameters["Target"];

            string firstName = contact.Contains("firstname") ? contact["firstname"].ToString() : string.Empty;

            string lastName = contact.Contains("lastname") ? contact["lastname"].ToString() : string.Empty;

            string email = contact.Contains("emailaddress1") ? contact["emailaddress1"].ToString() : string.Empty;


            //Prepare the customer data to be sent

            var customerdata = new

            {

                FirstName = firstName,

                LastName = lastName,

                Email = email

            };

            string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(customerdata);

            tracingService.Trace("Customer Data JSON: {0}", jsonData);

            try

            {

                using (HttpClient client = new HttpClient())

                {

                    client.BaseAddress = new Uri(_unsecureString);

                    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_secureString}");

                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = client.PostAsync("addCustomInfo", content).Result;

                    if (response.IsSuccessStatusCode)

                    {

                        tracingService.Trace("Customer data sent successfully.");

                    }

                    else

                    {

                        tracingService.Trace("Failed to send customer data. Status Code: {0}, Reason: {1}",

                            response.StatusCode, response.ReasonPhrase);



                    }

                }

            }

            catch (Exception ex)

            {

                tracingService.Trace("An error occurred while sending customer data.");

                throw new InvalidPluginExecutionException("An error occurred in SendCustomerDataUnSecureAndSecureConfig plugin.", ex);


            }


        }

    }


}



Saturday, 16 August 2025

Dynamics 365 Ribbon Button JavaScript customization function- Displays a popup message when the button is clicked.

 function RequestRibbonCustomisation(primaryControl) {

var formContext = primaryControl;

alert("Coming soon! Work in Progress.")

}

Retrieves the record GUID (ID) using isDirty function.

isDirty() → This function is used to check whether the form data has been changed but not yet saved.

// JavaScript source code

function retrieveEntityInfo(executionContext) {

    if (executionContext != null) {

        var formContext = executionContext.getFormContext();

        var accountId = formContext.data.entity.getId();

        if (accountId) {

            alert("Account GUID: " + accountId);

        } else {

            alert("This Account record has not been saved yet (no GUID).");

        }

    }

}


Monday, 11 August 2025

Convert Sql select statement result into JSON formate .

Formats the query result as JSON using the 'FOR JSON PATH' mode, where you have full control over the JSON structure by using column aliases.

SQL Query:-

SELECT 

    FirstName,

    LastName

FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

JSON Output- 

{"FirstName":"Ajit","LastName":"Agarwal"}


Monday, 23 June 2025

How to convert plugin assembly (dll) into base 64 bytes using console application (C#).

 using System;

using System.IO;

using System.ServiceModel.Description;

using Microsoft.Rest;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Xrm.Tooling.Connector;

namespace ConsoleApp2

{

    internal class Program

    {

        static void Main(string[] args)

        {

            string connectionString = @"AuthType=OAuth;

                Username=*****************;

                Password=*****************;

                Url=https://*****************.crm8.dynamics.com;

                AppId=*****************;

                 LoginPrompt=Auto";

            Console.WriteLine("Connecting to Dynamics 365..");


            using (CrmServiceClient serviceClient = new CrmServiceClient(connectionString))

            {

                if (!serviceClient.IsReady)

                {

                    Console.WriteLine("Failed to connect: " + serviceClient.LastCrmError);

                    return;

                }

                IOrganizationService service = (IOrganizationService)serviceClient.OrganizationWebProxyClient ?? (IOrganizationService)serviceClient.OrganizationServiceProxy;

                Console.WriteLine("connected to Dynamics Crm ");

                QueryExpression query = new QueryExpression("pluginassembly")

                {

                    ColumnSet = new ColumnSet("name", "content")

                };

                EntityCollection results = service.RetrieveMultiple(query);


                foreach (Entity plugin in results.Entities)

                {

                    string name = plugin.GetAttributeValue<string>("name");

                    string content = plugin.GetAttributeValue<string>("content");

                    if (string.IsNullOrEmpty(content))

                    {

                        Console.WriteLine($"Assembly '{name}' has no content.");

                        continue;

                    }

                    byte[] dllBytes = Convert.FromBase64String(content);

                    string fileName = $"{name}.dll";

                    File.WriteAllBytes(fileName, dllBytes);

                    Console.WriteLine($"Downloaded: {fileName}");

                }

                Console.WriteLine("All assemblies downloaded successfully.");

            }

        }

    }

}

Notes -Replace credentials as per your  CRM environment.

Download a plugin assembly (DLL) from Dynamics 365 CRM.

 CRM does not allow direct download of the DLL file from the UI. However, there are several ways to retrieve the plugin DLL from the CRM environment. we achieve this requirement using XrmToolBox.  

  • Open XrmToolBox.
  • Install and open Assembly Recovery Tool.
  • Connect to your Dynamics CRM instance.
  • It will list all deployed assemblies.
  • Select the assembly and click Download.
Connect D365 Environment 



Configuration ==> Tool Library ==>Search "Assembly Recovery Tool" and install.


Tool==>Assembly Recovery Tool.

Double click on "Assembly Recovery Tool" all Assemble file will be appear. 


Select "Assemble "and  click on "Export to Disk "


Note :- All Assemble file store under "pluginassembly" entity.







Saturday, 1 March 2025

How to Setup SLA in D365 Service module.

Setting Up SLA (Service Level Agreements) in Dynamics 365 Customer Engagement (CE)

A Service Level Agreement (SLA) in Dynamics 365 CE (Customer Service module) defines response and resolution times for service cases to ensure customer satisfaction. It helps in tracking, monitoring, and automating service commitments.


📌 Steps to Set Up SLA in Dynamics 365 CE

Step 1: Enable SLA in System Settings

Before configuring SLAs, ensure that SLAs are enabled:

  1. Navigate to: Customer Service Hub → Service Management → Service Terms
  2. Go to Service Configuration Settings
  3. Enable Service Level Agreements (SLAs)

📌 SLA Components in Dynamics 365 CE

SLAs in Dynamics 365 consist of:

  • SLA KPI (Key Performance Indicators): Measures response/resolution times.
  • SLA Items: Define individual conditions and success criteria.
  • Success Actions: Define what happens when SLA is met.
  • Failure Actions: Define what happens when SLA is breached.
  • Warning Actions: Sends notifications before SLA breaches.

📌 Step 2: Create a New SLA

  1. Navigate to: Customer Service Hub → Service Management → SLAs
  2. Click New
  3. Fill in the details:
    • Name: Define an SLA name (e.g., "Premium Support SLA").
    • Entity: Select Case (or another entity if needed).
    • Applicable From: Choose the field that determines SLA start time (e.g., Case Created On).
    • Business Hours: Assign working hours to exclude weekends/holidays.
    • SLA Type: Choose Enhanced SLA for advanced tracking.
  4. Click Save (but don’t activate yet).

📌 Step 3: Create SLA KPI(s)

  1. Navigate to SLA KPIs → Click New
  2. Define KPI details:
    • Name: (e.g., "First Response Time")
    • Entity: Case
    • Applicable From: (e.g., "Case Created On")
    • Field for Success Criteria: (e.g., "First Response Sent")
  3. Save and Close.

📌 Step 4: Add SLA Items

Now, configure the rules and conditions for SLA tracking.

  1. Open your SLA and click + Add SLA Item
  2. Define:
    • Name (e.g., "High Priority Response Time")
    • KPIs: Select SLA KPI (e.g., First Response KPI)
    • Applicable When: Set conditions (e.g., Case Priority = High)
    • Failure Time: (e.g., 2 hours for first response)
    • Warning Time: (e.g., 1.5 hours before failure)

📌 Step 5: Configure Actions (Failure, Warning, Success)

Each SLA item allows defining actions upon success, warning, or failure:

✅ Success Actions (When SLA is met)

  • Update a Case field (e.g., "SLA Status = Met")
  • Notify a supervisor
  • Send confirmation email

⚠️ Warning Actions (Before SLA is breached)

  • Notify an agent to take action
  • Escalate to a manager

❌ Failure Actions (When SLA is breached)

  • Update a Case field (e.g., "SLA Status = Failed")
  • Escalate case priority
  • Assign the case to another team

Save & Close SLA Item.


📌 Step 6: Activate and Apply the SLA

  1. Click Activate the SLA
  2. Set the Default SLA (if required)
  3. Apply SLA on cases automatically or manually.

📌 Step 7: Test & Monitor SLA Performance

  • Go to a Case record and verify the SLA timer.
  • Check SLA KPIs in the timeline.
  • Monitor SLA performance in dashboards and reports.

📌 Advanced Features

🔹 Pause & Resume SLA: Configure SLA pause for cases on hold.
🔹 Multiple SLAs: Assign different SLAs based on case type or customer.
🔹 Power Automate Integration: Trigger advanced notifications and escalations.

Saturday, 28 January 2023

How to get logged in User's Security Roles using Java Script in dynamic CRM 365.

 function GetloggedUser () {

    var roles = Xrm.Utility.getGlobalContext().userSettings.roles; 

    if (roles === null) return false; 

    var hasRole = false;

    roles.forEach(function (item) {

        if (item.name.toLowerCase() === "manager" || item.name.toLowerCase() === " System administrator") {

            hasRole = true;

        }

    }); 

    return hasRole;

}

Monday, 22 June 2020

Android Firebase Push Notification in asp.net C#



using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace AnroidPushNotification
{
public class AndriodPushNotification
{

public string SendPushNotificationForAndroidSWithoutImage()
{
PushNotificationParameters parameters = new PushNotificationParameters();

parameters.DeviceId = "Token ID";
parameters.ServerKey = "ServerKey ";
parameters.SenderId = "SenderId";
parameters.RequestTimeOut = 20000;
parameters.Title = "TestTitle";
parameters.SoundEnable = "Enabled";
parameters.NotificationEN = "TestEn";
parameters.NotificationAR = "TestAR";
parameters.Message ="testMessage";
string response;
try
{
WebRequest request = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
request.Timeout = parameters.RequestTimeOut;
request.Method = "Post";
request.ContentType = "application/json";
var data = new
{
//ApplicationId = parameters.ApplicationId,
to = parameters.DeviceId,
priority = "high",
content_available = true,
notification = new
{
title = parameters.Title,
sound = parameters.SoundEnable,
messageAR = parameters.NotificationAR,
messageEN = parameters.NotificationEN
}
};
var json = SerializeAndroidWithoutImage(parameters);
//tracingService.Trace("SendPushNotificationForAndroidWithoutImage: json" + json);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
request.Headers.Add(string.Format("Authorization:key={0}", parameters.ServerKey));
request.Headers.Add(string.Format("Sender: id={0}", parameters.SenderId));
request.ContentLength = byteArray.Length;
// tracingService.Trace("SendPushNotificationForAndroidWithoutImage : ContentLength" + byteArray.Length);

using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
// tracingService.Trace("SendPushNotificationForAndroidWithoutImage:dataStream " + dataStream.Length);

using (WebResponse webResponse = request.GetResponse())
{
using (Stream dataStreamResponse = webResponse.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(dataStreamResponse))
{
string sResponseFromServer = streamReader.ReadToEnd();
response = sResponseFromServer;
}
}
}


}


}
catch (Exception ex)
{
response = ex.Message;
}
return response;
}
public string SerializeAndroidWithoutImage(PushNotificationParameters parameters)
{
string result = string.Empty;
result = "{\"to\":\"" + parameters.DeviceId
+ "\",\"data\":{\"title\":\"" + parameters.Title
+ "\",\"body\":\"" + parameters.Message
+ "\",\"sound\":\"" + parameters.SoundEnable
+ "\",\"messageAR\":\"" + parameters.NotificationAR
+ "\",\"messageEN\":\"" + parameters.NotificationEN
+ "\"}}";


return result;

}
}
}


Wednesday, 11 September 2019

Dynamic CRM 365 - Option Set cascading Filtering using Java Script.




function lead_Filter_CustomerType_OnLoad()

var customerType = Xrm.Page.getAttribute("inf_customertype").getValue();
  if (customerType == 1)
  {
   Xrm.Page.getControl("inf_leadstatus").removeOption(8); // removeOption use for removing option set value at form load 
   Xrm.Page.getControl("inf_leadstatus").removeOption(9);
   Xrm.Page.getControl("inf_leadstatus").removeOption(10);
   Xrm.Page.getControl("inf_leadstatus").removeOption(10);   
  }
else if(customerType == 2)
 {
   Xrm.Page.getControl("inf_leadstatus").removeOption(1);
   Xrm.Page.getControl("inf_leadstatus").removeOption(2);
   Xrm.Page.getControl("inf_leadstatus").removeOption(3);
   Xrm.Page.getControl("inf_leadstatus").removeOption(4);
   Xrm.Page.getControl("inf_leadstatus").removeOption(5);
   Xrm.Page.getControl("inf_leadstatus").removeOption(6);
   Xrm.Page.getControl("inf_leadstatus").removeOption(7); 
  }
}


function lead_Filter_LeadStatusOnLoad()
{
var leadstatus = Xrm.Page.getAttribute("inf_leadstatus").getValue();
if (leadstatus == 8)
{
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(4);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(5);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(6);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(7);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(8);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(9);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(10);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(11);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(12); 
}
else if (leadstatus == 9)
{
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(1);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(2);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(3);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(6);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(7);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(8);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(9);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(10);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(11); 
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(12);
}
if (leadstatus == 10)
{
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(1);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(2);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(3);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(4);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(5);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(11);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(12);
}
if (leadstatus == 11)
{
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(1);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(2);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(3);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(4);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(5);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(6);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(7);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(8);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(9);
   Xrm.Page.getControl("inf_leadsubstatus").removeOption(10);

}
}



function lead_Filter_CustomerType_OnChange()
{
  var customerType = Xrm.Page.getAttribute("inf_customertype").getValue();
 
  var optionSet = Xrm.Page.ui.controls.get("inf_leadstatus");
  var optionSetValues = optionSet.getAttribute().getOptions();  
  optionSet.clearOptions();
  if (customerType == 1)
  {
  optionSetValues.forEach(function (element) {
  //using forEach store all option value in eleement
  if (element.value == "1") 
  optionSet.addOption(element);
  // addoption use for display option set value at form .
  if (element.value == "2")
  optionSet.addOption(element);
 
  if (element.value == "3")
  optionSet.addOption(element);
 
  if (element.value == "4") 
  optionSet.addOption(element);
 
  if (element.value == "5")
  optionSet.addOption(element);
   
  if (element.value == "6")
  optionSet.addOption(element);
   
  if (element.value == "7")
  optionSet.addOption(element);
  });
  }
   else if (customerType == 2)
  {
  optionSetValues.forEach(function (element) {
  if (element.value == "8") 
  optionSet.addOption(element);
 
  if (element.value == "9") 
  optionSet.addOption(element);
 
  if (element.value == "10")
  optionSet.addOption(element);
 
   if (element.value == "11") 
  optionSet.addOption(element);
  });
  }

}


function lead_Filter_LeadStatus_onChange()
{
var leadstatus = Xrm.Page.getAttribute("inf_leadstatus").getValue();
 
  var optionSet = Xrm.Page.ui.controls.get("inf_leadsubstatus");
  var optionSetValues = optionSet.getAttribute().getOptions();  
  optionSet.clearOptions();
  if (leadstatus == 8)
  {
  optionSetValues.forEach(function (element) {
  if (element.value == "1") 
  optionSet.addOption(element);
 
  if (element.value == "2")
  optionSet.addOption(element);
 
  if (element.value == "3")
  optionSet.addOption(element);  

  });
  }
   else if (leadstatus == 9)
  {
  optionSetValues.forEach(function (element) {
  if (element.value == "4") 
  optionSet.addOption(element);
 
  if (element.value == "5") 
  optionSet.addOption(element);

  });
  }
 
   else if (leadstatus == 10)
  {
  optionSetValues.forEach(function (element) {
  if (element.value == "6") 
  optionSet.addOption(element);
 
  if (element.value == "7") 
  optionSet.addOption(element);
 
  if (element.value == "8")
  optionSet.addOption(element);
 
   if (element.value == "9") 
  optionSet.addOption(element);
 
    if (element.value == "10") 
  optionSet.addOption(element);
  });
  }
 
   else if (leadstatus == 11)
  {
  optionSetValues.forEach(function (element) {
  if (element.value == "8") 
  optionSet.addOption(element);
 
  if (element.value == "11") 
  optionSet.addOption(element);
 
  if (element.value == "12")
  optionSet.addOption(element);
 
  });
  }

}






Friday, 4 January 2019

Bubble Sorting C#

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

namespace SortingBubbleSort
{
    class Program
    {

        static void Main(string[] args)
        {
            //a temporary int, to store a value when switching positions
            int temp = 0;
            //DATA : list of sortable items
            int[] data = { 89, 76, 45, 92, 67, 12, 99 };


            for (int outer = 0; outer < data.Length; outer++)
            {
                for (int inner = 0; inner < data.Length - 1; inner++)
                {
                    ////comparison statement
                    if (data[inner] > data[inner + 1])
                    {
                        temp = data[inner + 1];
                        data[inner + 1] = data[inner];
                        //switching operation
                        data[inner] = temp;


                    }
                }
            }
            //Sorted array
            foreach (int i in data)
            {
                Console.Write("\t{0}",i);
             
            }
            Console.Read();
        }      }
}
 
output:-
12 45 67 79 89 92 99

Monday, 10 December 2018

Different between var and Dynamic Variable in C#.

var  It is introduced  C#3.0 Version.
 dynamic It is introduced  C# 4.0 version

1).Var is statically  type of variable, where are dynamic is dynamically type of variable.

2)Errore will be occur at compile time in var, where as error will be occur at runtime
.
3)In var initialization is required at time of declaration. If you not initialize variable it will be throw error at compile time "Implicitly -typed variable must be initialized ". where as dynamic type variable initialization is not required at time of declaration.

4)var does not allow the change variable after assigned value where as dynamic type variable allow be change type after assigned .

5)var support intellisense because it arise errore at compile time where as dynamic type  variable not support intelligence because type is unknown runtime.

6)var variable can not be used for properties and return value from function .it is available only locally whereas dynamic variable can be used to create properties and return value from function





Saturday, 16 June 2018

How to call function in store procedure using Sql Server 2014?


How to add auto increament with string of number and letter?


CREATE TABLE [dbo].[tbl_Product](

[Id] [int] IDENTITY(101,1) NOT NULL,

ProductId As 'PRO'+Right('000'+convert (varchar(10),Id),6)persisted,

[ProductName] [nvarchar](100) NULL,

[Quantiy] [int] NULL,

[Price] [decimal](18, 1) NULL,

[CreateOn] [datetime] NULL
) ON [PRIMARY]


 Output-

Friday, 13 April 2018

Cursor In SQL SERVER

Cursor:- Cursor is  a database object to retrieve data from a result set one row at time. we use cursor when we need to update record databse table in Sigleton fashion means row wise.



  For Exampl :
   select * from Products

 know i want change  unit price of unit of each based on some condition.

Declare @UnitPrice decimal(5,2)
Declare @ProductId int
Declare UnitPriceUpdateCursore  Cursor FOR
Select ProductID From Products
open  UnitPriceUpdateCursore
Fetch Next From UnitPriceUpdateCursore into @ProductId
While (@@Fetch_Status=0)
Begin
select @UnitPrice=UnitPrice from Products

Begin Update Products set UnitPrice = case when UnitPrice between 5 And 10 then 15
                     when UnitPrice  between 11 AND 15  then 20
     else UnitPrice
                    end
Where ProductID=@ProductId
Fetch Next From UnitPriceUpdateCursore into @ProductId
END
End
Close UnitPriceUpdateCursore
Deallocate UnitPriceUpdateCursore
Set NoCount Off


Friday, 6 April 2018

MVC Validation

Expressions for input fields
Alphabets and Space
[a-zA-Z ]+$
Alphabets
^[A-z]+$
Numbers
^[0-9]+$
Alphanumeric
^[a-zA-Z0-9]*$
Email
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Mobile no.
^([7-9]{1})([0-9]{9})$
Date Format( mm/dd/yyyy | mm-dd-yyyy | mm.dd.yyyy)
/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d+$/
Website URL
^http(s)?://([\\w-]+.)+[\\w-]+(/[\\w- ./?%&=])?$
Credit Card Numbers
Visa
^4[0-9]{12}(?:[0-9]{3})?$
MasterCard
^5[1-5][0-9]{14}$
American Express
^3[47][0-9]{13}$
Decimal number
((\\d+)((\\.\\d{1,2})?))$


Thursday, 11 January 2018

How to bind data in Drop down List from Enum usig Array in Asp.net C#

Add New Class and rename as CommonEnum.
Note:- Set location in App_Code.So it can access any in a project. 

 Add method 
nameSpace Enum
{
Public ClassCommonEnum()
{

}
Public enum Operation 
{Insert =1,
Update=2,
Delete=3,
Select=4
}
}

Add New  Web Page 
 Add Asp .Net DropDownList control in .aspx page

<asp:DropDownList Id="ddlOperation"  runat= "Server"/>

Add name Space on web Page.cs

 Array arrop=Enum.GetValues(typeof(CommonEmum.Operation));
foreach(CommonEnum.Operation opt  in arrop)
{
ddlOperation.Items.Add(new ListItem(opt.ToString(),((Int)opt).Tostring()));

Saturday, 25 November 2017

Store Procedure for crud operation with transaction and exception handling (try catch block)

CREATE TABLE [dbo].[tblCustomer](
[CustID] [bigint] NOT NULL,
[CustName] [nvarchar](50) NULL,
[CustEmail] [nvarchar](50) NOT NULL,
[CustAddress] [nvarchar](256) NULL,
[CustContact] [nvarchar](50) NULL,
 CONSTRAINT [PK_tblCustomer] PRIMARY KEY CLUSTERED
(
[CustID] ASC,
[CustEmail] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE PROCEDURE [dbo].[SP_CUSTOMER_INSERT]
(
@CustName NVarchar(50)  
    ,@CustEmail NVarchar(50)  
    ,@CustAddress NVarchar(256)  
    ,@CustContact  NVarchar(50)  
)  
AS BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
DECLARE @CustID Bigint
  SET @CustID = isnull(((SELECT max(CustID) FROM [dbo].[tblCustomer])+1),'1')  
  Insert INTO tblCustomer(CustID,CustName,CustEmail,CustAddress,CustContact)Values(@CustID,@CustName,@CustEmail,@CustAddress,@CustContact)
  Select 1
  Commit Transaction
  End Try
  BEGIN CATCH
   DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;  
            SELECT @ErrorMessage = ERROR_MESSAGE(),@ErrorSeverity = ERROR_SEVERITY(),@ErrorState = ERROR_STATE();  
            RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);  
Rollback Transaction
END Catch
End
GO

CREATE  PROCEDURE [dbo].[SP_CUSTOMER_DELETE]
@CustID BIGINT  
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
DELETE tblCustomer
 WHERE [CustID] = @CustID   
        SELECT 1  
COMMIT TRANSACTION
END TRY
BEGIN CATCH
DECLARE @ERROR_MEASSAGE NVARCHAR(4000),@ERRORSERVERITY INT , @ERRORLINE INT ,@ERRORSTATE INT;
SELECT @ERROR_MEASSAGE=ERROR_MESSAGE(),@ERRORSERVERITY=ERROR_SEVERITY(),@ERRORLINE=ERROR_LINE(),@ERRORSTATE=ERROR_STATE();
RAISERROR (@ERROR_MEASSAGE ,@ERRORSERVERITY,@ERRORLINE,@ERRORSTATE);
ROLLBACK TRANSACTION
END CATCH
END

CREATE PROCEDURE [dbo].[SP_CUSTOMER_UPDATE]
 @CustID BIGINT 
    ,@CustName NVarchar(50) =NULL
    ,@CustEmail NVarchar(50)  =NULL
    ,@CustAddress NVarchar(256) =NULL 
    ,@CustContact  NVarchar(50) =NULL 
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
BEGIN TRANSACTION
UPDATE [dbo].[tblCustomer]
SET CustName=@CustName,
CustAddress=@CustAddress,
CustContact=@CustContact
WHERE CustID=@CustID AND [CustEmail]=@CustEmail
COMMIT TRANSACTION

END TRY

BEGIN CATCH 
SELECT  1    

DECLARE  @ErrorMessage  NVARCHAR(200),@ErrorSeverity INT ,@ErrorState int,@ErrorLinenumber INT;
select  @ErrorMessage =ERROR_MESSAGE(),@ErrorSeverity=ERROR_SEVERITY(), @ErrorState=ERROR_STATE(),@ErrorLinenumber=ERROR_LINE();
SELECT @ErrorMessage,@ErrorSeverity,@ErrorState,@ErrorLinenumber
RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState,@ErrorLinenumber)
ROLLBACK TRANSACTION
END CATCH
END

CREATE PROCEDURE [dbo].[SP_SELECT_CUSTOMER_BY_ID]
@CustID  BIGINT
AS BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
SELECT * FROM [dbo].[tblCustomer]
WHERE CustID=@CustID
SELECT 1
COMMIT TRANSACTION
END TRY
BEGIN CATCH 
DECLARE @ERRORMESAGE NVARCHAR(400),@ERRORSERVERITY INT,@ERRORSTATUS INT, @ERRORLINE INT,@ERRORPROCEDURE NVARCHAR(50);
SELECT @ERRORMESAGE=ERROR_MESSAGE(),@ERRORsERVERITY=ERROR_SEVERITY(),@ERRORSTATUS=ERROR_STATE(),@ERRORLINE=ERROR_LINE(),
@ERRORPROCEDURE=ERROR_PROCEDURE();
RAISERROR (@ERRORMESAGE,@ERRORsERVERITY,@ERRORSTATUS,@ERRORLINE,@ERRORPROCEDURE)
ROLLBACK TRANSACTION
END CATCH
END
---------------------------------------------------------------------
Note: -Default exception in SQL Server 2014 is

ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage;

The severity parameter specifies the severity of the exception.

Secure and Unsecure configuration in Dynamics CRM 365.

Overview : In Dynamics CRM, when we create a plugin, we sometimes need to pass data to that plugin, instead of writing this data inside the ...