Wednesday, April 29, 2015

How to code a jQuery Plugin for HTML Form with Radio Buttons

In this post we describe Step by step How to code a jQuery Plugin for HTML Form with Radio Buttons.
In this article we create from scratch a small jQuery Plugin which displays an HTML Form with radiobuttons inputs and Twitter Bootstrap CSS3 style .
This jquery plugin will display an HTML5 form as the following:




How to create a jQuery Plugin for HTML Form with Radio Buttons 



First , we need the jQuery and the Bootstrap files, so browse to http://jquery.com/download/ and get the latest version of the framework in CDN(Content Delivery Network):
How to code a jQuery Plugin for HTML Form with Radio Buttons    1


Do the same to get the CSS3 Bootstrap style from the  Bootstrap's official web site:
How to code a jQuery Plugin for HTML Form with Radio Buttons   2


Add it to a new HTML5 file at the "head" element :

How to code a jQuery Plugin for HTML Form with Radio Buttons       3



Also inside the "head" tag, add two new files: one a CSS which will contain some style, and the other one will be our jQuery plugin:
How to code a jQuery Plugin for HTML Form with Radio Buttons        4


The complete code for this tutorial can be downloaded from this GitHub repository:

Next, let's write a div to contain the web Form produced by our jquery plugin:

How to code a jQuery Plugin for HTML Form with Radio Buttons      5

After the body, append a script element , where we'll next call our plugin:

How to code a jQuery Plugin for HTML Form with Radio Buttons    6

Now, open the "jqueryplugin.js" javascript file and create the plugin definition  as follows:


How to code a jQuery Plugin for HTML Form with Radio Buttons        7

As you can see, we added some parameters to set the HTML Form.
The most important of them is "oRadio", which is a string array holding the texts for the radio buttons.
Since "this" represents here the container <div>, we append to it a "form" element this way:


How to code a jQuery Plugin for HTML Form with Radio Buttons   8

Then we take the form reference and add an <h1> Title and  a <div> for containing the radio buttons.
Now, because the "oRadio" object is an array, we loop through it with a "for" , appending to the <div> an <input> of "radiobutton" type for each text in the array:


How to code a jQuery Plugin for HTML Form with Radio Buttons     9

 As you can see, we add also the Bootstrap classes, like "Jumbotron".
We add also the corresponding text:

code a jQuery Plugin for HTML Form with Radio Buttons

 And finally append a new line. The entire for loop will look as this:


 jQuery Plugin for HTML Form with Radio Buttons

After the "for" loop, we append a button to the form:

Plugin for HTML Form with Radio Buttons

The complete javascript file should appear as follows:

HTML Form with Radio Buttons

This is the code to copy-paste:


$(function(){

   $.fn.RadioForm = function(sTitle,sAction,sRadioName,sButtonText,oRadio){        
       
      var oForm = $("<form />",{class:"jumbotron",method:"post",action:sAction}).appendTo(this); 
      
      oForm.prepend("<h1>"+sTitle+"</h1>"); 
       
      var oDiv = $("<div/>",{}).appendTo(oForm);
       
       
      for(i = 0; i < oRadio.length;i++)
      {
          
          
          $("<input/>",
            { 
               type:"radio",               
               name:sRadioName,
               id:oRadio[i] ,
               value:oRadio[i]
           
            }
           ).appendTo(oDiv);
          
          
          
          $("<label/>",{
              text:oRadio[i],
              "for":oRadio[i]
              
          }).appendTo(oDiv);
          
          $("<br />").appendTo(oDiv);
      }
       
       $("<button/>",{
           text:sButtonText,
           class:"btn btn-primary"
       }).appendTo(oForm);
   
   };



})

Now we add the following style to the "styles.css" file:

How to  jQuery Plugin for HTML Form with Radio Buttons

form {
    width:50%;
    margin:0 auto;
    position: relative;
    border:5px solid #c0c0c0;
    border-radius:10px !important;
}



And, back at the HTML file, we use the plugin to insert the runtime html form inside the container  <div>:

How to Plugin for HTML Form with Radio Buttons

The complete HTML5 file should be as follows:

code a  Plugin for HTML Form with Radio Buttons

This is the code :


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Plugin - Form with Radio Buttons</title>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css"></link>
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="Scripts/jqueryPlugin.js"></script>       
</head>
<body>
    <div class="container">         
        <div id="myDiv"></div>
    </div>   
    
