All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

Classic ASP Hosting - ASPHostPortal.com :: Cropping picture using jQuery, Jcrop with ASPJpeg

clock October 23, 2014 06:15 by author Ben

As we know the assorted websites like Facebook, LinkedIn, Google and so forth., are utilizing Impression Cropping instrument when we incorporate a brand new picture. I found many ways to do that perform but lately I received Jcrop for image cropping. Jcrop will be the quick and simple way to include impression cropping performance for your net software with all the jQuery help.


Jcrop is simply a device which lets you crop image with reside preview. But, after the cropping picture, you have to create a new picture using the picked X-Axis, Y-Axis, Width and Height. I found several tricks to produce new photo through Method.Drawing.Image but I could not get this better to use cropping impression. So I decided to utilize ASPJpeg for making new picture.

ASPJpeg is a server part which will assist your ASP.Net apps with all their image-management wants. With ASPJpeg, you can create high-quality thumbnails, logo-stamp images, extract metadata details from images, crop, improve, rotate, convert, and much much more. But, listed here we are going to use for CROPPING image.

How to begin? (Jcrop Set up)

Add the following files into your project

  • jquery.min.js
  • jquery.Jcrop.js
  • jquery.Jcrop.css


Now we'd like to include above documents into our <head> segment and some fashion courses for HTML factors also as create features inside the webpage with all the OnChange and OnSelect event handler. These occasions are utilized to update existing selection of coordinates within the Concealed Fields.

