Monday, April 29, 2013

Make System Tray Based Application in .NET,Open Application in start menu tray / notification area c#


Creating an application that lives in the system tray is easy, but it is not entirely obvious how to do so in Visual Studio. This recipe will show you the steps.

1) First, create a new Windows Application project in Visual Studio.NET. This can be either Visual Basic or C#
2) Drag a Notifyicon control and a ContextMenu control from the toolbox onto the form.
3) Click on the NotifyIcon control that you just added, and set the Icon property to whatever icon you want your application to have.
4) Set the ContextMenu property of the Notifyicon to the context menu that you added to your project.
5) Right click on the Context Menu control, and select Edit. Since this menu will be the right-click menu for your tray icon, you will want to add the items that the user will see. Make sure to add an Exit menu item.
6) Double click the Exit menu item, and add the following code:this.Close();
7) Now for the important settings. Click on the form, and go to the Properties window. Set the following settings:FormBorderSize: Fixed Tool Window
WindowState: Minimized
Opacity: 0%
ShowInTaskbar: False
The key thing to remember is that the default form is not to be used for application functionality, it is only used as the hidden background window. If you want to create a new window, you can just add another form to your application.

How to Loop through Enum Values in C#, Loop on Enum

enum WeekDays { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

string[] days = Enum.GetNames(typeof(WeekDays));//Hear You Can Set Your Enum Type
foreach (string s in days)
{
       Console.WriteLine(s);
}

How can I to clear a selection in a dataGridView c#

dataGridView1.ClearSelection();

C#: Split String Using a Variable Length Delimiter,Splitting Strings


Splitting Strings Using char[]


string words = "This is a list of words, with: a bit of punctuation.";string [] split = words.Split(new Char [] {' ', ',', '.', ':'});


This would produce the string array:
{ "This", "is", "a", "list", "of", "words", "with", "a", "bit", "of", "punctuation" }

Splitting Strings Using string[]

string words = "This is a list of words: aesthetics, praefect"; string[] separators = {", ", "ae"};
string[] split = words.Split(separators, StringSplitOptions.None);
This would produce the string array:
{ "This is a list of words: ", "sthetics", "pr", "fect" }

Sunday, April 28, 2013

ER Relational Data Model


ER to Relational Data Model

9.1 An Entity-Relationship (ER) Diagram

                                  --                                --------                            -----       ----             ||||||       N||-WORKS  -FOR----           -|Lname||-     ||  -----   ----      ||||||||||||||    |--|||||||-||-   -|||||||||||||      |Fname|-|-|      ||-|Name|-- ||M   |-Locations||-            |-|||||-- ||    ---------------|            |Name||| ||     -DEPARTMENT-----|||||||||||||        --||||  |  |||--|||||||-|- || ||||NumOfEmployees |||-        -Ssn--  | ||| -|Number|||----1- |||||||||-|||||||||         -------||||--|       ----    ----         |EMPLOYEE    -----1--MANAGING   ---         ----||--||-----     -----    -||--            ||    |||  ------    -----||||||||||||-          |||-------|||     ------   ||StartDate||-- employee|||--      ---|employer  --1--      N||SUPERVISION   ||1     ----- ----         ----      -----   -----        -----            --------     ----              -----                -        --DEPENDENTS    -OF----                             ----      -----                        ||||||  --------                       |Name- --   |N                        |||||--------------|          -|||||||||||||||--|--------------|           ||Relationship||| --DEPENDENT-----

9.2 A Relational Data Schema

EMPLOYEE
FnameLnameSSN¯SupervisorSSN
DEPARTMENT
NameNUMBER¯MANAGER-SSNStartDate
DEPENDENT
RelationshipEMPL-SSN¯Name¯
DEP-LOCATION
LocationDEP-NUMBER
WORKS-FOR
EmployeeSSNDeptNumber
Comments:
EMPLOYEE (SupervisorSSN)EMPLOYEE (SSN)
DEPARTMENT (MANAGER-SSN)EMPLOYEE (SSN)
DEPENDENT (EMPL-SSN)EMPLOYEE (SSN)
DEP-LOCATION (DEP-NUMBER)DEPARTMENT (NUMBER)
WORKS-FOR (EmployeeSSN)EMPLOYEE (SSN)
WORKS-FOR (DeptNumber)DEPARTMENT (NUMBER)
unique: DEPARTMENT.NAME
create table EMPLOYEE{ 
  Fname... 
  Lname... 
  SSN... primary key 
  SupervisorSSN... reference EMPLOYEE(SSN) 
} 
create table DEPARTMENT{ 
  NAME... 
  NUMBER... primary key 
  MANAGER-SSN... references EMPLOYEE(SSN) 
  StartDate 
} 
create table DEPENDENT{ 
  Relationship... 
  EMPL-SSN... references EMPLOYEE(SSN) 
  Name ... 
  primary key(EMPL-SSN,Name) 
} 
create table DEP-LOCATION{ 
  Location... primary key 
  DEPNUMBER... references DEPARTMENT(Number) 
} 
create table WORKS-FOR{ 
  EmployeeSSN... references EMPLOYEE(SSN) 
 DeptNumber... references DEPARTMENT(Number) 
}  

9.3 The Mapping

(Strong) Entity Type into Relation