</body>

<script>
        
$(function(){
            
    $("#myDiv").RadioForm("jQuery Plugin Form"," ",
                          "RadioOptions","Submit",
                          ["Option 1","Option 2","Option 3","Option 4","Option 5"]);                    
            
});
</script>
</html>


And the resulting HTML Form will appear as this:

Plugin for HTML Form with Radio



That's it....Hoping this article was useful to you,

Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן

Monday, April 27, 2015

How to Fix the OptimisticConcurrencyException in MVC

In this post we describe Step by step How to Fix the OptimisticConcurrencyException in MVC.  
We take care here in just 5 minutes of the errors raised by the Entity Framework while the EDM (Entity Data Model) is confronting a database concurrency issue.

In short, when two or more users try to modify data simultaneously , SQL offers two types of Concurrency Control:
1) Pessimistic Concurrency : lock the data table in advance because someone for sure will try to   affect your changes simultaneously. Action to perform: LOCK the table!
2) Optimistic Concurrency : make your changes and let's hope none will try to alter the record in the meantime. Action to perform: raise an error if the record was altered in the meantime!

Our approach here will be: if indeed the record was altered from the original (AKA the "OptimisticConcurrencyException" was thrown), then we'll refresh the data and save your important updates with a "Client Wins" policy.


How to Fix the OptimisticConcurrencyException in MVC


To apply our approach, we'll use here a "Save(object itemToSave, int #noOfItemsToSave )" method, wrapping the context's SaveChanges().
We just add here a "catch" block to the C# method which tries to update an item to the database.
This way we enforce refreshing the item and saving all your changes overriding the refreshed data.
Therefore, add the following method to your Data Repository (copy-paste:) :

public bool Save(object target, int RecordsNumber)
        {
            try
            {
                return Context.SaveChanges() == RecordsNumber;
            }
            catch (OptimisticConcurrencyException)
            {
                ObjectContext ctx = ((IObjectContextAdapter)Context).ObjectContext;
                ctx.Refresh(RefreshMode.ClientWins, target);
                return Context.SaveChanges() == RecordsNumber;
            }
        }


As you see, the return value tells that all edited items have been successfully persisted to database.
Then you can use this method from your MVC Controller as follows:


 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Blog blog)
        {
            if (ModelState.IsValid)
            {
                db.Update<Blog>(blog);
                db.Save(blog, 1);
                return RedirectToAction("Index");
            }
            ViewBag.BloggerID = new SelectList(db.Retrieve<Blogger>(null), "BloggerID", "Name", blog.BloggerID);
            return View(blog);
        }








Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן




Wednesday, April 22, 2015

How to Execute a CRM Workflow from SSIS - Dynamics CRM and SSIS Integration

In this post we describe Step by step How to Execute a CRM Workflow from SSIS - Dynamics CRM and SSIS Integration  ,  in Sql Server Integration Services.
In this article we create from scratch a small SSIS application which calls - executes a Dynamics CRM workflow (this walkthrough applies to SQLSERVER 2005-2008-2012) . You can schedule this SSIS application to run in the middle of the night , and automatically perform , for example, CRM email sending to customers . For example ,  you could add the small application which we design here , to a bigger one as the following:




How to Execute a CRM Workflow from SSIS - Dynamics CRM and SSIS Integration 



First , open the Toolbox and find the Data Flow Task item:


Execute a CRM Workflow from SSIS - Dynamics CRM and SSIS Integration

Add it to your SSIS application, and click on the "Edit" .
Inside the Data Flow Task item , add a Data Flow Source of your convenience (it can be a raw file, ADO NET, OLE DB , Excel, XML , or even a Dynamics CRM source) .
Connect to it some Data Flow Transformation (such as a Derived Column or a Data Conversion).
We are using here a Dynamics CRM and SSIS Integration tool from KingsWaySoft. 
According to the   KingswaySoft  Help manual which can be found here , starting from the version 3.0 of this tool, there is an option for calling a Dynamics CRM Workflow from SSIS. 
Therefore, look for a Data Flow Destination of the type "Dynamics CRM Destination", and append it to the previous items ,  sequentially connected:


How to Execute a CRM Workflow from SSIS - Dynamics CRM and SSIS Integration 1


Your Data Flow Task should by now look as the following:




How to Execute a CRM Workflow from SSIS


Now we'll edit the Dynamics CRM Destination's properties, to make it able to execute a CRM Workflow.
Open the "Edit" window in the Dynamics CRM Destination , and select the "Execute Workflow" option at "Action":


CRM Workflow from SSIS

The "Destination Entity" should be the ENTITY over which you want the Workflow act.
At the "Execute Workflow Option" you will be able to choose between all the available activated (published) workflows which are set to run over the current Entity.
Select the Workflow that you want to call from SSIS.
Then open the "Columns" tab:


 Dynamics CRM and SSIS Integration


This tab will automatically contain only one column. A very important Entity property will appear here: the ID for the Entity record on which you want the workflow to be run.
This property is of GUID type. However, you send it a string containing the required ID. It doesn't need to be of uniqueidentifier (GUID) type: as you can see at the snapshot above, we send a DT_WSTR SSIS type with length 100 . Also, the length doesn't have to be the length of a string containing a guid , that means 36 (32 digits plus 4) . 
That's all that the Dynamics CRM Destination item needs to execute your Workflow.
Build the SSIS application. Run it in debugger mode (F5) , and your workflow will be triggered!!!
If you receive an error message, just try to run your workflow by hand, right from the CRM entity form, because probably the cause of the error will be there.
Hoping this article was useful to you,

Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן

Tuesday, April 21, 2015

How to check SSIS Variables values at debugging runtime

In this tutorial we describe Step by step How to check SSIS Variables values at debugging runtime   in Sql Server Integration Services .
We'll see here in just 5 minutes how to watch SSIS variables values at debugging, distinguishing between those at Foreach Loop Containers and those at Data Flow Tasks , using the following SSIS application:
How to check SSIS Variables values at debugging runtime



How to check SSIS Variables values at debugging runtime


In the snapshot below can be seen the guiding principles of runtime variables checking  at an "Foreach Loop Container" :
check SSIS Variables values at debugging runtime

First, select the SSIS flow item where you want to watch the variables.
Remember that variables have a scope, therefore you must check that that scope includes the selected item.
For this example, we'll start with a Data Flow Task .
Once you decided what flow item to watch, right click the mouse on it, and click the "Edit Breakpoints" menu item:

values at debugging runtime

Then, select the Break condition to stop the runtime . It can be the On PreExecute event, or any of the Events that you see on the snapshot below:


Variables values at debugging runtime


In the case of a Foreach Loop Container, it is advisable that you spot the variables at the beginning of every loop iteration . Therefore select from the checklist the last item:



SSIS Variables values at debugging runtime

You can also set in which cases to stop the flow: always, or only when the breakpoint has been fetched determined times:

How to check   values at debugging


After you have set the breakpoints, debug the application and, when the breakpoint has been hit, open the "Locals" window. In this window you will find all variables in scope:

check SSIS Variables values at debugging runtime

How to check SSIS Variables values at debugging



That's all. We hope that this example will be useful to you.

Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן






Monday, April 20, 2015

Error 8 'System.Web.Http.HttpConfiguration' does not contain a definition for 'MapODataServiceRoute'


In this article we fix the Error 8 'System.Web.Http.HttpConfiguration' does not contain a definition for 'MapODataServiceRoute', while adding a route to an ASP.NET application containing an OData Web API.



 System.Web.Http.HttpConfiguration MapODataServiceRoute


The error is originated after the Microsoft decision to create a new assembly to support the v4.0 version of the OData protocol, but keeping the OLD assembly which supported the version 3.0. The resultant side by side scenario where applications can reference to v3.0 and v4.0 simultaneously, can be the source of errors as the one we're fixing here. 
May be one of the more important changes here is , the "QueryableAttribute"  has now been renamed "EnableQueryAttribute". You can explore the assemblies differences in this MSDN article.

The new OData v4.0 assembly is "System.Web.OData" instead of the OLD "System.Web.Http.OData" , and the new package is called "Microsoft.AspNet.OData".

So the error appears after you configure the OData Endpoint at the WebApiConfig  Register()  :

Error  8 'System.Web.Http.HttpConfiguration' does not contain a definition for 'MapODataServiceRoute'

public static void Register(HttpConfiguration config)
        {
            
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Note>("Notes");
            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: "OData",
                model: builder.GetEdmModel());          

        }

The "routePrefix" sets the name of the Service Endpoint.

