Reusable ASP.NET MVC user control in AngularJS (Same page)

November 13, 2012 Leave a comment

“AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. Out of the box, it eliminates much of the code you currently write through data binding and dependency injection. And it all happens in JavaScript within the browser making it an ideal partner with any server technology.” – According to AngularJS documentation

Here I am going to show how we can use same asp.net mvc user controls multiple times in a single page with different sets of data.
As I am using asp.net mvc as server side technology, asp.net mvc razor views are used to produce the templates for AngularJS. For AngularJS it’s not a matter which server side technology you are going to use. It will work based on the syntax it needs to make it an AngularJS application.

In this example the index.cshtml is using “Person” user control multiple times.

@{
    ViewBag.Title = "Dashboard";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-controller="PersonCntrl">
    <div ng-controller="Person1Cntrl" class="person-widget">
        @Html.Partial("UserControl/Person")
    </div>
    <div ng-controller="Person2Cntrl" class="person-widget">
        @Html.Partial("UserControl/Person")
    </div>
    <br />    
    <div>
        <input type="button" ng-click="clicked()" value="Click" style="width:200px; height:40px; margin-left:20px;" />
    </div>
</div>

Here in Index.cshtml we have three controllers. The personCntrl is the base controller and Person1Cntrl and Person2Cntrl are two child controllers. So here we are using two separate controllers to use the same user control multiple times. This is because we want to use separate scope for each user control instance.

The “person” user control:

div>
    <label>
        Name:</label>
    <input type="text" ng-model="person.name" />
</div>
<div>
    <label>
        Address</label>
    <textarea ng-model="person.address"></textarea>
</div>
<div>
    <label>
        Email</label>
    <input type="text" ng-model="person.email" />
</div>
<div>
    <label>
        Phone Number</label>
    <input type="text" ng-model="person.phone" />
</div>
<div>
<label>TIN No</label>
<input type="text" ng-model="person.tinNo"/>
</div>

Controllers:

function PersonCntrl($scope) {
    $scope.person1 = { name: "Mizan", address: "Bagmara, Rajshahi", email: "mizanur.rahman@selise.ch", phone: "01718786498", tinNo: "TIN-000000" };
    $scope.person2 = { name: "Tasnim", address: "Puthia, Rajshahi", email: "reza@selise.ch", phone: "00000000000", tinNo: "TIN-11111" };

    $scope.clicked = function () {
        alert($scope.person1.name);
        alert($scope.person2.name);
    };
}

function Person1Cntrl($scope) {
    $scope.person = $scope.person1;
}

function Person2Cntrl($scope) {
    $scope.person = $scope.person2;
}

The main trick is that we are setting the person1 to person in Person1Cntrl and person2 to person in Person2Cntrl. So, in first user control it will bind person1 object and in second user control it will bind person2 object in the view.

Now if we change in the view we will get the changes in the person1 and person2 object accordingly.

The output page will look like:

Image 1

Now if we change the value in the name field to “Mizan123” it will show “Mizan123” for alert($scope.person1.name);

Image 2

Thanks for reading this article. Any suggestion will be appreciated.

Categories: AngularJS, ASP.NET MVC

Cross-Origin Resource Sharing

March 1, 2012 Leave a comment

Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. Cross-site HTTP requests initiated from within scripts have been subject to well-known restrictions, for well-understood security reasons.
The Web Applications Working Group within the W3C has proposed the new Cross-Origin Resource Sharing (CORS) recommendation, which provides a way to web servers to securely handle cross site requests.
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser.
A simple cross site request happen when we will make an https ajax request for login from a page loaded with http protocol (I will give an example of this). This can be happen for an http ajax call to a separate domain.
Example:
Here I will show how to make an https ajax call to a WCF service from a page loaded with http.
From the javascript you should make the request in the following way

var url = “https://serveraddress/service1.svc/UserInfo”
var invocation = new XMLHttpRequest();
var invocationHistoryText;

function UserInfo() {
    if (invocation) {
        invocation.open('GET', url, true);
        invocation.onreadystatechange = handler;
        invocation.send();
    }
    else {
        alert("No Invocation TookPlace At All");
    }
}

function handler(evtXHR) {
    if (invocation.readyState == 4) {
        if (invocation.status == 200) {
            var response = invocation.response;
            alert(response);
        }
        else
            alert("Invocation Errors Occured");
    }
}

And from the service we need to add header Access-Control-Allow-Origin with value http://Serveraddress to allow cross site request.

  public string UserInfo()
        {
            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "http://serveraddress");            
return "This is your information";
}

