A day with .Net

My day to day experince in .net

Archive for the ‘c#.net’ Category

Exception handling in Task Parallel Library

Posted by vivekcek on May 31, 2012

The below code shows how to handle exception from parallel thread. In this case we handle exception from only one thread.

 var task1 = Task.Factory.StartNew(() =>
                {
                    throw new Exception("throwing unhandled exception");

                }
                       );
                try
                {
                    task1.Wait();
                }
                catch (AggregateException ag)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Exception ex in ag.InnerExceptions)
                    {
                        sb.AppendLine(ex.Message);
                    }
                    MessageBox.Show(sb.ToString());
                }
                finally
                {
                    task1.Dispose();
                }

Posted in c#.net | Tagged: , | Leave a Comment »

Cross-thread operation not valid task parallel library

Posted by vivekcek on May 31, 2012

I have 2 drop down list in a windows form application. On the selected index change event of first i want to add an item to second drop down. I just used Task Parallel Library and wrote the below code. It give me an error like “Cross-thread operation not valid: Control ‘ddlRqType’ accessed from a thread other than the thread it was created on.”

My Initial Code

 private void ddlCMType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCMType.SelectedItem.ToString() == "Portal")
            {
                Task.Factory.StartNew(() =>

                    {
                        ddlRqType.Items.Add("hai");
                    }
                    );
            }
        }


Then i corrected it using Invoke and delegate

  private void ddlCMType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCMType.SelectedItem.ToString() == "Portal")
            {
                Task.Factory.StartNew(() =>

                    {
                        this.Invoke(new MethodInvoker(delegate { ddlRqType.Items.Add("hai"); }));
                    }
                    );
            }
        }

Posted in c#.net | Tagged: , | Leave a Comment »

Datatable to XML using LINQ

Posted by vivekcek on May 29, 2012

If you want to create an XML like this below


<Root name="root" xmlns="http://www.google.com/namespace">
<Child id="1" name="vivek" />
<Child id="2" name="chanthu" />
</Root>

From the table

 

The below code will be useful


DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");

DataRow dr = dt.NewRow();
dr["id"] = "1";
dr["name"] = "vivek";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["id"] = "2";
dr["name"] = "chanthu";
dt.Rows.Add(dr);

XNamespace x1 = "http://www.google.com/namespace";

XElement xt = new XElement(x1 + "Root", new XAttribute("name", "root"),
from p in dt.AsEnumerable()
select new XElement(x1 + "Child", new XAttribute("id", p["id"]),
new XAttribute("name", p["name"])));

Posted in c#.net | Tagged: , , | Leave a Comment »

Convert String to Stream c#

Posted by vivekcek on May 28, 2012

string response = string.Empty;
byte[] byteArray = Encoding.UTF8.GetBytes(response); 
MemoryStream respstream = new MemoryStream(byteArray);

Posted in c#.net | Tagged: | Leave a Comment »

Face Capture and Face Detection in c# using webcam PART 1

Posted by vivekcek on July 14, 2011

Hi Friends your friend vivek is here.The past month was very tough lots of emotional issues.Each days with .NET giving me new knowledge.
This time i was planning to develop an image based authentication system.My plan was to implement this system with in one day.

    Vivek’s Targets

1. Capture your face from your web cam.
2. Store that image and your information to a database.
3. Next time when you came to system,the system will check your face against the image stored in database.

In this article i just wanna implement the first step,that is how to capture image using a web cam.A small image of the application is given below.Hi hi i haven’t put my face on the application
because some of my friends always complain that i am writing blog for impressing girls.I don’t want that impression went to waste box.So put a match box in my hand.

OpenCV

    OpenCV is a tool developed by Intel in C++.OpenCV can do almost all image processing operations.Initially i planned to use OpenCV.Then i changed my mind because OpenCV
    is C++ oriented.After some Google search i found EMGU CV wrapper for .NET and c#.

    1. Capture your face from your web cam.

