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

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

Press Release - ASPHostPortal.com Proudly Launches osCommerce 3.0.2 Hosting

clock January 30, 2014 10:06 by author Mike

ASPHostPortal.com is a premiere web hosting company that specializes in Windows and ASP.NET-based hosting with innovative technology  solutions, proudly announced the best osCommerce 3.0.2 hosting service with a combination of affordable price, high customer  satisfaction rate and commendable quality in all ASP.NET and Windows web hosting plans.

osCommerce 3.0.2 are made to showcase the new features being worked on and to generalize a version specific for testing to help fix  and improve subsequent alpha releases for a final, stable, secure, and production ready 3.0.2 releases. The osCommerce solution offers  great flexibility and empowers even amateur webmasters to develop highly competitive ecommerce websites.

Until recently, the cost involved in hiring a web development company to develop a similar ecommerce web site was prohibiting several  small businesses from selling on-line. The osCommerce solution is one of the best fruits of the open source community and which poses  a serious challenge to other similar commercial software products.


Installation for this software can be performed easily from within the web hosting control panel, even by customers with poor  programming experience. The installation process takes up to a minute to perform, thus enabling customers to deploy an entire  ecommerce storefront for their business within a few clicks of the mouse.

ASPHostPortal.com
is the among the few top web hosting company that tested and offer ASP.NET hosting plan that compliance with  osCommerce 3.0.2 hosting. There are several companies out there that offer e-Commerce hosting plan but at ASPHostPortal.com, we provide quality e-Commerce  hosting plan at affordable prices that will not only keep your operating costs low but also help you to maximize your profits.

ASPHostPortal.com
development teams have fully tested and deployed the latest osCommerce 3.0.2 in hosting control panel systems.  Clients can install and use osCommerce 3.0.2 hosting with few clicks of installation steps. For more information about this topics or  have any enquiries related to osCommerce hosting, please visit http://www.asphostportal.com/osCommerce-Hosting.

About the Company
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.



ASP.NET MVC 5.1 Hosting :: ASPHostPortal.com Proudly Launches ASP.NET MVC 5.1 Hosting

clock January 28, 2014 07:48 by author Ben

ASPHostPortal.com officially launches ASP.NET MVC 5.1  hosting at affordable prices. Instant Setup, Fast and Friendly Support!

ASPHostPortal.com, a leading innovator in Windows Hosting, announces the launch of ASP.NET MVC 5.1 Hosting. The ASP.NET MVC 5.1 Framework is the latest evolution of Microsoft’s ASP.NET web platform. It provides a high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility, combined with all the benefits of ASP.NET.

ASP.NET MVC 5.1 contains a number of advances over previous versions, including the ability to define routes using C# attributes and the ability to override filters,Enum support in Views, Support for current Context in Unobtrusive Ajax, Filter Overrides and etc. The user experience of building MVC applications has also been substantially improved.

The company believes in providing top-notch service at affordable price. They offer ASP.NET MVC 5.1 hosting with the following features such as Unlimited Domain, Unlimited Subdomain, 5 GB Disk Space, 2 SQL Database and Unlimited Email Account.
 
“Our customers have been asking us about MVC 5.1 and we are happy to deliver a hosting platform that supports all the latest in the Microsoft Web Stack.” said said Dean Thomas, Manager at ASPHostPortal.com.  "And it proves that we remain at the forefront in Microsoft technology".

Where to look for the best ASP.NET MVC 5.1 hosting service? How to know more about the different types of hosting services? Read more about it on http://www.asphostportal.com.


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.



ASPHostPortal.com Proudly Launches nopCommerce 3.2 Hosting

clock January 23, 2014 10:36 by author Mike

ASPHostPortal.com is a premiere web hosting company that specializes in Windows and ASP.NET-based hosting with innovative technology  solutions, proudly announced the best nopCommerce 3.2 hosting service with a combination of affordable price, high customer  satisfaction rate and commendable quality.

nopCommerce is an open source e-commerce solution that contains both a catalog frontend and an administration tool backend.  nopCommerce is a fully customizable shopping cart. It's stable and highly usable. From downloads to documentation, nopCommerce.com  offers a comprehensive base of information, resources, and support to the nopCommerce community. The latest version of nopCommerce is  3.2 with lots of awesome features.