  • Include the simple attributes
  • Include the simple components of the composite attributes
  • Identify the primary keys
  • Don’t include: non-simple components of composite attributes, foreign keys, derived attributes, relational attributes
      -||||||||| |||||||         ||||||||||||       ||Lname||-||Name-|-      -||Locations|||- -||||||||-|      |||||-------------|||||||||| -|Fname---|||||   | DEPARTMENT    |       -|Name||-    ----|||-------------|||||-|||||||||    |||||  |    --|||||||||-      |||NumOfEmployees ||||-    |Ssn-- |    -|Number|||-          |||||||||||||||    ||||-- |     -------------|     -EMPLOYEE----|
EMPLOYEE
FnameLnameSSN¯
DEPARTMENT
NameNumber¯

Binary 1:1 Relationship Types into Foreign Keys

  • Include as foreign keys, in the relation of one entity type, the primary keys of the other entity type
  • Include also the simple attributes of the relationship type
  • If possible, the first entity type should have total participation in the relationship (to save memory!)
       -|||||||||        -|Lname||-   ----------------|  |||||||||   -||||||||-|       |DEPARTMENT     ---|Number-|--  ||Fname|-|-||||    -------||-------|||||||||||| -Ssn -  |Name||--          ||1     |Name||--  |||---  |||            --------  |-------|----|    1 ----       ----  |EMPLOYEE------------MANAGING  ----                        ----- --||||||||||                            --||StartDate||-                                 ||||||||
EMPLOYEE|--------|-----| -Fname--|Lname---|SSN--|     MANAGING   -- -- -- --      DEPARTMENT-------- |       |        |     |--   |      |         |       |  |        |        | --------|--------|-123-| ----MSSN-- |StartDate-|Number |  -Number---Name----| |       |        | 321 |--- --123    |        1     ---- |1       |        | --------|--------|------  --------  |---  -- -|---- --|- ------------------| |       |        | 231 |     |321--  |--  ----2-- --  |  |2-------|--------| ------------------------
EMPLOYEE|--------|-----| Fname---|Lname---|SSN--|     -- -- --     --  DEPARTMENT-------- |       |        |     ---   |      |        |        |        | --------|--------|123--| ----MSSN-  -StartDate|Number---Name----- |       |        |321  ---- - 123   |        |  1     |        | --------|--------|------  ---|---- --   -- --|------------------ |       |        |231  |     |321-- |--     ----2-----|--------- ------------------------
DEPARTMENT
MANAGER-SSNStartDate

Binary 1:N Relationship Types into Foreign Keys

