Wednesday, December 2, 2015

MVC: Display string as HTML from database to view

Following is the way to display html in view:

For aspx:
<%= System.Web.HttpUtility.HtmlDecode(@Model.Html) %>

For Razor:

@Html.Raw(Server.HtmlDecode(@Model.Html))

Update EDMX from database

In database first approach, you create your database first and then you generate model from database. This creates respective entities in your project.

However any change in database schema, does not reflects automatically in your model. For this you need to update your model. Following are 2 techniques:


  1. Delete and create(not prefered solution): Here you just need to delete entitiy in model browser. And then you just need to right click and click "Generate Model from Database" this regenerate model from database. This is a good solutions for hobby projects or test projects. However this is not recomended.
  2. Update entities from database: Below are the steps to update entities from database:
    1. Right click model(in edmx file).
    2. Click update model from database:
    3. There ate three tabs(Add, Refresh & Delete).
    4. In Refresh tab expend tables > dbo(schema) > and select updated entity.


All done. Now you

Tuesday, November 3, 2015

IIS - Worker Process, ISAPI Extension, Application Pool, Web Farm & Web Garden

Application Pool:
An application pool is a group of one or more web applications that are served by a worker process(w3wp.exe) or set of worker processes.
OR
An application pool is a group of one or more worker processes, configured with common settings that serve requests to one or more applications.

Means n number of web application can be served by n number of worker process using same application pool. Applications within an application pool shares the same worker process.

You can also create multiple application pools to isolate multiple web application. This way you will be able to apply different level of security on multiple apps. Also an error in one app will never affect other applications.

Worker Process(w3wp.exe):
Application pool passes every request to worker process. Worker process (w3wp.exe) checks the URL of the request to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources(like images, javascript, css, aspx, ashx etc). When we install asp.net, its ISAPI extension (aspnet_isapi.dll) and adds its mapping in IIS.

ISAPI Extension:
ISAPI Extensions are true applications that run on IIS. They have access to all of the functionality provided by IIS. ISAPI extensions are implemented as DLLs that are loaded into a process that is controlled by IIS. Clients can access ISAPI extensions in the same way they access a static HTML page.

Web Farm:
A Web Farm is group of servers acting as a single server. It could be a setup of multiple servers work togather to host a single website(or any other application). A load balancer can be used to devide traffic between various servers.

Web Garden:
By default each and every application pool contain single worker process. But we can change associated worker process. An application pool with multiple worker process is called Web Garden. Following is the way to manage number of worker process in IIS:

1. Go to IIS(inetmgr).

2. Click on Application Pools.
3. Right click desired Application Pool.
4. Go to Advance Settings.

5. Increase Maximum Worker Processes.

Conver JSON to XML

Following is the method to convert json to xml:

string ConvertToJson(string json)
{
    XmlDocument rootxml = new XmlDocument();
    XmlDocument doc;
    doc = JsonConvert.DeserializeXmlNode(json,"root");
    return doc.OuterXml;

}

For this we need to use newtonsoft.json dll to our project.
This dll can be installed by package manager. Perform following steps to download this package:

1. Go to Tools > Library Package Manager > Manage NuGet Packages for Solution...

2. Search for newtonsoft
3. Install Json.net

Thursday, October 29, 2015

SQL Server: Save changes is not permitted. Resolution

Save changes is not permitted. The changes you have made require the following tables to be dropped and recreated. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

User canceled out of save dialog.

Solution:

  • Go to Tools > Options

  • Go to Designers > Table and Database Designers
  • Uncheck the Prevent saving changes that require the table recreation.

Tuesday, October 20, 2015

Difference between Eager Loading, Lazy Loading & Explicit Loading

Eagerly Loading

This is the process to load all the related entities while loading an entity. When we load an entity, we will be loading all the related entities all together. We use Include method to achieve Eager Loading. For example following will load all the Categories + All the Products of those categories:

using (InventoryContext ctx = new InventoryContext())
{
    var cats = ctx.Categories.Include(b => b.Products).ToList();
}

We can load related entities up to n number of levels.

Lazy Loading

Lazy loading is a concept where we delay the loading of the object until the point at which it is needed. Means lazy loading does not allow to load objects unnecessarily objects will be loaded only when they are needed.

Lazy loading created problem with serialization. Serializers access each and every property to serialize. Hence all the related entities will load. This will increase the overhead and will result in a large result set. So it is advised to turn Lazy loading OFF when work with Serialization.

Explicitly Loading

This is the process to load related entities keeping serialization off. For this we need to make explicit call to load related entity.

404.3 - IIS - Not Found The page you are requesting cannot be served because of the extension configuration

Normally this error comes when you try to run any application on IIS for the first time. This error could be with any of the following type of requests:

  1. Asp.net website - It means you are trying to run normal asp.net website.
  2. Web Service - When you try to host web service on IIS.
  3. WCS Service - When you try to host WCF Service on IIS.
To resolve this error:


  1. Click the Start button, and then click Control Panel.
  2. Click Programs, and then click Programs and Features.
  3. On the Tasks menu, click Turn Windows features on or off.
  4. In Role, select and IIS.
  5. In features, select .net framework 4.5 features > WCF Services > HTTP Activation.
  6. Save the setting.


Friday, October 16, 2015