The first feature that will grab the attention of every nopCommerce store owner is the new Facebook Shop. The next major functionality  that comes with nopCommerce 3.20 is its support for warehouses. What this means is that you can configure individual products to be  shipped from a specific location (warehouse). You can also configure the system to use the warehouse location when calculating the  shipping cost for the product. While we are on the nopCommerce 3.20 shipping functionality, there is another new feature worth  mentioning. Now the store owner can specify when a product will be shipped. In nopCommerce this information is referred to as delivery  date. This is useful for example when you are selling products, which are manufactured on demand.

Nopcommerce 3.2 is simply the best and most powerful open source shopping cart on the planet. It is the only open source shopping  cart application that supports both multi-sites and multi-vendors. NopCommerce is fast, easy, and fun. I definitely recommend  NopCommerce to anyone who wants to start an online business.


ASPHostPortal.com
is a popular online nopCommerce 3.2 hosting service provider with all of its hosting plans to help users to automate  and simplify website and server administration tasks such as installation and migration. There are several companies out there that offer e-Commerce hosting plan but at ASPHostPortal.com provide quality e-Commerce  hosting plan at affordable prices that will not only keep your operating costs low but also help you to maximize your profits.

nopCommerce is ASP.NET 4.0 based supporting MS SQL databases. It features an embedded graphic installer, so nopCommerce can be setup  in few minutes and run immediately. For more information about this topics or have any enquiries related to nopCommerce hosting,  please visit http://www.asphostportal.com/nopCommerce-Hosting.

About the Company
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.



.NET 4.5.1 Hosting - ASPHostPortal.com :: How to Publish ASP.NET Site in IIS 7 on Localhost

clock January 23, 2014 05:03 by author Ben

IIS (Internet Information Services) is a secure, reliable, and scalable Web server that provides an easy to manage platform for developing and hosting Web applications and services. In this tutorial I have explained all the setting to run the site successfully from IIS on local computer. Let's move to the procedure of deploying website.

Step 1: Run IIS by typing the command in inetmgr in windows command prompt

Step 2: In IIS right click on Sites Node and then Select Add Web Site as shown in the diagram below:


Step 3: Inside Add Website Window type the name of website under Site name and in Physical path select the location of the website on the local system.



Step 4: Select the site to be added in this project I have created website with the name Demo in .net and stored it on F drive of my computer. I am browsing that website for deployment . You can select your site to be added in IIS as shown in the diagram below:



Step 5: Under Binding change the port Number from 80 as it is the default port and assigned to Default website in IIS . I have set the port number to 8085.



Step 6: Next select the Application Pools in the left side in IIS then Right click on the Name of website added in the previous step and then select Advanced Settings



Step 7: In the Advanced Settings select the .Net Framework Version 4.0 and then click on ok button.

Step 8: Select the website and then double Click on Directory Browsing and Enable it.



Step 9: Now the whole procedure of adding website is done now to check the site in browser Right click on the website you added in IIS then go to Manage Web Site and then click on Browse.



ASP.NET MVC 5 Hosting :: Customizing ASP.NET MVC 5/Web API 2 Scaffolding Templates in Visual Studio 2013

clock January 20, 2014 17:25 by author Mike

In this article, I showed you how you can easily customize the default code generation(scaffolding) templates in ASP.NET MVC 5 and ASP.NET Web API 2 using Visual Studio 2013.

Scaffolding in ASP.NET allows you to automatically generate code in web application. This make it easy to quickly add boilerplate code in your application. There is a nice introduction of scaffolding in ASP.NET application using Visual Studio 2013 at here. The default templates are good for a lot of cases, but sometimes you want to customize these scaffolding templates for all your applications and sometimes you need to use different scaffolding templates in different projects. In this article, I will show you how to customize the default scaffolding t4 templates in ASP.NET MVC 5 and ASP.NET Web API 2 globally and per project.

Description:

If you need to customize the scaffold templates globally then just navigate to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates(depending upon where Visual studio reside),

In the above explorer, you can globally update the t4 templates of ASP.NET MVC 5 and ASP.NET Web API 2.

Now for per project base, just create a CodeTemplates folder in your application root and paste the above folders inside CodeTemplates folder,

Hopefully this article useful for someone.



Press Release - ASPHostPortal.com Proudly Launches DotNetNuke (DNN) 7.2 Hosting

clock January 16, 2014 06:08 by author Mike

