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 :: Tips to to using Microsoft Enterprise Library in ASP.NET for data access

clock August 23, 2016 19:37 by author Armend

Microsoft Enterprise Library is a collection of reusable software components used for  logging, validation, data access, exception handling etc.

Here I am describing how to use Microsoft Enterprise Library for data access.

Step 1: First download the project from http://entlib.codeplex.com/ URL.

Step 2: Now extract the project to get

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ObjectBuilder.dll


And give reference in the Bin directory by Right click on Bin -> Add Reference -> then give the path of these 4 dlls. Then

Step 3: Modification in the web.config for Connection String.

<add name="ASPHostPortalConnection" providerName="System.Data.SqlClient" connectionString="DataSource=ASPHostPortalSQLEXPRESS;Initial Catalog=ASPHostPortal;User ID=sa;Password=admintest;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>

Give the connection string as above where Datasource is your data source name, Initial Catalog is your database name and User ID and Password as in your sql server.

Step 4:

Now it is time to write the code.


Write the below 2 lines in the using block.

using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

Here I am writting some examples how to work on:

public DataTable Read()
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetStoredProcCommand("[Topics_Return]");
            DataSet dataSet = db.ExecuteDataSet(dbCommand);
            return dataSet.Tables[0];
        }
        catch
        {
            return null;
        }
    }


The above code is a sample that will return a dataset. Here Fewlines4bijuConnection is the connection name and Topics_Return is the stored procedure name that is nothing but a Select statement.

But if the stored procedure is taking parameter then the code will be like:

 public int Save()
    {
        Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
        DbCommand dbCommand = db.GetStoredProcCommand("Topics_Save");

        db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");
        db.AddInParameter(dbCommand, "@Description", DbType.AnsiString, "Here is the Descriptiont");      
        db.AddInParameter(dbCommand, "@PostedBy", DbType.Int32, 4);       
        db.AddOutParameter(dbCommand, "@Status", DbType.AnsiString, 255);
        try
        {
            db.ExecuteNonQuery(dbCommand);
            return Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));
        }
        catch
        {
            return 0;
        }
    }

As the code explained above ASPHostPortalConnection is the connection name and Topics_Save is the stored procedure name that is taking 3 (Subject,Description,PostedBy) input parameters and 1(Status) output parameter.

You may give values from textbox, I am here provideing sample values like  "Here is the subject", "Here is the Descriptiont" or you may give the UserID from session, I am here giving 4. The output parameter will give you a string as defined and the code to get the value is

int returnValue=Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));

you can pass input parameter as below

db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");

DbType.AnsiString since Subject is of string time, you can select different values like AnsiString, DateTime from the Enum as be the parameter type.
The above code describes if you are using any stored procedure.
Below is an example that shows how to use inline SQL statements.

public DataSet GetID(string title)
    {
       DataSet ds=new DataSet();

        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetSqlStringCommand("Select * FROM Topics where UserID=1 and
IsDeleted=0");          
            ds= db.ExecuteDataSet(dbCommand);
           return ds;         
        }
        catch
        {
            return ds;
        }
         return ds;
    }


Happy coding!!


About ASPHostPortal.com :

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP 5. x, etc. Their service include shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.

 



ASP.NET Hosting - ASPHostPortal.com :: Convert DataTable To JSON String in ASP.NET

clock August 16, 2016 19:56 by author Armend

In this post we will explain about how to Convert DataTable To JSON String in ASP.NET . First of all you need to create an "ASP.NET Empty Web Site". Then use the following procedure.

 

Step 1

Create a ConvertDataTableToJson class in the App_Code folder and provide the following:

Convert DataTable To JSON String.       
    using System.Data 
    using System.Text; 
    public class ConvertDatatableToJson 
    { 
       public string DataTableToJson(DataTable dt) 
       { 
          DataSet ds = new DataSet(); 
          ds.Merge(dt); 
          StringBuilder JsonStr = new StringBuilder(); 
          if (ds != null && ds.Tables[0].Rows.Count > 0) 
          { 
             JsonStr.Append("["); 
             for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
             { 
                JsonStr.Append("{"); 
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++) 
                { 
                   if (j < ds.Tables[0].Columns.Count - 1) 
                   { 
                      JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\","); 
                   } 
                   else if (j == ds.Tables[0].Columns.Count - 1) 
                   { 
                      JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\""); 
                   } 
                } 
                if (i == ds.Tables[0].Rows.Count - 1) 
                { 
                   JsonStr.Append("}"); 
                } 
                else    
                { 
                   JsonStr.Append("},"); 
                } 
             } 
             JsonStr.Append("]"); 
             return JsonStr.ToString(); 
          } 
          else 
          { 
             return null; 
          } 
       }

