Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET Hosting - ASPHostPortal.com :: How To Configuring your .NET application to use the ASP.NET Session State Store Provider

clock June 27, 2016 19:55 by author Armend

How To Configuring your .NET application to use the ASP.NET Session State Store Provider

In this post I will show you how to configure the ASP.NET session state store provider, you must update the web.config file for the ASP.NET application to include the ASP.NET session state store provider and its configuration.

Before you begin

  • Configure a data grid to store ASP.NET HTTP session state.
  • You must have the catalog server host and port.

Procedure

Update the web.config file of your ASP.NET application with settings for the ASP.NET session state store provider. You must update or add the text in bold in the following example to the web.config file

<system.web>
    …
    <sessionState
        mode="Custom"
        customProvider="WxsSessionStateStoreProvider">
        <providers>
                <add
                     name="WxsSessionStateStoreProvider"
                    type="IBM.WebSphere.Caching.SessionStateStore.WxsSessionStateStore,
                        IBM.WebSphere.Caching, Version=8.6.0.2000, Culture=neutral,
                        PublicKeyToken=b439a24ee43b0816"
                    wxsPropertyFile="\optional\path\to\NET-client.properties"
                    wxsHostAndPort="optionalHostAndPort"
                    wxsGridName="session"
                    wxsMapName="ASPNET.SessionState"
         />          
        </providers>
        </sessionState>
    …
</system.web>

wxsPropertyFile (optional)Specifies the fully qualified properties file that the provider uses when it connects to the data grid with the Connect API. If this attribute is not specified or is an empty string, the provider looks for the Client.Net.properties file in the current runtime directory of the web application process. If the provider does not find the file in the runtime directory, it looks for the Client.Net.properties file in the net_client_home\config directory.wxsHostAndPort (optional)Specifies a comma-separated list of catalog server host and port pairs to which the session state store provider connects when it accesses the data grid. The format follows:

<host name or host ip address>:<tcp port>[,<host name or host ip address>:<tcp port>]

If no value is specified, localhost:2809 is used.

wxsGridName (optional)

Specifies the name of the data grid to which the ASP.NET session store provider connects. If you created a data grid for ASP.NET session states, specify the data grid name that you created. If you do not specify a value, the provider connects to the session data grid.

wxsMapName (optional)

Specifies the map to which the provider connects. If you do not specify a value, the provider connects to the ASPNET.SessionState map.

  • Restart the target web application. The web application must restart so that the provider can be loaded by IIS. In most cases, after the web.config file is modified and current HTTP request processing is complete, the restart occurs automatically.

Results

ASP.NET session state from your ASP.NET application is stored in the data grid.



ASP.NET Hosting - ASPHostPortal.com :: How to Bind Data to a Label From a SqlDataSource

clock April 25, 2016 21:24 by author Dan

Label controls in ASP.NET don't have a smart tag that allows you to select a data source, so at first glance, it is not easy to see how to bind a value returned from a SqlDataSource or AccessDataSource control to the label. Here's how to programmatically access the data returned by such a DataSource and apply it to a non-databound control.

To programmatically access the contents of a SqlDataSource or AccessDataSource control you need to explicitly call its Select() method. This method accepts a single input parameter of type DataSourceSelectArguments. This parameter can contain information regarding the filters to apply or the column to Order By. For example, when working with a sortable GridView, sorting a column calls the Select() method, and passes in a DataSourceSelectArguments instance with its SortExpression property set to the column name the user chose to sort by. If you don't want the DataSource to sort or filter, you pass in DataSourceSelectArguments.Empty.

Depending on the DataSourceMode of the DataSource control, one of two objects are returned when the Select() method is called. If the DataSourceMode is set to DataReader, a DataReader object is returned. The type of DataReader (SqlDataReader, OleDbDataReader, OdbcDataReader etc) that is returned depends entirely on the provider type used - in other words, whether you are using the OleDb provider, SqlClient provider etc. It has nothing to do with the type of DataSource control. The examples below both query an Access database, but one uses the AccessDataSource control, and the other uses the SqlDataSource control. Both return OleDbDataReaders, because it is the OleDbProvider library that is used for the connection.

If the DataSourceMode is set to Dataset, or not set at all (which means that the default setting of Dataset is used) the object that is returned is a DataView. A DataView is like a DataTable on steroids. It exposes methods that allow you to filter and sort data, for example, and bind it. A DataView contains a collection of DataRowView objects, which represent each row in the returned results.