Visit for details https://developer.mozilla.org/En/HTTP_access_control

Categories: AJAX

Cross Domain WCF service Call using AJAX / Ajax Call to HTTPS service from HTTP page (With JSONP)

February 23, 2012 1 comment

I was going to implement SSL login for a mobile web site. The implementation was like that, we will invoke a WCF service and the user will then be logged in to the service hosted in IIS.
To make the service asp.net authentication compatible we have used attribute bellow in the service.

 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

The problem was that we have used http protocol to load the login page and we have to call a separate service using https(SSL).Which creates cross site http requests.

Cross-site HTTP requests:
Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. For instance, a resource loaded from Domain A (http://domaina.example) such as an HTML web page, makes a request for a resource on Domain B (http://domainb.foo), such as an image, using the img element (http://domainb.foo/image.jpg).
You can learn detail from here

https://developer.mozilla.org/en/http_access_control

To solve this problem we have to use JSonp instead of JSon.
JSONP or “JSON with padding” is a complement to the base JavaScript Object Notation JSON data format. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the Same origin policy.

Bellow I am describing the workthrough I have followed.

Step 1:
1. Create a self signed certificate in your IIS
a. Server Certificates – > Create Self Signed Certificate(right side) -> Enter a name(Service1) ->Ok
2. Website (Default Web Site) – >(Right Click Menu) -> edit Bindings-> Add-> Select “Https” in Type -> Specify IP-> Select certificate you have created (Service1) in the SSL Certificate dropdown -> Ok

Step2:
To make WCF service to support SSL (https) we need to set Security Mode=”Transport”

<binding name="DefaultBindingSSL">
    <security mode="Transport">
      </security>
</binding>

<service name="Service1">
        <endpoint address="" behaviorConfiguration="RESTFriendly" binding="webHttpBinding" bindingConfiguration="DefaultBindingSSL" contract="Sentrana.SpoonBytePro.IEnterAppService" />
</service>

Step 3:
In the service we have to write the response in the following way

var context = HttpContext.Current;
      	string Callback = context.Request.QueryString["callback"];
      JsonSerializer ser = new JsonSerializer();
context.Response.Write(Callback + "(");
      ser.Serialize(HttpContext.Current.Response.Output, loginResponse);
      context.Response.Write(");");

Here, loginResponse is the object we want to return to the client.

Step 4:
Now we can call from the client using the following URL
https://ServiceAddress/Service1.svc/Login?usrname=username&password=password&callback=?

“Callback=?” is the thing we need to make it JSONP
Bellow is a complete ajax call

$.ajax({
            url: https://ServiceAddress/Service1.svc/Login?usrname={username}&amp;password={password}&amp;callback=?,
            type: "GET",
            async: true,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            timeout: 10000,
            success: function (loginData) {
                    return;
                }

                var loginResponseFromServer = loginData;
                localStorage.setItem('LoginResponse', JSON.stringify(loginData));
            },
            error: function (xhr, settings, exception) {                
            }
        });

Some related links you can visit to learn more:

http://learn.iis.net/page.aspx/144/how-to-set-up-ssl-on-iis/
http://www.digicert.com/ssl-certificate-installation-microsoft-iis-7.htm
http://weblogs.asp.net/srkirkland/archive/2008/02/20/wcf-bindings-needed-for-https.aspx
http://api.jquery.com/jQuery.ajax/
http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
http://stackoverflow.com/questions/1012777/https-request-via-ajax-from-http-page

Categories: AJAX, WCF

LINQ Dynamic Query

December 27, 2011 Leave a comment

LINQ is a nice feature introduced in .Net 3.5 VS 2008 first. It is very effective because it can be used to query data from multiple sources.

LINQ queries are type safe which provides us lots of benefits like compile time error checking. When we use LINQ to SQL or Microsoft Entity Framework for data access we may need to create dynamic query based on different conditions. In such scenario we usually need to create queries concatenating strings and construct query strings on the fly.
To enable such a dynamic query working in .net Microsoft provides Dynamic Query Library which can be found here in http://msdn.microsoft.com/en-us/vstudio/bb894665.aspx

Also ScottGu writes a blog on how to use this in here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Bellow is a sample code

private IEnumerable<Order> GetOrdersSearchAdvanced(OrderAdvancedSearhViewModel advancedSearchOption, bool? enquiry)
        {
            IEnumerable<Order> orders;
            DateTime fromDate = DateTime.ParseExact(advancedSearchOption.FromDate, "dd.MM.yyyy", CultureInfo.InvariantCulture);
            DateTime toDate = DateTime.ParseExact(advancedSearchOption.ToDate, "dd.MM.yyyy", CultureInfo.InvariantCulture);
            var conditionQuery = "";

            if (!string.IsNullOrEmpty(advancedSearchOption.LeadName))
            {
                if (advancedSearchOption.Option1.ToUpper() == "AND")
                {
                    conditionQuery += " and NameGolf.Contains(@2)";
                }
                else if (advancedSearchOption.Option1.ToUpper() == "OR")
                {
                    conditionQuery += " or NameGolf.Contains(@2)";
                }
            }

            if (!string.IsNullOrEmpty(advancedSearchOption.Region))
            {
                if (advancedSearchOption.Option2.ToUpper() == "AND")
                {
                    conditionQuery += " and Region.Contains(@3)";
                }
                else if (advancedSearchOption.Option2.ToUpper() == "OR")
                {
                    conditionQuery += " or Region.Contains(@3)";
                }
            }

            orders = orderRepository.GetOrders(enquiry).Where("OrderDate>=@0 and OrderDate<=@1" + conditionQuery, fromDate, toDate, advancedSearchOption.LeadName, advancedSearchOption.Region);
            return orders;
        }

In order repository

public class OrderRepository
    {
private PAGSDataContext entities = new PAGSDataContext();

        public IQueryable<Order> GetOrders(bool? enquiry)
        {
            if (enquiry != null && enquiry.Value == true)
            {
                return entities.Orders.Where(x => x.Ordertype.ToUpper() == "E");
            }

            return entities.Orders.Where(x => x.Ordertype.ToUpper() == "O" || x.Ordertype.ToUpper() == "B");
        }
}
Categories: LINQ

JQuery Mobile – use single page architecture with multiple html files

December 13, 2011 1 comment

I am basically a .net developer with expertise in html, css, jquery, javascript etc. For one of my new project (a big project) I am working with jQuery Mobile now and also getting some knowledge of it day by day.
You can see the details about JQuery Mobile in http://jquerymobile.com
In JQuery Mobile we can specify multiple pages in a single html file with an attribute data-role=”page”.
For example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test </title>
</head>

<body>
<div data-role="page" id="page1 " align="center">
</div>

<div data-role="page" id="page2 " align="center">
</div>

<div data-role="page" id="page3 " align="center">
</div>
</body
</html>

We can also keep the pages in separate files.
The single page architecture is better in consideration of performance. But the problem is the manageability.[Note: If the page size is too big it can also make some performance problem]

So, The concept I am going to describe here is
– Keep the pages in a single html file at reasonable size and which pages will not be used from other html file pages.
– Keep the other pages in separate file as you can manage.
– Load the required pages dynamically in the current html page.

Suppose you have three files

File1.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test </title>
</head>

<body>
<div data-role="page" id="page1 " align="center">
</div>

<div data-role="page" id="page2 " align="center">
</div>

<div data-role="page" id="page3 " align="center">
</div>
</body
</html>

File2.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test </title>
</head>

<body>
<div data-role="page" id="page4 " align="center">
</div>

<div data-role="page" id="page5 " align="center">
</div>

<div data-role="page" id="page6 " align="center">
</div>
</body
</html>

Common.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test </title>
</head>

<body>
<div data-role="page" id="page7 " align="center">
</div>

<div data-role="page" id="page8 " align="center">
</div>

<div data-role="page" id="page9 " align="center">
</div>
</body
</html>

Here we need common.html from both File1.html and File2.html and we want to use single page architecture.

So, we will load the pages from common.html to File1.html dynamically when we need from File1.html and same for File2.html.

Here is the code which will load the pages for you.

