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 :: How to Running Scripts Pre and Post Publish in ASP.NET Core RC2

clock August 30, 2016 20:10 by author Armend

Running Scripts Pre and Post Publish in ASP.NET Core RC2

This week I ran into an issue when deploying a Service Fabric service where a library file was not being copied to the output directory. Since I am using ASP.NET Core for my API layer in the Service Fabric project, I had to go dig around to figure out how to get the file to copy to the deployment folder during the publishing of the ASP.NET Core application.

"note that this solution with project.json may change with as ASP.NET Core moves back to .csproj file".

What I learned is that in ASP.NET Core RC 2 you can add scripts to the prepublish and postpublish events by adding a scripts section to the project.json file. In my case I needed to copy a file to the deployment folder after the rest of the project as built.

{
  "buildOptions": {
       // ...
    }
  },
  //...

  "scripts": {
    "prepublish": ["<command1>, <command2>"],
    "postpublish": [ "xcopy <pathtofile> %publish:OutputPath%" ]
  }
}

Note that you can reference variables like %publish:OutputPath%. You can also supply multiple commands by separating them with a comma. As noted above this currently works in ASP.NET Core RC2 but might change when as we transition back to the .csproj file.

Best ASP.NET Hosting Recommendation

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



ASP.NET Hosting - ASPHostPortal.com :: Tips 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 :: How To Migrate Entity Framework Core for Class Library

clock August 9, 2016 18:41 by author Armend

How To Migrate Entity Framework Core for Class Library

In this post I will show you how to migrate EF core for class library projects. We need to pretend our class library is actually a .NET Core app. The trickery begins by updating our class library’s project.json with the following updates:

