ASP.NET 4.5 Hosting BLOG

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

ASP.NET MVC Hosting - ASPHostPortal.com :: Secure Your ASP.NET MVC Apps and Utilize Active Directory

clock February 25, 2015 06:11 by author Ben

Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one's web application.

By decorating the HomeController using the Authorize attribute (notice I didn't specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

[Authorize]
public class HomeController : Controller
{
  //...
}

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

[Authorize]
public ActionResult Create()
{
  //...
}

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there's security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

[HttpPost, Authorize, ValidateAntiForgeryToken]
public ActionResult Create()
{
  //...
}

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

public ActionResult LogOn()
        {
            return View();
        }
       
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect");
                }
            }

            // if we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

public class LogOnModel
        {
            [Required]
            [Display(Name = "User name")]
            public string UserName { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public string RememberMe { get; set; }
        }

Lastly, add the following to the project’s web.config file:

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Sending an email using exchange server from the ASP.NET Application

clock February 2, 2015 07:27 by author Dan

The .NET Framework 1.x had a System.web.mail class to send an email from the ASP.NET system. While this namespace and these classes still exist in the .NET Framework form 2.0 and later, they have been expostulated and supplanted by the new Mail API in the System.net.mail namespace in the Asp.net 2.0 structure. Asp.net 1.x's System.web.mail API was focused around CDO libraries. With the new Apis, Microsoft moved far from CDONTS based wrapper Apis and composed the new API utilizing Com+ segments to enhance the execution.

ASP.NET 2.0 sends an email utilizing Smtpclient class. In the most fundamental arrangement, You need to set the hostname of the hand-off server in the event that you are utilizing trade server or localhost in the event that you are utilizing neighborhood SMTP administration, port (25 as a matter of course), authentican certifications, or pointed out pickup index through the Deliverymethod property.

Here is the template for the System.NET.Mail configuration.

<configuration>
<!– Add the email settings to the element –>
<system.net>
<mailSettings>
<smtp deliveryMethod=”PickupDirectory” from=”fromemailaddress”>
<network
host=”relayServerHost”
port=”portNumber”
userName=”username”
password=”password”
defaultCredentials=”true/false”/>
</smtp>
</mailSettings>
</system.net>
</configuration>

localhost – local web server SMTP administration – If you need to send an email through neighborhood SMTP Service of the web server, basically include emulating lines of code in your web.config to send an email from the ASP.NET Pages.

<system.net>
<mailSettings>
<smtp deliveryMethod=”PickupDirectoryFromIis”>
<network host=”(localhost)” port=”25″ defaultCredentials=”true” />
</smtp>
</mailSettings>
</system.net>

Exchange Server – If you need to send an email from existing trade server email account, you need to setup the transfer administration from your webserver to trade server. Emulating web.config setup permits you utilize hand-off administration for trade server.

How about we say's exchange server name is "exmail.domainname.com", exchange username and secret key is "exchangeuserid" and "exchangepassword", you web.config settings would be

<system.net>
<mailSettings>
<smtp>
<network host=”exmail.domainname.com” port=”25″ userName=”exchangeuserid” password=”exchangepassword” defaultCredentials=”false” />
</smtp>
</mailSettings>
</system.net>

Next step would be to make a class to send a messages utilizing SMTP Service: Note that emulating code utilizes Web.config settings. Remarked out code won't utilize web.config mail settings. In spite of the fact that its preferrable, on the off chance that you don't need email designs in web.config document, utilize the remarked out code to design and send an email from the ASP.NET pages.

using System;using System.Net;using System.Net.Mail;
public class SMTPEmailSender
{
public SMTPEmailSender()
{
//
// TODO: Add constructor logic here
//
}

public static void SendSMTPEmail(string senderMailAddress,
string recipientMailAddress,
string mailSubject,
string mailBody)
{

//Create MailMessage to send an email.
MailMessage message = new MailMessage(senderMailAddress, recipientMailAddress);
message.Subject = mailSubject;
message.Body = mailBody;

//Use SMTPClient to send an email.
//Uses SMTP settings from web.config
SmtpClient client = new SmtpClient();
client.Send(message);

//Uses SMTP Settings from Code
/*
//Sample Code
//SmtpClient smtp = new SmtpClient(“exmail.domainname.com”, portnumber);
//smtp.Credentials = new NetworkCredential(“exchangeuserid”, “exchangepassword”, “DOMAIN”);
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //smtp.Send(message);
*/
}
}

Create a Test Page to send out emails. Here is the source code from the code behind to send an email from the test email page.

public partial class TestEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string fromEmailAddress = “[email protected]“;
string recipientEmailAddress = “[email protected]“;
string mailSubject = “Nik’s Website: Test Email”;
string mailBody = “Test Email.”;
if (recipientEmailAddress != null && recipientEmailAddress.Trim().Length != 0)
{
SMTPEmailManager.SendSMTPEmail(fromEmailAddress, recipientEmailAddress, mailSubject, mailBody);
}
Response.Write(“Test Email Sent Out”);
}
}

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET MVC Hosting - ASPHostPortal.com :: How to Use Areas in ASP.NET MVC

