Friday 16 March 2012

HttpBinding and TcpBinding

Problem
I would like to use HttpBinding and TcpBinding in the same service in WCS.


Impact
Use the same service with different Bindings a t the same time.

Solution
You can use the following code or change the configuration file as below:

1.      Code:
Uri httpAddress = new Uri("http://localhost:8000/OrderService/");
Uri tcpAddress = new Uri("net.tcp://localhost:8001/OrderService/");
Uri[] baseAddresses = { httpAddress, tcpAddress };

ServiceHost host = new
            ServiceHost(typeof(MyNamespace.OrderService), baseAddresses);

BasicHttpBinding basicBinding = new BasicHttpBinding();
WSHttpBinding wsBinding = new WSHttpBinding();
NetTcpBinding netBinding = new NetTcpBinding();
host.AddServiceEndpoint(typeof(MyNamespace.IOrderService),
                         basicBinding, "");
host.AddServiceEndpoint(typeof(MyNamespace.IOrderService),
                         wsBinding, "secure");
host.AddServiceEndpoint(typeof(MyNamespace.IOrderService),
                         netBinding, "");

2.      Configuration File:

<configuration>
  <system.serviceModel>
    <services>
      <service name="OrderService">
        <endpoint address="http://localhost:8000/OrderService/"
                  contract="MyNamespace.IOrderService"
                  binding="BasicHttpBinding">
        </endpoint>
        <endpoint address="http://localhost:8000/OrderService/secure"
                  contract="MyNamespace.IOrderService"
                  binding="wsHttpBinding">
        </endpoint>
        <endpoint address="net.tcp://localhost:8001/OrderService/"
                  contract="MyNamespace.IOrderService"
                  binding="NetTcpBinding">
        </endpoint>
      </service>
    </services>
  </system.serviceModel>
</configuration>

Conclusion
You can use differente types of binding to use the same service, the addresses have to be different for the different binding, al least the contracts are different.

Connection String Encryption

Problem
I would like to use Encryption in the connection string of the App.config file.

Impact
It will improve the security of the connection string section defined in the App.config.

Solution
You can use the following code to achieve the encryption of your connection string:


        public void EncryptDecrypt(bool protect)
        {
            richTextBox1.Text = "";

            // Define the Dpapi provider name.

            string strProvider = (radioButton1.Checked) ? "DataProtectionConfigurationProvider" : "RSAProtectedConfigurationProvider";

            string exePath = System.Windows.Forms.Application.ExecutablePath;

            try
            {
                // Open the configuration file and retrieve
                // the connectionStrings section.
 

                // For Web!
                // myConfiguration = System.Web.Configuration.
                //                  WebConfigurationManager.OpenWebConfiguration("~");
 

                // For Windows!
                // Takes the executable file name without the config extension.

                System.Configuration.Configuration myConfiguration = System.Configuration.ConfigurationManager.OpenExeConfiguration(exePath);
 

                System.Configuration.ConnectionStringsSection mySection = myConfiguration.GetSection("connectionStrings") as System.Configuration.ConnectionStringsSection;
 

                if (myConfiguration != null)
                {
                    mySection = myConfiguration.GetSection("connectionStrings") as
                        System.Configuration.ConnectionStringsSection;


                    if (mySection != null
                        && !mySection.IsReadOnly()
                        && !mySection.SectionInformation.IsProtected
                        && !mySection.SectionInformation.IsLocked
                        && protect)
                    {

                        // Encrypt the section.
                        mySection.SectionInformation.ProtectSection(strProvider);

                        // Indicates whether the associated configuration section
                        // will be saved even if it has not been modified.
                        mySection.SectionInformation.ForceSave = true;

                        // Save the current configuration.
                        myConfiguration.Save(ConfigurationSaveMode.Full);
                    }
                    else
                    {

                        // Remove encryption.
                        mySection.SectionInformation.UnprotectSection();

                        // Indicates whether the associated configuration section
                        // will be saved even if it has not been modified.
                        mySection.SectionInformation.ForceSave = true;

                        // Save the current configuration.
                        myConfiguration.Save(ConfigurationSaveMode.Full);
                     }
                }
            }

            catch (System.Exception ex)
            {
                throw (ex);
            }

            finally
            {
                GetConnectionString(exePath);
            }
        }