function loadPages(pagePathList, index) {
    if (index == undefined) {
        index = 0;
    }
 
    $.get(pagePathList[index], {}, function (data) {
        var startIndex = data.indexOf("<div data-role");
        var endIndex = data.indexOf("</body>");
        data = data.substring(startIndex, endIndex);
        $('[data-role="page"]').filter(":last").after(data);
 
        index++;
 
        if (index < pagePathList.length) {
            loadPagesToCurrentpage(pagePathList, index);
        }
    });
}


  $('#page1’).live('pagecreate', function (event, ui)
   {
var pagePathList = new Array();
pagePathList.push("common.html");	
loadPages(pagePathList);    
   }

Here I am loading the pages from common on page1 ‘pagecreate’ event. You can do it with the event as you need.

After the load the File1.html will look like (dynamically)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test </title>
</head>

<body>
<div data-role="page" id="page1 " align="center">
</div>

<div data-role="page" id="page2 " align="center">
</div>

<div data-role="page" id="page3 " align="center">
</div>
<div data-role="page" id="page7 " align="center">
</div>

<div data-role="page" id="page8 " align="center">
</div>

<div data-role="page" id="page9 " align="center">
</div>
</body
</html>

So we can show page9 from page1 as single page architecture Like

<div data-role="page" id="page1 " align="center">
	<a href="page9">show page 9</a>
</div>

Any suggestion will be appreciated.

Categories: JQuery Mobile

Popup / Message Box in JQuery Mobile

November 17, 2011 1 comment

JQuery Mobile:
JQuery Mobile is a new technology to develop device independent web site or app for iPhone, Android, blackberry etc.

You can see the details in website http://jquerymobile.com . Currently JQuery Mobile 1.0 RC3 is released. The JQuery Mobile team is working very hard and expect things will be more beautifull soon.

You can see the device supported by JQuery Mobile here http://jquerymobile.com/gbs/ .
As I am going to show you how can you develop a nice message box /popup for JQuery mobile eventually I will give you an API by which you can show popup in your JQuery mobile app, I am not describe the details of JQuery Mobile here.

I have made search in the web to find a nice popup or message box where I can add options like ok/ cancel/yes/no etc. and also I can modify and customize myself.

I found something in http://dev.jtsage.com/jQM-SimpleDialog/ which can be used for showing dialog and popup. But it makes something difficult for me when the page size is small or when I saw in mobile. The problem is it then show the top cross button and some other things. But I want something like a real popup message.

I also found another plugin JQuery-mobile-toast in https://github.com/jjoe64/jquery-mobile-toast.
But to me it looks difficult to add my custom html in the message box. So I have developed myself a new one which I think you will like.

So, lets see the code my example/api

MessageBox.js

var MESSAGE_TYPE = { "Information": 1, "Error": 2, "Confirmation": 3 };
 
MessageBox =
{
    close: function () {
        MessageBox.successEvent = function () { MessageBox.close() }
        MessageBox.cancelEvent = function () { MessageBox.close() }
        $(".popup_messagebox").remove();
        $(".cover_background").remove();
    },
 
    successEvent: function () { MessageBox.close(); },
 
    cancelEvent: function () { MessageBox.close(); },
 
    show: function (messageType, header, content, onSuccess, onCancel) {
        var popupStr = "<div align='center' class='popup_messagebox ui-simpledialog-container ui-overlay-shadow ui-corner-all pop ui-body-b in'>"
                    + getMessageContent(messageType, header, content) + "</div>";
        $("body").append(popupStr);
        $(".popup_messagebox").center();
        $(".popup_messagebox").trigger("create");
        $("body").append($('<div class="cover_background"></div>'));
 
        if (onSuccess != undefined || onSuccess != null) {
            this.successEvent = function () { onSuccess(); MessageBox.close(); }
        }
        else {
            this.successEvent = function () { MessageBox.close() }
        }
 
        if (onCancel != undefined || onCancel != null) {
            this.cancelEvent = function () { MessageBox.close(); onCancel(); }
        }
        else {
            this.cancelEvent = function () { MessageBox.close() }
        }
 
        $(".popup_messagebox #MsgOkButton").bind("click", this.successEvent);
        $(".popup_messagebox #CancelButton").bind("click", this.cancelEvent);
    }
}
 
function getMessageContent(messagType, header, content) {
    var messageContent = "";
    if (messagType == MESSAGE_TYPE.Information) {
        messageContent = '<div class="messagebox_container"><div class="messagebox_header">' + header + '</div>'
        + '<div class="messagebox_content">' + content + '</div>'
        + '</div>';
    }
    else if (messagType == MESSAGE_TYPE.Confirmation) {
        messageContent = '<div class="messagebox_container"><div class="messagebox_header">' + header + '</div>'
        + '<div class="messagebox_content">' + content + '</div>'
        + ''
        + '</div>';
    }
    else if (messagType == MESSAGE_TYPE.Error) {
        messageContent = '<div class="messagebox_container"><div class="messagebox_header">' + header + '</div>'
        + '<div class="messagebox_caption">Please fix the red marked errors(s)</div>'
        + '<div class="messagebox_content">' + content + '</div>'
        + '</div>';
    }
 

Code to make the popup centered

jQuery.fn.center = function (absolute) {
    return this.each(function () {
        var t = jQuery(this);

        t.css({
            position: absolute ? 'absolute' : 'fixed',
            left: '50%',
            top: '50%',
            zIndex: '1000000'
        }).css({
            marginLeft: '-' + (t.outerWidth() / 2) + 'px',
            marginTop: '-' + (t.outerHeight() / 2) + 'px'
        });

        if (absolute) {
            t.css({
                marginTop: parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(),
                marginLeft: parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
            });
        }
    });
};

CSS

.messagebox_container
{
    width:100%;
    height:100%;
    overflow:auto;
    background-color:Black;
    text-shadow: 0 0 0 white;
    padding-bottom:10px;
    text-align:center;
}
 
.messagebox_header
{
    font-size:24px;   
    color:White;
    margin:10px 0px 10px 0px;
    padding:0px 0px 0px 15px;
    text-align:left;    
}
 
.messagebox_caption
{
    color:White;
    font-size:14px;
    text-align:left;
    margin:10px 0px 10px 15px;
}
 
.messagebox_content
{
    color:Red;
    min-height:10px;
    text-align:left;
    padding:0px 10px 10px 15px;    
}
 
.ui-simpledialog-container
{
    border:solid 2px white !important;
    border-radius:.3em !important;
    -webkit-border-radius:.3em !important;
    background-color:Black !important;        
    
}
.popup_messagebox
{
    position:fixed;
    background-color:Black !important;
    padding:0 !important;
    border:solid 2px white;
    border-radius: .3em !important;
    min-width:280px !important;
    vertical-align:middle; 
    z-index:100000000000;   
}
 
.cover_background
{
    position:fixed;
    top:0px;
    left:0px;
    width:10000px;
    height:10000px;
    opacity:0.5;
    z-index:10000;
    background-color:Black;    
}

Now you can use the message box in the following way

MessageBox.show(MESSAGE_TYPE.Confirmation, "Header", "Message Content",
    function () {
                MessageBox.show(MESSAGE_TYPE.Information, "Header", "Yes Callback is called.");            
        });
    }, null);

The Parameters description for the Message box/popup:
messageType:
MESSAGE_TYPE.Information for information message
MESSAGE_TYPE.Error for error message
MESSAGE_TYPE.Confirmation for confirmation message.

header: Message box header content
content: Message box main content
onSuccess: Callback method for success button click(ok/yes)
onCancel: Callback method for cancel button click (Cancel/No)

The code is simple and you can modify in your way very easily I believe. Of course you can also use this popup in any web page also with CSS3 and HTML5 support for better look.

Categories: JQuery, JQuery Mobile

CSS3 Transition

October 20, 2011 Leave a comment

With css3, we can add effect when an element changing style such as when width, height etc.
To do this we need to do the following things:
a. Specify the CSS property we want to add effect.
b. Specify the duration of the effect.
Suppose we have a div with class “test”. So we can add transition effect with the following CSS style

 	div.test
        {
            width: 40px;
            height: 40px;
            background-color: #000000;
            transition: width 1s, height 1s, transform 1s, background-color 3s;
            -moz-transition: width 1s, height 1s, -moz-transform 1s; /* Firefox 4 */
            -webkit-transition: width 1s, height 1s, -webkit-transform 1s, background-color 1s; /* Safari and Chrome */
            -o-transition: width 1s, height 1s, -o-transform 1s; /* Opera */
            text-align: center;
            font-weight: bold;
            line-height: 40px;
        }
        
        div.test:hover
        {
            width: 80px;
            height: 80px;
            transform: rotate(180deg);
            -moz-transform: rotate(180deg); /* Firefox 4 */
            -webkit-transform: rotate(360deg); /* Safari and Chrome */
            -o-transform: rotate(180deg); /* Opera */
            font-size: 25px;
            color: White;
            line-height: 80px;
            background-color: #DD1188;
            cursor: pointer;
        }

And the test div in our document

<div class="test">
</div>

Here width, height, transform, background-color will be changed gradually in 1second with a nice effect on mouse over.
Look at the property
transition: width 1s, height 1s, transform 1s, background-color 3s;
Here we set the time duration for the property change.
Note: Internate Explorer not yet support transition.

Categories: Uncategorized