clock January 29, 2015 05:57 by author Mark

Today i will explains about how to use areas in ASP.NET MVC. When we create a new MVC project then Model, View and Controller folders are created automatically.
This structure is common for simple applications, but when your application grows and becomes complex then the single Model, View and Controller can become complicated. So we can maintain a complex MVC application using areas. Using areas, we can write more maintainable code for an application cleanly separated by the modules.

Step by Step

  • So first create a new MVC empty project.
  • Then right-click on Solution Explorer and click on add and select area.

  • Provide a name.

  • Now add a second Employee area. In your Solution Explorer show your Model, View and Controller in a different student and employee area.

  • Now add a Home Controller and in the Index action add an Index View for both the student and employee area.
  • Now run the project. (Ctrl+F5).
  • For the Teacher area the follwing is the URL localhost/Teachers/Home/Index.
  • Here Teachers is the area name, Home is the controller and Index is the Action name.

  • For the Teacher area the follwing is the URL localhost/Students/Home/Index.
  • Here Students is the area name, Home is the controller and Index is the Action name.

TOP No#1 Recommended ASP.NET MVC Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET MVC Hosting - ASPHostPortal.com :: Conditional Validation Utilize ValidationAttribute

clock January 21, 2015 05:57 by author Ben

In ASP.NET MVC we can validate each input field by decorating the corresponding property in the model class with some validation attributes like Required, MaxLength, MinLength, etc.

Sometime we need to validate a property according to another property value for example if we have a registration form and we need the user enter his age if he is a male and age not required if the user sex is female. So if we decorated the Age property with Required attribute it will show error message even if the user is female, so we need to bypass this check with females.

Assume our registration form will contains three fields, name, sex and age, and its model will be as follows

public class RegisterationModel
{
    [Required(ErrorMessage = "*")]
    public String Name { get; set; }

    [Required(ErrorMessage = "*")]
    [Display(Name = "Gender")]
    public Sex Sex { get; set; }

    [RequiredIf("Sex", Sex.Male, "enter your age")]
    public Int32? Age { get; set; }
}
public enum Sex
{
    Female = 1,
    Male = 2
}

Note we decorated the Age property with RequiredIf attribute, that we will create and it inherits ValidationAttribute class and override IsValid method.

The RequiredIf attribute accepts three pramaters in its constructor, first parameter is the name of the property will affect the validation (Sex property), second parameter is the value of that property that make the Age is required(Male), and third parameter is the error message that will be displayed if the validation failed.

public class RequiredIfAttribute : ValidationAttribute
{
    private String PropertyName { get; set; }
    private String ErrorMessage { get; set; }
    private Object DesiredValue { get; set; }