ASPHostPortal.com is a premiere web hosting company that specializes in Windows and ASP.NET-based  hosting with innovative technology solutions, proudly announced the best DotNetNuke (DNN) 7.2 hosting  service with a combination of affordable price, high customer satisfaction rate and commendable quality.


DotNetNuke is an open source web content management system that is built on ASP.net infrastructure and  solely has its life wire running smoothly on Microsoft platform. Furthermore, it is an open source web  content management system that started in the year 2002 by a team of developers which was headed by the  original creator Shaun Walker who happens to have bagged his certification as a certified Microsoft Most  Valuable Professional in the year 2004 and the latest version is 7.2 with lots of awesome features.

DotNetNuke (DNN) 7.2 includes a number of new features and enhancements that will benefit users and  developers alike along with a large number of bug fixes. DNN 7.2 version incorporates some of the  interesting features to elevate the existing functionality and make your site administration process a  lot easier. DNN 7.2 also allows you to install JavaScript libraries as first party extensions. Once  installed your module or skin can request that JavaScript library and the platform will automatically  add the library into the page. The API mirrors the one used for jQuery and JQuery UI making it very easy  to use.

Some benefits that the DotNetNuke content management system includes are greater site consistency,  improved site navigation, streamlined authoring process, faster turnaround time for new pages and  changes, increased site flexibility, support for decentralised authoring, increased security, reduced  duplication of information, greater capacity for growth, and reduced site maintenance costs. DotNetNuke is the best CMS (content management system) for businesses and  is easier to create and manage with ASPHostPortal.com.

ASPHostPortal.com is a popular online DotNetNuke (DNN) 7.2 hosting service provider with all of its  hosting plans to help users to automate and simplify website and server administration tasks such as  installation and migration. For more information about this topics or have any enquiries related to DotNetNuke (DNN) 7.2 hosting,  please visit http://www.asphostportal.com/DotNetNuke-Hosting

About the Company
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.



ASP.NET MVC 5 Hosting - ASPHostPortal.com :: How to create Default User Roles in ASP.NET MVC 5

clock January 15, 2014 07:02 by author Ben

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more.

In this article, We'll look into how to create default user roles in ASP.NET MVC 5. Let's begin by establishing where the user role is assigned, and that is the registration stage. In the default template, you have the AccountController that contains a Register action. The default implementation looks like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}


What's missing here is the role assignment, so let's add that. Right after the CreateUserAndAccount call, we can check whether a specific role exists, and if it is - add the registered user to it. In case the role is new, create it.

if (!Roles.RoleExists("Standard"))
    Roles.CreateRole("Standard");
Roles.AddUserToRole(model.UserName, "Standard");


Here I am working with a role called Standard, but obviously you can use another identifier for it. If you open the database that is carrying the app data, you will notice that there are two new tables introduced in the existing context - Roles and UsersInRoles.

As the data skeleton is established, you can now limit content access based on roles. In views, you could use the Authorize attribute:

[Authorize(Roles = "Admin")]

Or you could check for the role directly:


@if (Roles.GetRolesForUser().Contains("Admin"))
{
}

That's the tutorial How to create Default User Roles in ASP.NET MVC 5, for more information about ASP.NET MVC 5 Hosting please feel free to visit 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, .NET 4.5.1/ASP.NET 4.5, ASP.NET MVC 5.0/4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information.

 



ASP.NET 4.5.1 Hosting - ASPHostPortal.com :: How to Create a Sign Up/Registration Page in ASP.NET

clock January 10, 2014 07:17 by author Ben

Here is the simple step to create a sign up/registration page in ASP.NET. Lets check this out :
1. Open the Microsoft Visual Studio
2. Select one New Asp.Net Web application
3. Open the Design Default.aspx page
4. Drag and Drop one DropDown list and button from the Tool box.
5. Add one new item( i.e., New Registration Page) for the Drop down list
6. Procedure for adding items : Right click on the DropDown List and select properties and select items and add NewRegistration in Text Field.
7. Change the properties of the Dropdown list
a.Kept AutopostBack = True;
b.select the SelectedIndexChanged Event for that..
8. Open the code page that is Default.aspx.cs and and create a method in SelectedIndexChanged event of dropdownlist

using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
using System.Data.SqlClient; 
 
public partial class Dynamic_controls : System.Web.UI.Page 

    SqlConnection con; 
    SqlCommand com; 
  protected void Page_Load(object sender, EventArgs e) 
    {        
        
    } 