a. Download EmguCv and install it.
b. The installation folders bin folder contain all DLL’s for our development(C:\Emgu\emgucv-windows-x86 2.2.1.1150\bin).
c. Create a windows form project and add reference to Emgu.CV.dll,Emgu.CV.UI.dll,Emgu.Util.dll
d. Copy all OpenCV dll’s from Emgu’s bin folder(C:\Emgu\emgucv-windows-x86 2.2.1.1150\bin) to your applications Bin folder
e. Add Emgu controls to your visual studio toolbox from Emgu.CV.dll
f. Put an Emgu ImageBox in your form,in which we show captured image.
g. Put 2 buttons one to start capture image and next one to store that image to a database.

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 Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.Util;
namespace WebCamCapture
{
    public partial class Form1 : Form
    {
        private Capture _VivekCapTure;
        private bool _captureInProgress;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            #region if capture is not created, create it now
            if (_VivekCapTure == null)
            {
                try
                {
                    _VivekCapTure = new Capture();
                }
                catch (NullReferenceException excpt)
                {
                    MessageBox.Show(excpt.Message);
                }
            }
            #endregion
            if (_VivekCapTure != null)
            {
                if (_captureInProgress)
                {  //stop the capture
                    //captureButton.Text = "Start Capture";
                    Application.Idle -= ProcessFrame;
                }
                else
                {
                    //start the capture
                    //captureButton.Text = "Stop";
                    Application.Idle += ProcessFrame;
                }

                _captureInProgress = !_captureInProgress;
            }
        }
        private void ProcessFrame(object sender, EventArgs arg)
        {
            Image<Bgr, Byte> frame = _VivekCapTure.QueryFrame();
            captureImageBox.Image = frame;
            
        }
    }
}

Posted in c#.net | 2 Comments »

POP3 client using c#

Posted by vivekcek on June 14, 2011

Hi Friends,

This time i am coming with a very small solution for POP3 mail download from mail services like gmail,yahoo etc.Our client was an aggressive guy who need an application to download mail from his mail server and store these mails and attachments into a database table.The time given was 24 hours.After some Google search we decided to use OpenPop.NET an open source library.You can download it from http://hpop.sourceforge.net/.

Below i am going to explain the basics steps to test the DLL.

1. Create a windows form application.
2. Add reference to OpenPop.NET.DLL
3. Put a button in the form and check the code behind
4. Provide your mail credentials.

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.Threading;
using System.IO;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using OpenPop.Pop3.Exceptions;
using OpenPop.Common.Logging;
using Message = OpenPop.Mime.Message;
namespace mailtest
{
    public partial class Form1 : Form
    {
        private Pop3Client pop3Client;
        private Dictionary<int, Message> messages;
        public Form1()
        {
            InitializeComponent();
            pop3Client = new Pop3Client();
            messages = new Dictionary<int, Message>();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReceiveMails();
        }
        private void ReceiveMails()
        {
            try
            {
                if (pop3Client.Connected)
                    pop3Client.Disconnect();
                pop3Client.Connect("pop.gmail.com", 995, true);
                pop3Client.Authenticate("your@gmail.com", "yourpassword");
                int count = pop3Client.GetMessageCount();
                messages.Clear();
                int success = 0;
                int fail = 0;
                for (int i = count; i >= 1; i -= 1)
                {
                    try
                    {
                        Application.DoEvents();
                        string body;
                        Message message = pop3Client.GetMessage(i);
                        MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                        if (plainTextPart != null)
                        {
                            // The message had a text/plain version - show that one
                            body = plainTextPart.GetBodyAsText();
                        }
                        else
                        {
                            // Try to find a body to show in some of the other text versions
                            List<MessagePart> textVersions = message.FindAllTextVersions();
                            if (textVersions.Count >= 1)
                                body = textVersions[0].GetBodyAsText();
                            else
                                body = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
                        }
                        // Build up the attachment list
                        List<MessagePart> attachments = message.FindAllAttachments();
                        foreach (MessagePart attachment in attachments)
                        { }

                        // Add the message to the dictionary from the messageNumber to the Message
                        messages.Add(i, message);


                        success++;
                    }
                    catch (Exception e)
                    {

                        fail++;
                    }
                }
            }
            catch (InvalidLoginException)
            {
                //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
            }
            catch (PopServerNotFoundException)
            {
                //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
            }
            catch (PopServerLockedException)
            {
                //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
            }
            catch (LoginDelayException)
            {
                //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
            }
            catch (Exception e)
            {
                //MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
            }
            finally
            {

            }
        }
    }
}

Posted in c#.net | 2 Comments »

Validate an XML aganist an XSD Schema stored as embeded resource in a DLL

Posted by vivekcek on March 10, 2011

STEPS
—–

