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

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

ASP.NET Hosting - ASPHostPortal.com :: Protect Web Pages Using .htaccess Files

clock January 8, 2017 13:47 by author Armend

A .htaccess file (pronounced ‘dot aitch tee access’ or simply ‘aitch tee access’) is aspecial configuration file used on web servers running the Apache httpd web server software. When someone visits a page that is sitting in a directory alongside, or in the same branch as, a .htaccess file then that configuration file will be loaded by the server and processed.

.htaccess files are used to reconfigure the web server without needing to restart it. These files can be used to enable or disable additional functionality and features, such as creating redirects, disabling directory listings and password protecting directories.

If you want to password protect some of your web pages, then you need to use a .htaccess file with a .htpasswd password file. This tutorial will tell you step-by-step what you need to do.


Step By Step Instructions
Let's suppose you want to restrict files in a directory called members to username memberone with password memberonepassword. Here's what to do:
1. Create a file called .htaccess in directory members that looks like this:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd
require valid-user


Notes
:

  • In the AuthUserFile line, replace USERNAME with your ftp username.
  • The .htaccess file must be an ASCII text document.
  • A .htaccess file can be created in any word processor but must be saved as text only.
  • IF you upload your .htaccess file via FTP, the FTP client must be set to ASCII mode for transfer.
  • For security reasons, the .htaccess file on the server cannot be seen in a directory listing. If you don't see it after uploading it, don't worry.
    Also note that AuthName can be anything you want. The AuthName field gives the Realm name for which the protection is provided. This name is usually given when a browser prompts for a password, and is also usually used by a browser in correlation with the URL to save the password information you enter so that it can authenticate automatically on the next challenge.

2. Use the htpasswd command, from your home directory, to create a password file called .htpasswd in your home directory:
SSH to your home directory. This is simply done by connecting with your SSH client and NOT entering any path, and NOT changing directories after connecting. After connecting to your home directory via SSH, enter:

# htpasswd -c .htpasswd memberone

Type the password -- memberonepassword -- twice as instructed.
3. That's the setup done. Now test by trying to access a file in the directory members; your browser should demand a username and password, and not give you access to the file if you don't enter memberone and memberonepassword.


Multiple Usernames/Passwords

If you want to give access to a directory to more than one username/password pair, follow the steps above to create the .htaccess file and to create the .htpasswd file with one user. Then, add additional users to the .htpasswd file by using the htpasswd command without the -c:

# htpasswd .htpasswd membertwo
New password:
Re-type new password:
Adding password for user membertwo


Changing Passwords

If you want to change the password for an existing user, simply issue the same command as when you added the user. You will then be prompted for a new password. For example, if the user membertwo already exists and you want to change the password, just SSH to your home directory and enter:

# htpasswd .htpasswd membertwo


Password Protecting Multiple Directories
If you want to password protect multiple directories, and allow all users access to all password protected directories, then all you need to do is put the same .htaccess file in each directory that you want to password protect.

However, if you want to password protect multiple directories, and only allow certain users access to each directory, then you can create a different password file (all in your home directory) for each password protected directory.

Let's say you have 3 different directories (members, admins, board) you want password protected, and each one has a different set of users that you want to allow access. Then just do the following:

Create three .htaccess files and put them in their appropriate directory:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.members
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.admins
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.board
require valid-user

Remember to replace USERNAME with your ftp username (in lower case).

Create three .htpasswd files in your home directory:

# htpasswd -c .htpasswd.members memberone
# htpasswd -c .htpasswd.admins adminone
# htpasswd -c .htpasswd.board boardmemberone

That's it. Now when you need to add a user to one of the directories, just issue the htpasswd command on the appropriate .htpasswd 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 :: Tips Create User Roles in ASP.NET MVC

clock December 20, 2016 04:54 by author Armend

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"))
{
}

 

Best ASP.NET MVC 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 :: 7 Tips for Developing a Secure ASP.NET Web Application

clock December 13, 2016 04:52 by author Armend

7 Tips for Developing a Secure ASP.NET Web Application

As the usage of the internet and the number of web applications over the internet have gone exponentially high there are bad people who continuously work around the clock to hack them. It may be for personal gain or just as an amateur act. Despite the intention of the bad guy the damage caused to the organization hosting the site or its users should be taken into account. As a professional web application developer it is a must to be aware of the best practices to follow in order to make the application more secure. In this article I will be listing and explaining my top 7 tips for developing a secure asp.net application.

Don’t Let Your Users be Victims of Click Jacking

Have you ever thought about someone framing your website onto theirs, making your users to be the victims of click jacking? Yes, the attackers can load your website onto their site in an iframe. They can then skillfully place their transparent controls over your website and fetch the PII information, user credentials, make them perform an unwanted task like exposing their financial information, etc.
In order to prevent that you will have to use a frame busting technique. The following script will not allow your website to be iframed. This can be placed in your master pages.

  •     <script type="text/javascript" language="javascript">
  •         //Check if the top location is same as the current location
  •         if (top.location.hostname != self.location.hostname) {
  •             //If not then set the top to you current
  •             top.location.href = self.location.href;
  •         }
  •     </script>
  • In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
    The header should be added in the global.asax application start event.

    1. protected void Application_Start(object sender, EventArgs e)
    2. {
    3.             HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    4. }
    5.  

     

    In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
    The header should be added in the global.asax application start event.

    1. protected void Application_Start(object sender, EventArgs e)
    2. {
    3.             HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    4. }
    5.  

     

    White List the Request URL

    Though we have many techniques to perform the security preventions inside the application it is most important to prevent the bad data from being entered into your website at the first place. Most attacks happen through the query string values passed through the URL. It is a best security practice to define a common place like an HttpModule to white list the URL, i.e. sanitize the entire URL with a set of white listed characters and drop all the bad ones. It means you will not encourage any other characters apart from a white listed set defined in your application.
    It is important for you to know that black listing is not a foolproof mechanism and it can be broken by the hackers easily.

    Practice of Encoding the Data

    While processing and sending, the data in the response that is fetched from outside the trust boundary should always be encoded. The type of encoding may differ based on the usage of the non-trusted data. For example perform an HtmlEncode for the data that is sent to the client page.

    Label1.Text = Server.HtmlEncode(Request.QueryString["BadValue"]);

     

    Encoding the data will make the XSS scripts inactive and prevent them from being executed. Microsoft has provided the AntiXss library, which provides more sophisticated encoding methods including the JavascriptEncode.

    Using Cookies

    As a web developer you should take utmost care while using cookies, which may open a back door for the hackers to get into your applications. Following are the best practices while using a cookie to store information.
    1. Is your website is hosted under SSL? Then be sure to mark your cookies as secure. This will make them available only in the SSL transmissions.

    1. HttpCookie cookie = new HttpCookie("MySecureCookie");
    2. cookie.Value = "This is a PII information";
    3. cookie.Secure = true;

     

    If your website is not SSL enabled then always encrypt the values using a strong encryption mechanism like AES 256 and then store them in the cookies.

    Secure the Service Calls (WCF / Web Service)

    Are you exposing WCF services through basicHttpBinding? Then think again because the messages transmitted over will be plain text and any intruder will be able to trap the requests and even simulate them easily. Use wsHttpBinding, which will transport the messages in an encrypted format, which makes the life of the intruder hard.
    Though you make lots of protections for your WCF or web services it is a best practice to host the services under an SSL layer.
    Never Deploy the Application with debug=”true”
    It is strongly recommended not to deploy your applications in the production environment with compilation debug=”true” in your web.config. This will result in a big nightmare for performance and security of the application.
    This may leak too much information for the attackers, for example the stack trace in the event of an unhandled exception and the debug trace information. Such exposure of the internals will be good bucks for the attackers.

  • <system.web>
  •         <compilation debug="false" targetFramework="4.0" />
  •     </system.web>
  • Thinking About Turning Off ViewStateMAC?

    Turning off ViewStateMAC will create a security loophole in your asp.net application if you are using Viewstate on your web pages. The intruders will easily be able to intercept, read the 64 bit encoded values and modify them to do some bad things to your website. Having it turned on ensures that the viewstate values are not only encoded but also a cryptographic hash is performed using a secret key.

    1. <pages enableViewStateMac="true"></pages>

     

    I hope this article is useful for the developers who thrive at making their asp.net application an absolutely impossible place for the hackers to deal with.

    Happy reading!

    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 :: Repair Dropdown Boxes in ASP.NET Datagrids

    clock December 6, 2016 07:43 by author Armend

    Introduction

    Today, I will explain Step by Step to Repair Dropdown Boxes in ASP.NET Datagrids. Alright, this issue isn't silverlight, yet I did experience it in my day work. Truth be told, I've experienced it a few times, so I thought I would compose it up so I can discover it once more.

     

    Error

    You compose a page that contains an updatable datagrid, which, when in Editmode, contains a dropdown rundown containing lookup things. The Dropdownbox does not populate, and (later when you get it working) the correct listitem is not chosen.

    Cause

    Since the Dropdownbox down not existing when the page loads, there is nothing to tie.

    Step by Step

    You need to append your occasions to some non-standard page occasions to get it to work. The pertinent piece of the .aspx page is underneath (placed this in your datagrid)

    <asp:TemplateColumn HeaderText=”Tactic Category”>

    <HeaderStyle Font-Size=”Large” Font-Bold=”true” />
    <ItemTemplate>
    <%#DataBinder.Eval(Container.DataItem,”TacticCatName”)%>
    </ItemTemplate>
    <EditItemTemplate>
    <%–Notice the GetCat() routine here as the datasource.–%>
    <asp:DropDownList id=”ddTacticCatList” runat=”server” DataSource=”<%# GetCat() %>” DataTextField=”TacticCatName” DataValueField=”TacticCatID”>
    </asp:DropDownList>
    </EditItemTemplate>

    </asp:TemplateColumn>

    Your code-behind page should look like this (in C#)


    private void MainCode()
    {
    string strID = Request.QueryString["id"].ToString();
    //custom code to get the relevant dataset for the entire datgrid
    DataSet ds = LMR.TacticSubCatList(strID);
    //custom code to bind to the datagrid
    Utility.DGDSNullCheck(ds, dgTacticSubCatList, lblTacticSubCatList, “There are no tactic subcategories in the database at this time.”);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    MainCode();
    }
    }

    protected void dgTacticSubCatList_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    //grab the index
    dgTacticSubCatList.EditItemIndex = e.Item.ItemIndex;
    MainCode();
    }

    protected void dgTacticSubCatList_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    //get the id value of the selected datagrid item
    int intTacticSubCatID = (int)dgTacticSubCatList.DataKeys[(int)e.Item.ItemIndex];

    //this gets our textbox, also in the datagrid
    TextBox EditText = null;
    EditText=(TextBox)e.Item.FindControl(“tbTacticSubCatName”);
    string strEditText = Convert.ToString(EditText.Text);

    //get the value of our dropdown list
    DropDownList dd = (DropDownList)e.Item.FindControl(“ddTacticCatList”);
    string strTacticCatID = dd.SelectedValue.ToString();
    //do our database update
    LMR.TacticSubCatEdit(intTacticSubCatID.ToString(),strTacticCatID,strEditText);
    //reset the datagrid
    dgTacticSubCatList.EditItemIndex = -1;
    //give feedback and rebind
    lblFeedback.Text = “Your changes have been applied.”;
    MainCode();
    }

    protected void dgTacticSubCatList_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    dgTacticSubCatList.EditItemIndex = -1;
    MainCode();
    }
    protected DataTable GetCat()
    {
    //here is where we get the dataset to populate the dropdown list – it does have to go in an independant function
    DataSet ds = LMR.TacticCatList();
    return ds.Tables[0];
    }

    protected void dgTacticSubCatList_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
    if (e.Item.ItemType == ListItemType.EditItem)
    {
    //we set the selcted index in the ItemDataBound event
    string strID = Request.QueryString["id"].ToString();
    string strSubCatID = dgTacticSubCatList.DataKeys[(int)e.Item.ItemIndex].ToString();
    Holder.TacticSubCat tsc = LMR.GetTacticSubCat(strSubCatID);
    DropDownList dd = (DropDownList)e.Item.FindControl(“ddTacticCatList”);
    dd.SelectedIndex =dd.Items.IndexOf(dd.Items.FindByValue(strID));
    }
    }

     

    It's as simple as that. Hopefully this article will be usefull for you.

     

    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 :: Change Startup.cs and wwwroot folder name in ASP.NET Core

    clock November 22, 2016 06:45 by author Armend

    ASP.NET Core runs on conventions. It expects Startup.cs file for starting up the ASP.NET Core application and wwwroot folder for the application’s static contents. But what if you want to change the name of Startup.cs and wwwroot to your choice? Well, that can be done. In this short post, we will see how to change Startup.cs and wwwroot folder name in ASP.NET Core.

     

    Change Startup.cs class name

    You can easily change the startup class name. Open the Startup.cs file and change the startup class name from Startup to “MyAppStartup” (or anything of your choice). And also change the name of the constructor.

    public class MyAppStartup
    {
        public MyAppStartup(IHostingEnvironment env)
        {
           
        }
    }

    Now you need to tell ASP.NET Core about new Startup class name, otherwise application will not start. So open Program.cs file and change the UseStartup() call as follows:

    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<MyAppStartup>()
            .Build();
        host.Run();
    }

    That’s it.

    Change wwwroot folder name

    Earlier, I posted how to rename the wwwroot folder via hosting.json file but that doesn’t seem to work now. To change the name, right on wwwroot folder and rename it to “AppWebRoot” (or anything of your choice).
    Now, open Program.cs file and add highlighted line of code to Main().

    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseWebRoot("AppWebRoot")
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<MyStartup>()
            .Build();
     
        host.Run();
    }

    That’s it.
    Hope you liked it. Thank you for reading.

    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 :: How To Create a Connection String and Working with SQL Server LocalDB

    clock November 15, 2016 07:16 by author Armend

    Creating a Connection String and Working with SQL Server LocalDB

    The MovieDBContext class you created handles the task of  connecting to the database and mapping Movie objects to database  records. One question you might ask, though, is how to specify which database it will connect to. You don't actually have to specify which database to use,  Entity Framework will default to using  LocalDB. In this section we'll explicitly add  a connection string in the Web.config file of the application.

    SQL Server Express LocalDB

    LocalDB is a lightweight version of the SQL Server Express Database Engine that starts on demand and runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to  work with databases as .mdf files. Typically, LocalDB database files  are kept in the App_Data folder of a web project.
    SQL Server Express is not recommended for use in production web applications. LocalDB in particular should not be used for production with a web application because it is not designed to work with IIS. However, a LocalDB  database can be easily migrated to SQL Server or SQL Azure.
    In Visual Studio 2013 (and in 2012), LocalDB is installed by default with Visual Studio.
    By default, the Entity Framework looks for a connection string named the same as the object context class (MovieDBContext for this project).  For more  information see  SQL Server Connection Strings for ASP.NET Web Applications.
    Open the application root Web.config file shown below. (Not the Web.config file in the Views folder.)

     

    Find  the <connectionStrings>  element:

     

    Add the following connection string to the <connectionStrings>  element in the Web.config file.

    <add name="MovieDBContext"
       connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
       providerName="System.Data.SqlClient"
    />

    The following example shows a portion of the Web.config file with  the new connection string added:

    <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20130603030321.mdf;Initial Catalog=aspnet-MvcMovie-20130603030321;Integrated Security=True" providerName="System.Data.SqlClient" />
        <add name="MovieDBContext"    connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"
    />

    The two connection strings are very similar. The first connection string is  named DefaultConnection and is used for the membership database to control who can access the application. The connection string you've added specifies a LocalDB database named Movie.mdf located in the App_Data  folder.  We won't use the membership database in this tutorial, for more information on membership, authentication and security, see my tutorial Create an ASP.NET MVC app with auth and SQL DB and deploy to Azure App Service.
    The name of the connection string must match the name of the DbContext class.

    using System;
    using System.Data.Entity;
    namespace MvcMovie.Models
    {
        public class Movie
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public DateTime ReleaseDate { get; set; }
            public string Genre { get; set; }
            public decimal Price { get; set; }
        }

        public class MovieDBContext : DbContext
        {
            public DbSet<Movie> Movies { get; set; }
        }
    }

    You don't actually need to add the MovieDBContext connection string. If you don't specify a connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class (in this case MvcMovie.Models.MovieDBContext). You can name the database anything you like, as long as it has the .MDF  suffix. For example, we could name the database MyFilms.mdf.
    Next, you'll build a new MoviesController class that you can use  to display the movie data and allow users to create new movie listings.

    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 c



    ASP.NET Hosting - ASPHostPortal.com :: Handle Multiple Submit Buttons On The Same Form in MVC 6

    clock November 8, 2016 07:11 by author Armend

    In this post we will explain you about Handling multiple submit buttons on the same form in MVC.To fix this problem, I’m progressing to justify the varied techniques for handling multiple buttons on the same form in Sometimes you got situation like more than one submit buttons on a similar form in ASP.NET MVC 6. At that point, How we will handle the click event of every and each buttons on your form? Suppose you’ve got a user Login form.

    On the above picture, we have the SignUp, SignIn and the Cancel buttons. Suppose on Signup button click you have to open Signup window & on SignIn button click you have to open Login window and on Cancel button click you are returning to home page. For handling all of the above buttons, we have the following methods:

    • Export Gridview to Excel: Gridview to Excel
    • Insert,Update,Delete in ModalPopup CRUD operation in ModalPopup
    • Read and Write in Text File in ASP.NET Read and Write File in ASP.NET

    Now, Make the view Form with Multiple Button in Home Folder with the following code.

    MultipleCommand.cshtml
    @model Mvc4_Multiple_Submit_Button.Models.RegistrationModel
    @{
    ViewBag.Title = "Handling Multiple Command Buttons";
    }
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
    <h2>User's Signup Form</h2>
    @using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
    {
    <fieldset>
    <legend>Registration Form</legend>
    <ol>
    <li>
    @Html.LabelFor(m => m.Name)
    @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
    @Html.ValidationMessageFor(m => m.Name)
    </li>
    <li>
    @Html.LabelFor(m => m.Address)
    @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
    @Html.ValidationMessageFor(m => m.Address)
    </li>
    <li>
    @Html.LabelFor(m => m.MobileNo)
    @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 })
    @Html.ValidationMessageFor(m => m.MobileNo)
    </li>
    </ol>
    <button type="submit" id="btnSave" name="Command" value="Save">
    Save</button>
    <button type="submit" id="btnSubmit" name="Command" value="Submit">
    Submit</button>
    <button type="submit" id="btnCancel" name="Command" value="Cancel" onclick="$('#submitForm').submit()">
    Cancel (Server Side)</button>
    <button type="submit" id="btnCancelSecForm" name="Command" value="Cancel" onclick="$('#cancelForm').submit()">
    Cancel (Server Side by Second Form)</button>
    <button name="ClientCancel" type="button" onclick=" document.location.href = $('#cancelUrl').attr('href');">
    Cancel (Client Side)</button>
    <a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" style="display:none;">
    </a>
    </fieldset>
    }
    @using (Html.BeginForm("MultipleButtonCancel", "Home", FormMethod.Post, new { id = "cancelForm" })) { }

    Next step, in Homecontroller include the MultipleCommand Method to handle the multiple button with the following code.

    HomeController.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Mvc4_Multiple_Submit_Button.Models;
    namespace Mvc4_Multiple_Submit_Button.Controllers
    {
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
    return View();
    }
    public ActionResult MultipleCommand()
    {
    return View();
    }
    [HttpPost]
    public ActionResult MultipleCommand(RegistrationModel mReg, string Command)
    {
    if (Command == "Save")
    {
    //TO DO : for Save button Click
    }
    else if (Command == "Submit")
    {
    //TO DO : for Submit button Click
    }
    else
    {
    //TO DO : for Cancel button Click
    return RedirectToAction("Index");
    }
    return View();
    }
    [HttpPost]
    public ActionResult MultipleButtonCancel()
    {
    //TO DO : for Cancel button Click
    return RedirectToAction("Index");
    }
    }
    }


    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 :: How to publish ASP.NET Core web application via Visual Studio 2015

    clock November 3, 2016 07:04 by author Armend

    How to publish ASP.NET Core web application via Visual Studio 2015

    Create a web app
    From the Visual Studio Start page, tap New Project.
    In the center pane, tap ASP.NET Core Web Application (.NET Core) Create a web app

    In the New ASP.NET Core Web Application dialog, tap Web Application, and then tap OK.

     

    Login to your hosting control panel --> Websites --> Select the target site --> click Show Web Deploy Info. If you have not enable this feature, please enable it first at the same place. You will able to see the web deploy settings there or download the publishing xml configuration file directly.
    And then open your web application with Visual Studio 2015, right click the web application, then click"Publish" to start.
    You can chose Import  with Publish XML and Custom to fill in the deploy info.

    Click Validate Connections to check the deploy info,then you can tap Publish.

    Note:If you get certificate error with publish,please add below code to your PublishProfiles.
    <AllowUntrustedCertificate>True</AllowUntrustedCertificate>

     

    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

    Save



    ASP.NET Hosting - ASPHostPortal.com :: How To Deploy an ASP.NET Core Application on Linux with Docker

    clock October 25, 2016 08:41 by author Armend

    Deploy an ASP.NET Core Application on Linux with Docker

    Docker and containerization is all the rage these days. Adoption in the .NET community has been slow so far, but that’s changing. With the introduction of cross-platform .NET Core, it became much easier to run .NET code on Linux machines. And, since Docker is a primarily Linux-based technology, it’s now very straightforward to deploy ASP.NET Core applications using Docker. How? Let’s take a look.

     

    At a high level, containerization solves problems related to deploying and running your application on a server somewhere “out there.” I have fond memories of deploying code for the first time as a junior developer by manually copy-pasting binaries into production. Fortunately, no one is doing that anymore (right?). Today, automated build tools can handle the steps required to push code to a production machine. Containerization can take you one step further… by abstracting away the machine itself.

    How does Docker work?

    Docker is similar to a virtual machine, but without the overhead. A service called Docker Engine runs on your server, ready to host one (or many) containers. Containers that run on top of Docker Engine are completely isolated. As far as the applications inside each container are concerned, they’re running on separate machines. In reality, they’re just isolated processes on the same machine.
    Containers run Docker images, which are packages that represent everything needed to spin up your application or service inside the container: dependencies, shared libraries, application binaries, and so on. During development, you define the “recipe” that is built into the final image. This recipe is called a Dockerfile.

    Why use Docker instead of a virtual machine?

    If you’ve ever set up a web or application server, think of everything necessary to go from a “bare metal” virtual machine to a running production server: besides installing the OS, you have to get the latest patches, install framework runtimes and dependencies, grab third-party libraries, configure networking and routes to your other services, install your application code, and then configure it all. And, if you have multiple servers in your environment, or you’re frequently spinning up new servers, you have to do this a lot.
    Containerization allows you to do all of the setup work once, and build the result into an image you can immediately run on any machine using Docker Engine. It moves the focus away from setting up servers, and lets you instead focus on building images that include everything needed to run anywhere.

    • Containerization doesn’t replace virtual machines – in fact, the two technologies go hand-in-hand. A common approach is to have a handful of virtual machines in a cluster, each running Docker Engine and hosting many containers.

    Ultimately, there are use cases for both technologies. You probably don’t need to boot up an entire guest OS and tens or hundreds of background services just to run a single application – running inside a thin container makes more sense. Conversely, sometimes you do want to have an entire OS dedicated to a particular task, especially if it’s something CPU-intensive. Virtual machines are well-suited for the latter, and containerization makes the former easier to manage.
    If you’ve never set up Docker or deployed an ASP.NET Core project as a Docker image, this is the tutorial for you! I’ll walk through the steps required to:

    Setting up Docker

    It’s easy to get started with Docker. First, you have to install the Docker Engine on your machine (or your server)
    For my own testing, I installed Docker for Windows on my Windows 10 development environment, and also on my Mac. To make sure the service is installed correctly, run this from the terminal:

    > docker --version
    Docker version 1.12.0-rc4, build e4a0dbc, experimental

    If you see a version number, everything is working!

    Creating an ASP.NET Core project

    If you don’t already have the latest .NET Core tooling installed, grab that at the official .NET Core site. Once it’s installed on your machine, you can create a new directory and scaffold a new ASP.NET Core project easily

    mkdir AspNetCoreHelloWorld
    cd AspNetCoreHelloWorld
    dotnet new -t web

    To make sure everything is working, try running the project locally first:

    dotnet restore
    dotnet run

    Building a Dockerfile for ASP.NET Core

    Docker needs a Dockerfile that contains the “recipe” for creating an image based on the project. Create a new file called Dockerfile in the project directory:

    touch Dockerfile

    On Windows, you can run notepad Dockerfile instead, or use your favorite text editor. Make sure that this file isn’t saved with an extension like .txt – it’s supposed to have no extension.
    The Dockerfile contents are straightforward:

    FROM microsoft/dotnet:latest
    COPY . /app
    WORKDIR /app
    RUN ["dotnet", "restore"]
    RUN ["dotnet", "build"]
    EXPOSE 5000/tcp
    ENV ASPNETCORE_URLS http://*:5000
    ENTRYPOINT ["dotnet", "run"]

    Here’s what each of these instructions does:

    • FROM tells Docker that you want to base your image on the existing image called microsoft/dotnet:latest. This image already contains all the dependencies for running .NET Core on Linux, so you don’t have to worry about setting those up.
    • COPY and WORKDIR copy the current directory’s contents into a new directory inside the container called /app, and set that to the the working directory for the subsequent instructions.
    • RUN executes dotnet restore and dotnet build, which restores the packages needed to run the ASP.NET Core application and compiles the project.
    • EXPOSE tells Docker to expose port 5000 (the default port for ASP.NET) on the container.
    • ENV sets the environment variable ASPNETCORE_URLS in the container. This will ensure that ASP.NET Core binds to the correct port and address.
    • ENTRYPOINT specifies the command to execute when the container starts up. In this case, it’s dotnet run.

    Creating the Docker image

    Once you’ve created the Dockerfile, you’re ready to build an image:

    docker build -t mydemos:aspnetcorehelloworld .   
    docker build -t mydemos:aspnetcorehelloworld .

    See that trailing period? That tells docker to look in the current directory for a Dockerfile. The -t flag tags the image with tag mydemos:aspnetcorehelloworld.
    When the image finishes building, you can spin it up:

    docker run -d -p 8080:5000 -t mydemos:aspnetcorehelloworld
    docker run -d -p 8080:5000 -t mydemos:aspnetcorehelloworld

    The -d flag tells Docker to run the container in detached mode (in the background). The -p flag will map port 8080 on the host machine to port 5000 inside the container. Finally, the -t flag is used to specify which image to run. That’s it! You should see your container running when you check docker ps

    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 :: Using select tag helper in ASP.NET MVC 6

    clock October 11, 2016 20:12 by author Armend

    Using select tag helper in ASP.NET MVC 6

    Tag Helpers were introduced in ASP.NET MVC 6, and one the tag helper is Select tag helper. Select tag helper is used to generate dropdown list and it’s an alternative for Html.DropDownList. In this post, we will see how to use select tag helper and how to bind select tag helper to model data or enum values. Also read How to use image tag helper in ASP.NET Core MVC 1.0

    How to use select tag helper in ASP.NET MVC 6?

    Select tag helper uses asp-for which extracts the name of the specified model property into the rendered HTML. For example,

    <select asp-for="TimeZone"></select>

    Then your model should have a property defined “TimeZone”.

    public class RegisterViewModel
    {
        [Display(Name = "TimeZone")]
        public string TimeZone { get; set; }
    }

    But this will be a empty list without any option as we didn’t define any options for the select list. There are couple of ways to add options to select tag helper.

    Define directly in Markup

    You can directly define your options in markup.

    <select asp-for="TimeZone">
       <option value="-12">(UTC-12:00)</option>
       <option value="-11">(UTC-11:00)</option>
    </select>

    And selected option will be marked as “selected” when the page will be rendered.

    Define using a data source

    It’s a most common scenario when you want to bind your select list options either from any database table or any server side list. In such case, asp-items tag helper attribute should be used.

    <select asp-for="TimeZone" asp-items="ViewBag.TimeZoneList"></select>

    Now, we need to put TimeZoneList in ViewBag. Let’s first create a List and add options to it.

    public List<SelectListItem> TimeZoneList { get; private set; }
    public RegisterViewModel()
    {
         TimeZoneList = new List<SelectListItem>();
         TimeZoneList.Add(new SelectListItem
         {
             Text = "Select",
             Value = ""
         });
         foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
         {
              TimeZoneList.Add(new SelectListItem
              {
                   Text = z.DisplayName,
                   Value = z.Id
              });
         }
    }

    And from your controller, add the list to ViewBag.

    // GET: /Account/Register
    [HttpGet]
    [AllowAnonymous]
    public IActionResult Register()
    {
        RegisterViewModel rs = new RegisterViewModel();
        ViewBag.TimeZoneList = rs.TimeZoneList;
        return View();
    }

    Bind enum values

    You can also bind enum values to select list.

    public List<SelectListItem> PriorityList { get; private set; }
    public RegisterViewModel()
    {
        PriorityList = new List<SelectListItem>();
        PriorityList.Add(new SelectListItem
        {
           Text = "Select",
           Value = ""
        });
        foreach (ePriority eVal in Enum.GetValues(typeof(ePriority)))
        {
          PriorityList.Add(new SelectListItem { Text = Enum.GetName(typeof(ePriority), eVal), Value = eVal.ToString() });
        }
    }

    You can also use a static function to bind the select list, instead of using ViewBag.

    public static List<SelectItemList> GetTimeZoneList()
    {
        List<SelectListItem> TimeZoneList = new List<SelectListItem>();
        TimeZoneList.Add(new SelectListItem
        {
           Text = "Select",
           Value = ""
        });
        foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
         {
              TimeZoneList.Add(new SelectListItem
              {
                   Text = z.DisplayName,
                   Value = z.Id
              });
         }
        return TimeZoneList;
    }

    As static functions can be accessed only via classname. So in our case, it would be RegisterViewModel.GetTimeZoneList()

    <select asp-for="TimeZone"
       asp-items="RegisterViewModel.GetTimeZoneList()"></select>

    Summary

    In this post, I demonstrated how to use select tag helper and how to bind it using enum values as well as other data source. And that covers all the functionality provided by the select tag helper in MVC 6.

     

    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.



    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