  • Add as foreign keys, to the relation of the entity type at the N side, the primary keys of the entity type at the 1 side (don’t duplicate records!)
  • Include also the simple attributes of the relationship type
                 -|||||||||                  -|Lname||-             -||||||||-|        -|||||Fname|-|-|||||        |Ssn--     |Name||--          -------------|          -EMPLOYEE----|             |||  |||            || ---- ||          ||----  ----|| employee||--        --|employer      N |-SUPERVISION ---|1           ----    ----               ----
EMPLOYEE|--------|-----|     SUPERVISION--|     EMPLOYER-------|-------| Fname---|Lname---|SSN--|     SSN-|MGRSSN--|     SSN---|Fname---|Lname--| |       |        |     |    --   |        ------|     |        |       | --------|--------|123--| ----321-| 123 ----| ----123---|--------|-------| |       |        |321  |-- --231 | 123     ---   321   |        |       | --------|--------|---------- -- -- -- ----      ------|--------|-------- |       |        |231  |-                       231   |        |       | ------------------------                        ------------------------
EMPLOYEE|--------|------|-- -- --|     EMPLOYER--------|-------| -Fname--|-Lname--|SSN-- MGRSSN --|     -SSN---|Fname---|Lname- | |       |        |      |        |    -|      |        |       | --------|--------|-123- |-- -- --| --|||123---|--------|------ | |       |        | 321  |123     |--|| |321   |        |       | --------|--------|------|-- -- --||||  -------|--------|-------| |       |        | 231  |123     ||    |231   |        |       | ------------------------ -- -- --      ------------------------
EMPLOYEE|--------|-----|--  -- --| Fname---|Lname---|SSN--|MGRSSN --| |       |        |     |         | --------|--------|123--|--  -- --| |       |        |321  | 123      | --------|--------|--------  -- --| |       |        |231  | 123      | --------------------------  -- --
EMPLOYEE
SupervisorSSN

Binary M:N Relationship Type into Relation

  • We don’t want to duplicate records!
  • Set as foreign keys the primary keys of the participating entity types
  • Include the simple attributes of the relationship type
                       ------      |||||||||-     ----    ----   |||||Lname||| N |-WORKS  -FOR --- |Fname||--|      ||----      -----  |||||--||||||-|||    ---||---       |Name||--||        |M   -||-||  |  |||  ---------------|   -Ssn--  | |||   |DEPARTMENT    |       --- ||||    ----------|||---    --------||---|--||||-|- -|||||||||-    -EMPLOYEE----|-|Name||- ||Number||-
EMPLOYEE|--------|-----|     WORKS-|-FOR------|      DEPARTMENT|-------| -Fname--|Lname---|SSN--|     SSN-----Number----      -Number---Name----| |       |        |     |-----|     |          --------         |       | --------|--------|-123--||-----123-------1-------    -------1------------| |       |        | 321  |--- --123-------2-------------|    2    |       | --------|--------|------   ---     |          --- ---|----------------- |       |        | 231  |---  -321-------1------- --- ------------------------   --|231   |   2      --                              |-----------------
WORKS-FOR
EmployeeSSNDeptNumber

N-Ary Relationship Type

Similar to binary M:N relationship type

Multivalued Attribute into Relation

  • Include the given attribute
  • Include as foreign keys the primary attributes of the entity/relationship type owning the multivalued attribute
  • Keys not designated within primary keys are to be mentioned as such in side comments
   -|||||||       ||||||||||||||   -|Name|--       |||Locations||-      -||-------------|||-|||||      -DEPARTMENT-----| -|||||||--|    |||||-||||||||||||||||- ||Number||-     |||NumOfEmployees|||||
DEP-LOCATION
LocationDEP-NUMBER¯
Resembles the treatment of a relationship type.

Weak Entity+Relationship Types into Relation