<head runat="server">
<style type="text/css">
h2.panelTitle { font-size: 18px; margin-bottom: 5px; }
p.content { color: #5f5f61; width: 50%; }
div.imgCrop { width: 330px; float: left; }
div.imgPreview { width: 140px; float: left; margin-top: 40px; }
div.previewOverflow { width: 115px; height: 115px; overflow: hidden; }
div.previewText { color: #333; text-align: center; width: 115px; font-size: 14px; margin-top: 5px; }
div.clear { clear: both; height: 0; }
</style>
 
<link href="/_assets/js/jcrop/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<script src="/_assets/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/_assets/js/jcrop/jquery.Jcrop.js" type="text/javascript"></script>
 
<script type="text/javascript">
var imgWidth = 0;
var imgHeight = 0;
 
function getImageDimensions(w, h) {
imgWidth = w;
imgHeight = h;
}
 
// Initialize Jcrop
$(function() {
jQuery('#imgCrop').Jcrop({
    onSelect: storeCoords,
    onChange: storeCoords,
    minSize: [115, 115],
    setSelect: [0, 0, 115, 115],
    aspectRatio: 1
});
});
 
// Update every move of the cropping in the Hidden Fields and Live Preview
function storeCoords(c) {
  var rx = 115 / c.w;
  var ry = 115 / c.h;
 
  jQuery('#X1').val(c.x);
  jQuery('#Y1').val(c.y);
  jQuery('#X2').val(c.x2);
  jQuery('#Y2').val(c.y2);
  jQuery('#W').val(c.w);
  jQuery('#H').val(c.h);
 
  jQuery('#preview').css({
    width: Math.round(rx * imgWidth) + 'px',
    height: Math.round(ry * imgHeight) + 'px',
    marginLeft: '-' + Math.round(rx * c.x) + 'px',
    marginTop: '-' + Math.round(ry * c.y) + 'px'
  });
};
</script>
</head>


Add the following code in your <body> section


<body>
<form id="form1" runat="server">
  <div style="padding: 10px;">
    <!-- PANEL #1: Choose Upload File -->
    <asp:Panel runat="server" ID="step1">
      <h2 class="panelTitle"> Update a picture of yourself</h2>
      <asp:FileUpload ID="FileUpload1" runat="server" />
      &nbsp;
      <asp:Button runat="server" Text="Upload" ID="btnUpload" OnClick="btnUpload_Click" />
      <br />
      <asp:Label ID="lblError" runat="server" Visible="false" />
      <p class="content"> You can upload a JPG, GIF, or PNG file. (Do not upload pictures containing celebrities, nudity, artwork or copyrighted images.)</p>
    </asp:Panel>
 
    <!-- PANEL #2: Show the Image Corpping with Preview -->     
    <asp:Panel runat="server" ID="step2" Visible="false">
      <h2 class="panelTitle"> Crop this picture of yourself</h2>
      <p class="content"> You can drag the box to select the crop area, and use the handle to resize it.<br />
        <asp:LinkButton runat="server" ID="lbBackToUpload" Text="Back to upload" OnClick="lbBackToUpload_Click"></asp:LinkButton>
      </p>
      <div>
        <div class="imgCrop">
          <asp:Image ID="imgCrop" runat="server" />
        </div>
        <div class="imgPreview">
          <div class="previewOverflow">
            <asp:Image ID="preview" runat="server" />
          </div>
          <div class="previewText"> Preview</div>
        </div>
        <div class="clear"> </div>
      </div>
      <br />
      <asp:HiddenField ID="X1" runat="server" />
      <asp:HiddenField ID="Y1" runat="server" />
      <asp:HiddenField ID="X2" runat="server" />
      <asp:HiddenField ID="Y2" runat="server" />
      <asp:HiddenField ID="W" runat="server" />
      <asp:HiddenField ID="H" runat="server" />
      <asp:Button ID="btnCrop" runat="server" Text="Apply Changes" OnClick="btnCrop_Click" />
      &nbsp;
      <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
    </asp:Panel>
    <asp:Panel ID="pnlCropped" runat="server" Visible="false">
      <asp:Image ID="imgCropped" runat="server" />
    </asp:Panel>
  </div>
</form>
</body>


After added above snipts, we will work on the backend side. We have 5 methods to create on the backend side.
  • CancelCrop (Private Method)
  • btnUpload_Click
  • btnCrop_Click
  • btnCancel_Click
  • lbBackToUpload_Click

Add Reference of ASPJpeg

Ahead of the previously mentioned techniques we have to add ASPJpeg Reference into our Bin folder, follow the process to incorporate an ASPJpeg Reference File.

Step 1: Right click on the Bin Folder / Root Folder and select Add Reference


Step 2: Browse the AspJpeg.dll file from your Hard Drive and click OK to continue.


Lets have a look your added reference picture.


Lets have a look your added reference picture.

using System;
using System.IO;
using System.Web;
 
String tempPath = HttpContext.Current.Server.MapPath("uploads/temp/");
String savePath = HttpContext.Current.Server.MapPath("uploads/images/");
 
protected void btnUpload_Click(object sender, EventArgs e)
    {
        // Generate Random String
        String NewID = System.Guid.NewGuid().ToString("N").Substring(0, 10);
 
        // initialize variables
        String fileName = String.Empty;
        String fileExtension = String.Empty;
        Boolean fileOK = false;
        Boolean fileSaved = false;
 
        // Check: If file has been selected to upload
        if (FileUpload1.HasFile)
        {
            Session.Add("WorkingImage", FileUpload1.FileName);
            fileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
            String[] allowedExtensions = { ".jpg", "jpeg", ".png", ".gif" };
            for (int i = 0; i < allowedExtensions.Length; i++)
                if (fileExtension == allowedExtensions[i]) fileOK = true;
        }
 
        // Check: If fileOK variable is equest to true
        if (fileOK)
        {
            try
            {
                fileName = NewID + fileExtension;
                String tempLocation = tempPath + fileName;
                FileUpload1.PostedFile.SaveAs(tempLocation);
 
                ASPJPEGLib.IASPJpeg objJpeg = new ASPJPEGLib.ASPJpeg();
                objJpeg.Open(tempLocation);
                objJpeg.PreserveAspectRatio = 1;
 
                const int maxWidth = 300;
                if (objJpeg.OriginalWidth > objJpeg.OriginalHeight)
                {
                    objJpeg.Width = maxWidth;
                    objJpeg.Height = objJpeg.OriginalHeight * maxWidth / objJpeg.OriginalWidth;
                }
                else
                {
                    objJpeg.Height = maxWidth;
                    objJpeg.Width = objJpeg.OriginalWidth * maxWidth / objJpeg.OriginalHeight;
                }
 
                // Send generated image Width and Height to JavaScript for the Jcrop preview
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "getImageDimensions", "getImageDimensions(" + objJpeg.Width + "," + objJpeg.Height + ");", true);
 
                // Create new file with new width: 300
                objJpeg.Save(tempLocation);
 
                // Save Temprary Location and Filename into Session
                Session["TempLocation"] = tempLocation;
                Session["TempFileName"] = fileName;
                fileSaved = true;
            }
            catch (Exception ex)
            {
                lblError.Text = "File could not be uploaded." + ex.Message.ToString();
                lblError.Visible = true;
                fileSaved = false;
            }
        }
        else
        {
            lblError.Text = "Cannot accept files of this type.";
            lblError.Visible = true;
        }
 
        // Check: if fileSaved variable is equest to true
        if (fileSaved)
        {
            step1.Visible = false; // Panel #1: Disappear
            step2.Visible = true; // Panel #2: Appear
 
            // Fill the Origial Image and Preview with the below source
            imgCrop.ImageUrl = "~/uploads/temp/" + fileName;
            preview.ImageUrl = "~/uploads/temp/" + fileName;
        }
 
    }
 
    protected void btnCrop_Click(object sender, EventArgs e)
    {
        String newFileName = savePath + Session["TempFileName"];
 
        // Create instance for AspJpeg
        ASPJPEGLib.IASPJpeg objJpeg1 = new ASPJPEGLib.ASPJpeg();
 
        // Open file from temprary location
        objJpeg1.Open(Session["TempLocation"].ToString());
 
        // Set Quality: 80
        objJpeg1.Quality = 80;
 
        // Image Cropped with selected area
        objJpeg1.Crop(int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(X2.Value), int.Parse(Y2.Value));
 
        // Save file into uploads/images
        objJpeg1.Save(newFileName);
 
        step2.Visible = false; // Panel #2: Disappear
        pnlCropped.Visible = true; // Active Panel Cropped Image
 
        imgCropped.ImageUrl = "~/uploads/images/" + Session["TempFileName"];
 
        // Delete temprary file
        CancelCrop();
    }
 
    protected void lbBackToUpload_Click(object sender, EventArgs e)
    {
        CancelCrop();
 
        step1.Visible = true; // Panel appear #1
        step2.Visible = false; // Panel disappear #2
    }
 
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        CancelCrop();
 
        step1.Visible = true; // Panel appear #1
        step2.Visible = false; // Panel disappear #2
    }
 
    private void CancelCrop()
    {
        String tmpFileLocation = Session["TempLocation"].ToString();
 
        // Delete temprary files if exists
        if (File.Exists(tmpFileLocation))
            File.Delete(tmpFileLocation);
    }

Lastly, we've got finished the Jcrop Picture Cropping script. You'll be able to make use of your own FileUpload method for image uploading. I'm also impressed by a person who experienced developed great structural code. therefore, I followed him. Sorry to forgot reference website link.



ASP.NET SignalR Hosting - ASPHostPortal.com :: SignalR And Knockout In ASP.Net Web Pages Making use of WebMatrix

clock October 22, 2014 05:43 by author Ben

SignalR is actually a library that simplifies the creation and management of persistent connections among internet servers and clientele. This facilitates the development of programs that may screen updates to info held around the server in real-time. Chat apps will be the most evident beneficiaries of this technology, but line-of-business apps that need to report availability to customers can reward also. Listed here, I take a look at extending the canonical SignalR chat example to incorporate a "who's typing" feature, and that i also prolong my prior Knockout instance to make use of SignalR.