    public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
    {
        this.PropertyName = propertyName;
        this.DesiredValue = desiredvalue;
        this.ErrorMessage = errormessage;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
        if (proprtyvalue.ToString() == DesiredValue.ToString() && value == null)
        {
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

In the IsValid method we get the current instance of RegisterationModel class using ValidationContext object and get the value of the Sex property then compare it with the desire value(Male) which make the Age is required. If the current value of Sex property equal the desired value then IsValid will return new ValidationResult object with the supplied error message.

Unfortunately this technique is working in server side only.


Recommended ASP.NET MVC 6 Hosting


ASPHostPortal.com
ASPHostPortal.com
is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.




ASP.NET MVC Hosting - ASPHostPortal :: Describes Attribute Based Routing in ASP.NET MVC 5

clock January 20, 2015 05:19 by author Mark

This article will explains about describes Attribute Based Routing in ASP.NET MVC 5. Today we will have a look at one of the new features introduced in ASP.NET MVC 5, attribute based routing.

Pre-Context

We all know that ASP.NET MVC is a great platform that allows us to create and manage web applications in a much simpler manner compared to form-based web applications. There are a few things in MVC based web applications that works a little differently than standard web applications, one of them is routing.
Until now, there has been a routing table that you can define either in the Global.asax or in the RouteConfig.cs and all incoming requests would look it up to decide the rendering of a target view.
Here is the code that you might have seen previously to have note-variable routes in MVC 4 in the following example of the Route collection object.  

                         routes.MapRoute(  
                name: "Default",  
                url: "{controller}/{action}/{id}",  
                defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }  
                ); 

The big question: what is the need for this new routing methodology?
And the answer is: there was nothing really wrong with the previous approach of routing and in fact you can still use it in MVC 5 or use this new routing method in conjunction with the old one.
Here are a few advantages of attribute based routing:  

  • Helps developer in the debugging / troubleshooting mode by providing information about routes.
  • Reduces the chances for errors, if a route is modified incorrectly in RouteConfig.cs then it may affect the entire application's routing.
  • May decouple controller and action names from route entirely.
  • Easy to map two routes pointing to the same action.

All right, enough of talking. Let's see exactly how we can configure it and see it working.
First, we will need to enable attribute based routing on our MVC web application that can be done by only one line. All you need to do is put this line in the RegisterRoutes Method of the application.

    public static void RegisterRoutes(RouteCollection routes)  
    {  
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");         
        tes.MapMvcAttributeRoutes(); //Enables Attribute Based Routing   
        routes.MapRoute(  
            name: "Default",  
            url: "{controller}/{action}/{id}",  
            defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }  
        );                    
    } 

Now, here is how you can use the attribute based routing on a specific action method.

[Route("products/{id?}")]  
          public ActionResult Details(string id)   
          {  
              if (string.IsNullOrEmpty(id))   
              {  
                  return View("List", GetProductList());  
              }                   
              return View("Details", GetProductDetails());  
          }  

As shown in the method above, the Route is defined on a Details action method that lets users access the product details page either by of these paths:  
    /Product/Details/Id or /products/id
You might have observed the question mark in the route above, all it indicates is that the id is an optional parameter of the route and hence the action method logic checks if the id is null. It will show you the product listing page.

Route Prefixes

Route Prefixes are nothing but the prefix for any route that we want to apply, all we need to do is to define the route prefix on a controller so that all the action methods inside it can follow the prefix.
For example:   

         [RoutePrefix("products")]  
          public class ProductController : Controller  
          {  
              //This will be translated to /products          
             [Route]  
              public ActionResult List()  
              {  
                  return View();  
              }          
              //This will be translated to /products/2          
              [Route("{id?}")]  
              public ActionResult Details(string id)   
              {  
                  if (string.IsNullOrEmpty(id))   
                  {  
                     return View("List");  
                  }                       
                  return View("Details");  
              }  
      }

Route Constraints

Route constraints are nothing but a set of rules that you can define on your routing model / parameters that users need to follow when accessing the defined routes.
The way to define a constraint is by using the ":" character, let's have a look at the example below.
For example:

