a developer's notes – a semi-technical web development BLOG

August 28, 2014

Custom Error Pages in MVC 4

Filed under: Uncategorized — Duy Nguyen @ 11:52 am
Tags: , , , , , ,

Default solution: Use MVC HandleErrorAttribute

 

In MVC, by default, you will have in your Global.ascx, under Application_Start()

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

And in RegisterGlobalFilters, you will have…

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{
      filters.Add(new HandleErrorAttribute()); 
}

In your web.config, if you turn on custom errors like this…

<system.web>
    <!--<customErrors mode="On"></customErrors>-->
    <customErrors mode="On" defaultRedirect="myCustompage.html?"></customErrors>
</system.web>

customErrors mode=”On” = will turn on the default ~/Views/Shared/Error.cshtml view. (If you’re using IE, be sure to uncheck “Friendly Http Errors.” It works good but if you navigate to http://localhost/404, you will get the default yellow error screen unless you specify defaultRedirect=”myCustompage.htm”. Only then, will the application handle an internal application AND 404s, 500s, etc.

 Note: I’ve read lots of issues trying to preserve the error status code or the original stack trace

 

Alternative solution: Use Application_Error

 

You can also go the Application_Error route but will not have a backup error page if there is an error rendering the error page.

See this great blog post.
http://thirteendaysaweek.com/2012/09/25/custom-error-page-with-asp-net-mvc-4/

 

Some good other reads:

http://www.devcurry.com/2012/06/aspnet-mvc-handling-exceptions-and-404.html

http://colinmackay.co.uk/2011/05/02/custom-error-pages-and-error-handling-in-asp-net-mvc-3-2/

Advertisements

March 8, 2014

Checkbox returning “true,false” from FormCollection.

Filed under: ASP.NET MVC — Duy Nguyen @ 10:46 am
Tags: , , , , , , , , , ,

If you try Request.Form[“checkbox0”], you’ll get the value “true,false” .

Just check this:

form[key].Contains("true"); //some said chrome returns "on"

Or

You could simplify your code doing this:

var strArray = collection["YourCheckboxName"];
char[] delimiterChars = {‘,’};
string[] checkedvalue = strArray.Split(delimiterChars);
var returnValue = checkedValue.Length > 1;

If the checkbox is checked, then the array will contain 2 values, if not, only one.

December 4, 2013

WebClient .DownloadString with Proxy Server

Filed under: ASP.NET,ASP.NET MVC,C# — Duy Nguyen @ 9:19 am
Tags: , , , , , , ,

Code to use the default proxy settings

IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
client = new WebClient { Proxy = defaultWebProxy };
string downloadString = client.DownloadString("www.google.com");

or

WebClient client = new WebClient();
WebProxy wp = new WebProxy(" proxy server url here");
client.Proxy = wp;
string str = client.DownloadString("http://www.google.com");

If you need to set an account use this

using (WebClient webClient = new WebClient())
{
	webClient.Encoding = encoding;
	NetworkCredential netcredit = new NetworkCredential("MyNetworkUserID", "MyNetworkPassword", "corp");
	webClient.Credentials = netcredit;
	webClient.Proxy = new System.Net.WebProxy()
	{
		Credentials = new System.Net.NetworkCredential("MyNetworkUserID", "MyNetworkPassword", "corp")
	};
	// webClient.Proxy = null;//if I don't give webClient.Proxy-it returns Error "407-ProxyAuthentication Required!"
	result = webClient.DownloadString(url);
	  // result = webClient.DownloadString("http://www.google.com/");//just to check with google itself,still the same error
}

September 13, 2013

Google Maps API V3 with ASP.NET MVC 4 Example

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 1:06 pm
Tags: , , , , , , , , , , , ,

Here is the most basic example to get you started with Google Maps API V3. Create a basic template MVC 4 project and create a Home controller with this method:

    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }

Create a new view called Index.

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@section Scripts {
    <script type="text/javascript"  src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
}

@section Styles { @*Styles needed for Google Maps to appear*@
    html { height: 100% }
    body { height: 100%; margin: 0px; padding: 0px }
}

<h2>Hello, Google Maps</h2>

<div style="width: 100%; height: 100%">
    <div id="map_canvas" style="width:100%; height:100%; margin-left: 100px"></div>
</div>