So, with a DataReader, you would access the values during the DataReader.Read() operation, in very much the same way as if you are using plain ADO.NET code, whereas with the DataSet, you would need to create an object of the appropriate type - DataView, then iterate the DataRowView collection to access the values. In this, the code is remarkably similar to accessing values directly from a DataSet's table collection using plain ADO.NET.

The code below shows the contents of an aspx file, which contains two label controls, and two SqlDataSource controls. Each SqlDataSource control has its DataSource mode set to alternative values - DataSet and DataReader, and both of them have an OnSelecting event defined in which the value of the EmployeeID parameter is assigned:

<asp:Label ID="Label1" runat="server" /> <asp:Label ID="Label2" runat="server" />

<asp:SqlDataSource
    ID="SqlDataSource1"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataSet"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource1_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

<asp:SqlDataSource
    ID="SqlDataSource2"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataReader"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource2_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>


The following code snippet shows the aspx.cs file contents, where the parameter values are set in the Selecting event handler. In the Page_Load method, the data returned by each of the Sql DataSource controls is accessed and a value consigned to a label. The method of access depends on the DataSource mode, but is identical for both SqlDataSource and AccessDataSource:

[C#]
protected void Page_Load(object sender, EventArgs e)
{

    DataView dvSql = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    foreach (DataRowView drvSql in dvSql)
    {
        Label1.Text = drvSql["FirstName"].ToString();
    }

    OleDbDataReader rdrSql = (OleDbDataReader)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
    while (rdrSql.Read())
    {
        Label2.Text = rdrSql["LastName"].ToString();

    }
    rdrSql.Close();
}



protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

[VB]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

Dim dvSql As DataView =
    DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
    For Each drvSql As DataRowView In dvSql
        Label1.Text = drvSql("FirstName").ToString()
    Next

Dim rdrSql As OleDbDataReader =
    DirectCast(SqlDataSource2.Select(DataSourceSelectArguments.Empty), OleDbDataReader)
    While rdrSql.Read()

        Label2.Text = rdrSql("LastName").ToString()
    End While
    rdrSql.Close()
End Sub

Protected Sub SqlDataSource1_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub

Protected Sub SqlDataSource2_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub


When using this technique with Sql Server - or more specifically the SqlClient provider, change OleDbDataReader to SqlDataReader in the above code. Happy Coding.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our 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 Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to solve page html getting wrongly appended to file being downloaded

clock April 18, 2016 21:24 by author Dan

Today while writing a small web application where I needed to download a datatable as csv file. I faced issue of page html getting wrongly appended to file being downloaded. I was using Response.Write to download file on client machine.

Solution to my problem was easy, I just needed to add an extra line telling content-length. Below is method that I finally ended up using.

        private void DownloadDataAsCsv(DataTable dt)
        {
            string tab = "";
            StringBuilder sb = new StringBuilder();
            foreach (DataColumn dc in dt.Columns)
            {
                sb.Append(tab + dc.ColumnName);
                tab = ",";
            }
            sb.Append("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(tab + dr[i].ToString());
                    tab = ",";
                }
                sb.Append("\n");
            }
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition", "attachment; filename=Export.csv");
            Response.AddHeader("Content-Length", sb.ToString().Length.ToString());
            Response.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our 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 Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Prevent ASP.NET Website From Multiple Database Request

clock October 26, 2015 20:44 by author Dan

It is not good to execute multiple db request for loading single page.  Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database.

In order to improve performance you should execute single stored proc and bring multiple resultset in to single db request.  In this article i will explain you how to avoid multiple database request and how to bring multiple resultset into single db request.

Consider a scenario of loading a Product Page, which displays

  • Product Information and
  • Product Review Information

In order to bring 2 database request in single db request, your sql server stored proc should be declared as below.

SQL Server Stored Proc

CREATE PROCEDURE GetProductDetails
 @ProductId bigint,
AS
SET NOCOUNT ON

--Product Information
Select ProductId,
 ProductName,
 ProductImage,
 Description,
 Price
From Product
Where ProductId = @ProductId

--Product Review Information
Select  ReviewerName,
 ReviewDesc,
 ReviewDate
From ProductReview
Where ProductId = @ProductId

Asp.net, C# Code to bring multiple db request into single db request

Code Inside Data Access Class Library (DAL)

public DataSet GetProductDetails()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "GetProductDetails";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataSet dsResultSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);

