serving the solutions day and night

Pages

Wednesday, March 30, 2016

MS Dynamics CRM - Display Unique/Auto Number on the form before save.

My client requirement is display the unique reg number for new contact before the save record.
My Previous blog <a href="http://makdns.blogspot.com/2016/03/ms-dynamics-crm-generate-uniqueauto.html">MS Dynamics CRM - Generate Unique/Auto Number</a> will show the reg number on form after save the new contact. if the user clicks save and close, they can't see the number.

So i come up with the web service concept to generate unique number for new contact and display on the contact screen.
Also i am using SQL Server sys.sequences for generating new number.

Web Service Code
[ServiceContract]
public interface IVoterSearch
{
[OperationContract]
[WebInvoke(Method = "POST",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Xml,
    BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string RegNumber(string userGuid);
}

/*
 * Generate new reg number
    --https://msdn.microsoft.com/en-us/library/ff878091.aspx
    --drop SEQUENCE dbo.DNSContactRegNumber
    --select * from sys.sequences
    --CREATE SEQUENCE dbo.DNSContactRegNumber
--    AS int
--   START WITH 123456
--    INCREMENT BY 1;
    --SELECT NEXT VALUE FOR dbo.DNSContactRegNumber As NewRegNumber;
*/
public string RegNumber(string userGuid)
{
    //checking the user is login dynamics crm user for security purpose.
    var valid = IsUserValid(userGuid, crmDB);
    if (!(valid == string.Empty)) return valid;
    var regid = new XDocument();
    string NewRegNumber = "0";
    string dbExtCon = System.Configuration.ConfigurationManager.ConnectionStrings["DNS_EXT_DB_ConnectionString"].ConnectionString;
    try
    {
using (SqlConnection Con = new SqlConnection(dbCon))
{
   Con.Open();
   SqlCommand cmd = new SqlCommand();
   cmd.CommandText = "SELECT NEXT VALUE FOR dbo.DNSContactRegNumber As NewRegNumber";
   cmd.Connection = Con;
   SqlDataReader dr = cmd.ExecuteReader();

   while (dr.Read())
   {
NewRegNumber = dr["NewRegNumber"].ToString();
   }
   dr.Close();
}


regid = new XDocument(
   new XElement("Contact",
new XAttribute("Error", "0"),
new XAttribute("Message", ""),
new XAttribute("NewRegNumber", NewRegNumber)
   )
);
    }
    catch (Exception e)
    {
regid = new XDocument(
new XElement("Contact",
   new XAttribute("Error", "1"),
   new XAttribute("Message", e.Message.ToString()),
   new XAttribute("NewRegNumber", NewRegNumber)
)
   );
    }
    return regid.ToString();
}

//verify the login user is valid active system user.
private string IsUserValid(string userGuid, DNSCRMDBDataContext db)
{
    var exists = false;
    loginUserGuid = loginUserGuid.Replace("}", "").Replace("{", "");
    var valid = db.SystemUsers
  .Where(u => u.SystemUserId.ToString() == userGuid)
  .Select(u => u.IsDisabled)
  .FirstOrDefault().ToString();
    if (valid == string.Empty) exists = false;
    else exists = !bool.Parse(valid);

    if (!exists)
    {
var message = new XDocument( new XElement("List",
new XAttribute("Error", "1"),
new XAttribute("Message", "Invalid CRM USER")
));
return message.ToString();
    }

    return string.Empty;
}
Contact Form Onload JavaScript Code, calling the web service on form load event and assign new reg number.
/*
assign reg number when form is opened
Create New Reg Number & assign to the field.
*/
function NewRegNumber() {
var userId = Xrm.Page.context.getUserId();
var svcURL = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + "/DNS.VM.Service/";
$.ajax({
   type: "POST",
   url: svcURL + "Contact.svc/RegNumber",
   async: true,
   dataType: "xml",
   contentType: "application/json; charset=utf-8",
   data: JSON.stringify({ userGuid: userId}),
   success: function (xml) {
xml = $.parseXML($(xml).find("string").text());
$(xml).find("Contact").each(function () {
   var error = $(this).attr('Error');
   var regnumber = $(this).attr('NewRegNumber');
   var message = $(this).attr('Message');
   if (error == "1")
    alert(message);
   else
    Xrm.Page.data.entity.attributes.get("dns_regnumber").setValue(regnumber);
});
   },
   error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
   }
});
}

2 comments:

Philips Huges said...



Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

Personal Installment Loans
Title Car loan
Cash Advance Loan

Philips Huges said...

Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

Installment Loans Near Me
Title loans Near Me
Cash Advances Near Me