SQL: Stored Procedure vs Function - Difference

Following are the difference between sql stored procedures and sql functions

Stored Procedure Functions
Can return 0 or multiple values Function must return a value
SP can call functions Functions can not call SPs
Allow SELECT + DML(INSERT/UPDATE/DELETE) Allow SELECT operation only
Cant not be used in SELECT statements Can be used in SELECT statements
Cant not be used in WHERE/HAVING clause  Can be used in WHERE/HAVING clause
SPs can have INPUT and/or OUTPUT parameters Functions can have input parameters only
This is a precompiled set of statements, hence Compile statements everytime.
Transactions can be created in SPs Transactions can not be created
Allow TRY CATCH blocks Does not allow exception handling

Tuesday, October 13, 2015

IIS Error 403.14 Content listing disabled

This error is due to content listing IIS default settings. By default IIS does not allow to show directory listing of server. This is due to security permissions. This can be resolved by checking enabled directory listing checkbox in website in IIS. However it is not suggested to do so. simply write complete url of the page to access page. For example use http://localhost/default.aspx instead of http://localhost/

Tuesday, September 29, 2015

How to Enable / Disable Multiple RDP Sessions in Windows 2008 / 2008-R2

Following are the steps to enable multiple logins in Windows Server 2008/2008 R2:
1.       Login to Server (RDP).
2.       Click Start.
3.       Go to configuration:
a.       2008 R2 - Search for remote desktop session host configuration ( Start > Administrative Tools > Remote Desktop Services > Remote Desktop Session Host Configuration).


b.      2008 – Search for Terminal services configuration (Start > Administrative Tools > Terminal Services >Terminal Services Configuration).
4.       Double click Restrict each user to a single session.


Check/Uncheck Restrict each user for single session checkbox to Disable/Enable multiple RDP sessions.


Saturday, August 22, 2015

HTTP Error 500.19 - Internal Server Error IIS

This error is due to application pool of website. You might map wrong application pool to website. Please follow the below steps to check.
  1. Open inetmgr.exe(IIS).
  2. Click advance settings of website by clicking advance settings link in right side panel.
  3. Check application pol of website.
  4. Now click application pool.
  5. Double click website's application pool(or right click and properties of app pool).
  6. Application pool should be same as website name.

The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration

This error is due to version of application pool. You need to update version of app pool from v2 to v4. Follow the below steps:

  1. Open IIS.
  2. Right click website and click settings to check the application pool name of website. OR
  3. Click website, click advance settings in right side panel.
  4. Now click application pool.
  5. Double click website's application pool(or right click and properties of app pool).
  6. Change version in dropdown from v2 to v4.

Friday, August 21, 2015

IIS - Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list - ASP.net

This error is due to asp.net installation on IIS. To resolve this error you need to install asp.net on IIS. For this you need to execute aspnet_regiis.exe -i command. First location this exe. It should be on following location:
On Windows 32 bit:
C:\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i
On Windows 64 bit:
C:\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i


Thursday, August 13, 2015

asp.net-Export Datatable to Excel using handler(.ashx)

Following is the complete code of .ashx handler to create datatable and export datatable to excel file:

<%@ WebHandler Language="C#" Class="Export" %>

using System;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public class Export : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
        context.Response.ContentType = "application/ms-excel";
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;
        string exportContent = CreateExcel();
        response.Write(exportContent);
    }

    private string CreateExcel()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        //ds = GetDatasetFromDatabase();//implement this function to get data from database
        //dt = ds.Tables[0];//get datatable from dataset
        dt = GetTable();//dummy table filled with dummy data
        using (StringWriter sb = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sb))
            {
                Table table = new Table();// create a table to hold all the data which we need to export
                TableHeaderRow thr = new TableHeaderRow();
                TableRow row = new TableRow();
                TableHeaderCell thc;//create 1st row as header row
                foreach (DataColumn dc in dt.Columns)//loop to create header columns
                {
                    thc = new TableHeaderCell();
                    thc.Text = dc.ColumnName;
                    row.Cells.Add(thc);
                }
                table.Rows.Add(row);//add header row to table
                TableCell tc;
                foreach (DataRow dr in dt.Rows)//loop to crate all rows of excel
                {
                    row = new TableRow();//create new row of table
                    foreach (DataColumn dc in dt.Columns)//loop to create columns of individual row
                    {
                        tc = new TableCell();
                        tc.Text = dr[dc].ToString();
                        row.Cells.Add(tc);
                    }
                    table.Rows.Add(row);//add row to table
                }
                table.RenderControl(htw);//render table to html text writer
                return sb.ToString();//return table as string
            }
        }
    }
   
    DataTable GetTable()
    {
        // Here we create a DataTable with four columns.
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        // Here we add five DataRows.
        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        return table;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}



Use open url of handler in browser to download excel file. Following is the code to create link to download the excel:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Export.ashx">Export to Excel</asp:HyperLink>

<a href="Export.ashx">Export to Excel </a>

asp.net-use Session in .ashx handler

Following is the technique to use Session in .ashx handler:

public class DownloadHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
      string Name = "";
      if (context.Session["UserName"] != null)
         Name = context.Session["UserName"].ToString();
    }
}


Interface used:  IRequiresSessionState this interface is in System.Web.SessionState and Session will be available in context.Session["UserName"]