1.Add the schema to your library
2.Right click on the schmema file select properties set build action as embed resuorce.
3.Write a class XMLSchema in your library as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using System.Data;
namespace XMLParser
{
    public class XMLSchema
    {
        public bool ValidateXml(string xml,string xsdName)
        {
            try
            {
                //Declare a StreamReader and a StreamWriter
                StreamReader strmrStreamReader;
                //Extract the Resource using this line. Notice the namespace... ReadWriteResourceFromDLLorEXE!
                strmrStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("XMLParser."+xsdName));
                //Here we are creating a new file in the Application Startup path, and for fun
                //we are also changing the name to NewFile.txt
                System.Xml.Schema.XmlSchema xSchema = new System.Xml.Schema.XmlSchema();
                xSchema = XmlSchema.Read(strmrStreamReader, null);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(xSchema);
                settings.ValidationType = ValidationType.Schema;
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xml);
                XmlReader rdr = XmlReader.Create(new StringReader(xDoc.InnerXml), settings);
                while (rdr.Read())
                { }
               
            }
            catch
            {
                return false;
            }
            return true;


        }
        public bool ValidateXml(XmlDocument xml)
        {
            return false;
        }
    }
}

4.Create an instance of the XmlSchema class and call the method ValidateXml() with your xml and,the name of XSD u add as resource in your dll

Posted in c#.net | Leave a Comment »

How to Get CPU and Memory usage C#.Net

Posted by vivekcek on October 22, 2009

Ya after some long time i got chance to write an article
about,How to get CPU and Memory usage via our C#.NET.After some bit of research i found two methods are avialble,one by using WMI and System.Management class,till now i have n’t succeeded in implement the above scheme.Another simple methos avilable is using the PerformanceCounter class avilable in System.Diagnostic name space.You can find a lot of forums discussing about it also you can see that these codes show a 0% CPU use.So your are confused dont worry “Main hoon na”.

How to find the CPU usage?

1.Create a windows application in VS2005.
2.Add a timer to the Form set its interwell as 200,also set the enable property of timer true.
3.Declare an object of the performance counter class as
private PerformanceCounter cpuCounter; .
4.Create a method InitialiseCPUCounter() and initialize cpuCounter object as shown

private void InitialiseCPUCounter()
{
cpuCounter = new PerformanceCounter(
"Processor",
"% Processor Time",
"_Total",
true
);
}


5.On the tick event of the timer write the following code

private void updateTimer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = "CPU Usage: " +
Convert.ToInt32(cpuCounter.NextValue()).ToString() +
"%";
}

6.Dont forget to call the InitialiseCPUCounter() method from Forms constructor and also start the timer at there.

CPU usage

Full code is given below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsApplication5
{
    public partial class Form1 : Form
    {
        
        private PerformanceCounter cpuCounter;
        private PerformanceCounter ramCounter;
        public Form1()
        {
            InitializeComponent();
            InitialiseCPUCounter();
            InitializeRAMCounter();
            updateTimer.Start();
        }

        private void updateTimer_Tick(object sender, EventArgs e)
        {
            this.textBox1.Text = "CPU Usage: " +
            Convert.ToInt32(cpuCounter.NextValue()).ToString() +
            "%";

            this.textBox2.Text = Convert.ToInt32(ramCounter.NextValue()).ToString()+"Mb";
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void InitialiseCPUCounter()
        {
            cpuCounter = new PerformanceCounter(
            "Processor",
            "% Processor Time",
            "_Total",
            true
            );
        }

        private void InitializeRAMCounter()
        {
            ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);
        
        }
    }
}

Posted in c#.net | 3 Comments »

Decoding hex values using c#.net

Posted by vivekcek on August 24, 2009

The following method can be used for the above purpose.

private string Decode(string input)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int len = input.Length;
        int i = 0;
        int sIx = 0;
        while (true)
        {
            if (input[i] == '%')
            {
                sb.Append(input.Substring(sIx, i - sIx));
                string hc = input.Substring(i + 1, 2);
                int hi = int.Parse(hc, System.Globalization.NumberStyles.HexNumber);
                char c = (char)hi;
                sb.Append(c);

                sIx = i + 3;
                i = i + 2;
            }
            i++;

            if (i >= len)
            {
                sb.Append(input.Substring(sIx));
                break;
            }
        }

Posted in Asp.net, c#.net | 1 Comment »

Invoking javascript method vis webbrowser control

Posted by vivekcek on August 24, 2009

Some times when we are doing screen scrapping,We have to invoke some javascript methods in the page.For example if there is a method named “ChangeOptions” with 3 parameters “cmb_originCity”, “cmb_destCity”, “ArrCity”.Then we can invoke this by

object[] pp = new object[] { "cmb_originCity", "cmb_destCity", "ArrCity" };
                    this.WBrowser.Document.InvokeScript("ChangeOptions", pp);

Posted in c#.net | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.