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

February 13, 2015

The request was aborted: Could not create SSL/TLS secure channel

Filed under: ASP.NET,C# — Duy Nguyen @ 10:14 am
Tags: , , , , , ,

We had some trouble with posting data with a System.Net.WebClient request. We notice that it was sporadic and couldn’t figure it out. What we found out was that some calls had SecurityProtocolType.Ssl3 and other calls didn’t specify SecurityProtocolType.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

SecurityProtocolType is a static class, and what ended up happening was when one call changed the SSL type, it would affect other areas of the application. We had to explicitly set the protocol type in each request.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // or Ssl3

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
}

July 15, 2013

Using Visual Studio 2012 Web.config Transform

Filed under: ASP.NET — Duy Nguyen @ 12:15 pm

1. Open Configuration Manager

ConfigurationManager

2. Add a new configuration

CreateConfig

3. Add a new Config Transform

AddConfigTransform

You will now see the newly added config file.

AddedTransform

4. Modify the config file and add in sections of code that will be replaced with new configurations from your new environment. Highlighted in yellow, I have added a new connection string for the devlocal environment.

ModifyConfig

5. When you Publish or deploy your project, in the generated .zip file, the web.config will look like this… GeneratedWebConfig
When you deploy the application, the replaceable tokens will be replace by values in your “parameters.xml” file. If you don’t want this behavior and want the generated web.config file to contain the actual values, you can modify your .csproj file and add this

under the PropertyGroup section.

<AutoParameterizationWebConfigConnectionStrings>False</AutoParameterizationWebConfigConnectionStrings>

example:
AutoParameterizationOff

You can read more about this at http://msdn.microsoft.com/en-us/library/dd465318%28v=vs.100%29.aspx

May 7, 2013

Pass Hidden Input from View to MVC Controller

Filed under: ASP.NET,C# — Duy Nguyen @ 11:51 am
Tags: , , , , ,

Make sure your input has an id AND name attribute. Having just the id attribute will not work.

<% using (Html.BeginForm("MyAction", "Controller", FormMethod.Post, new { id = "formId", target = "_self" })) 
   { %>
     <input type="hidden" name="myHidden" id="myHidden" value="false" />
<% } %>

Then in the controller, access the form values like this.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(FormCollection form)
{
     string myHiddenInput= form["myHidden"];
}

April 6, 2013

Visual Studio 2012 Run tests in current context – Debug tests in current context

There is no longer a “Run tests in current context” or “Debug tests in current context“.

There is just a “Run Tests” and “Debug Tests” but they work exactly the same way as the old commands. If you right click within the body of a single test and select “Run Tests” it will run just that test now (as opposed to running all the tests in the class which was the behavior in the RC). If you click outside the method body but within the test class and select “Run Tests” it will run all the tests in that test class.

runTests

March 27, 2013

How to debug into javascript/jquery when working with Visual Studio

Filed under: ASP.NET,Javascript / JQuery — Duy Nguyen @ 12:12 am
Tags: , , ,

Add debugger in your javascript code.

Within your Javascript code, add the line

debugger;

1. Using Visual Studio:
You can execute (F5) your application and debug with Visual Studio and the application will stop on your line of code. Note** You have to use Internet Explorer if you want to use Visual Studio.

js_vs

2. Use Chrome:
Just add the same line of code but have the Developer Tools open when you navigate to your page that executes your javascript code.

js_chrome

3. Use Firefox:
Just add the same line of code but have Firebug open when you navigate to your page that executes your javascript code.

js_firefox

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.

August 14, 2012

Why use HTML Helpers in MVC?

Filed under: ASP.NET,C# — Duy Nguyen @ 10:05 am

Check out this article:

http://dotnet.dzone.com/articles/aspnet-mvc-html-helpers

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 26, 2012

C# ADO.NET Examples and Variations

Filed under: ASP.NET,C# — Duy Nguyen @ 11:20 pm
Tags: , , , , , , , ,

Getting back a record set and fill out a datatable
-Gets a record set
-Use SqlDataAdapter to execute SQL command

        /// <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;
        }