"buildOptions": {
        "emitEntryPoint": true
    },
    "frameworks": {
        "netcoreapp1.0": { }
    },
    "dependencies": {
        "Microsoft.NETCore.App": {
            "version": "1.0.0",
            "type": "platform"
        },
        "Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final",
        "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
        "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    },
    "tools": {
        "Microsoft.EntityFrameworkCore.Tools": {
            "version": "1.0.0-preview2-final"
        }
    }

The most important parts are the build options at the root level, the Microsoft.EntityFrameworkCore.Design package and theMicrosoft.EntityFrameworkCore.Tools tool.
This part of the workaround is straight from the horse’s mouth and can be found in the docs here: https://docs.efproject.net/en/latest/miscellaneous/cli/dotnet.html#targeting-class-library-projects-is-not-supported

You’ll also need to add a static void main() to complete the .NET Core app charade. Add an empty program.cs to your class library project.

public class Program
{
    public
static void Main(string[] args)
    {
    }
}

Lastly, we need to let our fake app know how to create your DbContext. The tools would normally gather this information from your startup.cs, but since that would be a huge pain to implement, let’s cheat and create an IDbContextFactory instead.
Add the following class to your class library:

public class TemporaryDbContextFactory : IDbContextFactory<PinchContext>
{
    public
PinchContext Create(DbContextFactoryOptions options)
    {
        var
builder = new DbContextOptionsBuilder<PinchContext>();
        builder
.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=pinchdb;Trusted_Connection=True;MultipleActiveResultSets=true");
        return
new PinchContext(builder.Options);
    }
}

This is just a quick way to let the app know what data provider we’re using and what the connection string is. Just hardcode it, don’t bother with the configuration system, this is only temporary and only used at development time.

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.

Simpan



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 Hosting - ASPHostPortal.com :: Tips To Set Up Custom Error Pages In IIS 7.5 With ASP.NET

clock July 13, 2016 23:25 by author Armend

Tips To Set Up Custom Error Pages In IIS 7.5 With ASP.NET

If we configure .NET Error Pages at the site level, ASP.NET stores the settings in the site’s web.config file. Since these settings are stored in the web.config file they are portable and can be easily moved to another server with the site’s content.

How to setup Custom Error Pages in IIS 7.5

Open Internet Information Services (IIS) Manager.  Select your website. Note: This could also be set at the server level and applied to all sites on the server. DoubleClick on the “.NET Error Pages” icon.

The .NET Error Pages features view will be displayed.

Click the “Edit Feature Settings” link to enable this feature. The “Edit Error Page Settings” dialog box will appear.

In order to change the default mode, we must also specify a “Default Page”. This page will be used for all status codes that are  not otherwise defined. In our example we are using a generic custom error page to trap all other errors. Once you enter the absolute URL for the default error page click OK.  Note:  It may be a good idea to use a static

HTML page here just in case ASP.NET is not functioning properly.
By default server errors are shown when logged on locally to the IIS server and custom errors will only be used from remote sessions. We will want to change this to “On” if we are logged on locally to the IIS server. Otherwise, it will display detailed server errors, and not our custom error pages.

Next we will explicitly define the 404 Error code.

To get the browser to throw a 404 error, we pointed it to a file on the test site that does not exist. As you can see in the following image the friendly HTTP 404 error page was shown in IE9.
A friendly HTTP 404 Error in IE9:

On the .NET Error Pages Actions menu click the Add link.

The “Add Custom Error Page” dialog will appear. This is where we define individual error pages per status code. For our example we will add a custom page for the HTTP 404 Error.

Now that we have turned on the feature and added a custom page for the 404 status code we can verify it is working. To verify visit a page that does not exist. In our example we will use http://mysite.com/deletedfile.aspx. You can see in the following image that the custom error page was shown.
Our custom 404 Error message in IE 9

As mentioned above this can also be managed from the site’s web.config file. Consider the following configuration section from our site’s web.config file.

<configuration>
  <system.web>
    <customErrors defaultRedirect=”http://mysite.com/errors/Error.aspx” mode=”RemoteOnly”>
       <error redirect=”http://mysite.com/errors/404.aspx” statusCode=”404″ />
    </customErrors>
  </system.web>
</configuration>

Everything we set in the GUI can easily be set directly in the web.config. This will also allow you to setup .NET Error Pages, if you are on a shared hosting Plan. Here at ASPHostPortal.com, our shared, dedicated and Windows cloud server hosting plans can all benefit from using custom .NET Error Pages.




ASP.NET Hosting - ASPHostPortal.com :: Dependency Injection In ASP.NET Core

clock June 28, 2016 20:19 by author Armend

This article explains the dependency injection feature available out of the box in ASP.NET core (ASP.NET 5). It will also cover some of the basics of dependency injection so that everyone can get the most out this article.

What is dependency Injection

Dependency Injection is the process of “injecting” the “dependency” whenever the dependency is requested by a client, where the dependency may be another service which the client (requester) may have no means of knowing how to create.

As an analogy, imagine a person (client) going to office carrying his lunch cooked by himself. In this scenario, the person has a “dependency” on food. But he had to know how to cook his food. But honestly, not everyone (client) knows to cook, but people do need food (dependency). This is where restaurants play the role of dependency Injection. They can supply food (“inject dependency”) to the people (client) without the person (client) needing to know how to cook.

This is also called as Inversion of control. Since the control for creation of the service has been passed from the requester to another entity which takes care of creating the dependencies needed by a class to perform its tasks. The entity which takes care of creating these requested dependencies and injecting them automatically to the client is known as the DI (dependency Injection) container.

Dependency Injection in ASP.NET Core

Ok, enough said about what dependency injection is. I am sure most of you knew it. If not, this is a great feature to know and a great tool to add to your tool belt! Let us now look at how to implement dependency injection out of the box in ASP.NET core.
ASP.NET core applications can leverage built in framework support for implementing dependency injection. It has support for the following types of lifetimes for configured services (injected dependencies).

  •     Transient – A new instance of the service is created each time it is requested. It can be used for stateless and light weight services.
  •     Scoped – A single instance is created once per request.
  •     Singleton – Created only once the first time they are requested.

Now for some code!

Use case

Implement a UniqueKeyProvider service. For demonstrating the lifetimes, we will create three differently named interfaces (one for each type of lifetime) for UniqueKeyprovider, all inheriting from the same parent interface having a single property, UniqueKey.
Also, to further illustrate the scoped and singleton lifetime, we will create another service, SomeService, which will have a dependency on all the three different UniqueKeyProvider services (the three different lifetime services).

1. Service Interface definition

Please note the three differently named interfaces, one for demonstrating each type of lifetime. 

namespace DependencyInjectionASPNetCore.Services 
    { 
        public interface IUniqueKeyProvider 
        { 
            Guid UniqueKey 
            { 
                get; 
                set; 
            } 
        } 
        public interface ITransientUniqueKeyProvider: IUniqueKeyProvider 
        {} 
        public interface IScopedUniqueKeyProvider: IUniqueKeyProvider 
        {} 
        public interface ISingletonUniqueKeyProvider: IUniqueKeyProvider 
        {} 
    } 

2. Service Class definition

    namespace DependencyInjectionASPNetCore.Services 
    { 
        public class UniqueKeyProvider: ITransientUniqueKeyProvider, 
        ISingletonUniqueKeyProvider, 
        IScopedUniqueKeyProvider 
        { 
            public Guid UniqueKey 
            { 
                get; 
                set; 
            } 
            public UniqueKeyProvider(Guid uniqueKey) 
            { 
                UniqueKey = uniqueKey; 
            } 
        } 
    } 

3. Registering the services in the startup.cs

Now register your services in the startup.cs file. This is the step where you are actually configuring your dependency injection container. You are basically instructing your dependency injection container that if the user requests for the service, ITransientUniqueKeyProvider, then please provide with a transient scoped instance of UniqueKeyProviderclass and similarly for the other services.
You need to register your services in the ConfigureServices method in the startup.cs file. Please refer to the code below for registration,

   

    services.AddTransient<ITransientUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid())); 
    services.AddScoped<IScopedUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid())); 
    services.AddSingleton<ISingletonUniqueKeyProvider>(provider =>newUniqueKeyProvider(Guid.NewGuid())); 
    services.AddTransient<ISomeService, SomeService>();
 