protected void ddlist_SelectedIndexChanged(object sender, EventArgs e) 
    { 
        Createnewaccount();  
    } 

9. Create new methods for Different controls by using the main method(i.e., Createnewaccount)

private void Createnewaccount ()
         {
             CreateDynamicTextBoxes ();
             CreateDynamicTextBoxes1 ();
             CreateDynamicCheckBoxes ();
             CreateDynamicCheckBoxes1 ();
             CreateDynamicRadioButtons1 ();
             BindDropDownLists ();
         }

10. Create all types of dynamic controls

 protected void CreateDynamicTextBoxes ( )
        {
           
            int c = 1 ;
            TextBox [ ] textBoxArr = new TextBox [ c ] ;/ / array of textboxes
            for (int i = 0 ; i < c ; i + + )
            {
                 
                textBoxArr [ i ] = new TextBox ( ) ;
                textBoxArr [ i ] . ID = " txtBox " + i.ToString ( ) ;
                PH_Name.Controls.Add ( textBoxArr [ i ] ) ;
                RequiredFieldValidator reqfldVal = new RequiredFieldValidator ( ) ;
                reqfldVal.ID = " RequiredValidator " + i ;
                reqfldVal.ControlToValidate = " txtBox " + i ;
                reqfldVal.ErrorMessage = " Not Empty " ;
                reqfldVal.SetFocusOnError = true ;
                PH_Name.Controls.Add ( reqfldVal ) ;
            }
        }
        protected void CreateDynamicTextBoxes1 ( )
        {
            int c = 1 ;
            TextBox [ ] textBoxArr1 = new TextBox [ c ] ;/ / array of textboxes
            for (int i = 0 ; i < c ; i + + )
            {
      
                textBoxArr1 [ i ] = new TextBox ( ) ;
                textBoxArr1 [ i ] . ID = " txtBox1 " + i.ToString ( ) ;
                PH_pwd.Controls.Add ( textBoxArr1 [ i ] ) ;
                RequiredFieldValidator reqfldVal1 = new RequiredFieldValidator ( ) ;
                reqfldVal1.ID = " RequiredValidator1 " + i ;
                reqfldVal1.ControlToValidate = " txtBox1 " + i ;
                reqfldVal1.ErrorMessage = " Not Empty " ;
                reqfldVal1.SetFocusOnError = true ;
                PH_pwd.Controls.Add ( reqfldVal1 ) ;
                 
            }
        }
        private void BindDropDownLists ( )
        {
            SqlDataSource sqlDS = new SqlDataSource ( ) ;
            sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings [ " SAMPLE_2 " ] . ToString ( ) ;
            sqlDS.SelectCommand = " Select CountryID , COUNTRY_NAME from countrynames " ;
            PH_country.Controls.Add ( sqlDS ) ;
            DropDownList ddl = new DropDownList ( ) ;
            ddl.ID = " ddlrank " ;
            ddl.DataSource = sqlDS ;
            ddl.DataTextField = " COUNTRY_NAME " ;
            ddl.DataValueField = " CountryID " ;
            PH_country.Controls.Add ( ddI ) ;
            foreach ( Control ctl in PH_country.Controls )
            {
                if ( ctl is DropDownList )
                {
                    ( ctl as DropDownList ) . DataBind ( ) ;
                }
            }
        }
        protected void CreateDynamicCheckBoxes ( )
        {
                   
                CheckBox chk ;
                chk = new CheckBox ( ) ;
                chk.ID = " chkhobbies " ;
                chk.Text = " savings " ;
                chk.AutoPostBack = false ;
                PH_trans.Controls.Add ( chk ) ;
             
        }
        protected void CreateDynamicCheckBoxes1 ( )
        {
           
            int c = 1 ;
            CheckBox [ ] chk = new CheckBox [ c ] ;
            for (int i = 0 ; i < c ; i + + )
            {
                chk [ i ] = new CheckBox ( ) ;
                chk [ i ] . ID = " chkhobbies1 " + i.ToString ( ) ;
                chk [ i ] . Text = " Current" ;
                chk [ i ] . AutoPostBack = false ;
                PH_trans.Controls.Add ( chk [ i ] ) ;
            }
        }
        protected void CreateDynamicRadioButtons ( )
        {
                Male = new RadioButton RadioButton ( ) ;
                Female = new RadioButton RadioButton ( ) ;
                male = new RadioButton ( ) ;
                female = new RadioButton ( ) ;
                male.Text = " Male " ;
                female.Text = " Female " ;
                male.Checked = false ;
                female.Checked = false ;
                male.GroupName = " unknown " ;
                female.GroupName = " unknown " ;
                male.ID = " malegender " ;
                female.ID = " unknown " ;
                male.AutoPostBack = false ;
                female.AutoPostBack = false ;
                PH_gender.Controls.Add ( male ) ;
                PH_gender.Controls.Add (female ) ;
        }
        protected void CreateDynamicRadioButtons1 ( )
        {
            RadioButtonList radio = new RadioButtonList ( ) ;
            radio.ID = " rblRow " ;
            radio.Items.Add ( new ListItem ( " Male " ) ) ;
            radio.Items.Add ( new ListItem ( " Female " ) ) ;
            PH_gender.Controls.Add ( radio ) ;
             
        }
        protected void CreateDynamicPanel ( )
        {
           
            int c = 1 ;
            TextPanel panel = new Panel ( ) ;
            for (int i = 0 ; i < c ; i + + )
            {
                TextPanel.ID = " txtPanel " + i.ToString ( ) ;
                PlaceHolder1.Controls.Add ( TextPanel ) ;
            }
        }