try
{
    var conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"];
    string strConnString = conString.ConnectionString;
    SqlConnection conn = new SqlConnection(strConnString);

    cmdToExecute.Connection = conn;

    cmdToExecute.Parameters.Add(new SqlParameter("@ ProductId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _productId));

    //Open Connection
    conn.Open();

    // Assign proper name to multiple table
    adapter.TableMappings.Add("Table", "ProductInfo");
    adapter.TableMappings.Add("Table1", "ProductReviewInfo");
    adapter.Fill(dsResultSet);

    return dsResultSet;             
}
catch (Exception ex)
{
    // some error occured.
    throw new Exception("DB Request error.", ex);
}
finally
{
    conn.Close();
    cmdToExecute.Dispose();
    adapter.Dispose();
}
}

Code Inside Asp.net .aspx.cs page

protected void Page_Load(object sender, EventArgs e)
{
   if (Request.QueryString[ProductId] != null)
   {
      long ProductId = Convert.ToInt64(Request.QueryString[ProductId].ToString()); 
  
      DataSet dsData = new DataSet();

      //Assuming you have Product class in DAL
      ProductInfo objProduct = new ProductInfo();
      objProduct.ProductId = ProductId;
      dsData = objProduct.GetProductDetails();

      DataTable dtProductInfo = dsData.Tables["ProductInfo"];
      DataTable dtProductReviews = dsData.Tables["ProductReviewInfo"];

      //Now you have data table containing information
      //Make necessary assignment to controls
      .....
      .....
      .....
      .....
      ..... 

    }
}


Finish, Happy coding.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our 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 Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com : Paging with ASP.NET Web API OData

clock October 20, 2015 08:58 by author Kenny

Paging with ASP.NET Web API OData

What is OData?

OData, short for Open Data Protocol, defines a protocol for the querying and updating of data utilizing existing Web protocols. OData is a REST-based protocol for querying and updating data and is built on standardized technologies such as HTTP, Atom/XML, and JSON. It is different from other REST-based web services in that it provides a uniform way to describe both the data and the data model. It is considered to be a flexible technology for enabling interoperability between disparate data sources, applications, services and clients.

Step by Step

When the API call returns the list of repositories in the body of the response as a JSON array:

[
  {
    "id": 1234,
    "name": "domain.com",
    "full_name": "user/domain.com",
    ...
  },
  {
    "id": 1111,
    "name": "test",
    "full_name": "user/test",
    ...
  }
]

It does not state the total number of records anywhere in the resulting JSON, not does it return the current page or the number of records per page which you requested. What it does however is to return the pagination information in the Link header of the request. So in the case of my API call above it returns the following Link header:

Link: <https://api.github.com/user/repos?page=5&per_page=2>; rel="next",
      <https://api.github.com/user/repos?page=8&per_page=2>; rel="last",
      <https://api.github.com/user/repos?page=1&per_page=2>; rel="first",
      <https://api.github.com/user/repos?page=3&per_page=2>; rel="prev"

So it allows you to request subsequent pages by requesting the URL in the Link header with the relation type (rel parameter value) of “next”. Also to get the total number of pages you will need to extract the page query parameter from the link with the relation type of last.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our 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 Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com : Dynamically Create Meta Description Using ASP.NET

clock October 13, 2015 08:37 by author Kenny

Dynamically Create Meta Description Using ASP.NET

HTML “meta description” allows us to describe web pages with short and sometimes elaborated details. Descriptions written inside the <meta> tag, must always to specific and are often limited to very few characters. Using Asp.Net, we can easily create “meta” descriptions dynamically, through code behind procedures, describing the contents of the page.

We all know how important it is to use meta tags when you’re building an internet web site. Meta tags provide metadata about the HTML document. They are not rendered in the browser but are used by search engines to parse web pages. The following article demonstrates how to store meta tags for each page in an XML file and how to use LINQ to read the XML data and dynamically create meta tags for each page in your website.

Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.

Add a Master Page to the project. Once that is completed, add a Web Content Page and select the newly created Master Page as the Master Page.

The next step is to create a new folder in the web site to demonstrate all pages in the website will have dynamic meta tags at runtime. Right click the website and choose Add > New Folder. Name the new folder ChildFolder. After this add a new Web Content Page to this folder. Leave the default name as this is not important.

Now that we have two pages in different folders, it’s now time to create an XML file that contains the data for the meta tags. Right click the website and choose Add > New Item > XML File. Name the file TagData.xml and add the following XML:

<metaTags>
 <tags pageName="/WebForm1.aspx">
    <tag name="keyword" value="This is a keyword"></tag>
    <tag name="description" value="This is a description"></tag>
    <tag name="author" value="malcolm sheridan"></tag>
 </tags>
 <tags pageName="/ChildFolder/WebForm1.aspx">
    <tag name="keyword" value="This is a keyword for the child pages"></tag>
    <tag name="description" value="This is a description for the child pages"></tag>
    <tag name="author" value="malcolm sheridan for this page too"></tag>
 </tags>
</metaTags>

In the XML above I have created a parent node called metaTags. Inside I have created a tags node which contains a pageName attribute. That value is how we will match the current requested page to the XML data. Each tags node contains a tag node that corresponds to the meta data we want sent to the browser. In this example I want to set meta tags for the all the pages to have keyword, description and author meta tags, but the values rendered to the browser will differ depending on what page the user is on. In a real world scenario this information would be stored inside a database, but I decided to keep this data inside an XML file to keep it simple and focus on how to do this.

Having outlined what meta tags we want sent to the browser, we now have to write the code that will read the XML file and dynamically add the meta tags at runtime. Seeing as though we’re using Master Pages this is the ideal spot to add it. Add the following code to read the XML file:

C#

XDocument doc = XDocument.Load(Server.MapPath("~/TagData.xml"));
var metaTags = doc.Descendants("tag")
              .Where(o => o.Parent.Attribute("pageName").Value == Request.Url.AbsolutePath)
               .Select(o => new
               {
                    Value = o.Attribute("value").Value,
                    Name = o.Attribute("name").Value
               });

VB.NET

Dim doc As XDocument = XDocument.Load(Server.MapPath("~/TagData.xml"))
Dim metaTags = doc.Descendants("tag").Where(Function(o) o.Parent.Attribute("pageName").Value = Request.Url.AbsolutePath).Select(Function(o) New With {Key .Value = o.Attribute("value").Value, Key .Name = o.Attribute("name").Value})

For flexibility and ease of use I have decided to use the power of LINQ to XML to read the XML data. To start with the XML document is load into an XDocument object. From there I have created a LINQ query to return all the tag nodes where the parent node has an attribute called pageName and the value is equal to the current page.   Then the object returned is an anonymous type that has a Value and Name property. The values of those properties are the value and name attribute values.

Now that we have the data in memory, the next step is to create the meta tag and add it to the page dynamically. To do this you use the HtmlMeta class. This allows you programmatic access to the HTML meta tags. Add the following code below to your project:

C#

foreach (var item in metaTags)
{              
     HtmlMeta meta = new HtmlMeta();
     meta.Name = item.Name;
     meta.Content = item.Value;
     Page.Header.Controls.Add(meta);
}

VB.NET

For Each item In metaTags
       Dim meta As New HtmlMeta()
       meta.Name = item.Name
       meta.Content = item.Value
       Page.Header.Controls.Add(meta)
Next item

The foreach loop enumerates through each item returned from the LINQ query. It assigns the Name and Content value to the HtmlMeta object. Finally the object is added to the page by calling Page.Header.Controls.Add(meta). Run the project and once the default page has loaded, view the HTML source and you’ll see the meta tags have been added to the website.

MetaTags

Browsing to the second page and viewing the HTML source, you’ll find the meta tags have been added to the page but they’re different values from the previous page.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our 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 Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Remove Html Tags from a String in ASP.NET

clock October 12, 2015 07:47 by author Dan

When we update content using WYSIWYG HTML editor (ck-editor) then it used HTML tag for formatting the content. But some time we need the same content without any formatting so then we require the removing HTML tag from that content.

Here I use two variation for this first one is using a simple loop And Second one is using Regex.

// How convert a html tag to blank space in a string using c#.net/asp.net code
// Replacing the html tag <> to blank space, you can copy data with html tag and then convert to normal text
// eg. INPUT   -->  <div width="5">Testing <i>Testing</i></div>
        OUTPUT--> Testing Testing
//
//C#.NET , ASP.NET

Method 1 : (Using Character Array)

 public string replace(string s)
 {
    int l = s.Length;
    int j = 0;
    char[] ch = s.ToCharArray();
    s = "";
    for (int i = 0; i < l; i++)
    {
        if (ch[i] == '<')
            j = 1;
        if (j == 1)
        {
            if (ch[i] == '>')
                j = 0;
            ch[i] = ' ';
        }
        s = s + ch[i].ToString();
    }
    return (s);
 }

Method 2 (Using Regular Expressions- Regex)

 using System.Text.RegularExpressions;
 public string replace(string s)
 {
   String result = Regex.Replace(s, @"<[^>]*>", String.Empty);
 }

Finish.. Happy Codiing..

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our 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 Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET 5 Hosting - ASPHostPortal :: How To Configuration in ASP.NET 5

clock September 21, 2015 11:33 by author Kenny

How To Configuration in ASP.NET 5

Goodbye XML, Hello JSON

In the past, ASP.NET has been built on a foundation of XML. Web Forms .aspx and .ascx files are basically XML files and configuration in previous versions of ASP.NET is managed in an XML file called web.config. The web.config file has a particular structure and a class (System.Web.Configuration.WebConfigurationManager) devoted to providing access to it. In ASP.NET 5 JSON is the preferred format for storing structured information such as configuration. This change has largely been driven, I suspect, by the desire to appeal to web developers working on other platforms who are more used to JSON as a structured data format. The first article in this series has already looked at the new JSON solution and project files: global.json and project.json.

The default replacement for the web.config file is config.json. You can also choose to use an XML file if you prefer, and INI files, environment variables, command line arguments and an in-memory option are supported natively too. The template for a config.json file is labelled as ASP.NET Configuration File in the Add New Item dialog:

When you add one, the templated content provides a placeholder for a connection string:

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
        }
    }
}

Strongly Typed AppSettings

In earlier versions of ASP.NET, it is quite common to store application-wide constants in the appSettings section of a web.config file. You can store these values in the config.json file instead. Previous Beta release templates included an example of this, but it has been removed from the Beta 6 template. The steps described below demonstrate how to use the config.json file to store appsettings and how to provide strongly-typed access to them.

Add the highlighted code to the config.json file:

{
    "AppSettings" : {
        "SiteTitle" :  "My Web Site"
    },
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
        }
    }
}

Right click on the Properties node in Solution Explorer (depicted by a wrench icon) and select Add » New Item.

Add a C# class file named AppSettings.cs and replace its default content with the following:

namespace WebApplication2
{
    public class AppSettings
    {
        public string SiteTitle { get; set; }
    }
}

Change the dependencies section in project.json to include the highlighted lines below

  "dependencies": {
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
    "Microsoft.AspNet.Mvc": "6.0.0-beta6",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta6"
  },

Make the following highlighted changes to Startup.cs:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.Runtime;

namespace WebApplication2
{
    public class Startup
    {
        public IConfiguration Configuration { get; set; }

        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
                .AddJsonFile("config.json");
            Configuration = builder.Build();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            var appSettings = app.ApplicationServices.GetService<IOptions<AppSettings>>();
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(appSettings.Options.SiteTitle);
            });
        }
    }
}

Press Ctrl+F5 to run the application without debugging. You should see "My Web Site" written to the browser.

You started by adding a new section called AppSettings to the config.json file and declaring a property with a value. Then you created a C# class called AppSettings with one property that matches the one you added to the config file. The AppSettings class is designed to provide strongly typed access to the appSettings section of the config.json file. You added a couple of packages to the project.json file to make them available to the application. The first package enables you to use JSON as the format for your configuration data. The second package introduces MVC into the application.

In the Startup class, you added a constructor where you instantiated a variable representing the project's configuration as the config.json file and assigned that to a property that you created of type IConfiguration. This holds the values loaded from the configuration source (the config.json file). You made the AppSettings available to the application by registering it with the dependency injection system in the ConfigureServices method. The method you used mapped the json values from the configuration file to the AppSettings class. You also registered the MVC framework with the dependency injection system. Finally, you used the GetService<T> extension method to retrieve the AppSettings from the DI system in the Startup class'sConfigure method where you used them to write the SiteTitle value to the browser.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our 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 Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET MVC 6 Hosting - ASPHostPortal :: Bootstrap Tree View in ASP.Net MVC

clock August 24, 2015 07:42 by author Kenny

Bootstrap Tree View in ASP.Net MVC

The ASP.NET MVC is an almost open source web application framework that implements the model–view–controller (MVC) pattern. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NETfeatures, such as master pages and membership-based authentication. Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites.

We create two classes, one is AuthorViewModel and another is BookViewModel. AuthorViewModel is the main class that has an association with the BookViewModel class. In other words each AuthorViewModel class object has a list of BookViewModel class objects. The following is the code snippet for the BookViewModel class. 

namespace TreeView.Models   
{  
    public class BookViewModel   
    {  
        public long Id   
        {  
            get;  
            set;  
        }  
        public string Title   
        {  
            get;  
            set;  
        }  
        public bool IsWritten   
        {  
            get;  
            set;  
        }  
    }  
}  

The following is the code snippet for the AuthorViewModel class.

using System.Collections.Generic;  
 
namespace TreeView.Models {  
    public class AuthorViewModel   
    {  
        public AuthorViewModel()   
        {  
            BookViewModel = new List < BookViewModel > ();  
        }  
        public int Id   
        {  
            get;  
            set;  
        }  
        public string Name   
        {  
            get;  
            set;  
        }  
        public bool IsAuthor   
        {  
            get;  
            set;  
        }  
        public IList < BookViewModel > BookViewModel   
        {  
            get;  
            set;  
        }  
    }  
}

Now we create a controller “HomeController” that has two action methods for both GET and POST requests. The action method's name is “Index”. The Get request action method returns a tree view in the UI whereas the POST request method gets the posted data from the UI. The following is the code snippet for HomeController.

using System.Collections.Generic;  
using System.Linq;  
using System.Web.Mvc;  
using TreeView.Models;  
 
namespace TreeView.Controllers  
{  
    public class HomeController : Controller  
    {  
        [HttpGet]  
        public ActionResult Index()  
        {  
            List<AuthorViewModel> model = new List<AuthorViewModel>();  
 
            AuthorViewModel firstAuthor = new AuthorViewModel  
            {  
                Id = 1,  
                Name = "User1",  
                BookViewModel = new List<BookViewModel>{  
                    new BookViewModel{  
                        Id=1,  
                        Title = "JQuery",  
                        IsWritten = false  
                    }, new BookViewModel{  
                        Id=1,  
                        Title = "JavaScript",  
                        IsWritten = false  
                    }  
                }  
            };  
 
            AuthorViewModel secondAuthor = new AuthorViewModel  
            {  
                Id = 2,  
                Name = "User2",  
                BookViewModel = new List<BookViewModel>{  
                    new BookViewModel{  
                        Id=3,  
                        Title = "C#",  
                        IsWritten = false  
                    }, new BookViewModel{  
                        Id=4,  
                        Title = "Entity Framework",  
                        IsWritten = false  
                    }  
                }  
            };  
            model.Add(firstAuthor);  
            model.Add(secondAuthor);  
            return View("Index", model);  
        }  
 
        [HttpPost]  
        public ActionResult Index(List<AuthorViewModel> model)  
        {  
            List<AuthorViewModel> selectedAuthors = model.Where(a => a.IsAuthor).ToList();  
            List<BookViewModel> selectedBooks = model.Where(a => a.IsAuthor)  
                                                .SelectMany(a => a.BookViewModel.Where(b => b.IsWritten)).ToList();  
            return View();  
        }  
    }  

The preceding code shows how books are associated with an author in the GET action method and how to get a selected tree node (authors and books) in the POST request. 

Bootstrap CSS is already added to the application but we write a new custom CSS for the tree view design. The following is the code snippet for the tree CSS.

.tree li {  
    margin: 0px 0;    
    list-style-type: none;  
    position: relative;  
    padding: 20px 5px 0px 5px;  
}  
 
.tree li::before{  
    content: '';  
    position: absolute;   
    top: 0;  
    width: 1px;   
    height: 100%;  
    right: auto;   
    left: -20px;  
    border-left: 1px solid #ccc;  
    bottom: 50px;  
}  
.tree li::after{  
    content: '';  
    position: absolute;   
    top: 30px;   
    width: 25px;   
    height: 20px;  
    right: auto;   
    left: -20px;  
    border-top: 1px solid #ccc;  
}  
.tree li a{  
    display: inline-block;  
    border: 1px solid #ccc;  
    padding: 5px 10px;  
    text-decoration: none;  
    color: #666;      
    font-family: 'Open Sans',sans-serif;  
    font-size: 14px;  
    font-weight :600;  
    border-radius: 5px;  
    -webkit-border-radius: 5px;  
    -moz-border-radius: 5px;  
}  
 
/*Remove connectors before root*/  
.tree > ul > li::before, .tree > ul > li::after{  
    border: 0;  
}  
/*Remove connectors after last child*/  
.tree li:last-child::before{   
      height: 30px;  
}  
 
/*Time for some hover effects*/  
/*We will apply the hover effect the the lineage of the element also*/  
.tree li a:hover, .tree li a:hover+ul li a {  
    background: #dd4814; color: #ffffff; border: 1px solid #dd4814;  
}  
/*Connector styles on hover*/  
.tree li a:hover+ul li::after,   
.tree li a:hover+ul li::before,   
.tree li a:hover+ul::before,   
.tree li a:hover+ul ul::before{  
    border-color:  #dd4814;  
}  
.tree-checkbox{  
    margin :4px !important;  
}  
 
   
.tree:before {  
    border-left:  1px solid #ccc;  
    bottom: 16px;  
    content: "";  
    display: block;  
    left: 0;  
    position: absolute;  
    top: -21px;  
    width: 1px;  
    z-index: 1;  
}  
 
.tree ul:after {  
    border-top: 1px solid #ccc;  
    content: "";  
    height: 20px;  
    left: -29px;  
    position: absolute;  
    right: auto;  
    top: 37px;  
    width: 34px;  
}  
*:before, *:after {  
    box-sizing: border-box;  
}  
*:before, *:after {  
    box-sizing: border-box;  
}  
.tree {  
    overflow: auto;  
    padding-left: 0px;  
    position: relative;  

Now we create an Index view that renders in the browser and shows the tree view for the author and book. The following is the code snippet for the Index view.

@model List  
<TreeView.Models.AuthorViewModel>  
@section head{  
@Styles.Render("~/Content/css/tree.css")  
}  
    <div class="panel panel-primary">  
        <div class="panel-heading panel-head">Author Book Tree View</div>  
        <div id="frm-author" class="panel-body">  
@using (Html.BeginForm())  
{  
            <div class="tree">  
@for (int i = 0; i < Model.Count(); i++)  
{  
                <ul>  
                    <li>  
                        <a href="#">  
@Html.CheckBoxFor(model => model[i].IsAuthor, new { @class = "tree-checkbox parent", @id = @Model[i].Id })  
                            <label [email protected]>  
                                <strong>Author:</strong>  
@Html.DisplayFor(model => model[i].Name)  
                            </label>  
                        </a>  
                        <ul>  
@for (int j = 0; j < Model[i].BookViewModel.Count(); j++)  
{  
int k = 1 + j;  
@Html.HiddenFor(model => model[i].BookViewModel[j].Id)  
                            <li>  
                                <a href="#">  
@Html.CheckBoxFor(model => model[i].BookViewModel[j].IsWritten, new { @class = "tree-checkbox node-item", @iid = i + "" + j })  
                                    <label [email protected]@j>  
                                        <strong>Book @(k):</strong> @Html.DisplayFor(model => model[i].BookViewModel[j].Title)  
                                    </label>  
                                </a>  
                            </li>  
}  
                        </ul>  
                    </li>  
                </ul>  
}  
            </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>  
@section scripts{  
@Scripts.Render("~/Scripts/tree.js")  

Thereafter we create an important part of this example. We create the JavaScript file tree.js with the following code.

(function($)   
{  
    function Tree() {  
        var $this = this;  
        function treeNodeClick()   
        {  
            $(document).on('click', '.tree li a input[type="checkbox"]', function() {  
                $(this).closest('li').find('ul input[type="checkbox"]').prop('checked', $(this).is(':checked'));  
            }).on('click', '.node-item', function() {  
                var parentNode = $(this).parents('.tree ul');  
                if ($(this).is(':checked')) {  
                    parentNode.find('li a .parent').prop('checked', true);  
                } else {  
                    var elements = parentNode.find('ul input[type="checkbox"]:checked');  
                    if (elements.length == 0) {  
                        parentNode.find('li a .parent').prop('checked', false);  
                    }  
                }  
            });  
        };  
        $this.init = function() {  
            treeNodeClick();  
        }  
    }  
    $(function() {  
        var self = new Tree();  
        self.init();  
    })  
}(jQuery)) 

As in the preceding JavaScript code, the create tree view has the following features.

  1. When we select an author parent node then all the associated books will be selected.
  2. When a book is selected the associated parent author will be selected automatically.
  3. When all child book nodes are selected for a parent author node then the parent node will be selected.
  4. When the parent node is unselected then the child books will be automatically unselected.

Figure 1 shows the parent child (author-book) tree view.



Cheap SQL SSRS 2014 Hosting :: How to Configure Available Memory for SQL Server Reporting Services 2014

clock July 18, 2014 07:35 by author Ben

Reporting Services is a server-based reporting platform that provides comprehensive reporting functionality for a variety of data sources. Reporting Services includes a complete set of tools for you to create, manage, and deliver reports, and APIs that enables developers to integrate or extend data and report processing in custom applications. Reporting Services tools work within the Microsoft Visual Studio environment and are fully integrated with SQL Server tools and components.

Today we're going to cover how to configure available memory for SQL Server Reporting Services 2014. If you need to configure the amount of memory available to an instance of SSRS 2014 you have to get your hands dirty and edit the RsReportServer.config file. The RsReportServer.config file stores settings that are used by Report Manager, the Report Server Web service, and background processing.

The location of the rsconfile file is generally:

\Program Files\Microsoft SQL Server\MSRS1111.MSSQLSERVER\Reporting Services\ReportServer

Within the RsReportServer.config file, configuration settings that control memory allocation for the report server include WorkingSetMaximum, WorkingSetMinimum, MemorySafetyMargin, and MemoryThreshold. If you were to open the file you will see that the WorkingSetMinimum and WorkingSetMaximum are not present by default.

<Service>
 <IsSchedulingService>True</IsSchedulingService>
   <IsNotificationService>True</IsNotificationService>
     <IsEventService>True</IsEventService>
       <PollingInterval>10</PollingInterval>
         <WindowsServiceUseFileShareStorage>False</WindowsServiceUseFileShareStorage>
           <MemorySafetyMargin>80</MemorySafetyMargin>
         <MemoryThreshold>90</MemoryThreshold>
       <RecycleTime>720</RecycleTime>
    <MaxAppDomainUnloadTime>30</MaxAppDomainUnloadTime>
 <MaxQueueThreads>0</MaxQueueThreads>


This is because you have to enter them yourself, as if you are hosting multiple applications on the same computer and you determine that the report server is using a disproportionate amount of system resources relative to other applications on the same computer.

<Service>
  <IsSchedulingService>True</IsSchedulingService>
    <IsNotificationService>True</IsNotificationService>
      <IsEventService>True</IsEventService>
        <PollingInterval>10</PollingInterval>
          <WindowsServiceUseFileShareStorage>False</WindowsServiceUseFileShareStorage>
        <MemorySafetyMargin>80</MemorySafetyMargin>
      <MemoryThreshold>90</MemoryThreshold>
    <RecycleTime>720</RecycleTime>
 <WorkingSetMaximum>786432</WorkingSetMaximum>
<WorkingSetMinimum>524288</WorkingSetMinimum>
 <MaxAppDomainUnloadTime>30</MaxAppDomainUnloadTime>
   <MaxQueueThreads>0</MaxQueueThreads>


The Reasons To Use SQL Reporting Service (SSRS) 2014 Hosting with ASPHostPortal.com

  • Fully Integrated with SharePoint
  • The report development environment is a Standard Microsoft Platform - SSRS Reports are developed in BIDS (Business Intelligence Development Studio).
  • Customizable Report Rendering - SSRS provides a .NET Web Service programmatically accessible to extend the delivery of reports beyond the browser. The SSRS reports can be rendered to HTML. PDF(Portable Document Format), Microsoft Excel, XML, MHTML (MIME HTML), TIFF (Tagged Image File Format). Microsoft Word, and ATOM. The SSRS .NET Web Service allows embedding reports in custom applications where the look and feel of the report viewer can be easily controlled and customized.
  • Mobile Support - Starting SQL Server 2012 Service Pack 1 (SP1), SSRS supports viewing and basic interactivity with reports on Microsoft Surface devices and devices with Apple iOS6 and Apple Safari Browser such as iPAD. SSRS reports can also be view on Windows 8 devices.


About ASPHostPortal.com

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

Sign in