Note that I am also registering another service, ISomeServicewhich I am just using for demo purposes for showing the nature of transient and singleton lifetime. Also note that SomeService implementation requires dependency on the three Unique Key providers, which will be injected through dependency injection.Implementation of ISomeservice provided below,

4. IsomeService and Someservice Implementation

    public class ISomeService 
    { 
        ITransientUniqueKeyProvider TransientUniquekeyProvider 
        { 
            get; 
            set; 
        } 
        IScopedUniqueKeyProvider ScopedUniquekeyProvider 
        { 
            get; 
            set; 
        } 
        ISingletonUniqueKeyProvider SingletonUniquekeyProvider 
        { 
            get; 
            set; 
        } 
    } 
    public class SomeService: ISomeService 
    { 
        public ITransientUniqueKeyProvider TransientUniquekeyProvider 
        { 
            get; 
            set; 
        } 
        public IScopedUniqueKeyProvider ScopedUniquekeyProvider 
        { 
            get; 
            set; 
        } 
        public ISingletonUniqueKeyProvider SingletonUniquekeyProvider 
        { 
            get; 
            set; 
        } 
        public SomeService(ITransientUniqueKeyProvider transientprovider, 
            IScopedUniqueKeyProvider scopedprovider, 
            ISingletonUniqueKeyProvider singletonprovider) 
        { 
            TransientUniquekeyProvider = transientprovider; 
            ScopedUniquekeyProvider = scopedprovider; 
            SingletonUniquekeyProvider = singletonprovider; 
        } 
    } 