You can see the connection string using the following code:

public void GetConnectionString(string filePath)
        {
            StreamReader fileStream = new StreamReader(filePath + ".config");
            richTextBox1.Text = fileStream.ReadToEnd();
            fileStream.Close();
        }

Creating User-Selectable Themes

Problem 
I am using MasterPages and I want to allow to the user to change the Themes of the web pages with minimal effort.

Impact
It will which let you add personalization to the web site with different appearance and achieve a visual consistency.


Solution
You can use different Themes to customize your website.  We use two different ways:

1.      Using sessions:

  protected void Page_PreInit(object sender, EventArgs e)
  {
      if (Session["theme"] != null)
      {
          Page.Theme = (string)Session["theme"];
      }
  } 

  protected void ButtonSubmit_Click(object sender, EventArgs e)
  {
      string theme = Page.Theme;
      string test = (string)Session["theme"];
      TextBox masterButton = (TextBox)Master.FindControl("Button1");

      //switch themes
      if (theme != "PurpleTheme")
      {
            Session["theme"] = "PurpleTheme";
            masterButton.Text = "Change to Pink";
      }
      else
      {
            Session["theme"] = "RedTheme";
            masterButton.Text = "Change to Purple";
      }
  }

2.      Using different MasterPages: This is the content page, which allows users to select a master page based on a query string provided with the request. The @ MasterType directive, which assigns a strong type to the page's Master property, references the base type.
<%@ Page Language="C#" Title="Content Page" MasterPageFile="~/MasterPink.master"%>
<%@ MasterType TypeName="BaseMaster" %>


<script runat="server">

    protected void Page_PreInit(Object sender, EventArgs e)
    {
        this.MasterPageFile = " MasterPink.master";
        if(Request.QueryString["color"] == "purple")
        {
            this.MasterPageFile = "MasterPruple.master";
        }
        this.Title = Master.MyTitle;
    }

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>

Conclusion
In the example I show two way in order to change the Themes of the website by using sessions and different MasterPages. You can use a theme property in a user profile to make a user's theme selection persist after the user leaves your site or closes the browser.

Strongly type instead of FindControl

Problem
You can use FindControl method to find a control in your previous page, but you have to cast to get the control and if anything goes wrong (for instance: the type or control name is misspelled), you will get the error at runtime.
Impact
I will like to use a different and secure way to access the controls values from the previous page, where I can get any errors at compile time.

Solution
You can use the Strongly Type method to access the data from previous page. You can follow the following steps:
 
1. In the previous page form where you have the controls to access, you have to create the public properties for each control that will return the value you want.

   public string FirstName  
    {
        get { return TextBoxFName.Text; }
        set { TextBoxFName.Text = value; }
    }

    public string LastName
    {
        get { return TextBoxLName.Text; }
        set { TextBoxLName.Text = value; }
    }

    public string Email
    {
        get { return TextBoxEmail.Text; }
        set { TextBoxEmail.Text = value; }
    }

2. Add the PreviousPageType directive in the page where you will work with the data to access to the previous page controls:
 <%@ PreviousPageType VirtualPath="~/ContactUs.aspx" %>

3. Finally, you can access to the value of the controls from the previous page utilizing PreviousPageName.PropertyName:

Label1.Text = "Thanks " + ContactUs.FirstName + " " + ContactUs.LastName + " for contact us. You will receive a message to your" + ContactUs.Email + " from our company soon." + System.Environment.NewLine;


Conclusion
Avoid using FindControl method, try to use the Strongly Type method to access the data from previous page. You will get the errors at compile time, and it will  be a secure and flexible method to use.