When you compile, you receive the following error message:



Because the Extension Methods in the new OData v4.0 assembly were moved to "System.Web.OData.Extensions", and the method "MapODataRoute" has been renamed to "MapODataServiceRoute", we must reference to that extensions namespace.
Therefore go to the usings section up in your C# file, and add the Extensions namespace to allow the use of the extension method that we are supposed to use:



using System.Web.Http.OData;
using System.Web.OData.Builder;
using System.Web.Http;
using System.Web.OData.Extensions;



That's all!!!!


By Carmel Shvartzman

עריכה: כרמל שוורצמן

Sunday, April 19, 2015

How to Send Emails from an MVC App using Gmail SMTP


In this post we describe Step by step How to Send Emails from an MVC App using Gmail SMTP and C#.  
We implement here in just 15 minutes an Email sender in Asp.Net MVC, using the SMTP from Gmail.
The complete code for this tutorial can be get from the following GitHub repository:
https://github.com/CarmelSoftware/MVC_EmailSender
Also, we use Twitter Bootstrap for the Web design of the app:

How to Send Emails from an MVC App using Gmail SMTP



Step by step How to Send Emails from an MVC App using Gmail SMTP



First, let's allow the Gmail security options to sending Emails from "less secure applications", by entering to    https://www.google.com/settings/security/lesssecureapps  :

How to Send Emails from an MVC App using Gmail SMTP


Then , open your MVC project and create a class to represent the Email object:

How to Send Emails from an MVC App using Gmail SMTP


Next, add an empty Controller:


How to Send Emails


Add a View for the Index Action method:


How to Send Emails from an MVC


We want to create an Email entity , so use the "Create" scaffold template, and the "Email" Model class:


Send Emails from an MVC App using Gmail SMTP

You will automatically get the following View:


Emails from an MVC App using Gmail SMTP

Now, let's customize this template to use the Twitter Bootstrap:


How to Send Emails from an MVC App

If you like, copy paste the code from the GitHub repository at  https://github.com/CarmelSoftware/MVC_EmailSender .
The next step is to take care of the Email object that this View will send to the Controller using the HTTP POST method. We add another Action method to take care of that. Change the "Index" action name for something more relevant to our issue, like "JustSendIt" (also, change the name of the View accordingly):



How to Send Emails from an MVC App using Gmail

This Controller method will receive and send the Email using an utility class that we'll code next.
Now add another action method named "Details" for showing the user the email contents that have been sent:



How to Send Emails from an MVC App using Gmail SMTP     1
This method just fetches the Email object stored at the TempData and display its properties . Add a Strongly typed View for en Email object using the "Details" template:

How to Send Emails from an MVC App using Gmail SMTP      2




How to Send Emails from an MVC App using Gmail SMTP    3

Customize the tool generated markup with the following, to add the CSS3 style from Twitter Bootstrap:


How to Send Emails from an MVC App using Gmail SMTP    4

Add the most updated versions of the Twitter Bootstrap and the JQuery javascript framework , at the _Layout.cshtml file in the Shared folder:

How to Send Emails from an MVC App using Gmail SMTP    5

Add the Data Annotations to the Email class, to generate the javascript that validates the data at client side:


Send Emails from an MVC App using Gmail SMTP

Finally, let's code the class that will send Emails using Gmail. Create the following utility class, that uses the SmtpClient, the MailMessage and the MailAddress classes:


How to Send from an MVC App using Gmail SMTP


Take care of respecting the Port 587 and the rest of the settings; elsewhere, this will not work.
Also, add a method for safely reading settings from the Web.config file, as follows:

Send Emails  MVC App using Gmail SMTP
Set the above AppSettings keys at the Web.config file, using exactly the same User Name and User Password as at your Gmail account:

 MVC App using Gmail SMTP


Then, your Controller will receive a boolean flag ("Item1" from the Tuple) and redirect the HTTP request to the Details action, or in case of error, will show the Error Message in Item2 and redirect back to the main web page:

How to MVC App using Gmail
To browse to the main web page, change the RouteConfig's default route as follows:


App using Gmail SMTP
Run the application:


 using Gmail SMTP
This Bootstrap design will also display the validation checking as follows:


Gmail SMTP

After sending the Email, the Details View displays its contents:


How to Send SMTP


We hope that this post has helped you ..

Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן