ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 Hosting - ASPHostPortal :: Timeout in Regular Expressions ASP.NET 4.5

clock December 10, 2015 21:07 by author Jervis

Regular expressions are common forms of parsing a document and get meaning. It has been very popular and most of the people do use it regularly to solve their complex problems.

Lets start by the new Regex Api introduced with the framework. The improvement that has been made is minor yet handy at certain cases. The Regex class of .NET 4.5 supports Timeout. Lets take a look how to work with it.

Lets try to write a simplest RegEx validator to look into it. 

Try
{
    Regex regexpr =
new Regex("[A-Z ]{10}", RegexOptions.Singleline, TimeSpan.FromMilliseconds(1));
    Match mch = regexpr.Match(
"ABHISHEK SUR");
   
if (mch.Success)
        Console.WriteLine(
"Match found");
   
else
        Console.WriteLine(
"Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine(
"Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(
true);
}

Here in the code you can see I simply check a string with a Regular expression. It eventually finds success as Pattern matches the string. Now this code is little different than what we have been doing for last few years. The constructor overload of Regex now supports a Timespan seed, which indicates the timeout value after which the Regular expression validator would automatically generate a RegexMatchTimeoutException. The Match defined within the Regex class can generate timeout after a certain time exceeds.

 You can specify Regex.InfiniteMatchTimeout to specify that the timeout does not occur. The value of InfiniteMatchTimeout is -1ms internally and you can also use Timespan.Frommilliseconds(-1) as value for timespan which will indicate that the Regular expression will never timeout which being the default behavior of our normal Regex class. Regex also supports AppDomain to get default value of the Timeout. You can set timeout value for "REGEX_DEFAULT_MATCH_TIMEOUT" in AppDomain to set it all the way through the Regular expressions being used in the same AppDomain. Lets take a look how it works.

Try
{
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(2));

    Regex regexpr = new Regex("[A-Z ]{10}", RegexOptions.Singleline);
    Match mch = regexpr.Match("ABHISHEK SUR");
    if (mch.Success)
        Console.WriteLine("Match found");
    else
        Console.WriteLine("Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine("Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(true);
}

Now this works exactly the same as the previous one. Here the Regex constructor automatically checks the AppDomain value and applies it as default. If it is not present, it will take -1 as default which is Infinite TImeout and also if explicitely timeout is specified after the default value from AppDomain, the Regex class is smart enough to use the explicitly set value only to itself for which it is specified. The Regex Constructor generates a TypeInitializationException if appdomain value of Timespan is invalid. Lets check the internal structure.

This is the actual code that runs in background and generates the timeouts. In fact while scanning the string with the pattern, there is a call to CheckTimeout which checks whether the time specified is elapsed for the object. The CheckTimeout throws the exception from itself.

The Constructor sets DefaultMatchTimeout when the object is created taking it from AppDomain data elements.

If you read MSDN thoroughly, it suggests to use Timeouts when specifying the Regular expressions. If the pattern is supplied from external or you are not sure about the pattern that needs to be applied to the string, it is always recommended to use Timeouts. Basically you should also specify a rational limit of AppDomain regex default to ensure no regular expression can ever hang your application.

This is a small tip on the new Regex enhancements introduced with .NET 4.5 recently.  

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Enabling Unobtrusive Validation From Scratch in ASP.NET 4.5 Webforms

clock December 19, 2014 04:55 by author Ben

I used to be fiddling with ASP.NET 4.5 and Visual Studio 2012 particularly with all the new Validation attributes and i identified they function great, specially the new unobtrusive validation, then I attempted to permit this sort of validation over a new Vacant Net Software, and that i identified that this just isn't out-of-the-box, you'll need to create some configurations to your Net Application.

You'll find a few ways to allow the unobtrusive validation over a Internet Software:

Through the web.config file

<configuration> 
  <appsettings> 
   <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms"> 
  </add></appsettings> 
 </configuration> 

Via the Global.asax file

protected void Application_Start(object sender, EventArgs e)
{
   ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
}

On each page:

protected void Page_Load(object sender, EventArgs e)
{
   this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.WebForms;
}

To disable the unobtrusive validation set the UnobtrusiveValidationMode property to None. Unobtrusive validation is actually enabled by default in ASP.Net 4.5.

We'll start with a simple example, create an Empty Web Application and add a MasterPage called Site.master and a content page for this master called Default.aspx.
Add the following code to the Default.aspx file:

<asp:TextBox runat="server" ID="txt" />
    <asp:RequiredFieldValidator ErrorMessage="txt is required" ControlToValidate="txt" runat="server" Text="*" Display="Dynamic" />
    <asp:Button Text="Send info" runat="server" />

If you try to run a simple ASPX page using a validator, the following exception will be thrown:

    "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)". Before fixing this, let's disable the unobtrusive validation to see the result.

On the page:

protected void Page_Load(object sender, EventArgs e)
{
   this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}

Now run the page and the validation will work as it used to work in ASP.Net 4.0 If you examine the rendered HTML, you will see that the gross inline script is rendered:

<script type="text/javascript">
//<![CDATA[
var Page_Validators =  new Array(document.getElementById("ContentPlaceHolder1_ctl00"));
//]]>
</script>

<script type="text/javascript">
//<![CDATA[
var ContentPlaceHolder1_ctl00 = document.all ? document.all["ContentPlaceHolder1_ctl00"] : document.getElementById("ContentPlaceHolder1_ctl00");
ContentPlaceHolder1_ctl00.controltovalidate = "ContentPlaceHolder1_txt";
ContentPlaceHolder1_ctl00.errormessage = "txt is required";
ContentPlaceHolder1_ctl00.display = "Dynamic";
ContentPlaceHolder1_ctl00.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
ContentPlaceHolder1_ctl00.initialvalue = "";
//]]>
</script>


<script type="text/javascript">
//<![CDATA[

var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}
       
document.getElementById('ContentPlaceHolder1_ctl00').dispose = function() {
    Array.remove(Page_Validators, document.getElementById('ContentPlaceHolder1_ctl00'));
}
//]]>
</script>

Now let's re-enable the unobtrusive validation. In order to fix the previous exception, we need to install the following Nuget packages: (I like to install jQuery first to get the latest version, although this is not required.)

  1. jQuery
  2. ASPNET.ScriptManager.jQuery
  3. Microsoft.AspNet.ScriptManager.MSAjax
  4. Microsoft.AspNet.ScriptManager.WebForms

At this point, if you run the application again, the exception will be gone =) how cool eh?. This is because the following Nuget packages automatically register the scripts needed with the ScriptManager control.

Let's examine the code added by these Nuget packages using ILSpy:

AspNet.ScriptManager.jQuery

public static class PreApplicationStartCode
    {
        public static void Start()
        {
            string str = "1.8.1";
            ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
            {
                Path = "~/Scripts/jquery-" + str + ".min.js",
                DebugPath = "~/Scripts/jquery-" + str + ".js",
                CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".min.js",
                CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".js",
                CdnSupportsSecureConnection = true,
                LoadSuccessExpression = "window.jQuery"
            });
        }
    }

Microsoft.AspNet.ScriptManager.MSAjax

public static void Start()
{
    ScriptManager.ScriptResourceMapping.AddDefinition("MsAjaxBundle", new ScriptResourceDefinition
    {
        Path = "~/bundles/MsAjaxJs",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/MsAjaxBundle.js",
        LoadSuccessExpression = "window.Sys",
        CdnSupportsSecureConnection = true
    });
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjax.js", "window.Sys && Sys._Application && Sys.Observer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxCore.js", "window.Type && Sys.Observer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxGlobalization.js", "window.Sys && Sys.CultureInfo");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxSerialization.js", "window.Sys && Sys.Serialization");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxComponentModel.js", "window.Sys && Sys.CommandEventArgs");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxNetwork.js", "window.Sys && Sys.Net && Sys.Net.WebRequestExecutor");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxHistory.js", "window.Sys && Sys.HistoryEventArgs");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxWebServices.js", "window.Sys && Sys.Net && Sys.Net.WebServiceProxy");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxTimer.js", "window.Sys && Sys.UI && Sys.UI._Timer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxWebForms.js", "window.Sys && Sys.WebForms");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxApplicationServices.js", "window.Sys && Sys.Services");
}
private static void AddMsAjaxMapping(string name, string loadSuccessExpression)
{
    ScriptManager.ScriptResourceMapping.AddDefinition(name, new ScriptResourceDefinition
    {
        Path = "~/Scripts/WebForms/MsAjax/" + name,
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/" + name,
        LoadSuccessExpression = loadSuccessExpression,
        CdnSupportsSecureConnection = true
    });
}

Microsoft.AspNet.ScriptManager.WebForms

public static void Start()
{
    ScriptManager.ScriptResourceMapping.AddDefinition("WebFormsBundle", new ScriptResourceDefinition
    {
        Path = "~/bundles/WebFormsJs",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/WebFormsBundle.js",
        LoadSuccessExpression = "window.WebForm_PostBackOptions",
        CdnSupportsSecureConnection = true
    });
}

As you can see these Nuget packages automatically register the scripts using the ScriptManager object (besides installing the required JavaScript files)

Run the application and examine the rendered HTML. You will note that it's much cleaner now, in this case the inline script has been moved to an external file that can be rendered using bundles to increase performance. The rendered script looks like:

<script src="Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.8.1.js" type="text/javascript"></script>

Much better right?. Notice how ASP.Net used HTML5 custom attributes:

<input name="ctl00$ContentPlaceHolder1$txt" type="text" id="ContentPlaceHolder1_txt" />
    <span data-val-controltovalidate="ContentPlaceHolder1_txt" data-val-errormessage="txt is required" data-val-display="Dynamic" id="ContentPlaceHolder1_ctl00" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="display:none;">*</span>
    <input type="submit" name="ctl00$ContentPlaceHolder1$ctl01" value="Send info" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ContentPlaceHolder1$ctl01&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" />

The data-val-* are custom attributes used by the unobtrusive validation engine

If you click the button to trigger the validation you will be pleased to see that it works as expected...but we are not done yet =/

The settings we have applied won't work if you intend to use an UpdatePanel control (yeah the evil UpdatePanel again...). This is because this control requires a ScriptManager control on the page (or MasterPage) and we do not have any yet. So let's add a simple ScriptManager control to the master page and see what happens. Add the following code to the Site.master page right under the <form...

<asp:ScriptManager runat="server" ID="scriptManager">
        </asp:ScriptManager>

Run the page again and fire the validation... oops... the client validation has gone =( We only have server validation. I'm not sure why this happens but my best guess is that the just added ScriptManager control is overriding our code settings.

To fix it, change the declaration of the ScriptManager control on the Site.master page to:

<asp:ScriptManager runat="server" ID="scriptManager1">
        <Scripts>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
        </Scripts>
    </asp:ScriptManager>

Run the application and our little example will work again as expected

Sadly these new settings are the equivalent to the settings added by code and we need to add them to be able to use the traditional Microsoft AJAX controls.

There's one last thing we need to configure, this is because there's actually a bug with the ValidationSummary control.

To test it, update the Default.aspx page as follows:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <asp:TextBox runat="server" ID="txt" />
    <asp:RequiredFieldValidator ErrorMessage="txt is required" ControlToValidate="txt" runat="server" Text="*" Display="Dynamic" />
    <asp:Button Text="Send info" runat="server" />

Now run the page again, scroll down until you can see the button and click it... woot your page jumped to the top... the workaround to solve this little bug is to add the following code to the Site.master

<script>
            window.scrollTo = function () {

            };
        </script>

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Uploading Several Data files Employing jQuery and Generic Handler in ASP.NET 4.5

clock December 5, 2014 09:11 by author Ben

This post describes the best way to upload numerous data files in ASP.NET Kinds using the jQuery and Generic Handler. Generally builders utilize the FileUpload Server management to add data files from the client device for the server that's rendered as as an Enter factor and set to file and helps you to pick out the file or various information. We can easily make use of the jQuery to help make an Ajax connect with towards the server and Submit the many picked documents for the Generic Handler as opposed to an entire webpage postback.

 


On this short article for creating the application, I am utilizing Visual Studio 2013 that has the framework 4.5.1. So, let us start with all the following course of action.

Creating WebForms

Step 1: Open Visual Studio and create the ASP.NET Web Application.

Step 2: Select the WebForms project template to proceed.

Visual Studio automatically creates the project and adds files and folders to the project by default.

Creating WebForm


Step 1: Just right-click on the project and add a new folder named "UploadedFiles".


Step 2: Just right-click on the project and add a new Web Form and replace the body content from the following content:

<form id="form1" runat="server">

    <h2>ASP.NET</h2>
    <p class="lead">Selcting Multiple Files using jQuery and Generic Handler</p>  

 

    <div class="form-group">
        <div>
            <asp:Label runat="server" AssociatedControlID="MultipleFilesUpload">Select Files</asp:Label>           
            <asp:FileUpload ID="MultipleFilesUpload" runat="server" AllowMultiple="true" />          

        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <asp:Button runat="server" ID="BtnUpload" Text="Upload Files" CssClass="btn btn-default" />
        </div>
    </div>  
 </form>


In the code above, I used the AllowMultiple property of FileUpload that is set to true. It is one of the HTML 5 features used in here.

Step 2: Now in the <head> section add the following code:

<script src="Scripts/jquery-1.10.2.js"></script>

<link href="Content/bootstrap.css" rel="stylesheet" />

<link href="Content/Site.css" rel="stylesheet" />

<script type="text/javascript">
    $(document).ready(function () {
        $("#BtnUpload").click(function (event) {
            var uploadfiles = $("#MultipleFilesUpload").get(0);
            var uploadedfiles = uploadfiles.files;
            var fromdata = new FormData();
            for (var i = 0; i < uploadedfiles.length; i++) {
                fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);
            }
             var choice = {};
            choice.url = "UploadHandler.ashx";
            choice.type = "POST";
            choice.data = fromdata;
            choice.contentType = false;
            choice.processData = false;
            choice.success = function (result) { alert(result); };
            choice.error = function (err) { alert(err.statusText); };
            $.ajax(choice);
            event.preventDefault();
        });
    });
</script>

Via the code over, the data files are chosen inside the file upload handle working with the information residence of the DOM factor. the loop iterates by means of many of the information then calls the append() method of the FormData to incorporate the data files into the FormData item.

Now, the info is usually to be sent into the server. The £.ajax() is employed to transfer the information. The choice item supplies numerous options such as focus on URL and HTTP process. Now we have set the URL home on the GenericHandler file named UploadHandler.ashx . We now have established the contentType and processData home to phony with which the jQuery will not likely URL encode the info while sending into the server. The achievements and mistake properties are utilised to display the messages as a result of an warn.

Creating Generic Handler

Step 1: Add the Generic Handler by right-clicking on the project named UploadHandler.


Step 2: Modify the code with the following code:

namespace UploadMultipleFilesApp
{
    public class UploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection SelectedFiles = context.Request.Files;
                for (int i = 0; i < SelectedFiles.Count; i++)
                {
                    HttpPostedFile PostedFile = SelectedFiles[i];
                    string FileName = context.Server.MapPath("~/UploadedFiles/" + PostedFile.FileName);
                    PostedFile.SaveAs(FileName);                   
                }
            }
            else
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Please Select Files");
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("Files Uploaded Successfully!!");
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

In this article we will see which the information which might be posted to your server and will be accessed using the Ask for object. Each individual element in the HttpFileCollection is of type HttpPostedFile. FileName property is utilized to receive the file identify of posted file and return it and also the similar name id used to conserve the file.

Run WebForm

Now run the webform and choose the files as shown below that the files are selected.


After clicking on Upload Files, the message is generated.


Summary

This article explained the best way to choose numerous information and add them utilizing jQuery and Generic Handler in ASP.NET Web Forms. Joyful Coding and thanks for looking at.

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Add Multiple Files Utilizing ASP.NET 4.5

clock November 28, 2014 05:07 by author Ben

In earlier versions of ASP.NET (edition under ASP.NET 4.5), we didn't have any inbuilt functionality to add several files at the same time. ASP.NET FileUpload handle permits uploading just one file in a time. Alternate answers to add numerous files are third party controls like Telerik or Devexpress. We can also use various jQuery Plugin like Uploadify to attain comparable performance.


In ASP.NET 4.5, we can add multiple documents simultaneously making use of ASP.NET FileUpload control. In ASP.NET 4.5, FileUpload Control support HTML5 several attribute.

Under are the steps to add numerous information utilizing ASP.NET 4.5 :

  1. In Visual Studio 2012, In Visual Studio 2012, create a new website using .Net 4.5 framework.
  2. Add a new web form (for example FileUpload.aspx) in newly created website.
  3. In code-beside file of FileUpload.aspx, write following code for FileUpload Control:

<asp:fileupload AllowMultiple="true" id="MultipleFileUpload" runat="server">
</asp:fileupload>

In above code, I have set AllowMultiple property of FileUpload Control to true.

Add one button to upload multiple files using FileUpload Control on button click.

<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

Write below code on button click event handler.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (MultipleFileUpload.HasFiles)
        {
            StringBuilder UploadedFileNames = new StringBuilder();

            foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
            {
                string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Files/"), FileName));
                UploadedFileNames.AppendFormat("{0}<br />", FileName);
            }
            Response.Write("Uploaded Files are : <br/>" + UploadedFileNames);
        }
    }

On button click, I am checking for multiple files and saving those files into Files folder of web application.
Compile source code and run the website application.

 

I had selected five images to upload. Once I had clicked on Upload button, all five images were uploaded successfully in Files folder.



ASP.NET 4.5 HOSTING - ASPHostPortal.com :: A simple SPA with AngularJs, ASP.NET MVC, Web API and EF

clock November 14, 2014 06:41 by author Mark

Introduction

SPA stands for Single Page Application. Here I will demonstrate a simple SPA with ASP.NET MVC, Web API and Entity Framework. I will show a trainer profile and its CRUD operation using AngularJS, ASP.NET MVC, Web api and Entity Framework.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

  • PM> Install-Package jQuery
  • PM> Install-Package angularjs -Version 1.2.26
  • PM> Install-Package Newtonsoft.Json
  • PM> Install-Package MvcScaffolding

Step 3: Create Connection String

Create connection string and name DB name as SPADB
    <connectionStrings>
  <add name="SPAContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=SPADB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 4: Create model

Create Trainer model
    public class Trainer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Venue { get; set; }
}

Step 5: Create Repository

Create repository for Trainer model.

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to create repository. I used repository pattern for well-structured and more manageable.

PM> Scaffold Repository Trainer

After running the above command you will see SPAContext.cs and TrainerRepository.cs created in Model folder. For well manageability, I create a directory name Repository and put these two files in the Repository folder. So change the namespace as like SPA.Repository instead of SPA.Model. I also create a UnitOfWork for implement unit of work pattern.
The overall folder structure looks like following. 
SPAContext.cs
    public class SPAContext : DbContext
{
    public SPAContext()
        : base("SPAContext")
    {
    }
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, add the following
    // code to the Application_Start method in your Global.asax file.
    // Note: this will destroy and re-create your database with every model change.
    //
    // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<SPA.Models.SPAContext>());
    public DbSet<SPA.Models.Trainer> Trainers { get; set; }
    public DbSet<SPA.Models.Training> Trainings { get; set; }
}

TrainerRepository.cs
    public class TrainerRepository : ITrainerRepository
{
    SPAContext context = new SPAContext();
    public TrainerRepository()
        : this(new SPAContext())
    {
    }
    public TrainerRepository(SPAContext context)
    {
        this.context = context;
    }
    public IQueryable<Trainer> All
    {
        get { return context.Trainers; }
    }
    public IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties)
    {
        IQueryable<Trainer> query = context.Trainers;
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }
    public Trainer Find(long id)
    {
        return context.Trainers.Find(id);
    }
    public void InsertOrUpdate(Trainer trainer)
    {
        if (trainer.Id == default(long))
        {
            // New entity
            context.Trainers.Add(trainer);
        }
        else
        {
            // Existing entity
            context.Entry(trainer).State = System.Data.Entity.EntityState.Modified;
        }
    }
    public void Delete(long id)
    {
        var trainer = context.Trainers.Find(id);
        context.Trainers.Remove(trainer);
    }
    public void Save()
    {
        context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}
public interface ITrainerRepository : IDisposable
{
    IQueryable<Trainer> All { get; }
    IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties);
    Trainer Find(long id);
    void InsertOrUpdate(Trainer trainer);
    void Delete(long id);
    void Save();
}

UnitOfWork.cs
public class UnitOfWork : IDisposable
{
    private SPAContext context;
    public UnitOfWork()
    {
        context = new SPAContext();
    }
    public UnitOfWork(SPAContext _context)
    {
        this.context = _context;
    }
    private TrainingRepository _trainingRepository;
 
    public TrainingRepository TrainingRepository
    {
        get
        {
            if (this._trainingRepository == null)
            {
                this._trainingRepository = new TrainingRepository(context);
            }
            return _trainingRepository;
        }
    }
    private TrainerRepository _trainerRepository;
    public TrainerRepository TrainerRepository
    {
        get
        {
            if (this._trainerRepository == null)
            {
                this._trainerRepository = new TrainerRepository(context);
            }
            return _trainerRepository;
        }
    }
    public void Dispose()
    {
        context.Dispose();
        GC.SuppressFinalize(this);
    }
}

Step 6: Add migration

  • Run the following command to add migration
  • PM> Enable-Migrations
  • PM> Add-Migration initialmigration
  • PM> Update-Database –Verbose

Step 7: Create API Controllers

Create Trainers api Controllers by clicking right button on Controller folder and scaffold as follows.

Step 8: Modify Controllers

Now modify the controllers as follows. Here I used unit of work pattern.
    public class TrainersController : ApiController
{
    private UnitOfWork unitOfWork = new UnitOfWork();
    public IEnumerable<Trainer> Get()
    {
        List<Trainer> lstTrainer = new List<Trainer>();
        lstTrainer = unitOfWork.TrainerRepository.All.ToList();
        return lstTrainer;
    }
    //// GET api/trainers/5
    public Trainer Get(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        return objTrainer;
    }
    public HttpResponseMessage Post(Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    private IEnumerable<string> GetErrorMessages()
    {
        return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
    }
    // PUT api/trainers/5
    public HttpResponseMessage Put(int Id, Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        else
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    // DELETE api/trainers/5
    public HttpResponseMessage Delete(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        if (objTrainer == null)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
        unitOfWork.TrainerRepository.Delete(id);
        unitOfWork.TrainerRepository.Save();
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

Step 9: Create Layout and Home Controller

Create _Layout.cshtml in Views->Shared folder and create HomeController and create inext view of Home controller by right click on index action and add view. You will see index.cshtml is created in Views->Home
Home Controller
    public class HomeController : Controller
{
    //
    // GET: /Home/
 
    public ActionResult Index()
    {
        return View();
    }
}

_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Index.cshtml
    @{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Home</h2>
<div>
    <ul>     
        <li><a href="/Registration/Trainers">Trainer Details</a></li>
        <li><a href="/Registration/Trainers/add">Add New Trainer</a></li>
    </ul>
</div>
<div ng-view></div>

Step 10: Create registrationModule

Create registrationModule.js in Scripts->Application. This is for angularjs routing.
    var registrationModule = angular.module("registrationModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers/all.html',
            controller: 'listTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/:id', {
            templateUrl: '/templates/trainers/edit.html',
            controller: 'editTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/add', {
            templateUrl: '/templates/trainers/add.html',
            controller: 'addTrainersController'
        });
        $routeProvider.when("/Registration/Trainers/delete/:id", {
            controller: "deleteTrainersController",
            templateUrl: "/templates/trainers/delete.html"
        });
        $locationProvider.html5Mode(true);
    });

Step 11: Create trainerRepository

Create trainerRepository.js in Scripts->Application->Repository. This increase manageability for large application.
    'use strict';
//Repository for trainer information
registrationModule.factory('trainerRepository', function ($resource) {
    return {
        get: function () {
            return $resource('/api/Trainers').query();
        },
        getById: function (id) {
            return $resource('/api/Trainers/:Id', { Id: id }).get();
        },
        save: function (trainer) {
            return $resource('/api/Trainers').save(trainer);
        },
        put: function (trainer) {
            return $resource('/api/Trainers', { Id: trainer.id },
                {
                    update: { method: 'PUT' }
                }).update(trainer);
        },
        remove: function (id) {
            return $resource('/api/Trainers').remove({ Id: id });
        }
    };
});

Step 12: Create trainerController

Create trainerController.js in Scripts->Application->Controllers
    'use strict';
//Controller to get list of trainers informaion
registrationModule.controller("listTrainersController", function ($scope, trainerRepository, $location) {
    $scope.trainers = trainerRepository.get();
});
//Controller to save trainer information
registrationModule.controller("addTrainersController", function ($scope, trainerRepository, $location) {
    $scope.save = function (trainer) {
        trainer.Id = 0;
        $scope.errors = [];
        trainerRepository.save(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});

//Controller to modify trainer information
registrationModule.controller("editTrainersController", function ($scope,$routeParams, trainerRepository, $location) {
    $scope.trainer = trainerRepository.getById($routeParams.id);
    $scope.update = function (trainer) {
        $scope.errors = [];
        trainerRepository.put(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});
//Controller to delete trainer information
registrationModule.controller("deleteTrainersController", function ($scope, $routeParams, trainerRepository, $location) {
        trainerRepository.remove($routeParams.id).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
});

Step 13: Create templates

Create all.html, add.html, edit.html, delete.html in templateds->trainers folder.
All.html
    <div>
    <div>
        <h2>Trainers Details</h2>
    </div>
</div>
<div>
    <div>
        <table>
            <tr>
                <th>Name </th>
                <th>Email </th>
                <th>Venue </th>
                <th>Action</th>
            </tr>
            <tr ng-repeat="trainer in trainers">
                <td>{{trainer.name}}</td>
                <td>{{trainer.email}}</td>
                <td>{{trainer.venue}}</td>
                <td>
                    <a title="Delete" ng-href="/Registration/Trainers/delete/{{trainer.id}}">Delete</a>
                    |<a title="Edit" ng-href="/Registration/Trainers/{{trainer.id}}">Edit</a>
                </td>
            </tr>
        </table>
    </div>
</div>

Add.html
    <form name="trainerForm" novalidate ng-submit="save(trainer)">
    <table>
        <tbody>
            <tr>
                <td>Trainer Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" required ng-minlength="5" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <input name="venue" type="text" ng-model="trainer.venue" />
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <input type="submit" value="Save" ng-disabled="trainerForm.$invalid" />
                    <a href="/Registration/Trainers" class="btn btn-inverse">Cancel</a>
                </td>
            </tr>
        </tbody>
    </table>
</form>
Edit.html
    <form name="trainerFrom" novalidate abide>
    <table>
        <tbody>
            <tr>
                <td>
                    <input name="id" type="hidden" ng-model="trainer.id"/>
                </td>
            </tr>
            <tr>
                <td>Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <textarea name="venue" ng-model="trainer.venue"></textarea>
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <button type="submit" class="btn btn-primary" ng-click="update(trainer)" ng-disabled="trainerFrom.$invalid">Update</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

Step 14: Add references to the Layout

Modify the _Layout.cshtml to add references
_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-resource.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script src="~/Scripts/Application/registrationModule.js"></script>
    <script src="~/Scripts/Application/Repository/trainerRepository.js"></script>
    <script src="~/Scripts/Application/Controllers/trainersController.js"></script>
</head>
<body>
    @RenderBody()
</body>
</html>

Now run you application and add, delete, modify and get all trainer information. Thanks for your patient! Laughing



ASP.NET 4.5 HOSTING - ASPHostPortal :: Design application layout by bootstrap theme

clock November 12, 2014 06:48 by author Mark

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC  Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

  • Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme

  • Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

Step 4: Create a Layout page

  • Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>  
    <div>
        @RenderBody()
    </div>
</body>
</html>

Step 5: Create HomeController and index view

  • Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <h2>Home Page</h2>

Step 6: Add Navigation bar

  • If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml

<!DOCTYPE html>
 <html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>
    <div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  <div class="navbar-collapse collapse navbar-inverse-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Active</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="dropdown-header">Dropdown header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left">
      <input type="text" class="form-control col-lg-8" placeholder="Search">
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now run the application, you will get a nice layout. Thanks for your patient Smile



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use Rangevalidator control in ASP.NET 4.5

clock November 7, 2014 06:26 by author Mark

If you want to understand how RangeValidator  control work in ASP.NET 4.5 Now, we will discuss about How to Use Rangevalidator control in ASP.NET 4.5. Rangevalidator control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age between 1 until 100.

In the codesnippet below, TextBox txtAge get age of the person. If User fill with any number that isn’t between 1 – 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, Age is an integer, the Type is specified as integer. Write the code below:

&lt;asp:TextBox ID="txtAge" runat="server"&gt;&lt;/asp:TextBox&gt;
&lt;asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 &amp; 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" &gt;
&lt;/asp:RangeValidator&gt;

Properties for Rangevalidator control:

Type – Specifies the data type of the value to check. Data types supported include Currency, Date, Double, Integer and String.

MinimumValue – Minimum value that allowed

MaximumValue – Max value allowed in that field

The Rangevalidator only checks if the data is within the allowed range. If you wanna check for a required field, use RequiredFieldValidator. In the Age field, I am using both RequiredFieldValidator & RangeValidator. In this example I am using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Then the error message will always occupy the gap on the screen even if the validation passes.

<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

This pushes “Age is Required” error message to the correct. To correct this we’ve got set Display=”Dynamic”. This renders the error message with style display:none. If a tag has this style, it’ll not occupy space when not visible.
Code-Behind page code
:
protected void btnSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.Color.Green;
        lblStatus.Text = "Data Saved successfully";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.Color.Red;
        lblStatus.Text = "Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls

None – Error message not rendered and displayed next to the control. used to show the error message only within the ValidationSummary control

Static – The error message is displayed next to the control if validation fails. space is reserved on the page for the message although validation succeeds. The span tag is rendered with style visibility:hidden

Dynamic – The error message is displayed next to the control if validation fails. space isn’t reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

 

 

 



ASP.Net 4.5 Hosting - ASPHostPortal.com :: How You Can Develop Asynchronous Device Page in ASP.Net 4.5

clock November 4, 2014 05:15 by author Ben

Within this tutorial we'll make use of the most recent ASP.Net 4.5 methods to come back up with a asynchronous gadget web page via help of Visual Studio Express.

The sample software that we're going to use listed here makes use of new async and awaits key phrases and they're obtainable in .NET 4.5 and Visual Studio 2012. This allows the complier to hold the responsibility of getting care from the complex transformations that are necessary for asynchronous programming. Also the compiler will allow you to write the code using the C#'s synchronous manage movement constructs. Therefore the compiler on its own applies the transformations which can be necessary to deploy call-backs. This is done in order to prevent blocking threads.



ASP.Net asynchronous web pages has to comprise in the Web page directive and Async feature label set to “true”. The code detailed under demonstrates the Page directive with all the value of Async attribute set to accurate for the DeviceAsync.aspx page.

<%@ Page Async="true" Language="C#" AutoEventWireup="true"
    CodeBehind="DeviceAsync.aspx.cs" Inherits="WebAppAsync.DeviceAsync" %>

The below code reflects the Device synchronous Page_Load method as well as the DeviceAsync asynchronous page. In case the browser supports the HTML5 <mark> element, the changes can be seen in DeviceAsync in yellow highlight.

protected void Page_Load(object sender, EventArgs e)
{
   var deviceService = new DeviceService();
   DeviceGridView.DataSource = deviceService.GetDevice();
   DeviceGridView.DataBind();
}

The below displays the asynchronous version:
protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(GetDeviceSvcAsync));
}

private async Task GetDeviceSvcAsync()
{
    var deviceService = new DeviceService();
    DeviceGridView.DataSource = await deviceService.GetDeviceAsync();
    DeviceGridView.DataBind();
}

The beneath lists the changes that were applied to permit DeviceAsync page to be asynchronous.

  • This is a need to to set the Webpage directive Async attribute to "true".
  • The RegisterAsyncTask indicates is deployed to sign up an asynchronous task that includes of the code which can be operated asynchronously.
  • The new GetDeviceSvcAsync approach is labelled with the async key phrase that informs the compiler to make callbacks for parts of the body and in addition to generate a Job of its personal which is returned.
  • Should you recognize, we appened "Async" towards the asynchronous technique title although this is not required however it is the conference while you're writing asynchronous methods.
  • The return sort in the Task defines the perform in progress and offers the callers of the approach having a deal with through which to halt for your completion of the asynchronous operation. The return type in the new GetDeviceSvcAsync method is Activity.
  • Internet support call helps make use of the await keyword.
  • The asynchronous web service API was referred to as GetDeviceAsync.

GetDeviceAsync is another asynchronous method that's known as inside of the GetDeviceSvcAsync method physique. Task<List<Device>> is immediately returned by a GetDeviceAsync that will finally full on the availability of the info. For your purpose that you'd not want to proceed additional just before you have the device data, the code waits for the task making use of the await keyword. 1 might make usage of the await keyword just in techniques annotated with all the async search term.

Until finally we have the completion from the task, the thread is not blocked from the await search term. It indications up the rest of the method as being a callback within the job, and immediately returns. Within the completion in the awaited activity, that callback will likely be invoked thereby resuming the implementation from the method right exactly where it left off.

The below code displays the GetDevice and GetDeviceAsync techniques:

public List<Device> GetDevice()
{
   var uri = Util.getServiceUri("Device");
   using (WebClient webClient = new WebClient())
   {
        return JsonConvert.DeserializeObject<List<Device>>(
            webClient.DownloadString(uri)
        );
    }
}

public async Task<List<Device>> GetDevicesAsync()
{
    var uri = Util.getServiceUri("Devices");
    using (HttpClient httpClient = new HttpClient())
    {
        var response = await httpClient.GetAsync(uri);
        return (await response.Content.ReadAsAsync<List<Device>>());
    }
}

The asynchronous modifications which were utilized are same as those applied to the DevicesAsync above.

  • Async key phrase was used to annotate the method signature, the return sort was changed to Task<List<Device>>, and Async was appended for the technique title.
  • The asynchronous HttpClient is utilized rather than synchronous WebClient class.
  • The await keyword was used to the HttpClient GetAsync asynchronous method.

The below image displays the asynchronous device see.

The browsers screen of the gadget info is same concerning the check out that's created by the synchronous contact. Here the only difference will be the asynchronous model might be more execute ant below main hefty loads.

Methods that are hooked up with RegisterAsyncTasks will likely be executed instantly after PreRender. 1 may also utilize async void page events directly as may be seen from the under code:

protected void Page_Load(object sender, EventArgs e) {
    await ...;
    // do work
}

The disadvantage for the async occasions is that the programmers now don't have the complete use of the occasions when activities are applied. Example, in case both an .aspx as well as a .Master signifies Page_Load occasions and a minimum of 1 of them is asynchronous, there's no guarantee from the execution.

Getting a developer, it is recommended to apply the above stated procedure to come up with the asynchronous unit web page making use of the newest ASP.Net 4.5 systems.

 



ASP.Net 4.5 Hosting - ASPHostPortal.com :: Producing Data-driven Web Apps Utilizing ASP.Net 4.5 Web Forms

clock October 16, 2014 06:30 by author Ben

Data binding is less complicated and more effective in ASP.Net 4.5 Kinds.This publish discuss about making Data-driven software using ASP.Net 4.5 preview. Additionally, it discuss about distinct Info access methods, especially about design entry binding features in Internet Types. You need to install Visual Studio 11 Developer preview to use this function.

Typical ASP.Net developer could use a single from the following Info Access mechanisms for binding the data

  • You could set up your Database Initial - Making a Schema and creating product from it. Listed here model is actually a class which you're going to communicate with your databases from your code.
  • You may setup your Product Initial - Instead of developing the database first, we design the entity model initial eg: making use of entity framework. Style your product first after which generate a schema and code.
  • You could setup your Code First- On this strategy you very first write code to design and style the product and after that produce a schema making use of that code.

Your model designer floor could search like beneath should you stick to the any of above Information Accessibility mechanisms


This post discuss the third strategy Code Very first Information Entry mechanism to connect with the databases. This method makes use of the Product Binding , the phrase barrowed from MVC. In MVC whenever you call an motion method which received some parameters in which you need to move values from question string or from cookie assortment and bind these values into parameters. Design Binding does this in MVC. The concept is comparable Web Types but context is little little bit different.

Step1 Construct courses which represent your model.

Incorporate a folder within your remedy referred to as Model and then add new item class named Issue.



The difficulty class code getting some homes which appear like as below


Consequently the above mentioned code turns into a database desk. You can discover info annotations on every home. You'll be able to specify your validation at a single spot. eg: Required in above properties.

Produce an additional class which represent the database context named IssuesDb.


Now add the connection string in web.config file with same name as your DbContext. Here it is IssuesDb.

Create another class which initializes your database as shown below

public class Dbinitializer : DropCreateDatabaseIfModelChanges<IssuesDb>

    {

      protected override void Seed(IssueDb context)

        {

            context.Issues.Add(new Issue { CreatedBy="xyz",

            CreatedOn = new DateTime(), Title="Issue1"})

            context.Issues.Add(new Issue { CreatedBy="abc",

             CreatedOn = new DateTime(), Title="Issue2"})

            context.Issues.Add(new Issue { CreatedBy="aaa",

           CreatedOn = new DateTime(), Title="Issue3"})       

      

       }

You'll be able to override the tactic See to insert some values into the produced desk.

Step2 Displaying the above specifics in UI. We will set up a Gridview to Model Binding to list the details from database table.


We are not performing anything at all new listed here , Product Binding is merge of concept from Object information resource and MVC Design Binding. Specify your ModelType and SelectMethod to point out the main points.

We will also template fields to gridview and established the binding expression to point out the values but in different way.

The normal way is one thing proven below


The problem with the above expression is we do not know the type of the column. Now you will get an intellisense inside data binding expressions with a name Item.


The GetIssues method code will look like as below


Before running your application, Initialize the database initializer class in Global.asax file Application Start method

DataBase.SetInitializer(new IssueDbInitializer());


It also creates database and tables as you specified in the model class


Step3 Now let us add a filter to this application.

Add a lable, text box and a button to UI.


Now modify GetIssues method as shown below where Model Data binding comes into the picture.


The method having a parameter named createdSince that is a textbox id and we have been telling the strategy it is a handle. You are able to go ahead and take price from parameter and filter the values as demonstrated below


Instead of finding the control and writing the code, Model Binding takes the input from the user and retrieves the values from Dbcontext.

Points to note:

There's no If !(IsPostBack) or button handlers to attain this functionality. Just get in touch with this process by passing the worth from this handle. that is it!. We will dynamically manipulate the query by just using the values in the user.

Step4 Adding a FormView which exhibits all particulars and permits you to insert and edit the issue. The FormView markup seems like as below


The GetIssue method code as below. The idea is enable autogenerated select column in gridview and show the details when you select the particular issue.


You saying to method to get the id value from issuesGrid control and return the issue details. Run the application then you will see the below result


Note that we've not composed any code to re-bind the values from database to grid. Design Binding maintain observe from the values of parameters across the submit backs. It truly retailers these values in viewstate.

The InsertMethod code seems as below


and above code you can see we are validating whether user is logged in or not and based  on that we are using ModelState to add the model error message.

ModelState represents the current state of Model Binding system on your page.

You can pass this error message to Validation Summary on your page by setting ShowModelStateErrors = true.


Another new point to notice is TryUpdateModel method which is an explicit Model Binding. This method tells model to try and bind the data from current request in to this issue variable.

The binding expression in InsertItem template in gridview will look like


Previously we do something like this


Run the application you then will begin to see the under screen


The update method exactly looks like insert method but having an additional parameter named id which is an id of record in the current Model Binding expression.


We have seen the new data-related improvements in ASP.NET 4.5 Web Forms with Model Binders and Data annotations.



ASP.NET 4.5 Hosting :: Publishing Your ASP.NET 4.5 Site with Visual Studio 2012

clock May 6, 2014 08:33 by author Ben

Microsoft Visual Studio 2012 is loaded with new capabilities for Windows 8, the web, SharePoint, mobile, and cloud development—as well as the application management lifecycle tools you need to break down team barriers and reduce cycle times to deliver value continuously.

Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

This Article can tell you how to publish your asp.net 4.5 site in vistul studio 2012.
Steps to Publish Web Application in Visual Studio 2012:
Step 1: Right click on the web project in the solution explorer window and then select the option Publish.

Step 2: Publish Web Application Window will open .Here under the option Select or Import a publish profile Select the option New in the drop down.

Step 3: In New Profile Window give any name to Profile and then click on Ok.

Step 4: Next in Connection Select the Publish method File System.

Step 5: Again in Connection for Target location select the folder on your computer where you want to publish the web application and then click on Next Button.
Step 6: In Settings Select the Configuration Release in the drop down and then click on Next Button.

Step 7: Finally in the Preview Click on Publish to Publish the web Project to  folder selected in the Step 5 above.



Best and Affordable Visual Studio 2012 Hosting with ASPHostPortal.com

We have supported site developed with
Visual Studio 2012 Hosting. Host your site on our Windows Server 2012 today. Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

For fast, secure and reliable Visual Studio 2012 Hosting, look no further than ASPHostPortal.com for all your web hosting related needs. Microsoft Visual Studio 2012 provides many new capabilities to support development on the latest platforms with modern lifecycle tools to make it easier for teams to deliver value continuously.

Visual Studio Updates help ensure you always have the best solution for building modern applications and for managing the modern application lifecycle. New to Windows Extensions, Modules, and Libraries? Ready to try out? Sign up for a FREE Trial Hosting account from ASPHostPortal.com with absolutely no cost and get going in minutes. Our Windows Server is also compatible with Visual Studio 2005, Visual Studio 2008, and Visual Studio 2010.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in