Now it is time to wrap it all up and test it through a controller. I am using the Home controller’s Index action. Please refer to the below code from the controller and view.

5. Home Controller

    public class HomeController: Controller 
    {  
        private ITransientUniqueKeyProvider _transientUniquekeyProvider; 
        private IScopedUniqueKeyProvider _scopedUniquekeyProvider; 
        private ISingletonUniqueKeyProvider _singletonUniquekeyProvider; 
        private ISomeService _someserviceProvider; 
        public HomeController(ITransientUniqueKeyProvider transientprovider, 
            IScopedUniqueKeyProvider scopedprovider, 
            ISingletonUniqueKeyProvider singletonprovider, ISomeService someserviceprovider) 
        { 
            _transientUniquekeyProvider = transientprovider; 
            _scopedUniquekeyProvider = scopedprovider; 
            _singletonUniquekeyProvider = singletonprovider; 
            _someserviceProvider = someserviceprovider; 
        } 
        public IActionResult Index() 
        { 
            ViewBag.transientID = _transientUniquekeyProvider.UniqueKey; 
            ViewBag.scopedID = _scopedUniquekeyProvider.UniqueKey; 
            ViewBag.singletonID = _singletonUniquekeyProvider.UniqueKey; 
            ViewBag.someServiceProvider = _someserviceProvider; 
            return View(); 
        } 
    } 

Note the constructor which takes in the dependencies. So when the request comes to this page, the framework notes that it needs an implementation for these services. It checks the DI container and finds the registration, and based on that the valid instance is passed to the constructor. The same happens in case of the ISomeService dependency which the controller’s constructor needs.

6. Index View

In the view file, we are just displaying the values that we set in the view bag. Results provided in the next section.

<div style="margin-top:35px"> 
lt;pstyle="font-weight:bold;text-decoration:underline"> 
These are the values that were injected into the home controller 
</p> 
<p> 
    Transient value of Guid: @ViewBag.transientID 
</p> 
<p> 
    Scoped value of Guid: @ViewBag.scopedID 
</p> 
<p> 
    Singleton value of Guid: @ViewBag.singletonID 
</p> 
</div> 
 
<div> 
    <p style="font-weight:bold;text-decoration:underline"> 
 
        These are the values that were injected into Someservice Implementation 
        </p> 
        <p> 
            Transient value of Guid: @ViewBag.someServiceProvider.TransientUniquekeyProvider.UniqueKey 
        </p> 
        <p> 
            Scoped value of Guid: @ViewBag.someServiceProvider.ScopedUniquekeyProvider.UniqueKey 
        </p> 
        <p> 
            Singleton value of Guid: @ViewBag.someServiceProvider.SingletonUniquekeyProvider.UniqueKey 
        </p> 
</div>

I really hope it was useful and fun. Happy coding!

 



ASP.NET Hosting - ASPHostPortal.com :: ASP.NET Seo Tips

clock June 21, 2016 20:41 by author Armend

When running an online business, majority of our focus is on the design, architecture of the website and how efficiently it displays our product. These are not the only things that are required to target the infinite Internet audience. One need to keep in mind that the main source of audience come from search engines such as Google, Yahoo, Bing and others. So the application or the website should be able to follow simple rules and handle your business efficiently. ASP.NET application is spreading rapidly and if you are using an ASP.NET website few simple guidelines has to be considered. The below mentioned points need to be implemented:

 

Page Titles

Page titles between tags is one important thing that many fail to practice in SEO. When a search is made in Google, these titles show up as links in the result. So that explains its importance. The common mistake among website owners is giving the same title for all pages. Page titles drive traffic to your site, hence it is important to have a proper title to attract visitors. Adding titles is not as hard as you imagine. If you have a product catalog use your product name as title. You can also choose to give a different title that is related to your product.

Meaningful URL

URLs that are long with query parameters do not look neat and it is difficult for the visitor to remember. Instead use formatted URLs for your static pages. URL which has a meaning explains the content in your website. Although experts agree with using an URL that has query parameters, it is better to have a meaningful URL. Components like UrlRewritingNet can be used for this purpose. Mapping support in URL is offered by IIS7 which has plenty of features.

Structure of the Content

Content without a structure is not possible.  You will have titles, headings, sub headings, paragraphs and others. How would you emphasize some quotes or important points in your content? If you follow the below mentioned steps, the structure of your content will be semantically correct.

  • Divide long stories or parts using headings. Short paragraphs make more sense to the readers. Use tags to bring beauty to your content.
  • If you want to emphasize an important point or quote, place them between tags.

Visitors can create structured content if you use FCKEditor and the like. Integrating these to your website is not complex.

Clean the Source Code

Don’t panic, it is advisable to clean up the source code and minimize the number of codes. The following simple steps will assist you in cleaning the source code: You can use

  •     External stylesheets and not inline CSS
  •     -js files instead of inline JavaScript
  •     HTML comments is not encouraged
  •     Avoid massive line breaking
  •     Avoid using viewstate when not required

The relation between the content and the code (JavaScript, HTML, CSS) determines the ranking of your website. Smaller source codes help build a strong relation.

Crawlable Site

Do not use

  • Silver or flash light for menus or to highlight information
  • Menus based on JavaScript
  • Menus based on buttons
  • Intro-pages

Do use

  • Simple tags wherever possible
  • Sitemap
  • “Alt” for images
  • RSS

Test the Site

What happens to the requests that are sent when the site is slow? Sometimes requests are sent by robots and if they are unable to connect to your site continuously, they drop the site from their index. Enable your site to respond fast to requests even during peak hours. Moreover, visitors don’t like to visit slow sites. Use the various tools available and conduct the stress test for your site. Perform this and locate all the weak parts of the site. Fix them so that your site gets indexed.

Test the AJAX site

Spiders can only run a few parts of your AJAX website because they don’t run JavaScripts. Spiders can only analyze the data and hence they remain invisible to robots. The AJAX sites do not get indexed which does not help in search engine optimization. To make the site spider friendly, try and keep away from initial content loading into the JavaScript. You can also follow this only for pages that you like to index.  Make it easy for robots so that they can navigate. Try this simple trick to see how your AJAX site will appear to the robots. Disable JavaScript from the browser and visit your AJAX site. You can view the pages which robots will index.

 



ASP.NET Hosting - ASPHostPortal.com :: How to Publishing an ASP.NET 5 Project to a Local IIS Server

clock June 16, 2016 17:45 by author Armend

In this post we will show you how to publishing an ASP.NET 5 project to a local IIS server. Recently I deployed a new ASP.NET 5 web application to a local IIS server. Though there are several online resources available about deployment, I encountered some problems that were difficult to diagnose and fix. In this post I will talk about the general deployment process and the steps I followed for a successful deployment.

ASP.NET 5 applications are meant to be cross-platform. Included in this cross-platform effort is the development of a new, cross-platform web server, named Kestrel. The Kestrel web server can be activated from the command line and can be used on any operating system.
Of course, ASP.NET 5 applications can still be hosted in IIS. But even in this case, the underlying web server will still be Kestrel. The role of IIS is greatly minimized.
In this post we will be deploying a web application using Kestrel as a web host first. Afterwards, we will be deploying to IIS.

Deployment to Kestrel

Let's say that we have an existing ASP.NET 5 application. We can publish the application from the command line. First, navigate to the root web folder of the application (the folder where the project.json file is in). Then, type in the following command:

dnu publish --runtime active -o ..\publish