<script type="text/javascript">

    function initialize() {

        var canvas = $("#map_canvas");

        var latitude = 30.3296604;
        var longitude = -97.8743174;

        var latlng = new google.maps.LatLng(latitude, longitude);
        var options = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(canvas[0], options);

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(latitude, longitude),
            map: map
        });
    }

    $(function () { //Same as $(document).ready()
        initialize();
    });
       
</script>

Now run the application and you should see the map.

googleMapsExample

March 12, 2013

The type initializer for ‘System.Data.Entity.Internal.AppConfig’ threw an exception.

I had a class library project that contains the Entity Framework .edmx file. In the same solution, I had a console application that consumed the class library project. But when I tried to run the console application to run a simple query on the DbContext object, got this error:

The type initializer for ‘System.Data.Entity.Internal.AppConfig’ threw an exception.

In the app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="AdventureWorksLTEntities" connectionString="metadata=res://*/AWModel.csdl|res://*/AWModel.ssdl|res://*/AWModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DNGUYEN-DESKTOP;initial catalog=AdventureWorksLT;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

Make sure the <startup> element is AFTER the <connectionStrings> element.

January 28, 2012

ASP.NET Gridview Example

Filed under: ASP.NET,C# — Duy Nguyen @ 4:22 pm
Tags: , , , , , , , , , ,

1. Create the Gridview on the ASPX page.

            <asp:GridView ID="customersGrid" 
                runat="server"
                AllowPaging="true" 
                AllowSorting="true"                 
                PageSize="20" 
                OnPageIndexChanging="gridView_PageIndexChanging" 
                AutoGenerateColumns="false" 
                OnSorting="gridView_Sorting"
                CssClass="mGrid"  
                PagerStyle-CssClass="pgr"  
                AlternatingRowStyle-CssClass="alt"
                RowStyle-CssClass="normRow">
                
                <Columns>
                    <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" SortExpression="CustomerID" />
                    <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                    <asp:BoundField DataField="MiddleName" HeaderText="MiddleName" SortExpression="MiddleName" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                    <asp:BoundField DataField="Suffix" HeaderText="Suffix" SortExpression="Suffix" />
                    <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                    <asp:BoundField DataField="SalesPerson" HeaderText="SalesPerson" SortExpression="SalesPerson" />
                    <asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress" SortExpression="EmailAddress" />
                    <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
                </Columns> 

                <PagerSettings Mode="NumericFirstLast" PageButtonCount="5"  FirstPageText="First" LastPageText="Last"/> 

            </asp:GridView>

2. On the C# code behind, create a method to load the gridview. There are other ways of preserving the datasource other than using Session, but for this purpose, we will use Session.

        public void LoadCustomersGrid()
        {
            DataTable customersTable;

            if (!IsPostBack)
            {
                customersTable = CustomerService.GetAllCustomers();
                Session["session_customer_dataTable"] = customersTable;
                this.customersGrid.DataSource = customersTable;
            }
            else
            {
                DataView dataView = Session["session_customer_dataView"] as DataView;

                if (dataView != null)
                {
                    this.customersGrid.DataSource = dataView;
                }
                else
                {
                    customersTable = Session["session_customer_dataTable"] as DataTable;
                    this.customersGrid.DataSource = customersTable;
                }
            }

            this.customersGrid.DataBind();
        }

Here are the three methods for Paging and Sorting

        public void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.customersGrid.PageIndex = e.NewPageIndex;
            this.customersGrid.DataBind();
        }

        protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable customersTable = this.customersGrid.DataSource as DataTable;
            DataView dataView;

            if (customersTable != null)
            {
                dataView = new DataView(customersTable);
            }
            else
            {
                dataView = this.customersGrid.DataSource as DataView;
            }

            if ((ViewState["gridSortDirection"] == null) || (ViewState["gridSortDirection"].ToString() == "DESC"))
            {
                dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(SortDirection.Ascending);
                ViewState["gridSortDirection"] = "ASC";
            }
            else
            {
                dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(SortDirection.Descending);
                ViewState["gridSortDirection"] = "DESC";
            }

            Session["session_customer_dataView"] = dataView;

            this.customersGrid.DataSource = dataView;

            //sets the page back to 0 if the user reorders the grid
            this.customersGrid.PageIndex = 0;
            this.customersGrid.DataBind();
        }

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;

            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;

                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }

            return newSortDirection;
        }