Getting back a record set and reading one record at a time
-Gets a record set
-Use SqlDataReader

        /// <summary>
        /// Uses a reader object to bind to the object properties
        /// </summary>
        /// <returns></returns>
        public static List<Customer> GetAllCustomersList()
        {
            string connectionString = @"Data Source=(local);Initial Catalog=AdventureWorksLT2008R2;Integrated Security=SSPI";

            List<Customer> Customers = new List<Customer>();
            Customer cust; 

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = @"select * from SalesLT.Customer";
                command.CommandType = CommandType.Text; //CommandType.Text is used for SQL statements.
                
                //if you are using a stored proc
                //command.CommandType = CommandType.StoredProcedure;
                //command.CommandText = "sp_get_all_customers"; 

                connection.Open();

                SqlDataReader reader = null;
                reader = command.ExecuteReader();

                // read one record at a time
                while (reader.Read())
                {
                    cust = new Customer();
                    cust.CustomerID = (int)reader["CustomerID"];
                    cust.Title = reader["Title"].ToString();
                    cust.Suffix = reader["Suffix"].ToString();
                    cust.FirstName = reader["FirstName"].ToString();
                    cust.MiddelName = reader["MiddleName"].ToString();
                    cust.LastName = reader["LastName"].ToString();
                    cust.CompanyName = reader["CompanyName"].ToString();
                    cust.SalesPerson = reader["SalesPerson"].ToString();
                    cust.EmailAddress = reader["EmailAddress"].ToString();
                    cust.PhoneNumber = reader["Phone"].ToString();
                    Customers.Add(cust);
                }
            }
            
            return Customers;
        }

Update, delete or insert into a database.
-No return value
-Use ExecuteNonQuery()

        /// <summary>
        /// Use ExecuteNonQuery method to insert a record
        /// </summary>
        /// <returns>number of records</returns>
        public static void InsertdataToDb()
        {
            string connectionString = @"Data Source=(local);Initial Catalog=AdventureWorksLT2008R2;Integrated Security=SSPI";
            int count = -1;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = @"insert into Cars_Demo" + " " + "values ('Jeep', '1992')"; //use appropriate SQL statments

                command.CommandType = CommandType.Text; //CommandType.Text is used for SQL statements.

                connection.Open();
                count = (int)command.ExecuteNonQuery(); //note ExecuteNonQuery is used!
            }
        }

This is how you retrieve a SINGLE value from the database. It has to be the first record, first column.
-Get a (known) single Record
-Use ExecuteScalar()

        /// <summary>
        /// Use ExecuteScalar method to get the first record, first column value from a query
        /// </summary>
        /// <returns>number of records</returns>
        public static int GetNumberOfRecords_Demo()
        {
            string connectionString = @"Data Source=(local);Initial Catalog=AdventureWorksLT2008R2;Integrated Security=SSPI";
            int count = -1;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();

                //in line sql
                command.CommandText = @"select count(*) from Cars_Demo";
                command.CommandType = CommandType.Text; 

                //using stored procedures
                //command.CommandType = CommandType.StoredProcedure;
                //command.CommandText = "myProc";

                connection.Open();
                count = (int)command.ExecuteScalar(); //note ExecuteScalar is used!
            }

            return count;
        }

This is how you retrieve a OUTPUT PARAMETER value from a stored procedure.
-Get a (known) single Record back
-Use ExecuteReader() or ExecuteNonQuery()

        /// <summary>
        /// How to get a value back from a sql output parameter
        /// </summary>
        /// <returns>number of records</returns>
        public static int CallaProcWithReturnValue()
        {
            string connectionString = @"Data Source=(local);Initial Catalog=AdventureWorksLT2008R2;Integrated Security=SSPI";
            int numberOfHondas;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "sp_proc_w_output_parameter";

                command.Parameters.Add(new SqlParameter("@numOfHondaCars", SqlDbType.Int));
                command.Parameters["@numOfHondaCars"].Direction = ParameterDirection.Output;

                connection.Open();

                // if you are using ExecuteNonQuery()
                command.ExecuteNonQuery();
                connection.Close(); // Get output params AFTER we've processed and close connection
                numberOfHondas = (int)command.Parameters["@numOfHondaCars"].Value;

                // if you are using a reader
                //SqlDataReader reader = null;
                //reader = command.ExecuteReader();

                //while(reader.Read())
                //{
                //    //do something
                //}

                //reader.Close();

                // Get output params AFTER we've processed
                // CLOSED the SqlDataReadeer FIRST!
                //numberOfHondas = (int)command.Parameters["@numOfHondaCars"].Value;
            }
            return numberOfHondas;
        }

ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.
ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete. You don’t expect a return value or a record set. (returns number of rows affected if proc does not have SET NOCOUNT ON.
ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB.

Next Page »

Create a free website or blog at WordPress.com.