Tuesday, 23 October 2012

BackgroundWorker Example

In this example, I will use the BackgroundWorker to call several methods (no simultaneously).I will show how to use a Progress Bar control to report the progress of the process, updating the text value in the middle of the control. I also will show how to update the text in a TextBox control, using delegate.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;
 
 
namespace ExcelFileReader
{
    public partial class Form1 : Form
    {
            private BackgroundWorker bw = new BackgroundWorker();
        delegate void SetTextCallback(string text);
 
 
        public Form1()
        {
            InitializeComponent();
           
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
 
        }
 
        #region Test1
        private void Test1(BackgroundWorker worker, DoWorkEventArgs e)
        {
            SetTextBox1("Stating the process with Test1...");
           
            int LastRow = 100; // This is the reference value for the ProgressBar
            for (int rCnt = 1; rCnt <= LastRow; rCnt++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Do something here
                   Thread.Sleep(1000); // Replace for your code
                    worker.ReportProgress(((rCnt * 100) / LastRow));
 
                }
            }
            wb.Close();
            worker.ReportProgress(100);
            SetTextBox1("Master File process completed!");
 
        }
        #endregion
 
      private void button1_Click(object sender, EventArgs e)
        {
            if (bw.IsBusy != true)
            {
                    textBox1.Text = "";
                    bw.RunWorkerAsync();
 
                }
            }
           
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
 
        }
 
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
 
            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
            }
            else
            {
                switch (varstring)
                {
                    case "Test1":
                        Test1(worker, e);
                        break;
                    case "Test2":
                        Test2(worker, e);
                        break;
                    case default:
                        Test3(worker, e);
                        break;
                }
 
            }
        }
 
        private void SetTextBox1(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetTextBox1);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                if (text != "")
                    this.textBox1.Text += text + System.Environment.NewLine;
 
            }
        }
       
 
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.progressBar1.CreateGraphics().DrawString(e.ProgressPercentage.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(this.progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }
 
 
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.textBox1.Text = "Canceled!";
            }
 
            else if (!(e.Error == null))
            {
                this.textBox1.Text = ("Error: " + e.Error.Message);
            }
 
            else
            {
                this.textBox1.Text += "Done!";
            }
        }
 
    }
}
 
 
 
In the application, you should add too Button controls (Start and Stop/Cancel), a Progree Bar control, and a TextBox control. We create the BackgroundWorker dinamically in the code, but you can add the BackgroundWorker control.
 
Thanks for reading.

 


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();
        }