11. Add the following code to store the data in database

protected void btn_submit_Click ( object sender , EventArgs e )
        {
            for (int i = 0 ; i < 1 ; i + + )
            {
                 
                txtvalue string = " txtBox " + i.ToString ( ) ;
                txtvalue1 string = " txtBox1 " + i.ToString ( ) ;
                ddlvalue string = " ddlrank " ;
                chkvalue string = " chkhobbies " ;
                chkvalue1 string = " chkhobbies1 " + i.ToString ( ) ;
                rbvalue string = " rblRow " ;
                 
                TextBox txt = ( TextBox ) PlaceHolder1.FindControl ( txtvalue ) ;
                TextBox txt1 = ( TextBox ) PlaceHolder1.FindControl ( txtvalue1 ) ;
                DropDownList Dddl = ( DropDownList ) PlaceHolder1.FindControl ( ddlvalue ) ;
                CheckBox Dchk = ( CheckBox ) PlaceHolder1.FindControl ( chkvalue ) ;
                CheckBox Dchk1 = ( CheckBox ) PlaceHolder1.FindControl ( chkvalue1 ) ;
                RadioButtonList Drd = ( RadioButtonList ) PlaceHolder1.FindControl ( rbvalue ) ;
                if ( txt ! = null )
                {
                    try
                    {
                        string strText = txt.Text ;
                        strText1 string = txt1.Text ;
                        strddl string = Dddl.SelectedItem.Text ;
                        strchk string = Dchk.Text ;
                        strchk1 string = Dchk1.Text ;
                        strrdb string = Drd.Text ;
                        / / Store value in database textbox Cell
                        con = new SqlConnection ( ConfigurationManager.ConnectionStrings [ " SAMPLE_2 " ] . ToString ( ) ) ;
                        con.Open ( ) ;
                        com = new SqlCommand ( " insert into Dynamic_Form ( UserName , LastName , DropdownlistValue , Chksavings , Chkcurrent , Radiovalue ) values ​​( ' " + strText + " ' , ' " + strText1 + " ' , ' " + strddl + " ' , ' " strchk + + " ' , ' " + strchk1 + " ' , ' " + strrdb + " ' ) " , con ) ;
                        com.ExecuteNonQuery ( ) ;
                        con.Close ( ) ;
                        lbl_error.Text = " Account Successfully Created " ;
                         
                    }
                    catch ( Exception ex )
                    {
                        throw ex ;
                        / / lbl_error.Text = " There is a problem while creating Account " ;
                         
                    }
                }
            }
        }

Now, run your program and see the result :



ASP.NET MVC 4.0 Hosting with ASPHostPortal :: How To Save Email from External Login in ASP.NET MVC 4.0 with SimpleMembership

clock January 9, 2014 06:16 by author Ben

ASP.NET MVC 4 web application allows users to log in from an external provider, such as Facebook, Twitter, Microsoft or Google and then integrate into your web application. Some OAuth/OpenId providers like Facebook, Google allow to access email. This article explains how to save the email in your database.

Before implementing, first lets consider following points:
1. User name is different from Email.
2. Email might be different for different providers.
3. Email is optional(some external provider like twitter doesn’t allow to access email).

 

Getting Started:
1. Create a new ASP.NET MVC 4 --> Internet Application Project
2. Open App_Start --> AuthConfig.cs, uncomment the external services which you want to use and pass proper parameters. In this article, we will use Facebook,Twitter and Google providers.

OAuthWebSecurity.RegisterTwitterClient(
        consumerKey: "xxxx",
        consumerSecret: "xxxxxxxx");
    OAuthWebSecurity.RegisterFacebookClient(
        appId: "yyyy",
        appSecret: "yyyyyyyy");
    OAuthWebSecurity.RegisterGoogleClient();


3. In Account Model, add Email property in RegisterExternalLoginModel class:

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

4. To add Email field in OAuthMembership table, add following class:

[Table("webpages_OAuthMembership")]
   public class OAuthMembership
   {
       [Key, Column(Order = 0), StringLength(30)]
       public string Provider { get; set; }
       [Key, Column(Order = 1), StringLength(100)]
       public string ProviderUserId { get; set; }
       public int UserId { get; set; }
       [StringLength(100)]
       public string Email { get; set; }
   }


5. add OAuthMembership in Userscontext

public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }
        public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<OAuthMembership> OAuthMemberships { get; set; }
    }

It will create the required structure in database when you run the application and open register page first time.

Controller Changes:
In AccountController, To set email from the external provider, replace the following lines in ExternalLoginCallback method :

// 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;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });


with the following lines:

// 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;
               var model = new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData };
               switch (result.Provider) {
                   case "facebook":
                   case "google":
                       {
                           model.Email = result.UserName;
                           model.UserName = "";
                           break;
                       }
                   case "twitter":
                       {
                           model.Email = "";
                           model.UserName = result.UserName;
                           break;
                       }
                   default:
                       break;
               }
               return View("ExternalLoginConfirmation", model);

Facebook and Google provide email as user name, so email is assigned for these providers.

In ExternalLoginConfirmation view, add following Email in form:

@Html.HiddenFor(m => m.Email)

It will post Email also when form is submitted. In ExternalLoginConfirmation method, To save email for new user,replace the following lines:

// Insert name into the profile table
            db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
            db.SaveChanges();
            OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
            OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
            return RedirectToLocal(returnUrl);

with these lines:

// Insert name into the profile table
                       user = new UserProfile { UserName = model.UserName };
                       db.UserProfiles.Add(user);
                       db.SaveChanges();
                       OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);                                           
                       if (!String.IsNullOrEmpty(model.Email)) {
                           var oauthItem = db.OAuthMemberships.FirstOrDefault(x => x.Provider == provider && x.ProviderUserId == providerUserId && x.UserId == user.UserId);
                           if (oauthItem != null) {
                               oauthItem.Email = model.Email;
                               db.SaveChanges();
                           }
                       }
                       OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
                       return RedirectToLocal(returnUrl);

This will save email in database for new user. Now if same user wants to add other external provider then in ExternalLoginCallback method, replace following line

OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);

with following lines:

OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
               if (result.Provider == "facebook" || result.Provider == "google")
               {
                   using (UsersContext db = new UsersContext())
                   {
                       UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == User.Identity.Name);                     
                       if (user != null)
                       {                         
                               var oauthItem = db.OAuthMemberships.FirstOrDefault(x => x.Provider == result.Provider && x.ProviderUserId == result.ProviderUserId && x.UserId == user.UserId);
                               if (oauthItem != null)
                               {
                                   oauthItem.Email = result.UserName;
                                   db.SaveChanges();
                               }                         
                       }
                   }
               }

That's the tutorial How To Save Email from External Login in ASP.NET MVC 4.0 with SimpleMembership. If you're looking for best Windows ASP.NET hosting, ASP.NET MVC 4.0 hosting, cloud hosting, and SharePoint hosting, please feel free to visit http://ASPHostPortal.com. Come to the website to know more details.

 



.NET Entity Framework Hosting - ASPHostPortal.com :: Using Database Migration

clock January 7, 2014 09:16 by author Mike