And here is the data layer call to get the list to bind to the gridview.

        /// <summary>
        /// Uses a datatable so that you can sort the gridview
        /// </summary>
        /// <returns></returns>
        public static DataTable GetAllCustomers()
        {
            DataTable dt;

            string connectionString = @"Data Source=(local);Initial Catalog=AdventureWorksLT2008R2;Integrated Security=SSPI";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                //in-line sql
                SqlCommand command = connection.CreateCommand();
                command.CommandType = CommandType.Text;
                command.CommandText = "select * from SalesLT.Customer";

                // For stored procedures
                //SqlCommand command = connection.CreateCommand();
                //command.CommandType = CommandType.StoredProcedure;
                //command.CommandText = "sp_get_all_customers";

                dt = new DataTable();
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(dt);
            }

            return dt;
        }

January 25, 2012

Reading values from a config file

Filed under: ASP.NET,C# — Duy Nguyen @ 9:00 am
Tags: , , , , , , , , , ,

From the c# code behind:

 private string myConfigMapping = ConfigurationManager.AppSettings["ComputerName"];

Add your config file. (app.config or web.config)

<?xml version="1.0"?>
<configuration>
	<connectionStrings>
		<add name="connectionString" connectionString="Data Source=(local);Initial Catalog=AdventureWorksLT2008R2;Integrated Security=SSPI"/>
	</connectionStrings>
	<appSettings>
		<add key="ComputerName" value="John-PC"/> //Add your key and value here!
	</appSettings>
	<startup>
		<supportedRuntime version="v2.0.50727"/>
	</startup>	
</configuration>

January 24, 2012

Method to get the count of a string occurrence in a string

Filed under: C# — Duy Nguyen @ 10:08 pm
Tags: , , , , , , , , ,
        /// <summary>
        /// Contains static text methods.
        /// </summary>
        public static class TextTool
        {
            /// <summary>
            /// Count occurrences of strings.
            /// </summary>
            public static int CountStringOccurrences(string text, string pattern)
            {
                // Loop through all instances of the string 'text'.
                int count = 0;
                int i = 0;
                while ((i = text.IndexOf(pattern, i)) != -1)
                {
                    i += pattern.Length;
                    count++;
                }
                return count;
            }
        }

January 12, 2012

Try / Catch block VS Using block

Filed under: ASP.NET,C# — Duy Nguyen @ 3:48 pm
Tags: , , , , , , , , , , ,

Try / catch and Using are much different. Try/catch is used for exception handling while Using is used to ensure the object is disposed.

Can you combine a try / catch inside of a Using if you like.

September 29, 2011

Why can’t I run my .NET 4.0 site on Windows 2003 with IIS 6?

Filed under: ASP.NET — Duy Nguyen @ 10:44 pm
Tags: , , , , , , , , , , , , , , , , , ,

IIS 6 (that comes with Windows 2003) does not let you have more than one framework at a time running in the same instance like IIS7 that can create Application PoolS targeting different frameworks. This just means a single application pool can’t be used for two different frameworks like IIS7.

You have a two options:

  1. Downgrade the .NET application to 3.5 with Visual Studio 2010. Just go to the Website project properties, Application tab and there is a drop down with all the framework releases, select 3.5.

    VS2010 will reload the project and modify the web.config. If you added A web service reference, thEN you may have to delete them and re-add them under 3.5

  2. Configure IIS6 with a second application pool and a second web site.

    • Create a new application pool…

      and new web site…

      Then assign this application pool to the Framework 4 web application that will be hosted by your new site. To assign the application pool, in the IIS console open the properties section of the web application, and click on the “Home directory” tab and select the application pool which you have created earlier.

    • Then you need to change the ASP.NET version of your application. Right click your virtual directory that hosts your application and click the property and check the ASP.Net. Select Framework 4.

    • Select ASP.NET 4.0 on IIS6 under Web Service Extension. Go to the IIS6 console open “web service extension node” which is right below the “default website” node. You will see the entire ASP.Net framework list that is installed. By default these frameworks might be prohibited so please select ASP.Net Framework 4 and click allow button.

      *If you don’t see ASP.NET 4.0, make sure the framework is installed on the server! If it is, then open a command prompt go to this directory: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
      Then run this command: aspnet_regiis -i

      You will now see ASP.NET 4.0. If you don’t set ASP.NET 4.0 to ALLOW, You will get a “404 Page is not found.”

Check out this great article:

http://stackoverflow.com/questions/2821514/default-aspx-with-iis-6-0-and-net-4

Next Page »

Blog at WordPress.com.