Very first, what is the trouble that SignalR is made to remedy? The net functions on the Request-Response design. Browsers along with other person brokers make requests and net server offer a reaction to that request.The reaction is distributed for the delivery tackle supplied within the ask for by the person agent. And that is the natural purchase of issues on the web - servers can not make responses without a request. For your most element, this is not a concern, but if you need to display real-time updates with your net webpage, you have required to vacation resort to methods like frequently polling the server making use of AJAX to determine if any modifications experienced been produced to info. Alternatively, you can use Comet engineering, which retains a persistent connection open between the server and the customer. HTML5 introduced two new techniques - Server Despatched Occasions and WebSockets. SignalR is really a user-friendly wrapper about every one of these technologies which makes it a lot much easier to develop apps that need the real-time show of knowledge. SignalR utilises HTML5 Web Sockets API where it is obtainable, and falls again onto other technologies where they may be not - Server Sent Events, Eternally Frames or Long Polling, the final two of which are Comet strategies.

SignalR is currently in pre-release - Release Prospect one to be precise. It is obtainable by way of Nuget or Github. Nevertheless, as it is pre-release, it is not obtainable by way of the WebMatrix Nuget client. But you can get it using Visible Studio (and Express For Net edition, which is free) if you pick "Include Prerelease" as an alternative of the default "Stable Only" choice. Or you can use the Package Manager Console and simply sort:

Install-Package Microsoft.AspNet.SignalR -Pre


It is suggested to set up the package by doing this (via Nuget) as you'll find quite a few bits and pieces to be set up:

The centre bit of a SignalR application is actually a hub, that is similar to a Controller in ASP.Net MVC. A hub is accountable for getting enter and creating output. Hubs are created as server-side classes that inherit from Microsoft.AspNet.SignalR.Hubs.Hub. Public methods created within a hub course are meant to be known as from consumer code. They normally outcome inside a reaction becoming despatched to the consumer. Here's the hub and technique that the Chat example in the ASP.Net internet web site features:

using Microsoft.AspNet.SignalR.Hubs;

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        Clients.All.broadcastMessage(name, message);
    }
}


This should be saved as ChatHub.cs (a C# class file) in App_Code. A making use of directive is extra to the top in the file that makes Microsoft.AspNet.SignalR.Hubs available to the code. At runtime, a JavaScript file is produced dynamically which consists of a client-side implementation from the public Deliver technique in order that it may act as a proxy towards the server-side method. You write an implementation from the broadcastMessage approach in client-code in order that the Hub method can call it and therefore supply a reaction. You'll be able to also decide who ought to get the response through the choices obtainable:


Here's the full client-side code starting with the Layout page:

@{
    
}

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@Page.Title</title>
        <link href="~/Styles/site.css" rel="stylesheet" type="text/css" />
        <script src="~/Scripts/jquery-1.6.4.min.js" ></script>
        <script src="~/Scripts/jquery.signalR-1.0.0-rc1.min.js"></script>
        <script src="~/signalr/hubs"></script>
        @RenderSection("script", required: false)
    </head>
    <body>
        @RenderBody()
    </body>
</html>


Notice that there is a reference to a script called hubs in a signalr folder, neither of which exist. This is a placeholder for the dynamically generated script that translates the Hub methods to client code.

 

@{

}

    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>

@section script{
    <script type="text/javascript">
        $(function () {
 
            var chat = $.connection.chatHub;

            chat.client.broadcastMessage = function (name, message) {
                $('#discussion').append('<li><strong>' + name
                    + '</strong>:&nbsp;&nbsp;' + message + '</li>');
            };

            
            $('#displayname').val(prompt('Enter your name:', '')); 
            $('#message').focus();
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    var encodedName = $('<div />').text($('#displayname').val()).html();
                    var encodedMsg = $('<div />').text($('#message').val()).html();
                    chat.server.send(encodedName, encodedMsg);
                    $('#message').val('').focus();
                });
            });
        });
    </script>
}

Some HTML factors are produced at the top of the file - a textual content box, button, a hidden area and an unordered checklist. Inside the script block, a client-side proxy is developed for your server-side ChatHub class:

var chat = $.connection.chatHub;

The client-side model in the hub is generated utilizing camel-case (first word lower scenario). Remember that you have to write down your personal client-side implementation of the dynamic broadcastMessage approach? The following section displays that. It requires the two strings offered from the Hub approach, and uses them to generate a list item which is additional for the unordered list. The subsequent few lines create the user by prompting to get a title which can be stored in the concealed discipline, and placing the main target within the textbox. Then the link to the hub is opened, along with a simply click function handler is additional to the button which leads to the Deliver approach inside the server edition of the hub becoming invoked:

chat.server.send(encodedName, encodedMsg);

So just to recap, the button click invokes the client-side chat.server.send method, which calls the public ChatHub.Send method, which responds with Clients.All.broadcastMessage which invokes the client-side chat.client.broadcastMessage function.

There is one final thing needed to get this working, asn that is to register the default route for hubs, which is best done in an _AppStart.cshtml file:

@using System.Web.Routing
@using Microsoft.AspNet.SignalR

@{
    RouteTable.Routes.MapHubs();
}

The chat example is easy to understand and illustrates the basic workflow nicely. But it is not a complete application by any stretch of the imagination. It needs more, and a common feature of chat applications is an indicator of who is currently typing. We can use the workflow logic above to plan an implementation.

Something on the client needs to invoke a server-side method. Keystrokes are as good an indication of typing as any, so that will do:

$('#message').keypress(function () {
    var encodedName = $('<div />').text($('#displayname').val()).html();
    chat.server.isTyping(encodedName);
});

From the definition of the client method, it should be easy to discern the name and signature of the additional method required in the ChatHub class:

public void IsTyping(string name){
    Clients.All.sayWhoIsTyping(name);
}

With each keypress, the name of the current user is passed to the server-side IsTyping method, which responds by calling a client-side function called sayWhoIsTyping:

chat.client.sayWhoIsTyping = function (name) {
    $('#isTyping').html('<em>' + name + ' is typing</em>');
    setTimeout(function () { 
        $('#isTyping').html('&nbsp;');
    }, 3000);
};

It's a rough and ready function, which takes the name passed from the server-side method, and displays it as part of a string in a div with an ID of isTyping. The text is cleared after 3 seconds.

SignalR with Knockout

I've created about Knockout prior to. In case you are undecided what Knockout is all about, you should go through the previous article first. In that prior write-up, the instance exhibits a straightforward software in which the user can choose a goods, and in the ensuing listing, choose 1 item to check out the small print. There is certainly an easy button that results within the ViewModel's unitsInStock worth reducing by one as if a obtain were created, as well as the UI being up-to-date because of this. And that is among the advantages of Knockout - adjustments to observable values inside the ViewModel result in that modify being mirrored wherever it's certain within the UI. Nevertheless the alter is localised to the personal user's browser. If a product unit is actually obtained, or indeed if more are made accessible, it might be considered a really good concept if ALL existing users are notified in the change in unitsInStock in real-time, right? Seems like a activity for SignalR.

The quantity of adjustments required for the existing Knockout sample code are actually quite tiny. I amended the existing ViewModel purchase perform and added an additional operate to manage reordering products. I also additional two computed observables (they used to be known as dependent observables); one which functions out if the consumer can purchase an item based on availability, and the other that works out if the reorder degree continues to be achieved:

viewModel.buy = function() {
    var id = this.productId();
    productsHub.server.buyProduct(id);
};

viewModel.reorder = function() {
    var quantity = this.reorderQuantity();
    var id = this.productId();
    productsHub.server.reorderProduct(quantity, id);
};

viewModel.canBuy = ko.computed(function() {
    return this.unitsInStock() > 0;
}, viewModel);

viewModel.canReorder = ko.computed(function() {
    return this.unitsInStock() <= this.reorderLevel();
}, viewModel);

I also added a reorderLevel home towards the ViewModel, and after that extra a textbox and button for reordering, and wired up its visibility for the canReorder computed observable. The reordering button and textbox will only be seen in the event the units in inventory reaches the reorder level price. The Acquire A single button is currently only enabled if you will find units in inventory. Earlier, when there were no models in stock, the end result of clicking the Buy A single was an inform indicating that no inventory existed:

<div class="row" data-bind="visible: canReorder">
    <span class="label"><input data-bind="value: reorderQuantity" class="reorder" /></span>
    <span><button data-bind="click: reorder">Reorder</button></span>
</div>
<div class="row">
    <span class="label">&nbsp;</span>
    <span><button data-bind="click: buy, enable: canBuy">Buy One</button></span>
</div>

When you have been following alongside to date, you'll be able to see that the two ViewModel features: purchase and reorder stage to server-side Hub methods that don't at present exist: BuyProduct (indicated by productsHub.server.buyProduct) and ReorderProduct (indicated by productsHub.server.reorderProduct). So listed here is the code for your ProductHub with its methods:

using Microsoft.AspNet.SignalR.Hubs;
using WebMatrix.Data;

public class ProductHub : Hub
{
    public void BuyProduct(int productId) {
        using (var db = Database.Open("Northwind")) {
            var unitsInStock = db.QueryValue("SELECT UnitsInStock FROM Products WHERE ProductId = @0",
 productId);
if (unitsInStock > 0) { db.Execute("UPDATE Products Set UnitsInStock = UnitsInStock - 1 WHERE ProductId = @0",
productId); unitsInStock -= 1; } Clients.All.updateAvailableStock(unitsInStock, productId); } }
public void ReorderProduct(int quantity, int productId){ using (var db = Database.Open("Northwind")) { db.Execute("UPDATE Products Set UnitsInStock = UnitsInStock + @0 WHERE ProductId = @1",
quantity, productId);
var unitsInStock = db.QueryValue("SELECT UnitsInStock FROM Products WHERE ProductId = @0",
productId); Clients.All.updateAvailableStock(unitsInStock, productId); } } }

This time, the adjustments brought on by user motion will likely be saved within the database, which did not occur in the prior Chat example. The BuyProduct approach retrieves the existing quantity of units in stock for the chosen product, and permits a purchase if you'll find are any. The revised quantity of units in stock, combined with the product ID are sent towards the all currently linked clientele by way of an updateAvailableStock technique. The ReorderProduct method simply raises the UnitsInStock value by whatever quantity was handed in towards the method from the ViewModel function. Once more, the revised variety of units in stock is broadcast to all related customers.

So how can the customer deal with this broadcast? It requirements an updateAvailableStock perform in order that the hub methods can get in touch with it:

productHub.client.updateAvailableStock = function(unitsInStock, productId) {
    if (viewModel.productId() == productId) {
        viewModel.unitsInStock(unitsInStock);
        $('span[data-bind="text: unitsInStock"]').effect('highlight', { color: '#9ec6e2' }, 3500);
    }
};

First is checks to see when the ID in the solution being up to date may be the 1 presently sure to the ViewModel, and when it is, the worth is updated as well as a emphasize result is used towards the span that shows the models in inventory:


ll that remains to do is to create a client-side proxy for the ProductHub and establish a connection:

productsHub = $.connection.productHub;

$.connection.hub.start();


Both of these examples are available as part of a sample site available at GitHub.

SignalR is a lot more powerful than these introductory demonstrations illustrate. You can write your own PipelineModule class and inject your own processing code into the hub pipeline. You can add authorization really easily to a hub method or a complete hub using data annotiation style attributes.



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.



Orchard 1.8 Hosting - ASPHostPortal.com :: How to Use Infoset for Orchard 1.8 and Smart App Banners Module

clock October 9, 2014 12:34 by author Ben