   //route gets called as /products/productname  
        [Route("products/{id:alpha}")]  
            public ActionResult GetProduct(string name)  
            {  
                return View();  
            }         
    //route gets called as /products/2  
            [Route("products/{id:int}")]  
            public ActionResult GetProduct(int id)  
            {  
                return View();  
            } 

Now you might have observed in the example above that though the method name is the same the route's parameter has some constraint on it. In other words the first method will be called if the route is accessed with a string as parameter and the second method will be called if the route is accessed with an integer in the route parameter.
You can also define your custom route constraints using an IRouteConstraint interface.

Route Areas

A Route area is nothing but the way to specify the area in a route, basically just to let the route know that the controller belongs to some area.

[RouteArea("business")]  
      [RoutePrefix("products")]  
      public class ProductController : Controller  
      {  
          //This will be translated to /business/products/list      
          [Route]  
          public ActionResult List()  
          {  
              return View();  
          }  
  }

TOP No#1 Recommended ASP.NET MVC 5 Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.

 

 



ASP.NET Hosting - ASPHostPortal.com :: Scaffolding for ASP.NET Webforms

clock January 7, 2015 05:41 by author Ben

Those who knows ASP.NET MVC, might already knows the power of scaffolding. With VS.Net 2013 we will have scaffold template included for asp.net web forms.  By scaffold template you can generate a boilerplate code for asp.net web forms in a min. The Web Forms scaffold generator can automatically build Create-Read-Update-Delete (CRUD) views based on a model.

 


Step by Step example of using scaffold template inside asp.net web forms to generate CRUD operations.

Step 1:
Download VS.Net 2013 Express Preview

Step 2:
Create Asp.net WebForm Project

Step 3:
Add Model Class and named it as "Product.cs"  (Right click Model class and Add new class)


Step 4:
Create POCO Class with following content in it.  Yes you can take advantage of DataAnnotations of Entity framework.

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

namespace WebApplication3.Models
{
    public class Product
    {
        [ScaffoldColumn(false)]
        public int ID { get; set; }

        [StringLength(25)]  
        public string ProductName { get; set; }
        public string Description { get; set; }
       
        [DataType(DataType.Currency)]
        public int Price { get; set; }       
    }
}


In above code

  • [ScaffoldColumn(false)] will not generate any presentation code for that field
  • [StringLenght(25)] will limit product name upto 25 characters only.
  • [DataType(DataType.Currency)] will limit to enter only proper currency value.

Step 5:
Build your application.  (Cntrl + Shift + B)

Step 6:
Now its time to use scaffold template to generate code for CRUD operations in asp.net web forms.
Right click on model class and add scaffold for Product class.


Step 7:
Click on Add button as shown in figure to "Generates ASP.NET Web Forms pages for read/write operations based on a given data model."


Step 8:
Select Model class as "Product.cs", Since we haven't created or have any data context class, select "Add new data context" and Click on "Add" button.


Step 9:
If you wish you can change name of your data context class.  For this demo purpose I am keeping everything to default generated by VS.Net.  Press "OK" button.


Step 10:
You will noticed that VS.Net 2013 has generated new data context file inside model folder and has also created CRUD operations for Product class.


Step 11:
Run the application and enjoy the boilerplate code...  You will also noticed that web forms project has extension-less url and also has responsive design using Twitter bootstrap out of the box...

Type the url: /Product  notice it is extension-less url and


Click on "Create new" link and create new product

Data Entry few product.  Notice fancy validation on entering wrong values.  "Everything is out of box, you don't need to write a single line of code to make this working... Isn't that cool"


Product Listing


Similarly you can edit record, delete record. Hope you enjoyed this post...

 



ASP.NET 4.5 Hosting - ASPHostPortal :: How to Drag Drop Elements in ASP.NET MVC 5 using HTML 5, Web API and jQuery

clock December 22, 2014 05:24 by author Mark

Providing rich web UI experiences like Charts, Editable tabular interface, offline capabilities, dragging-dropping data on the page etc. can be a challenging task. To implement these features, a developer must plan the application based upon different browsers capabilities. A couple of years ago, this was achievable with a lot of efforts using some complex JavaScript code.

As the web progressed, modern browsers has made it possible to take web development to the next level. To complement, there are several libraries like jQuery, Angular, DOJO, etc. that can provide new UI rich features to enhance your applications. But wouldn’t it be nicer if the HTML itself provides some of these cool features using markup?
HTML5 has been developed with the current and future browser development in mind. Apart from being backward compatible, HTML5 contains many new elements and APIs for adding Rich UX capabilities to the application. Drag-Drop is one such useful feature available in HTML5 that can be used for data management on the page.
In HTML 5, an element can be made draggable using draggable=true in the markup. To monitor the process of drag-drop, we need to make use of the following events: dragstart, drag, dragenter, dragleave, dragover, drop, dragend.
The process of implementation has the following elements:

  • The source element applied with attribute draggable=true.
  • The data payload which means the data to be dragged and dropped.
  • The target where the drop is made.

Drag-Drop in ASP.NET MVC 5 using HTML 5, Web API and jQuery

To implement the Drag-Drop application, we will be using the following technologies:
ASP.NET MVC 5
WEB API with Attribute Routing
jQuery

  • Step 1: Open Visual Studio 2013 (the application uses Ultimate with Update 3), and create an Empty MVC application.
  • Step 2: In the App_Data folder of the application add a new SQL Server database with the name ‘Application.mdf’ as below:

In this database, add a new table called ‘Products’ using the following script:
CREATE TABLE [dbo].[Products] (
    [ProductId]   INT          IDENTITY (1, 1) NOT NULL,
    [ProductName] VARCHAR (50) NOT NULL,
    [Quantity]    INT          NOT NULL,
    PRIMARY KEY CLUSTERED ([ProductId] ASC)
);

The above table will contain products which we will fetch in our View.

  • Step 3: In the Models folder, add a new EntityFramework with the name ApplicationEDMX. In the wizard that comes up, select the Application.mdf database and the Products table designed in the above step. After completing the wizard, the following table mapping gets displayed.

  • Step 4: In the controllers folder, add a new Empty WEB API Controller with the name ProductsAPIController. In this API controller add the following code:

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using A1_HTML5_DragDrop.Models;
namespace A1_HTML5_DragDrop.Controllers
{
    public class ProductsAPIController : ApiController
    {
        ApplicationEntities ctx;
 
        public ProductsAPIController()
        {
            ctx = new ApplicationEntities();
        }
 
        [Route("Products")]
        public IEnumerable<Product> GetProducts()
        {
            return ctx.Products.ToList();
        }
    }
}

The above code declares an object of ApplicationEntities, which got generated using EntityFramework. The GetProducts() returns a list of products. This method is applied with an Attribute Route ‘[Route(“Products”)]’ which will provide the URL to make call to this method using client-side framework (e.g. ajax method). You can read more on Attribute routing in my other article Practical Use of ASP.NET Web API Attribute Routing in an MVC application.

  • Step 5: In the controllers folder, add a new Empty MVC controller of the name ProductController. This controller class will generate an Index method. Scaffold a new Empty view from the Index method.
  • Step 6: Add the following markup in the Index view:

<table>
    <tr>
        <td>
            <h1>Product List</h1>
        </td>
        <td>
            <h1>Selected Products</h1>
        </td>
    </tr>
    <tr>
        <td>
            <div id="dvleft">
                <ul id="lstproducts">
                </ul>
            </div>
        </td>
        <td>
            <div id="dvright">
                <ul id="lstselectedproducts"></ul>
            </div>
        </td>
    </tr>
</table>

The above markup has a table with two rows. The first row shows headers for Product List and selected products. The second row contains <div>s containing list in it. The ‘lstproducts’ list will show the Products retrieved from the server. The ‘lstselectedproducts’ will show selected products by the end-user using Drag-Drop.
Add the following styles in the View (better to use a separate stylesheet but I will keep it here for readability):
<style type="text/css">
    table, td {
        background-color:azure;
     border:double;
    }
    #dvright,#dvleft {
        background-color:azure;
       height:200px;
       width:300px;
    }
</style>

  • Step 7: In the page add the following Script:

<script type="text/javascript">
    $(document).ready(function () {
        loadProducts();
        //Function to set events for Drag-Drop
        function setEvents() {
            var lstProducts = $('li');
            //Set Drag on Each 'li' in the list
                $.each(lstProducts, function (idx, val) {
                    $('li').on('dragstart', function (evt) {
                        evt.originalEvent.dataTransfer.setData("Text", evt.target.textContent);
                        evt.target.draggable = false;
                    });
                });
            //Set the Drop on the <div>
                $("#dvright").on('drop', function (evt) {
                    evt.preventDefault();
                    var data = evt.originalEvent.dataTransfer.getData("Text");
                    var lst = $("#lstselectedproducts");
                    var li = "<li>"+data+"</li>";
                    li.textContent = data;
                    lst.append(li);
                });
 
            //The dragover
                $("#dvright").on('dragover', function (evt) {
                    evt.preventDefault();
                });
        }
        ///Function to load products using call to WEB API
        function loadProducts() {
            var items="";
            $.ajax({
                url: "/Products",
                type: "GET"
            }).done(function (resp) {
                $.each(resp, function (idx, val) {
                    items += "<li draggable='true'>" + val.ProductName + "</li>";
                });
                $("#lstproducts").html(items);
                setEvents();
            }).error(function (err) {
                alert("Error! " + err.status);
            });
        }
    });
</script>

The script has the following specifications:

  • The function ‘loadProducts()’ makes an ajax call to WEB API. When the call is successful, the iteration is done through the response. This iteration adds the <li> tag in the ‘lstproducts’ list with the draggable attribute set to true.
  • The function ‘setEvents()’ performs the following two step operations:
  • subscribe to the ‘dragstart’ event for each <li> and set the data transfer with the ‘Text’ property. This is the text content of the <li> selected. Once any <li> is dragged, the drag on the same is disabled using evt.target.draggable =false; statement.
  • The <div> of id ‘dvright’ is subscribed to ‘drop’ event, it accepts the dragged Text. Once the text is accepted, it is set to the <li> which is dynamically appended in the list with id as ‘lstselectedproducts’.
  • Step 8: Run the application, the Products data gets loaded:

    Drag the Product from the ‘Product List’ and drop it in the ‘Selected Products’ as seen here:

    • The above Red Mark shows the Drag Action. Once the drop operation is over the result will be as seen here:

Conclusion:

The HTML 5 Native support for Drag-Drop provides an easy mechanism of handling Data as well as UI operations. Since the support is native to HTML 5, no additional library is required.



ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Implement a Simple Captcha in C# .NET

clock December 1, 2014 06:07 by author Mark

Implement a simple captcha in C# .NET

  • Create a page with name “Captcha.aspx
  • Place the following html code in body part of the page

IMG height="30" alt="" src=BuildCaptcha.aspx width="80">
asp:TextBox runat="Server" ID="txtCaptcha">
    <asp:Button runat="Server" ID="btnSubmit"
     OnClick="btnSubmit_Click"
       Text="Submit" />
     On “btnSubmit_Click” place the following code
         if (Page.IsValid && (txtCaptcha.Text.ToString() ==
         Session["RandomStr"].ToString()))
           {
             Response.Write("Code verification Successful");
           }
    else
{
  Response.Write( "Please enter info correctly");
}

  • Include the following code in “BuildCaptcha.aspx"

Bitmap objBMP = new Bitmap(60, 20);
Graphics objGraphics = Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Wheat);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
  //' Configure font to use for text
      Font objFont = new Font("Arial", 8, FontStyle.Italic);
      string randomStr = "";
      char[] myArray = new char[5];
      int x;
   //That is to create the random # and add it to our string
     Random autoRand = new Random();
     for (x = 0; x < 5; x++)
{
  myArray[x] = System.Convert.ToChar(autoRand.Next(65,90));
  randomStr += (myArray[x].ToString());
}
     //This is to add the string to session, to be compared later
       Session.Add("RandomStr", randomStr);
    //' Write out the text
       objGraphics.DrawString(randomStr, objFont, Brushes.Red, 3, 3);
    //' Set the content type and return the image
  Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();

There you go you can test the page with captcha. Happy Programming Laughing



ASP.NET MVC Hosting - ASPHostPortal.com :: How to Structure The Application in ASP.NET MVC Areas

clock November 25, 2014 05:11 by author Ben

