20 December 2015

BizTalk consume web service using dynamic address

Create a dynamic port
Set URL of the port using expression

/* set port address */
portDynamicSend(Microsoft.XLANGs.BaseTypes.Address) = msgDynamicAddress.DestinationURL;
/* set port type */
portDynamicSend(Microsoft.XLANGs.BaseTypes.TransportType) = "WCF-BasicHttp";

Modify the message using expression

msgSend2 = msgSend;
/* set web service operation name */
msgSend2(BTS.Operation)="Propose";
msgSend2(WCF.PropagateFaultMessage)= true;


/* if security is required, add the below lines */
msgSend2(WCF.SecurityMode)="Transport";
msgSend2(WCF.TransportClientCredentialType)="None";

How to add legend to Chart.js graph



 @model C2.Models.ChartModel  
 @{  
   ViewBag.Title = "Chart";  
 }  
 <h2>Chart</h2>  
 <div>  
   <h3>Data</h3>  
   @*@Html.Raw(Model.ChartHtmlDisplay)*@  
 </div>  
 <div style="width:50%">  
   <div>  
     <canvas id="canvas" height="450" width="600"></canvas>  
   </div>  
   <div id="divLegend">  
   </div>  
 </div>  
 <script>  
   var lineChartData = {  
   @Html.Raw(Model.ChartHtml)  
   };  
   window.onload = function(){  
     var options = {  
       legendTemplate : '<ul>'  
               +'<% for (var i=0; i<datasets.length; i++) { %>'  
                +'<li>'  
                +'<span style=\"color:<%= datasets[i].pointColor %>;font-family:Arial;font-size:1em\">'  
                +'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'  
                +'</span>'  
               +'</li>'  
              +'<% } %>'  
             +'</ul>'  
     }  
     var ctx = document.getElementById("canvas").getContext("2d");  
     //don't forget to pass options in when creating new Chart  
     var lineChart = new Chart(ctx).Line(lineChartData, options);  
     //then you just need to generate the legend  
     var legend = lineChart.generateLegend();  
     //and append it to your page somewhere  
     $('#divLegend').html(legend);  
     var ctx = document.getElementById("canvas").getContext("2d");  
     window.myLine = new Chart(ctx).Line(lineChartData, {  
          responsive: true  
     });  
   }  
 </script>  



17 November 2015

An easy way to generating year, month list with SQL

DECLARE @startmonth      int = 1
DECLARE @endmonth        int = 12
DECLARE @startyear       int = 2012
DECLARE @endyear         int = 2015
;
WITH monthlist AS
(
    SELECT @startmonth AS m
    UNION ALL
    SELECT m+1 FROM monthlist WHERE m+1<=@endmonth
)
,yearlist AS
(
    SELECT @startyear AS y
    UNION ALL
    SELECT y+1 FROM yearlist WHERE y+1<=@endyear
)
        SELECT y,
               m
          FROM yearlist
    CROSS JOIN monthlist
      ORDER BY y,
               m
        OPTION (maxrecursion 1000)

12 November 2015

MVC web service in JSON

Here is an example

    public class HomeController : Controller
    {
        public ActionResult ListJobs()
        {
            List jobs;
            GraphEntities db = new GraphEntities();
            jobs = db.Jobs.ToList();
            return Json(jobs, JsonRequestBehavior.AllowGet);
        }


Here is the output

[{"JobID":1,"Job1":"Software Engineer"},{"JobID":2,"Job1":"Junior Programmer"},{"JobID":3,"Job1":"Senior Programmer"},{"JobID":4,"Job1":"Database Administrator"},{"JobID":5,"Job1":"Business Analyst"}]

How to use partial view in MVC, an example

Here is the index page

@model  WebApplication1.Models.GridData
<!doctype html>
@{Layout = null;}
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Home</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
</head>
<body>
   <h1>Header</h1>
        <input type="button" name="btnGetJob" id="btnGetJob" value="GetJob" class="Button" onclick="GetJob();" />
        <div id="divDataGrid">
            @Html.Partial("_DataGrid", Model)
        </div>
    <script>
        function GetJob()
        {$.ajax({
                        type: "POST",
                        url: "/Home/_DataGrid",
                        success: function (data) {
                            $('#divDataGrid').html(data);
                        },
                        error: function () {
                            alert('error');
                        },
                        complete: function () {}
                   })
        }
    </script>
</body>
</html>

Here is the partial view

@model WebApplication1.Models.GridData
@{Layout = null;}
<table class="table">
    <tr>
        <th>
            @Html.DisplayTextFor(model => model.message)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model.jobs)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Job1)
            </td>

        </tr>
    }