Entity Framework (EF) is an object-relational database mapper that enables easy database access for .NET developers using domain-specific .NET objects that EF can generate for you. As we saw in the first blog post on Entity Framework, you can use EF to create your database from the classes you have defined in your project code. You can add or remove properties from your classes and have EF migrate the changes into your database as well.

As developers, you often face projects where the specifications change over time for many reasons. Sometimes the client isn’t sure exactly what they need or their needs change during the course of the project. The design and analysis may determine that you need to add fields to the database or even remove fields from the database for one reason or another. For example, you may have new requirements to keep track of a user’s email address. Or you may need to add and track a user’s cell phone. A field/column entitled fName may even need to be renamed to firstName, or maybe you need to split a name into separate fields. There are many reasons that database fields/columns may need to change on a given project.

See the following classes:

   public class Seminar
    {
        public int SeminarId { get; set; }
        public string Name { get; set; }
        public virtual List Topics { get; set; }

    }

    public class Topic
    {
        public int TopicId { get; set; }
        public string Title { get; set; }

        public int SeminarId { get; set; }
        public virtual Seminar Seminar { get; set; }
    }

And our database looked like this:

Now, for the sake of our discussion, let’s say that we already have run our application at least once so our database has already been created, and we have decided that we want to add the keynote speaker’s name to the database. We can do that by just adding it as a property in our SeminarID class and then getting a DBA to write the necessary SQL. If you were allowed, you could write the SQL to add the field/column to the database table. That would just modify the database, however, and that is not the best approach since you may need to change it later. The best approach is to automate tracking and manage the migrations as the project grows. To do that we will use Code First Migrations.

First, you need to enable Code First Migrations using the Package Manager Console. If it isn’t already open, select Tools->Library Package Manager->Package Manager Console. Now run the command shown below. Notice that we used the Namespace of our application and the name of our DbContext class to create a fully qualified context:

Enable-Migrations -ContextTypeName SafariCodeFirst.SeminarContext

Visual Studio will process the command and you should get a result that looks something like this:

You will also get a new Migrations folder added to your project that contains two files.

Configuration.cs contains the settings that Migrations uses to do its magic work. We won’t touch it for this blog post, but in a future post we will show you how to use it to provide seed data for your database. The other file is named <timestamp>_IntialCreate.cs and contains the code shown here:

namespace SafariCodeFirst.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Seminars",
                c => new
                    {
                        SeminarId = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                    })
                .PrimaryKey(t => t.SeminarId);

            CreateTable(
                "dbo.Topics",
                c => new
                    {
                        TopicId = c.Int(nullable: false, identity: true),
                        Title = c.String(),
                        SeminarId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.TopicId)
                .ForeignKey("dbo.Seminars", t => t.SeminarId, cascadeDelete: true)
                .Index(t => t.SeminarId);

        }

        public override void Down()
        {
            DropIndex("dbo.Topics", new[] { "SeminarId" });
            DropForeignKey("dbo.Topics", "SeminarId", "dbo.Seminars");
            DropTable("dbo.Topics");
            DropTable("dbo.Seminars");
        }
    }
}

Closer examination shows that it contains the code to take you from an empty database to one that contains the tables for the Seminar and Topic classes defined in our code.

Now that we have enabled Migrations and the basics are all in place, let’s modify our Seminar class to add a key note speaker so that our Seminar class now looks like this:

   public class Seminar
    {
        public int SeminarId { get; set; }
        public string Name { get; set; }
        public string Speaker { get; set; }
        public virtual List<Topic> Topics { get; set; }

    }

Next, we need to run migrations again using the command Add-Migration AddSpeaker. You can give this any name you want, but it is good to make it descriptive of the changes. Add-Migration will check for changes between the model classes and the last migration that was run, createing a new migration. You will notice that it is called <timestamp>_AddSpeaker.cs, and it has been added to the Migrations folder in our project. The timestamp part of the name is what Migrations uses to keep changes in order to track which changes have been applied. Now we need to run Update-Database so that any pending changes get applied to the database. I like to use the –Verbose switch so that I can see what is going on.

Now if you refresh the database in Server Explorer you will see that your changes have taken place and the new field/column have been added to the Seminars table.

We can go on and on like this, adding and dropping properties from our model classes and running the Add-Migration and Update-Database commands, as our database changes over the life cycle of our application. We still need to manually add code to the application to collect the user’s input or display the data to the user, but as you have seen, all of the hard work in our project has been taken care of for us by the Entity Framework and Code First Migrations.



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