What this will do is create a new folder named 'publish' alongside the root web folder. Inside this 'publish' folder , there will be three subfolders: 'approot', 'logs', and 'wwwroot'. The 'approot' folder will contain the source files and packages needed by the application. The 'logs' folder will contain any logs that the application emits. The 'wwwroot' folder will contain javascript, html, css files, etc. as well as the web.config file.
Now we can start the Kestrel web server. First, navigate to the 'approot' folder. There will be a file named web.cmd. Start it by typing 'web' from the command line or double-clicking on it from a windows explorer window.

You might notice that a lot of text appears on the command line as soon as the command is run. This is especially true when there are Entity Framework migrations involved. Among the sea of text, the URL of the localhost web server will be displayed, and will look something like this:

Hosting Environment: Production
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Once we find this text, we can just navigate to the appropriate URL using a browser. There we should see the web app up and running.
Congratulations, we have just deployed our ASP.NET 5 web application!
Deployment to IIS
Once we successfully launch the app through Kestrel, we can go for deploying in IIS. We need to do a few things for it to work properly.

  • Use an application pool with No Managed Code as the .NET CLR Version.
  • Create a Login in SQL Server with the login name as IIS APPPOOL\{apppoolname}. This Login should have access to whatever database the web application will use.
  • Create access rights to the 'wwwroot' folder for the user group IIS_IUSRS.

In addition, if we are going to put the application inside IIS Default Web Site and use a virtual directory, we need to modify the Startup.cs to handle this.
The first step is to rename the Configure method to something else, for example Configure1.
Then, we need to create a new Configure method. This would have the same signature as the original Configure method. The implementation would look something like this:

public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.Map("/virtualdirectoryname", (app1) => this.Configure1(app1, env, loggerFactory));
}

So we see that this new Configure method just calls the Configure1 method, taking into account the virtual directory name.
Once all of these are in place, we can go ahead and deploy to IIS using the usual process. We can add a new application in IIS Default Web Site and use the application pool we created earlier (using No Managed Code). The physical path should point to the 'wwwroot' location. The alias should be the same as the one we put in the Configure method in Startup.cs.
Afterwards, just browse to the website and it should all be good!

Conclusion

Although the concept of deployment stayed the same, the process and tools involved for deploying ASP.NET 5 applications has changed. In this post we took a look at how to deploy to the Kestrel web server, then later to IIS. Though it might seem like a long process, most of the steps should only be performed the first time around. Subsequent deployments should be faster and more straightforward.



ASP.NET hosting - ASPHostPortal.com :: ASP.NET Core Web API, Multiple Get or Post Methods with Single Controller

clock June 13, 2016 19:23 by author Armend

ASP.NET Core Web API, Multiple Get or Post Methods with Single Controller

WHY ??

I was assigned a duty to develop a RESTful API for my company. And I was like, why not try out the new .NET Core. So I started an MVC Web API project. No surprise, it was similar to .NET 4.5+. Single Get or Post method for each controller. But I wanted a service controller with several get methods for customer.
Let's get to it.

Instead of modifying the webapiconfig, the Route options is directly in the controller class.

//
// Default generated controller
//

[Route("api/[controller]")
public class myApiController : Controller
{
    [HttpGet]
    public string GetInfo()
    {
        return "Information";
    }
}
//
//A little change would do the magic
//

[Route("api/[controller]/[action]")]
public class ServicesController : Controller
{
    [HttpGet]
    [ActionName("Get01")]
    public string Get01()
    {
        return "GET 1";
    }
    [HttpGet]
    [ActionName("Get02")]
    public string Get02()
    {
        return "Get 2";
    } 
    [HttpPost]
    [ActionName("Post01")]
    public HttpResponseMessage Post01(MyCustomModel01 model)
    {
        if (!ModelState.IsValid)
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        //.. DO Something ..
        return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
    }
    [HttpPost]
    [ActionName("Post02")]
    public HttpResponseMessage Post02(MyCustomModel02 model)
    {
        if (!ModelState.IsValid)
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        //.. DO Something ..
        return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
    }
}

//

I hope this article helpful. 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, 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.



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