  • Include simple attributes
  • Add the owner’s primary key attributes, as foreign key attributes
  • Declare into a primary key the partial keys of the weak entity type combined with those imported from the owner
        --|||||||| -|||||||||Lname||-            ---- ||Fname|---||||||          ----- -----          ||Name||-      -----       -----      --|||- |||     -----               ----      -Ssn--  |   ---- --DEPENDENTS   -OF---       -------|-----|     -----     -----       |EMPLOYEE    |-|||||||--------       ------------- -|Name---   |              ||||       ----------------|        ||Relationship||-----------------||        |||||||||||||||| --DEPENDENT-----
DEPENDENT
RelationshipEMPL-SSN¯NAME¯
Reference: Ch. 7.1 in textbook.

entity-relationship model (ERM or ER model)

What is entity-relationship model (ERM or ER model)? - Definition from WhatIs.com

Thursday, April 25, 2013

append text in file ,append string text to the text File, insert string to the file


private void WriteToLog(string file, string message)
        {
            using (StreamWriter w = File.AppendText(file))
            {
                w.WriteLine( DateTime.Now.ToString() + ": " + message); w.Close();
            }
        }

Capture To the Screen

Fastest Way to convert String to Csv


private DataTable StrTOCSV(string content)
        {
            DataTable tbl = new DataTable();
            if (content.Length > 0)
            {
                string[] rows = content.Split('\n' );
                if (rows.Length > 0)
                {
                    //Create Columns in Datatable.
                    string[] cols = rows[0].Split(new [] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (cols.Length > 0)
                    {
                        foreach (var item in cols)
                        {
                            tbl.Columns.Add(item);
                        }
                    }
                    //Add rows in datatable
                    for (int i = 1; i < rows.Length; i++)
                    {
                        string[] coldata = rows[i].Split(new [] { "," }, StringSplitOptions.RemoveEmptyEntries);

                        DataRow dr = tbl.NewRow();

                        for (int j = 0; j < cols.Length; j++)
                        {
                            if (coldata.Length > 0)
                            {
                                if (j <= coldata.Length)
                                {
                                    dr[j] = coldata[j];
                                }
                            }
                        }
                        tbl.Rows.Add(dr);

                    }

                }

            }
            return tbl;
        }

Convert Array To List In C#


List<string > ArrayToList(string[] arr)
        {
            List<string > retVals = new List<string >();
            foreach (string item in arr)
            {
                retVals.Add(item);
            }
            return retVals;
        }

Tuesday, April 23, 2013

Download Image From URL in C#

string url = "paste here your image url" ;
            WebRequest requestPic = WebRequest .Create(url);
            WebResponse responsePic = requestPic.GetResponse();
            Image webImage = Image .FromStream(responsePic.GetResponseStream());
            ImgChart.Image = webImage;

download data from Url in c#

string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" + Cmbsym.Text + "&f=sl1d1t1c1hgvbap2" ;
            string GetData = GetDataFromURL(yahooURL);



public static string GetDataFromURL( string URL)
        {
            string Content = "" ;
            int Failure = 0;
            HttpWebRequest WebReq;
            HttpWebResponse WebResp = null ;
            StreamReader Strm = null ;
        TryAgain:
            try
            {
                if (Failure == 3)
                    return "" ;

                WebReq = ( HttpWebRequest)WebRequest .Create(URL);
                WebReq.Timeout = 50000;
                WebResp = ( HttpWebResponse)WebReq.GetResponse();
                Strm = new StreamReader (WebResp.GetResponseStream());
                Content = Strm.ReadToEnd();
                Strm.Close();
                Strm.Dispose();
                WebResp.Close();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("(404) Not Found" ))
                { }

                if (Strm != null )
                {
                    Strm.Close();
                    Strm.Dispose();
                }

                if (WebResp != null )
                {
                    WebResp.Close();
                }
                Failure++;
                goto TryAgain;
            }

            return Content;
        }

Send Mail In New Thread Using Background Worker in C#

using System.Net.Mail;

public static void DoMails( string Msg)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler (worker_DoWork);
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = false;
            worker.RunWorkerAsync(Msg);//passing argument
        }

        private static void worker_DoWork( object sender, DoWorkEventArgs e)
        {
            DoMail(e.Argument.ToString());
        }

private static void DoMail( string Msg)
        {
            string MailFrom = "Abc@gmail.com"; //from Mail id
            string MailTo = "Xyz@yahoo.com";//to mail id
            string SmtpHostServer = "smtp.gmail.com"; // your server
            string MailUserID = MailFrom;
            string MailPassword = From mail id password;
            string MailSubject = "Hello";//your subject
            string MailMsg = Msg; //your msg
            string MailPort = Properties.Settings .Default.Port;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(SmtpHostServer);

                mail.From = new MailAddress (MailFrom);
                mail.To.Add(MailTo);
                mail.Subject = MailSubject;
                mail.Body = MailMsg;
                //if you have attachment file then decomment below code
                //if (File.Exists(TxtAttechment.Text))
                //{
                //    Attachment FileAttachments = new Attachment(TxtAttechment.Text);
                //    mail.Attachments.Add(FileAttachments);
                //}

                SmtpServer.Port = "956";//your server port
                SmtpServer.Credentials = new System.Net.NetworkCredential (MailUserID, MailPassword);
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
            }
            catch
            {
                //MessageBox.Show("Mail Not Send : " + ex.Message.ToString());               
            }
        }