This week I discovered a difficulty related to structuring an ASP.NET MVC web applications one advancement crew was dealing with. The things they have been trying to do was quite straightforward: to create a folder framework each having their particular subfolders for View/Controller/Scripts/CSS and so on. The appliance assets like JS/CSS etc. were not getting rendered properly. The difficulty was owing to NET.config file lying underneath the subfolder, which when moved to the Views folder below that subfolder things went good. The purpose of this post just isn't to debate regarding the specifics of that difficulty and it is solution.But to discuss regarding how we will very easily framework our ASP.NET MVC Web application as per distinct modules, which is an clear need for just about any big application.


ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions operates good to get a smaller sized software. But for relatively bigger a single there is a necessity to customise.The framework also offers adequate provisions for the same.You'll be able to have your personal controller manufacturing facility to get custom methods to making the controller classes and custom see engine for finding the rendering the sights. But when the necessity would be to structure the applying to distinct subfolders as per modules or subsites I believe using “Area” in ASP.NET MVC will likely be useful to make a streamlined software.

You can add a area to some ASP.NET MVC undertaking in Visual Studio as shown beneath.

Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.

The code (auto generated) for the SalesAreaRegistration class is shown below:

public class SalesAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Sales";
        }
    }
 
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Sales_default",
            "Sales/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

System.Web.Mvc.AreaRegistration may be the summary base class use registering the places to the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) must be overriden to sign up the realm by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the mandatory information (like Routes) required to sign-up the area.

In Global.asax.cs Application_Start occasion we must RegisterAllAreas() technique as demonstrated under:

AreaRegistration.RegisterAllAreas();

The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.

I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults
                new String[] { "AreasDemo.Controllers" }
            );
}

Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

<li>@Html.ActionLink("Sales", "Index", "Home", new { area="Sales"},null)</li>

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);



ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Export Data from SQL Server to Excel in ASP.net using c#

clock November 24, 2014 06:26 by author Mark

Introduction:

Here I will explain how to export data from sql server to excel in asp.net using c# or export data from sql server database to excel in asp.net using c#.

Description:

Now I will explain to you, how to export data from sql server to excel in asp.net using c#.
Before implement this example first design one table UserInformation in your database as shown below
Once table created in database enter some dummy data to test application after that write the following code in your aspx page

Column Name

Data Type

Allow Nulls

UserId

int

Yes

UserName

varchar(50)

Yes

Location

varchar(50)

Yes

<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <title>Export data from sql server database to excel in asp.net using c#</title>
  </head>
      <body>
      <form id="form1" runat="server">
         <div>
            <asp:Button ID="btnExport" Text="Export Data" runat="server" onclick="btnExport_Click" />
         </div>
       </form>

      </body>
</html>

Now open code behind file and write the following code :  

using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
        Response.ContentType = "application/ms-excel";
        DataTable dt = GetDatafromDatabase();
        string str = string.Empty;
        foreach (DataColumn dtcol in dt.Columns)
        {
            Response.Write(str + dtcol.ColumnName);
            str = "\t";
        }
        Response.Write("\n");
        foreach (DataRow dr in dt.Rows)
        {
            str = "";
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                Response.Write(str + Convert.ToString(dr[j]));
                str = "\t";
            }
            Response.Write("\n");
        }
        Response.End();
    }
    protected DataTable GetDatafromDatabase()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Select TOP 10 UserName,LastName,Location FROM UserInformation", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            con.Close();
        }
        return dt;
    }
}

VB.NET
Imports System.Data
Imports System.Data.SqlClient
Partial Class VBCode
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    End Sub
    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
        Response.ClearContent()
        Response.Buffer = True
        Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "Customers.xls"))
        Response.ContentType = "application/ms-excel"
        Dim dt As DataTable = GetDatafromDatabase()
        Dim str As String = String.Empty
        For Each dtcol As DataColumn In dt.Columns
            Response.Write(str + dtcol.ColumnName)
            str = vbTab
        Next
        Response.Write(vbLf)
        For Each dr As DataRow In dt.Rows
            str = ""
            For j As Integer = 0 To dt.Columns.Count - 1
                Response.Write(str & Convert.ToString(dr(j)))
                str = vbTab
            Next
            Response.Write(vbLf)
        Next
        Response.[End]()
    End Sub
    Protected Function GetDatafromDatabase() As DataTable
        Dim dt As New DataTable()
        Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
            con.Open()
            Dim cmd As New SqlCommand("Select TOP 10 UserName,LastName,Location FROM UserInformation", con)
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            con.Close()
        End Using
        Return dt
    End Function
End Class



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