</table>

Here is the data model 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class GridData
    {
        public string message { get; set; }
        public  List<Job> jobs { get; set; }

        public GridData()
        {
            GraphEntities db = new GraphEntities();
            jobs = db.Jobs.ToList();
        }
    }
}

Here is the controller

    public class HomeController : Controller
    {
        private static int SessionCount = 0;
        public ActionResult Index()
        {
            GridData gd = new GridData();
            gd.message = SessionCount.ToString();
            return View(gd);
        }
        public ActionResult _DataGrid()
        {
            SessionCount++;
            GridData gd = new GridData();
            gd.message = SessionCount.ToString();
            return View(gd);
        }
        ...

Here is the output


15 October 2015

Using Chart.js with MVC



This is how the view might look

 @model wapitest.Models.ChartData  
 <!doctype html>  
 @{  
   ViewBag.Title = "Index";  
   Layout = null;  
 }  
 <html>  
 <head>  
   <title>Line Chart</title>  
   <script src="~/Scripts/Chart.js"></script>  
 </head>  
 <body>  
   @Model.title  
   <div style="width:30%">  
     <div>  
       <canvas id="canvas" height="450" width="600"></canvas>  
     </div>  
   </div>  
   <script>  
           var lineChartData = {  
             labels : @Html.Raw(Model.label) ,  
                datasets : [  
                     {  
                          label: "D1",  
                          fillColor : "rgba(220,220,220,0.2)",  
                          strokeColor : "rgba(220,220,220,1)",  
                          pointColor : "rgba(220,220,220,1)",  
                          pointStrokeColor : "#fff",  
                          pointHighlightFill : "#fff",  
                          pointHighlightStroke : "rgba(220,220,220,1)",  
                          data : @Model.data  
                     },  
                     {  
                          label: "D2",  
                          fillColor : "rgba(151,187,205,0.2)",  
                          strokeColor : "rgba(151,187,205,1)",  
                          pointColor : "rgba(151,187,205,1)",  
                          pointStrokeColor : "#fff",  
                          pointHighlightFill : "#fff",  
                          pointHighlightStroke : "rgba(151,187,205,1)",  
                          data : [7,6,5,4,3,2,1]  
                     }  
                ]  
           }  
      window.onload = function(){  
           var ctx = document.getElementById("canvas").getContext("2d");  
           window.myLine = new Chart(ctx).Line(lineChartData, {  
                responsive: true  
           });  
      }  
   </script>  
 </body>  
 </html>  


This is the model

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 namespace wapitest.Models  
 {  
   public class ChartData  
   {  
     public string label { get; set; }  
     public string data { get; set; }  
     public string title { get; set; }  
   }  
 }  


And this is the controller function

     public ActionResult Chart()  
     {  
       ViewBag.Title = "Line chart";  
       ChartData cd = new ChartData();  
       cd.title = "Chart Title";  
       cd.data = "[1,5,10,15,5,4,3]";  
       cd.label = @"[""mon"", ""tue"", ""wed"", ""thu"", ""fri"", ""sat"", ""sun""]";  
       return View(cd);  
     }  

12 October 2015

How to do inline css

 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <title>Welcome to our survey</title>  
   <link href="~/Scripts/jquery-ui.css" rel="stylesheet">  
   <script src="~/Scripts/jquery-1.10.2.js"></script>  
   <script src="~/Scripts/jquery-ui.js"></script>  
   <STYLE type="text/css">  
     body{  
       font-family:Verdana,Arial,sans-serif;  
       font-size:0.8em;  
     }  
     .QuestionLabel {  
       left:10em;  
       position:relative  
     }  
     .AnswerInput{  
       left:15em;  
       position:relative  
     }  
   </STYLE>  
 </head>  
 <body>  
   <label for="country" class="QuestionLabel">Select your country: </label>  
   <input id="country" class="AnswerInput">  
   <br />  

Posting data in MVC example

Here is the view

 <!doctype html>  
 @{  
   ViewBag.Title = "Index";  
   Layout = null;  
 }  
 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <title>Save City</title>  
   <link href="~/Scripts/jquery-ui.css" rel="stylesheet">  
   <script src="~/Scripts/jquery-1.10.2.js"></script>  
   <script src="~/Scripts/jquery-ui.js"></script>  
 </head>  
 <body>  
   <label for="country">Select your country: </label>  
   <input id="country">  
   <br />  
   <label for="city">Select your city: </label>  
   <input id="city">  
   <br />  
   <input type="button" name="btnclick" id="btnclick" value="click" />  
   <div id="divAlert"> </div>  
   <script>  
     $('#btnclick').click(function () {  
     $.ajax({  
       url: '@Url.Action("InsertCity", "Home")',  
       type: 'POST',  
       data: JSON.stringify({ countryName: $('#country').val(), city: $('#city').val() }),  
       contentType: 'application/json; charset=utf-8',  
       dataType: 'json',  
       success: function (rdata) {  
         $('#divAlert').html(rdata.result);  
       },  
       error: function (req, status, error) {  
         alert("R: " + req + " S: " + status + " E: " + error);  
       }  
     });  
   })  
   </script>  
 </body>  
 </html>  


Here is the controller function

     [HttpPost]  
     public JsonResult InsertCity(string countryName, string city)  
     {  
       string cnnStr = ConfigurationManager.ConnectionStrings["GraphConnection"].ConnectionString;  
       SqlConnection dcnn = new SqlConnection(cnnStr);  
       dcnn.Open();  
       SqlCommand dcmd = new SqlCommand("dbo.InsertCity", dcnn);  
       dcmd.CommandType = CommandType.StoredProcedure;  
       dcmd.Parameters.AddWithValue("@CountryName", countryName);  
       dcmd.Parameters.AddWithValue("@City", city);  
       SqlParameter dRet = new SqlParameter("@ReturnValue", SqlDbType.Int, 4);  
       dRet.Direction = ParameterDirection.ReturnValue;  
       dcmd.Parameters.Add(dRet);  
       dcmd.ExecuteNonQuery();  
       int iRet = Utility.ConvertToInt(dRet.Value);  
       return Json(new { result = "successfully submitted" }, JsonRequestBehavior.AllowGet);  
     }  



08 October 2015

How to create autocomplete text box in MVC

Here is the View page, notice I include jquery-ui.css, jquery-1.10.2.js and jquery-ui.js and I am calling the FindCountry function from the controller

 <!doctype html>  
 @{  
   ViewBag.Title = "I2";  
   Layout = null;  
 }  
 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <title>autocomplete demo</title>  
   <link href="~/Scripts/jquery-ui.css" rel="stylesheet">  
   <script src="~/Scripts/jquery-1.10.2.js"></script>  
   <script src="~/Scripts/jquery-ui.js"></script>  
 </head>  
 <body>  
   <label for="country">Select your country: </label>  
   <input id="country">  
   <script>  
     $("#country").autocomplete({  
       source: function (request, response) {  
         var item = new Array();  
         $.ajax({  
           async: false,  
           cache: false,  
           type: "POST",  
           url: "@(Url.Action("FindCountry", "Home"))",  
           data: { "term": request.term },  
         success: function (data) {  
           for (var i = 0; i < data.length ; i++) {  
             item[i] = { label: data[i].Value, Id: data[i].Key };  
           }  
         }  
         });  
         response(item);  
       },  
     });  
   </script>  
 </body>  
 </html>  


and here is the function in the controller

     [AcceptVerbs(HttpVerbs.Post)]  
     public JsonResult FindCountry(string term)  
     {  
       string cnnStr = ConfigurationManager.ConnectionStrings["GraphConnection"].ConnectionString;  
       SqlConnection dcnn = new SqlConnection(cnnStr);  
       SqlCommand dcmd = new SqlCommand("dbo.FindCountry", dcnn);  
       dcmd.CommandType = CommandType.StoredProcedure;  
       dcmd.Parameters.AddWithValue("@Term", term);  
       SqlDataAdapter da = new SqlDataAdapter();  
       da.SelectCommand = dcmd;  
       DataSet ds = new DataSet();  
       da.Fill(ds);  
       List<KeyValuePair<string, string>> cty = ds.Tables[0].AsEnumerable().Select(row => new KeyValuePair<string, string>((string)row["CountryCode"], (string)row["CountryName"])).ToList();  
       return Json(cty, JsonRequestBehavior.AllowGet);  
     }  

21 September 2015

How to convert dataset to KeyValuePair using Linq

Here is an example
 
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Autocomplete3(string term)
        {
            string cnnStr = ConfigurationManager.ConnectionStrings["GraphConnection"].ConnectionString;
            SqlConnection dcnn = new SqlConnection(cnnStr);
            SqlCommand dcmd = new SqlCommand("dbo.GetCountry", dcnn);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = dcmd;
            DataSet ds = new DataSet();
            da.Fill(ds);

            List> cty = ds.Tables[0].AsEnumerable().Select(row => new KeyValuePair((string)row["CountryCode"], (string)row["CountryName"])).ToList();

            return Json(cty, JsonRequestBehavior.AllowGet);
        }