Orchard 1.8 will have a nice overall performance enhancement permitting builders to use Infoset to retailer Content Component information. I talked somewhat about the swap to this doc db type of storage in Orchard CMS within the post, Orchard CMS Shift to Doc Storage and Module Development. I've been taking benefit of Infoset in my new Orchard Tasks. In doing this I desired to share an additional great Orchard Module that utilizes Infoset in Orchard 1.8 - Intelligent App Banners Module. Wise App Banners are a way iOS Developers promote their applications in the iOS Application Shop on their internet sites. This Orchard CMS Module helps iOS builders screen their Smart App Banners on their own Orchard Websites.

 

Infoset in Orchard 1.8

Take a peek at my earlier website post on Infoset to see an example of Retrieve and Shop used in the Content material Element to avoid wasting info within the Orchard CMS Databases. This new technique of storing Material Part info is supposed to increase the performance of Orchard 1.8 by minimizing the amount of table joins in Orchard. It's going to also reduce the chances of SELECT N + one queries.

From my viewpoint being an Orchard Developer, I also really like the decrease in boilerplate code when making Orchard Modules, Material Parts, etc. In many cases this can eradicate the necessity to develop custom made tables in the Orchard Database making use of Schema.CreateTable. It could also eradicate the need for a ContentPartRecord and/or customized Handler to the ContentPart in simple senarios. In fact, with all the Intelligent App Banner Module I just produced utilizing Infoset in Orchard 1.8, I indeed had all of these code financial savings.

Smart App Banner Orchard 1.8 Module

I built the Smart App Banners Orchard Module as an early Christmas existing for a existing consumer that develops iOS applications within the App Shop. I always believed it absolutely was awesome viewing Smart Application Banners on my iphone and iPad and desired to create an Orchard Module to show them on Orchard Internet sites.

The module includes a sensible App Banner Material Element that 1 can connect to Material Varieties in Orchard CMS. You are able to connect it to one thing as simple as a Page or perhaps your own personal custom Application Type. Incorporating the Content Element for the Page Content material Sort is so simple as attaching the Content material Element for the Content material Type.



As soon as you have added the Smart Application Banner Material Part to the Page Content material Sort you'll see the numerous settings for app-id, affiliate-data, and app-argument which will be utilized to display the Wise App Banner within the Orchard Web site. At a minimum, you will want to populate the App Id of your apple iphone or iPad Application to display the Smart Application Banner. The Affiliate Info and App Argument are optional for every the Apple Suggestions.



This takes place to be the App Id to the NFL Application in the App Retailer, which can show the next Smart App Banner within the site when seen using an iPad.



On condition that the iphone and iPad will be the two most popular cellular gadgets accustomed to browse the internet, it only tends to make perception that iOS Builders making use of Orchard CMS for his or her websites have a Smart Application Banners Orchard Module. It absolutely was also an enjoyable, personal venture for me to when again use Infoset in Orchard 1.8 to retailer and retrieve Content Component Data.

 



ASP.NET SignalR Hosting ASPHostPortal.com :: How you can Push Data from Server to Client Making use of SignalR

clock October 3, 2014 20:11 by author Ben

In real-time environments the server is aware from the information updates, occasion occurrences, and so forth. however the customer doesn’t understand it unless the request is initiated by the client towards the server seeking the updates. This is typically attained through techniques like constant polling, extended polling, and so forth. and these methodologies incur lots of site visitors and load to the server.

 


The alternate method to simplify and reduce the overhead is to make the server effective at notifying the clients. There are lots of systems launched to attain this and a few of them are WebSockets, SSE (Server Sent Activities), Lengthy polling, and so forth. Every of those techniques has its personal caveats like WebSockets are supported only on browsers that assistance HTML5 and SSE just isn't supported on Web Explorer.

SignalR is surely an Asp.Net library, which can be created to utilize the present transport systems underneath primarily based within the client nature and the assistance it provides. ASP.NET SignalR is effective at pushing the information to some wide selection of clientele like a Internet webpage, Window application, Window Cellphone Application, and so on. The onus is now taken out in the developers of stressing about which server push transportation to use and selecting the fallbacks in the event of unsupported situations.


Composition of SignalR

To start out with SignalR it is vital that you know the components. The server component from the SignalR engineering demands web hosting a PersistentConnection or even a SignalR hub.

  1. PersistentConnection - This can be a server endpoint to press the messages for the clientele. It enables the developers to accessibility the SignalR features at a low stage.
  2. Hub - It really is built on top of the PersistentConnection exposing high-level APIs and it allows the builders to produce the server to consumer calls within an RPC style (Remote Method Contact).

Within the client front SignalR offers various consumer libraries to different customers like Home windows Application, Internet Type, Home windows Cellphone, iOS, Android, and so on. The clientele must make use of the consumer libraries to get connected to the SignalR hub. These client libraries are available as NuGet deals.




Sample Application

Let us construct a sample chat software that broadcasts the messages to all linked customers or to specific teams. In this instance think about the customers to become a Windows software as well as a net kind customer.


Creating an Asp.Net SignalR Hub

Open Visual Studio and develop an vacant Asp.net MVC application named MyChatApplicationServer. Now open up the NuGet deals, lookup and include Microsoft ASP.Net SignalR.

Now right click on within the venture, include the SignalR Hub class and name it as MyChatHub. Add the following code to the course.

public class MyChatHub : Hub
    {
        public void BroadcastMessageToAll(string message)
        {
            Clients.All.newMessageReceived(message);
        }
 
        public void JoinAGroup(string group)
        {
            Groups.Add(Context.ConnectionId, group);
        }
 
        public void RemoveFromAGroup(string group)
        {
            Groups.Remove(Context.ConnectionId, group);
        }
 
        public void BroadcastToGroup(string message, string group)
        {
            Clients.Group(group).newMessageReceived(message);
        }
    }

The HUB course also provides the qualities Clientele, Groups, Context and events like OnConnected, and so on.

Ultimately it's also wise to add Owin startup course to map the obtainable hubs as proven below.

    [assembly: OwinStartup(typeof(MyChatApplicationServer.Startup))]
   
    namespace MyChatApplicationServer
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.MapSignalR();
            }
        }
    }

Pushing Data to a Web Form Client

Now create an internet form client venture named WebClient and incorporate a simple HTML file ChatWebClient.html with all the following code. Include the references towards the necessary script documents.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.1.min.js"></script>
    <script src="http://localhost:32555/signalr/hubs/" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var myChatHub = $.connection.myChatHub;
            myChatHub.client.newMessageReceived = function (message) {
                $('#ulChatMessages').append('<li>' + message + '</li>');
            }
            $.connection.hub.url = "http://localhost:32555/signalr";
            $.connection.hub.start().done(function () {
                $('#btnSubmit').click(function (e) {
                    myChatHub.server.broadcastMessageToAll($('#txtEnterMessage').val(), 'Web user');
                });
            }).fail(function (error) {
                console.error(error);
            });;
         
        });
    </script>
</head>
<body>
    <div>
        <label id="lblEnterMessage">Enter Message: </label>
        <input type="text" id="txtEnterMessage" />
        <input type="submit" id="btnSubmit" value="Send Message" />
        <ul id="ulChatMessages"></ul>
    </div>
</body>
</html>

You'll find two ways of applying the customer function one with proxy as well as other without having. The above instance is the a single without a proxy.

In the link begin you may also point out which transport SignalR must use.
Pushing Info to a Home windows Application Consumer

Let us include a home windows application and subscribe for the SignalR host. Create a new windows software named WinFormClient and from the nugget offers install Microsoft ASP.Net SignalR .Internet consumer package deal. Within the Program.cs add the subsequent code.

    namespace WinFormClient
    {
        public partial class Form1 : Form
        {
            HubConnection hubConnection;
            IHubProxy hubProxy;
            public Form1()
            {
                InitializeComponent();
                hubConnection = new HubConnection("http://localhost:32555/signalr/hubs");
                hubProxy = hubConnection.CreateHubProxy("MyChatHub");
                hubProxy.On<string>("newMessageReceived", (message) => lstMessages.Items.Add(message));
                hubConnection.Start().Wait();
            }
   
            private void btnSubmit_Click(object sender, EventArgs e)
            {
                hubProxy.Invoke("BroadcastMessageToAll", textBox1.Text, "Window App User").Wait();
            }
        }
    }

When done go on and operate each the net and Windows consumer. Enter the messages and look at how the information is getting pushed throughout each the clients although they may be of a distinct character.



SignalR is able of serving several connected clients irrespective of the customer system or technology. I hope this short article offers a good sum of data about pushing information from the server to consumer using Asp.Internet SignalR.



ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Increase The Overall Performance of ASP.NET 4.5.1 in your App

clock October 1, 2014 07:23 by author Ben

ASP.NET is really a framework for creating net applications created by Microsoft. Initially the technologies. NET is the successor of ASP which is also a computer software product from Microsoft. With .NET ASP gives a platform for developers to design and create dynamic websites and net portals.



You will find certain items that ought to be regarded as when improving the performance from the application in developing a net application. Here are a few of the tips to improve the performance of ASP.NET 4.5.1:

Turn off Session State
Disable session state if you do not need, as this can improve the all round efficiency. By default the session state is always active. However, you'll be able to disable session state for any specific pages.

Turn off Tracing
If tracing is enabled, tracing will add a whole lot of overhead in producing applications. Though tracing is actually a useful function inside the development because it enables developers to track and trace application sequence, tracing may be turned off, unless you want to monitor the trace logging.

Avoid Page Validation Server (Steer clear of Server-side Validation)
Within this case, must be attempted use of client-side validation, not the server side. Server-side validation will consume a lot of sources around the server which can have an effect on application efficiency.

Stay away from Exceptions (Avoid Exceptions)
Exceptions may be 1 of the biggest resource eater which resulted within the lower of web applications and windows applications. Therefore, it is much better to prevent the use and handling of exceptions which can be not beneficial.

Avoid frequent connections for the database (Steer clear of Frequent Calls to Database)
Connections are frequently made for the database can devote time response and resources (resources). This can be avoided by utilizing batch processing. Producing the minimum database connection as a connection is opened and not closed, may cause efficiency slowdown.

Stay away from utilizing Recursive Functions and Nested Loops
To improve application performance, attempt to always steer clear of utilizing nested loops and recursive functions simply because these functions consume a whole lot of memory.

Turn off the View State

In ASP.NET, the default view state will probably be active and will slow down the website. So if you don't use a kind postback, it's much better to disable view state.

Use Caching
Web page caching could be employed to get a particular period of time and towards the required duration will not visit the server and are served from the cache. In the case of static internet pages and dynamic, Partial Caching [Fragment Caching] may be utilized to break into a couple of pages a user control.



ASP.NET 4.5.2 Hosting Tutorial :: How to Send Multiple Value to Server using JSON in ASP.NET

clock September 15, 2014 10:49 by author Ben

JSON is JavaScript Object Notation. JSON is a syntax for storing and exchanging data. JSON is an easier to use alternative to XML. JSON uses JavaScript syntax, but the JSON format is text only, just like XML. Text can be read and used as a data format by any programming language. using JSON with JavaScript in an ASP.Net page is a straightforward process if you remember to follow certain steps. If you get this right, then you can use JQuery to load your JSON and your JavaScript code can easily access the JSON data.

Json.Net is a popular framework for working with JSON. In particular, it has a bunch of features that are not supported by the DataContractJsonSerializer such as being much more flexible in what kind of types it can serialize and exactly how they should be serialized.

And now I will tell you how to Send multiple value to Server using JSON in ASP.NET.

Step 1 : Create WebService Method.

    [WebMethod]
    public string GetData(string Data)
    {
        System.Web.Script.Serialization.JavaScriptSerializer JSON = new System.Web.Script.Serialization.JavaScriptSerializer();
        Object obj = JSON.DeserializeObject(Data);
        Hashtable ht = new Hashtable();
        foreach (KeyValuePair d in (Dictionary)obj)
        {
            ht.Add(d.Key, d.Value);
        }
        return "GetData successfully.";
    }


Step 2 : Create JavaScript function using jQuery.ajax
Declare Array type in JavaScript and serialize to JSON Data and pass value to WebService.

    function SendData() {
        var arg = {};
        arg["Data1"] = "String1";
        arg["Data2"] = 950;
        arg["Data3"] = "String2";
        arg = Sys.Serialization.JavaScriptSerializer.serialize(arg);

        $.ajax({
            url: "WebService.asmx/GetData",
            data: "{ 'Data': '" + arg + "' }",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                alert(data.d);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            }
        });
    }

 



Cheap and Best BugNET Hosting :: How to Install BugNET with SQL Server 2008

clock July 23, 2014 09:29 by author Ben

BugNET is an open source bug tracking tool based on SQL written in ASP.NET language. It is a cross-platform application used to keep the codebase simple. BugNET supports many features such as email notifications, multiple databases and projects supports, easy navigation, excellent security etc. The main goals are to keep the codebase simple, well documented, easy to deploy and scalable.

Installing BugNET
There are three ways you can install BugNET. You can:

  • Install it using the Web Deployment Package.
  • Download the BugNET .zip file and install it as described in Manually Installing BugNET Using a zip file.
  • Download the BugNET source code and build BugNET from the command line or in Visual Studio.


Requirements

  • ASP.NET 4
  • A web server such as IIS Express 8, 7.5 or IIS 7.x.
  • Microsoft SQL Server 2008 Express or greater.


ASPHostPortal windows hosting is compatible with the BugNET. We offer BugNET based hosting plan from just $5/month (see our BugNET Hosting Plan).

And now we'll tell you about How to Install BugNET Using SQL Server 2008:

  1. Extract the contents of the install package to a folder on your computer.
  2. Create a directory in the c:\inetpub\wwwroot\ folder called bugnet (c:\inetpub\wwwroot\bugnet)
  3. Copy the contents of the BugNET folder in the install package to the c:\inetpub\wwwroot\bugnet\ folder
  4. Go to the properties of the c:\inetpub\wwwroot\bugnet\ folder, click on the Security tab, be sure to add the permissions for the appropriate user (WinXp/2000 uses the local ASPNET account, Win2003/Vista/2008/7 use the local Network Service account). Give this account modify permissions on (if necessary):
  5. Uploads - if using file system based uploads
  6. Create a virtual directory in IIS for the bugnet folder.
  7. Open up the the web server IIS Console, start-> run-> INETMGR
  8. Expand the websites node
  9. Expand the default websites node
  10. Right click on the BugNET folder under the default website, click on Convert to Application, if you don't have that option, choose properties and then add the application.
  11. Configure the database server.
  12. Load the SQL Server Management tool
  13. Expand the Server/Security node
  14. Create a blank SQL Database (e.g db name 'BugNet') on your sql server using a case insensitive collation.
  15. Configure the SQL User Security/Account to allow IIS and ASP.NET access to the database in SQL.


When the installation is complete, you may log in with the admin user account.
Username: admin
Password: password


Cheap and Best BugNET Hosting with ASPHostPortal.com
ASPHostPortal.com BugNET optimised hosting infrastructure features independent email, web, database, DNS and control panel servers and a lightning fast servers ensuring your site loads super quick! Reason why you should choose us to host your BugNET site:

Easy to Use Tools - ASPHostPortal.com use World Class Plesk Control Panel that help you with single-click BugNET installation.
Best Programming Support - ASPHostPortal.com hosting servers come ready with the latest PHP version. You can get access directly to your MySQL from our world class Plesk Control Panel.
Best Server Technology - The minimal specs of our servers includes Intel Xeon Dual Core Processor, RAID-10 protected hard disk space with minimum 8 GB RAM. You dont need to worry about the speed of your site.
Best and Friendly Support - Our customer support will help you 24 hours a day, 7 days a week and 365 days a year to assist you.
Uptime & Support Guarantees - We are so confident in our hosting services we will not only provide you with a 30 days money back guarantee, but also we give you a 99.9% uptime guarantee.



Cheap ASP.NET Web Pages 3.2 Hosting :: New Features on ASP.NET Web Pages 3.2

clock July 22, 2014 13:01 by author Ben

Windows and ASP.NET hosting specialist, ASPHostPortal.com, has announced the availability of new hosting plans that are optimized for the latest update of the Microsoft Web Pages technology. The Web Pages 3.2,  introduces many new features including several that focus on premium media experiences and business application development.

ASP.NET Web Pages is a framework that you can use to create dynamic web pages. A simple HTML web page is static; its content is determined by the fixed HTML markup that's in the page. Dynamic pages like those you create with ASP.NET Web Pages let you create the page content on the fly, by using code.

The latest ASP.NET Web Pages 3.2  package has the following version: “3.2.0”. You can install or update these packages through NuGet. The release also includes corresponding localized packages on NuGet.

You can install or update to the released NuGet packages by using the NuGet Package Manager Console:

Install-Package Microsoft.AspNet.WebPages -Version 3.2.0

Nuget has many packages for ASP.NET Web Pages, such as:

ASP.NET Web Helpers Library
This package contains web helpers to easily add functionality to your site such as Captcha validation, Twitter profile and search boxes, Gravatars, Video, Bing search, site analytics or themes. This package is not compatible with ASP.NET MVC.

Microsoft WebPages OAuth library
This package contains the runtime assemblies for ASP.NET Web Pages. ASP.NET Web Pages and the new Razor syntax provide a fast, terse, clean and lightweight way to combine server code with HTML to create dynamic web content.

Microsoft ASP.NET Razor

This package contains the runtime assemblies for ASP.NET Web Pages. ASP.NET Web Pages and the new Razor syntax provide a fast, terse, clean and lightweight way to combine server code with HTML to create dynamic web content.

The  Advantages of ASP.NET WebPages 3.2 are :

- Framework to build dynamic web pages, typically suited for small-scale applications.
- Web pages can be developed using WebMatrix, a free tool from Microsoft which integrates web page editor, database utilities, integration with different browsers, local
- Uses Razor view engine, which is intelligent enough to understand the difference between server-side code and HTML code.


About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



Cheap and Best DotNetOpenAuth Hosting :: Integrating OpenAuth/OpenID With Your ASP.NET MVC Application

clock July 22, 2014 08:47 by author Ben

DotnetOpenAuth is a open source library that allows the developers to add the OpenId and OAuth capabilities to their ASP.NET Web Application. It allows the developers to include the OpenId support by just dragging and dropping a ASP.NET control to the Web Page.


What is OpenId?

OpenId is a single sign-on scheme – the idea is that you keep your login and profile information in one place so that you don’t have to login at every Web location and create new user credentials on each site. The  idea of a single sign on isn’t new of course – lots of these things have been around over the years with the most remembered probably being Microsoft’s Passport/Windows Live ID (not that anybody likes Windows Live Id).

What is OAuth?

OAuth is the main protocol. It is stable and ready to be implemented. Libraries are already available for many popular platforms such as PHP, Rails, Python, .NET, C, and Perl. We expect most upcoming work to focus on implementations and the development of extensions to the protocol.

And now, we'll tell you about Integrating OpenAuth/OpenID with your ASP.NET MVC application, for this tutorial I use ASP.NET MVC 4.0 and Visual Studio 2012.

Step 1: Create a new project

  • Go to File 
  • New Project  Web
  • Empty Asp.Net MVC 4 Application

Step 2: Add the following libraries

  • Use Nuget to get the following packages
  • DotNetOpenAuth.AspNet
  • Microsoft.AspNet.Providers.Core
  • Microsoft.AspNet.Providers.LocalDb
  • Microsoft.AspNet.Membership.OpenAuth

Step 3: Change web.config to use formsauthentication

<authentication mode="Forms">

   <forms loginUrl="~/Auth/Logon" timeout="2880" />

</authentication>

Step 4: Adding AuthConfig

Add a new class called AuthConfig.cs to folder App_Start that class will contains the register functions for all services that we will integrate

Add the following code to AuthConfig.cs and don’t forget to get services Api keys from each service website

public static void RegisterAuth()
{

OAuthWebSecurity.RegisterMicrosoftClient(
clientId: "",
clientSecret: "");
OAuthWebSecurity.RegisterTwitterClient(
consumerKey: "",
consumerSecret: "");
OAuthWebSecurity.RegisterFacebookClient(
appId: "",
appSecret: "");
OAuthWebSecurity.RegisterGoogleClient();
OAuthWebSecurity.RegisterLinkedInClient(
consumerKey: "",
consumerSecret: "");
OAuthWebSecurity.RegisterYahooClient();
}



Register AuthConfig to application start Go to Global.asax and add the following line to Application_Start function
AuthConfig.RegisterAuth();

Step 5: Adding Login functionality

Add a new controller for Authentication functionality called it AuthController.cs
add Logon Action for login page

public ActionResult Logon()
{
return View(OAuthWebSecurity.RegisteredClientData);
}


as you can notice that we user OAuthWebSecurity.RegisteredClientData as a model that object will contain all registered services that we put at AuthConfig class. Add a markup for login page

@using Microsoft.Web.WebPages.OAuth;
@model ICollection<AuthenticationClientData>
//Add this inside body
<div>
        @using (Html.BeginForm("ExternalLogin", "Auth", new { ReturnUrl = ViewBag.ReturnUrl }))
        {
            @Html.AntiForgeryToken()
            <p>
                @foreach (AuthenticationClientData p in Model)
                {
                    <button type="submit" name="provider" value="@p.AuthenticationClient.ProviderName" title="Log in using your @p.DisplayName account">@p.DisplayName</button>
                }
            </p>
        }
    </div>

as you can notice that we are looping against the services that we already registered in a previous step each AuthenticationClientData represent a service so we create a button to call that service we are adding all the buttons inside single form that calling ExternalLogin action method. Add ActionMethod ExternalLogin

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public void ExternalLogin(string provider, string returnUrl)
{
  OAuthWebSecurity.RequestAuthentication(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}


We are using OAuthWebSecurity.RequestAuthentication this function is requesting the authentication from the requested provider service “Facebook – Twitter – etc.”

[AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl = "")
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }
            //if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            //{
            //    return RedirectToLocal(returnUrl);
            //}
            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                OAuthAccount oAuthAccount = new OAuthAccount(result.Provider, result.ProviderUserId);
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }
 private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

We have to verify authentication to ensure that the account is successfully authenticated if not redirect users to ExternalLoginFailure action if user is authenticated then we are going to login user to the system using simple membership we are going to talk about that in later posts then check if the current user is logged in add the new account else user is new, ask for their desired membership name then redirect to ExternalLoginConfirmation action with user information at RegisterExternalLoginModel class

public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model)
       {
           return View(model);
       }
RegisterExternalLoginModel
public class RegisterExternalLoginModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
        public string ExternalLoginData { get; set; }
    }

and now run your program.

DotNetOpenAuth Hosting with ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch.

ASPHostPortal.com will now DotNetOpenAuth Hosting (extensions for ASP.NET (WebPages)) service on all of our hosting plans, starting at just $5.00/mo! We offer completely Windows ASP.NET  website hosting that is fast, reliable and packed with fantastic features to publish your websites online.



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

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

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

Tag cloud

Sign in