Step 2

Insert the grid view control into the Default.aspx page then write the following design code:

<asp:GridView ID="ui_grdVw_EmployeeDetail" runat="server" Width="50%" AutoGenerateColumns="false" HeaderStyle-CssClass="pageheading"> 
    <Columns> 
    <asp:TemplateField HeaderText="S.NO"> 
    <ItemTemplate> 
    <%#Container.DataItemIndex+1 %> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee ID"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmployeeID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_id") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee Name"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmployeeName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Name") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee Post"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmpJob" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_job") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Department"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_Department" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Dep") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    </Columns> 
    </asp:GridView> 
    <br /> 
    <asp:Button ID="ui_btn_Convert1" runat="server" Text="Manually Convert To Json" OnClick="ui_btn_Convert1_Click" /><br /><br /><br /> 
    <asp:Label ID="ui_lbl_JsonString1" runat="server"></asp:Label>

Step 3

Now, open the Deafult.asps.cs then write the following code:
    using System; 
    using System.Data;
 

    public partial class _Default : System.Web.UI.Page 
    { 
       #region Global Variable 
       DataTable dt; 
       ConvertDatatableToJson dtJ; 
       string JsonString = string.Empty;    
       #endregion 
        
       protected void Page_Load(object sender, EventArgs e) 
       { 
          if (!IsPostBack) 
          { 
             ui_grdvw_EmployeeDetail_Bind(); 
          } 
       }       
       protected void ui_grdvw_EmployeeDetail_Bind() 
       { 
          dt = new DataTable(); 
          EmployeeRecord employeeRecord = new EmployeeRecord(); 
          dt = employeeRecord.EmpRecord(); 
          ViewState["dt"] = dt; 
          ui_grdVw_EmployeeDetail.DataSource = dt; 
          ui_grdVw_EmployeeDetail.DataBind(); 
       }       
       protected void ui_btn_Convert1_Click(object sender, EventArgs e) 
       { 
          dtJ = new ConvertDatatableToJson(); 
          JsonString = dtJ.DataTableToJson((DataTable)ViewState["dt"]); 
          ui_lbl_JsonString1.Text = JsonString; 
       } 
    }

Step 4

Press F5, run the project.

Now, convert the DataTable to a JSON string using the newtonsoft DLL.

Step 1

Download the Newtonsoft DLL and move it to the ASP.Net project's bin folder.

Step 2

Then, insert a button and label UI Control in the Deafult.aspx page as in the following:

<asp:Button ID="iu_btn_Convert2" runat="server" Text="Newtonsoft Convert To Json" OnClick="iu_btn_Convert2_Click" /> 
    <br /> 
    <br /> 
    <asp:Label ID="ui_lbl_JsonString2" runat="server"></asp:Label>

Step 3

Now, write the following code in Default.aspx.cs:
using this namespace

using Newtonsoft.Json;

And then:

protected void iu_btn_Convert2_Click(object sender, EventArgs e) 
    { 
       dt = (DataTable)ViewState["dt"]; 
       JsonString = JsonConvert.SerializeObject((DataTable)ViewState["dt"]); 
       ui_lbl_JsonString2.Text = JsonString; 
    }

Now, run the project and click on the Newtonsoft Convert to JSON     

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 :: Asp.net Export Excel Show/Hide Loading image

clock August 2, 2016 19:58 by author Armend

This Tip will explain how to hide the loading gif image after the file is downloaded . It  will be helpful when we are using  Response Object to export the excel or any other file format.

 

Sometimes while  downloading an excel or any file from an Asp application, it might take some time to Generate the File, the delay  depends on many factors( file size, loops, server bandwidth etc ). So we repesent the File Generation process using a rotating GIF image next to the button.
But when we are using Response object we wont get the event after the file is downloaded to the browser, in this case it will be difficult to hide the loading gif which is being shown on the screen

The below steps will guide how to  Show the Gif while Generating and hide it once the file is completly downloaded.

Hide the GIF after download

  • When the download button is clicked, show the loading gif image using onclicentClick event and CSS properties
  • On the Client click event invoke a Javascript method which Contains a  Setinterval  object that moniters  for our cookie (created in c# Response object).
  • In the Server button click Event Create an HttpCookie and append it to the Respone object.
  • So when the File is downloaded completly the Cookie is added to the Page, Now the SetInterval function will capture the cookie and Hides the Loading Gif image.
  • Note: whenever the download button is clicked, previous cookie has to be deleted.

Using the code

protected void btnExportExcel_Click(object sender, EventArgs e)
          {
            DataTable dt = new DataTable();
            dt = GetDataFromDb();
            System.Threading.Thread.Sleep(3000); // for testing purpose to create 3 seconds delay
            //Create a temp GridView
            GridView gv = new GridView();
            gv.AllowPaging = false;
            gv.DataSource = dt;
            gv.DataBind();
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=ExcelReport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gv.RenderControl(hw);
            // Append cookie
            HttpCookie cookie = new HttpCookie("ExcelDownloadFlag");
            cookie.Value = "Flag";
            cookie.Expires = DateTime.Now.AddDays(1);
            Response.AppendCookie(cookie);
            // end
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }

HTML/ASPX Code

<table>
            <tr>
                <td>
                    <asp:Button Text="Download" ID="btnExportExcel" OnClientClick="jsShowHideProgress();" runat="server" OnClick="btnExportExcel_Click" />
                </td>
                <td>
                    <img style="display: none" id="imgloadinggif" src="Images/loading.gif" alt="loading.." />
                </td>
            </tr>
        </table>

Javascript Code:

function jsShowHideProgress() {
    setTimeout(function () { document.getElementById('imgloadinggif').style.display = 'block'; }, 200);
    deleteCookie();

    var timeInterval = 500; // milliseconds (checks the cookie for every half second )

    var loop = setInterval(function () {
        if (IsCookieValid())
        { document.getElementById('imgloadinggif').style.display = 'none'; clearInterval(loop) }

    }, timeInterval);
}

// cookies
function deleteCookie() {
    var cook = getCookie('ExcelDownloadFlag');
    if (cook != "") {
        document.cookie = "ExcelDownloadFlag=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC";
    }
}

function IsCookieValid() {
    var cook = getCookie('ExcelDownloadFlag');
    return cook != '';
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: How To Configure your ASP.​NET Core 1.0 Application

clock June 14, 2016 20:26 by author Armend

The Web.Config is gone and the AppSettings are gone with ASP.NET Core 1.0. How do we configure our ASP.NET Core Application now? With the Web.Config, also the config transform feature is gone. How do we configure a ASP.NET Core Application for specific deployment environments?

Configuring

Unfortunately a newly started ASP.NET Core Application doesn't include a complete configuration as a sample. This makes the jump-start a little difficult. The new Configuration is quite better than the old one and it would make sense to add some settings by default. Anyway, lets start by creating a new Project.
Open the Startup.cs and take a look at the controller. There's already something like a configuration setup. This is exactly what the newly created application needs to run.

public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables();
    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights
        // pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}

But in the most cases you need much more configuration. This code creates a ConfigurationBuilder and adds a appsettigns.json and environment variables to the ConfigurationBuilder. In development mode, it also adds ApplicationInsights settings.
If you take a look into the appsettings.json, you'll only find a ApplicationInsights key and some logging specific settings (In case you chose a individual authentication you'll also

see a connection string):
{
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Where do we need to store our custom application settings?
We can use this appsettings.json or any other JSON file to store our settings. Let's use the existing one to add a new section called AppSettings:

{
...
    "AppSettings" : {
        "ApplicationTitle" : "My Application Title",
        "TopItemsOnStart" : 10,
        "ShowEditLink" : true
    }
}

This looks nice, but how do we read this settings?

In the Startup.cs the Configuration is already built and we could use it like this:

var configurationSection = Configuration.GetSection("AppSettings");
var title = configurationSection.Get<string>("ApplicationTitle");
var topItmes = configurationSection.Get<int>("TopItemsOnStart");
var showLink = configurationSection.Get<bool>("ShowEditLink");
We can also provide a default value in case that item doesn't exist or in case it is null
var topItmes = configurationSection.Get<int>("TopItemsOnStart", 15);

To use it everywhere we need to register the IConfigurationRoot to the dependency injection container:

services.AddInstance<IConfigurationRoot>(Configuration);

But this seems not to be a really useful way to provide the application settings to our application. And it looks almost similar as in the previous ASP.NET Versions. But the new configuration is pretty much better. In previous versions we created a settings facade to encapsulate the settings, to not access the configuration directly and to get typed settings.
No we just need to create a simple POCO to provide access to the settings globally inside the application:

public class AppSettings
{
    public string ApplicationTitle { get; set; }
    public int TopItemsOnStart { get; set; }
    public bool ShowEditLink { get; set; }
}

The properties of this class should match the keys in the configuration section. Is this done we are able to map the section to that AppSettings class:

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

This fills our AppSettings class with the values from the configuration section. This code also adds the settings to the IoC container and we are now able to use it everywhere in the application by requesting for the IOptions<AppSettings>:

public class HomeController : Controller
{
    private readonly AppSettings _settings
    public HomeController(IOptions<AppSettings> settings)
    {
        _settings = settings.Value;
    }
    public IActionResult Index()
    {
        ViewData["Message"] = _settings.ApplicationTitle;
        return View();
    }

Even directly in the view:

@inject IOptions<AppSettings> AppSettings
@{
    ViewData["Title"] = AppSettings.Value.ApplicationTitle;
}
<h2>@ViewData["Title"].</h2>
<ul>
    @for (var i = 0; i < AppSettings.Value.TopItemsOnStart; i++)
    {
        <li>
            <span>Item no. @i</span><br/>
            @if (AppSettings.Value.ShowEditLink) {
                <a asp-action="Edit" asp-controller="Home"
                   asp-route-id="@i">Edit</a>
            }
        </li>
    }
</ul>

With this approach, you are able to create as many configuration sections as you need and you are able to provide as many settings objects as you need to your application.
What do you think about it? Please let me know and drop a comment.

Environment specific configuration

Now we need to have differnt configurations per deployment environment. Let's assume we have a production, a staging and a development environment where we run our application. All this environments need another configuration, another connections string, mail settings, Azure access keys, whatever...
Let's go back to the Startup.cs to have a look into the constructor. We can use the IHostingEnvironment to load different appsettings.json files per environment. But we can do this in a pretty elegant way:

.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

We can just load another JSON file with an environment specific name and with optional set to true. Let's say the appsettings.json contain the production and the default

  • settings and the appsettings.Staging.json contains the staging sepcific settings. It we are running in Staging mode, the second settings file will be loaded and the existing settings will be overridden by the new one. We just need to sepcify the settings we want to override.
  • Setting the flag optional to true means, the settings file doesn't need to exist. Whith this approatch you can commit some default setings to the source code repository and the top secret access keys and connections string, could be stored in an appsettings.Development.json, an appsettings.staging.json and an appsettings.Production.json on the buildserver or on the webserver directly.

Conclusion

As you can see, configuration in ASP.NET Core is pretty easy. You just need to know how to do it. Because it is not directly visible in a new project, it is a bit difficult to find the way to start.

 



ASP.NET Hosting - ASPHostPortal.com :: Tips to configure Kestrel URLs in ASP.NET Core RC2

clock June 10, 2016 19:44 by author Armend

How to configure Kestrel URLs in ASP.NET Core RC2

ASP.NET Core is completely decoupled from the web server environment that hosts the application. ASP.NET Core supports hosting in IIS and IIS Express, and self-hosting scenarios using the Kestrel and WebListener HTTP servers. Additionally, developers and third party software vendors can create custom servers to host their ASP.NET Core apps.

Prior to the release of ASP.NET Core RC2 Kestrel would be configured as part of the command bindings in project.json:

"commands": {
  "web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://localhost:60000;http://localhost:60001;"
},

If no URLs were specified, a default binding of http://localhost:5000 would be used.

As of RC2 we have a new unified toolchain (the .NET Core CLI) and ASP.NET Core applications are effectively just .NET Core Console Applications. They have a single entry point where we programatically configure and run the web host:

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

Here we're adding support for both Kestrel and IIS hosts via the appropriate extension methods.
When we upgraded SaasKit to RC2 we used the UseUrls extension to configure the URLs Kestrel would bind to:

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://localhost:60000", "http://localhost:60001")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

I didn't really like this approach as we're hard-coding URLs. Fortunately it's still possible to load the Kestrel configuration from an external file.
First create a hosting.json file in the root of your application with your required bindings. Separate multiple URLs with a semi-colon:

{
  "server.urls": "http://localhost:60000;http://localhost:60001"
}

Next update Program.cs to load your hosting configuration, then use the UseConfiguration extension to pass the configuration to the WebHostBuilder:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

If you're launching Kestrel with Visual Studio you may also need to update launchSettings.json with the correct launchUrl:

"RC2HostingDemo": {
  "commandName": "Project",
  "launchBrowser": true,
  "launchUrl": "http://localhost:60000/api/values",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
}

Now the web application will listen on the URLs configured in hosting.json:

Hosting environment: Development
Content root path: C:\Users\ben\Source\RC2HostingDemo\src\RC2HostingDemo
Now listening on: http://localhost:60000
Now listening on: http://localhost:60001
Application started. Press Ctrl+C to shut down.



ASP.NET Hosting - ASPHostPortal.com :: ASP.NET MVC vs ASP.NET - Which is better?

clock June 3, 2016 22:54 by author Dan

When developers start to build new web projects they face two options- either using ASP.NET MVC framework or ASP.NET web forms. These days, more and more companies are however choosing the MVC based framework to revise their existing sites significantly or to develop new ones. The framework has a multitude of benefits as well as technical goodies which have made it the darling among the developers.

MVC, short for Model-View-Controller is an architectural pattern that helps in division of an application into three basic components- the controller, the model and the view. This framework is a great alternative to the web forms pattern when creating applications since it is highly testable as well as lightweight presentation framework. It comes integrated with all current .NET features like authentication based on membership as well as master pages. Most developers are quite familiar with the pattern. Here is a low-down on the advantages that the MVC based framework offers over the web forms.

Separating application tasks or concerns- A huge advantage in the framework is that it clearly separates Business Logic, Data, Model, UI, test-driven development and testability. Core contracts of the framework are interface-based for which mock objects may be used for the testing. These mock objects are simulated objects imitating the behaviours of application's actual objects. The application can be unit-tested without making the controllers run, making the testing more flexible as well as fast. Any framework may be used for the testing.

Clientcaching

Silverlight makes this available to us. When we integrate Silverlight full advantage may be taken of the feature. This leads to faster application loading; in fact some part of processing may be done through web browsers, this makes the execution of client site as well as the server side a lot faster. You can even integrate JQuery and MVC so that the code written runs in browser, taking away a huge load away from the server.

HTML size

In ASP.NET there is a huge problem in the HTML size of view state as well as controls. All data rendered is stored by view state with the final result being the final HTML getting too large. For those on slow internet connections, the loading time will be slow as well as delayed. The current framework takes care of that problem since the view state concept is absent here.

Supporting ASP.NET routing

This URL-mapping component is very powerful, letting you build applications with searchable and comprehensible URLs. Through this there is no need for URLs to include extensions of file-names since the design supports patterns of URL naming and these work good enough for SEO or search engine optimization as well as REST or representational state transfer addressing.

Pluggable as well as extensible framework

The design of MVC's components makes them easily customizable or replaceable. Individual view engine, action-method parameter serialization, URL routing policy as well as other components can be plugged in. The use of DI or Dependency Injection and IOC or Inversion of Control container models is also supported. With DI you can inject objects into classes and it does not rely on class for creation of object itself. The testing is made easier by the condition imposed that when an object is required by another object then another object should be sourced from an external source like configuration file.

The biggest advantage of ASP.NET MVC platform is that it contains all the features as well as advantages of .NET since the basis is the same for both. However, some disadvantages are that understanding codes during the process of customization may not be an easy process. Another problem is the cost- the start-up costs are much higher in the MVC platform when compared to the web form based one. But looking at the benefits that are enjoyed by the developers and the end result, this is but a small price to pay for. You can get in touch with a asp.net application development company who can help you develop web apps that are stable, scalable and secure.

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to Add the Store Locator in ASP.NET MVC Application

clock April 22, 2016 23:13 by author Dan

Recently, a reader wrote in and asked what steps would be necessary to include a “Directions” link with each marker in the map so that, when clicked, the user would see the driving directions from the address they entered and the store of interest. I decided to update the ASP.NET MVC application to include this new feature request. Now, the results page shows a “Directions” link in both the grid of nearby stores and in the info window that pops up when you click a map marker. Clicking the “Directions” link opens a new browser window and loads Google Maps, showing the directions from the user-entered address to the selected store’s address.

To show the driving directions I send the user to the following URL: http://maps.google.com/maps?f=d&source=s_d&saddr=startingAddress&daddr=destinationAddress.

When the user is sent to the store locator page, the user-entered address (a/k/a, the starting address) is passed through the querystring via a field named Address, so we already know the starting address. But how do we get our hands on the destination address? Recall that view is passed a model that is a collection of NearbyStoreLocation objects; the NearbyStoreLocation class has properties like Address (the street address), City, Region, PostalCode, and so forth. We can build up the address by concatenating these various address parts.

Rather than requiring the view to build up the address, I added a new read-only property to the NearbyStoreLocation class named FormattedAddress, which returns an address Google Maps can parse by piecing together the address-related properties into a string.

public string FormattedAddress
{
get
{
var addrPieces = new List<string>(5);
if (!string.IsNullOrEmpty(this.Address))
addrPieces.Add(this.Address);
if (!string.IsNullOrEmpty(this.City))
addrPieces.Add(this.City);
if (!string.IsNullOrEmpty(this.Region))
addrPieces.Add(this.Region);
if (!string.IsNullOrEmpty(this.CountryCode))
addrPieces.Add(this.CountryCode);
if (!string.IsNullOrEmpty(this.PostalCode))
addrPieces.Add(this.PostalCode);
return string.Join(", ", addrPieces.ToArray());
}
}

In the view, the link to the directions can be build like so:

<a target="_blank" href="http://maps.google.com/maps?f=d&source=s_d&saddr=<%=Server.UrlEncode(Request.QueryString["Address"]) %>&daddr=<%=Server.UrlEncode(store.FormattedAddress) %>">Directions</a>

And that’s it! Adding the Directions link to the info popup window is a tad more involved because the quotation marks must be escaped using \”. Happy Programming!

Best ASP.NET 4.6 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 5 Hosting - ASPHostPortal :: SEO For ASP.NET Web Sites

clock December 16, 2015 00:36 by author Kenny

SEO For ASP.NET Web Sites

One of the main sources of audience for these internet applications are the Search Engines like Google, Bing, Yahoo etc. Hence, the end application should not only handle your business problems efficiently but also follow some simple rules so that it yields good results in internet arena. This article, will list some of the simple guidelines which you need to consider if your Asp.Net application is an internet site.

1.    Add descriptive and unique Page Title for every page

Every page in your website should have a unique and descriptive page title that can describe what the page offers. You can set the Page Title either declaratively or in the code behind file. Refer below,

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" Title="My Home Page"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

In code behind,

Page.Title = "My Home Page";

2.    Links should be hyperlinks, no linkbutton or javascript navigation for crawlable links

Make sure all your links in your page are hyperlinks. Search engines can crawl a page only if it is linked through a hyper link (anchor tag). Javascript navigations are not search engine friendly since search engines will not understand it.

3.    Use javascript navigation for site related pages that have no search values

Page rank is distributed across the links on your page. Some of the internal website pages like About us, disclaimer, Registration, login, contact us, user profile pages can be navigated through javascript so that the page rank are not distributed to them. Doing like this will make rest of the crawlable content links benefited.

4.    Add Meta Keyword and Description tag for every page

Add Meta keyword and Meta description tag with relevant contents. Search engines will use these tags to understand what the page offers. You can dynamically set the meta tags from codebehind file using the below code,

HtmlHead head = (HtmlHead)Page.Header;

 HtmlMeta metasearch1 = new HtmlMeta();

 HtmlMeta metasearch2 = new HtmlMeta();  

 metasearch1.Name = "descriptions";

 metasearch1.Content = "my personal site";

 head.Controls.Add(metasearch1);

 metasearch2.Name = "keywords";

 metasearch2.Content = "ASP.Net,C#,SQL";

 head.Controls.Add(metasearch2);

The above code will add the below Meta tags to output html.

<meta name="descriptions" content="my personal site" />

<meta name="keywords" content="ASP.Net,C#,SQL" />

In ASP.Net 4.0, Microsoft added 2 new properties on the Page directive (Page object) that lets you to define the Meta keywords and Description declaratively and dynamically from codebehind.

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" MetaKeywords="asp.net,C#" MetaDescription="This is an asp.net site that hosts asp.net tutorials" CodeFile="Default.aspx.cs" Inherits="_Default" %>

In codebehind,

protected void Page_Load(object sender, EventArgs e)

    {

        Page.MetaKeywords = "asp.net,C#";

        Page.MetaDescription = "This is an asp.net site that hosts asp.net tutorials.";

    }

The similar can thing can be achieved in previous versions of .Net Framework by using a custom BasePage class.

5.    Make descriptive urls

Make your website URL descriptive. URL’s that has lots of query string values, numeric ids are not descriptive. It will provide enough information what the page offers. For example, http://www.example.com/products.aspx?catid=C91E9918-BEC3-4DAA-A54B-0EC7E874245E is not descriptive as http://www.example.com/Windows-Hosting

Apart from other parameters, search engines will also consider the website url to match your page for a searched keyword.



ASP.NET Hosting - ASPHostPortal.com :: How to Check Duplicate User Names In ASP.NET Web Pages Sites

clock October 5, 2015 11:39 by author Kenny

How to Check Duplicate User Names In ASP.NET Web Pages Sites

The Web Pages Starter Site template provides a useful starting point for developing a Razor Web Pages site that includes membership. But it doesn't include any mechanism for preventing duplicate user names. This article offers one solution to the problem that uses jQuery.

If you ask how to prevent duplicate user names in forums, one of the suggestions that is often put forward is to apply a unique constraint in the database column that holds the user name. Any attempt to submit a duplicate value will result in an exception being raised in the relevant database provider. You can catch this exception and show the user an appropriate message. This works but it's a fairly clunky solution. And many people feel that you should not use exceptions as a means to manage your business rules.

The solution featured in this article uses AJAX to query the database and to give the user immediate feedback when they enter their chosen user name. The AJAX call requests a page that exists purely to query the database to see if the selected user name is already in use. The solution also includes a server side chekc to ensure that users who have disabled JavaScript so not slip through the net. The solution requires a couple of amendments to the Register.cshtml file in the Starter Site, and the addition of 3 files. But first, the changes to the Register.cshtml page. The first change is in the inclusion of a JavaScript file called dupecheck.js.

@* Remove this section if you are using bundling *@
@section Scripts {
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/dupecheck.js"></script>
}

And the second is the server side check to see if the username is in use:

if(Functions.IsDuplicate(email)){
    ModelState.AddError("email", "User name is already taken");
}

I placed this in the if(IsPost) section just after the initial variables that represent the submitted values (email, password and confirmPassword) are declared. The code calls a function named IsDuplicate. The function is declared in a file called Functions.cshtml which is placed in a folder called App_Code:

@functions {
    public static bool IsDuplicate(string username){
        var db = Database.Open("StarterSite");
        var commandText = @"SELECT COUNT(Email) FROM UserProfile WHERE Email = @0";
        return (int)db.QueryValue(commandText, username) > 0;
    }
}

Note that the name of the folder is important. The function returns a bool. The value of the bool is determined as a result if the SQL query which gets a count of the rows containing the provided user name. By default, the Starter Site uses a column called Email in the UserProfile table for the storage of user names. This function is also called in a separate file named DupeCheck.cshtml. This file is placed in the root of the site:

@{
    Layout = null;
    if(IsAjax){
        var username = Request["username"];
        var result = Functions.IsDuplicate(username);
        Json.Write(new { isDupe = result }, Response.Output);
    }
}

DupeCheck.cshtml is designed to work exclusively with AJAX. The code includes an instruction to nullify any layout pages that might have been set in a _PageStart file, and then it uses the IsAjax property to determine if the page has been requested via an AJAX call. If it has, it uses the IsDuplicate method to check the availability of the posted username and returns the result to the calling code. The result is an anonymous type that has one propery: isDupe, which is a boolean. The anonymous type is serialised to JSON by the Json helper.

The final part of the solution is the dupecheck.js file. This uses jQuery:

$(function () {
    $('#email').change(function () {
        $.post(
            '/DupeCheck',
            { username: $(this).val() },
            function (data) {
                var emailValidation = $('span[data-valmsg-for="email"]');
                if (data.isDupe) {
                    if (emailValidation.hasClass('field-validation-valid')) {
                        emailValidation.removeClass('field-validation-valid');
                        emailValidation.addClass('field-validation-error');
                        emailValidation.text('That name is already taken!');
                    }
                } else {
                    if (emailValidation.hasClass('field-validation-error')) {
                        emailValidation.removeClass('field-validation-error');
                        emailValidation.addClass('field-validation-valid');
                        emailValidation.text('');
                    }
                }
            },'json'
        );
    });
});

An event handler is attached to the change event of the user name input (which has an id if email in the Starter Site). The current value is posted to the DupeCheck.cshtml page via AJAX. The code above checks the response from the server to see if the value is a duplicate, and if it is, an appropriate error message is displayed to the user.

Best ASP.NET 4.6 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 6 Hosting - ASPHostPortal :: Remote Validation in ASP.NET MVC

clock August 24, 2015 08:07 by author Kenny

Remote Validation in ASP.NET MVC

ASP.NET is an open-source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. Remote validation is used to make server calls to validate data without posting the entire form to the server when server side validation is preferable to client side.  It's all done set up model and controller which is pretty neat. 

Using the Code

To implement remote validation in an application we have two scenarios, one is without an additional parameter and the other is with an additional parameter. First we create an example without an additional parameter. In this example we check whether a username exists or not. If the username exists then that means the input user name is not valid. We create a view model class "UserViewModel" under the Models folder and that code is:

using System.Web.Mvc;  
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

 

Now we create a static data source, in other words we create a static list of UserViewModel in which we could check whether a username exists or not. You can also use the database rather than a static list. The following code snippet is for StaticData.

using RemoteValidation.Models;  
using System.Collections.Generic;  
 
namespace RemoteValidation.Code   
{  
    public static class StaticData   
    {  
        public static List < UserViewModel > UserList   
        {  
            get {  
                return new List < UserViewModel >   
                {  
                    new UserViewModel   
                    {  
                        UserName = "User1", Email = "[email protected]"  
                    },  
                    new UserViewModel   
                    {  
                        UserName = "User2", Email = "[email protected]"  
                    }  
                }  
            }  
        }  
    }  

 

Now we create a controller "ValidationController" in which we create an action method to check whether a user name exists or not and return a result as a JSON format. If the username exists then it returns false so that the validation is implemented on the input field. The following code snippet shows ValidationController under the Controllers folder.

using RemoteValidation.Code;  
using System.Linq;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class ValidationController: Controller   
    {  
        [HttpGet]  
        public JsonResult IsUserNameExist(string userName)   
        {  
            bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower())).FirstOrDefault() != null;  
            return Json(!isExist, JsonRequestBehavior.AllowGet);  
        }  
    }  
}

 

Now we add remote validation on the UserName of the UserViewModel property as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  

 

As in the preceding code snippet, the IsUserNameExist is a method of ValidationController that is called on the blur of an input field using a GET request. Now we create UserController under the Controllers folder to render a view on the UI.

using RemoteValidation.Models;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class UserController: Controller   
    {  
        [HttpGet]  
        public ActionResult AddUser()   
        {  
            UserViewModel model = new UserViewModel();  
            return View(model);  
        }  
    }  

Now we add jquery.validate.js and jquery.validate.unobtrusive.js to the project and create a bundle as in the following code snippet.

using System.Web.Optimization;  
 
namespace RemoteValidation.App_Start   
{  
    public class BundleConfig   
    {  
        public static void RegisterBundles(BundleCollection bundles)   
        {  
            bundles.Add(new StyleBundle("~/Content/css").Include(  
                "~/Content/css/bootstrap.css",  
                "~/Content/css/font-awesome.css",  
                "~/Content/css/site.css"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
                "~/Scripts/jquery-{version}.js"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
                "~/Scripts/jquery.validate*"));  
        }  
    }  

Thereafter we add the following keys in the web.config file.

<add key="ClientValidationEnabled" value="true" />   
<add key="UnobtrusiveJavaScriptEnabled" value="true" />  
 
 

Thereafter we create a view for the AddUser action method. The following code snippet is for the AddUser view.

@model RemoteValidation.Models.UserViewModel  
 
< div class = "panel panel-primary" > < div class = "panel-heading panel-head" > Add User < /div>    
    <div class="panel-body">    
        @using (Html.BeginForm())    
        {    
            <div class="form-horizontal">    
                <div class="form-group">    
                    @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.UserName)    
                    </div > < /div>    
                <div class="form-group">    
                    @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.Email)    
                    </div > < /div>                    
                <div class="form-group">    
                    <div class="col-lg-9"></div > < div class = "col-lg-3" > < button class = "btn btn-success"  
                     id = "btnSubmit"  
                     type = "submit" > Submit < /button>    
                    </div >
               < /div>    
            </div >  
} < /div>    
</div >   
@section scripts   
{  
    @Scripts.Render("~/bundles/jqueryval")  

Let's run the application and put values into the user name field to execute the remote validation as in the following image.

Figure 1: Remote validation on user name


Now we move to another option, we pass an additional parameter in the remote validation. We pass both the user name and email as a parameter and check whether the username and email combination exist or not on the email input. That's why we add one more method in ValidationController as in the following code snippet for it.

[HttpGet]  
public JsonResult IsUserExist(string email, string userName)   
{  
    bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower()) && u.Email.ToLowerInvariant().Equals(email.ToLower())).FirstOrDefault() != null;  
    return Json(!isExist, JsonRequestBehavior.AllowGet);  

Now we call this method on the Email property of UserViewModel as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        [Remote("IsUserExist", "Validation", ErrorMessage = "User already exist", AdditionalFields = "UserName")]  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

As in the preceding code snippet, we are passing an additional field using AdditionalFields in Remote. If we must pass more than one parameter then these will be comma-separated. Now run the application and the result will be as shown in the following image.  



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