Friday, November 30, 2012

Singleton - Design Pattern (OOP)

Intent

  1. Ensure a class has only one instance, and provide a global point of access to it.
  2. Encapsulated " just in time initialization " \ "initialization on first use "


Issue 
When the application needs one instance of an object ( one and only one ).
As an extra factor, Lazy Initialization and Global access are necessary.

Monday, October 1, 2012

Closing Multiple Forms in C# ( including parent form )


Open Form2 from Form1, close Form1 from Form2


Form1:
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }
Form2:
public partial class Form2 : Form
{
    Form opener;

    public Form2(Form parentForm)
    {
        InitializeComponent();
        opener = parentForm;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        opener.Close();
        this.Close();
    }
}

Convert Image to Base64 String and Base64 String to Image

Convert Image to Base64 String and Base64 String to Image

Learn how to convert Image to Base64 String and Base64 String to Image. (Online Converter Image to Base64)

Online Converter Image to Base64
This article will help you to learn how we can convert an image into a base64 string and base64 string back to image.

Image to Base64 String

public string ImageToBase64(Image image, 
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Base64 String to Image

public Image Base64ToImage(string base64String)
{
  // Convert Base64 String to byte[]
  byte[] imageBytes = Convert.FromBase64String(base64String);
  MemoryStream ms = new MemoryStream(imageBytes, 0, 
    imageBytes.Length);

  // Convert byte[] to Image
  ms.Write(imageBytes, 0, imageBytes.Length);
  Image image = Image.FromStream(ms, true);
  return image;
}

C# | Utility

Information Courtesy : http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx

Friday, August 31, 2012

Creating a Database Connection and Data Access in Windows Mobile 6.5 Application - C#


In this article we will be talking about a major subject for mobile application development : Database Connection

If you want to develop Windows Mobile applications you should install Visual Studio 2008 and these SDKs:
After installing these SDKs we open Visual Studio 2008 and we choose File->New->Project->Smart Device->Smart Device Project.

1.gif
After that we see the screen below and we choose

from Target Platforms-> Windows Mobile 6 Professional SDK 
from .NET Compact Framework version->3.5 
from Templates-> Device Application as you can see.

2.gif
After making these settings we see our emulator on the screen and everything is ready to start coding.

3.gif
To develop database applications in mobile devices we need to install SQL Compact Edition (SQLCE).We installed it when we install our SDKs at the beginning. So we can add a database to our project and try to get data from database.

To see Server Explorer in our project we choose Server Explorer from View menu. In Solution Explorer we right click to project and choose Add->New Item.We choose from Data tab Database File.

4.gif
Now it is time to create a new table. It is exactly same as the SQL Server, we just right click on Tables under Databases and choose Create New Table.

5.gif
We save our table as tbl1 and as you can see below we create two column named id and name. We mark id as primary key.

6.gif 

Now, to see our table's data we right click on tbl1 and choose show table data.

7.gif

As you guess our table is empty because we did not add anything to table.We add our data in table save it. 

8.gif
Now it is time to acces database on our project and get the data. To do this first we have to add SqlServerCe to our project as a reference. We right click to our project and choose Add Reference. We choose System.Data.SqlServerCe from reference list as shown below. From now on Visual Studio will recognize SqlCe commands in our project.

9.gif
We turn back to our application and drag a textbox and a buton to our form.Our scenario is that : We want to see on the textbox the name of the person whose id=1.So we expect to see on textbox "duygu".

10.gif
We open applications code behind and add namespace System.Data.SqlServerCe.

After that we double click the buton and write these codes:

11.gif
First 3 lines as you can guess we create our connection string. On 4th line we create our connection and 5th line we write the query for our scenario. 7th line we run our command cmd and get data from database and show it on textbox. As you can see all steps are same as SQL Server. Now we can run our project we pres F5 and see a screen like that:

12.gif
We make settings as above and click deploy. It could take some time to run we should wait and finally we can see our application as shown below.

13.gif

Windows Mobile 6.5 Database Connection and Data Access


We just click the buton and see the result of our application.

14.gif
Also we see the information we want. 

We talked about connecting database and getting data from database on Mobile applications and we saw there is no difference between Sql Server and SQL Compact Edition on these steps.

Friday, July 13, 2012

To check is the Text Property has some value inside of it, and its not null, - C#


if(!String.IsNullOrEmpty(textBox.text)
{
   //code here
}
else
   MessageBox.Show(Please insert some text...");


//or:
if(textBox.Text != Stirng.Empty)
{
   //code here
}
else
   MessageBox.Show(Please insert some text...");

Sunday, July 8, 2012

Retrieve System Date to a String C#

String s = DateTime.Now.ToString("dd/MM/yyyy");
MessageBox.Show(s);

Read all the Records in a Database to a GridView



 private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection connection = new SqlConnection();

            SqlDataAdapter dataAdapter;
            DataSet dataSet;
            connection.ConnectionString = Trial.Program.Globals.db.connectionString;

            connection.Open();

            dataAdapter = new SqlDataAdapter("select * from Item", connection);

            dataSet = new DataSet();
            DataTable t = new DataTable();

            dataAdapter.Fill(t);
            dgvAllItems.DataSource = t;

            connection.Close();  }

Index ID incrementer for writing new Data to SQL using C# form



private void Form1_Load(object sender, EventArgs e)
        {
            SqlDataAdapter dataAdapter;
            DataSet dataSet;
            //IEnumerator iEnumerator;
            SqlConnection connection = new SqlConnection(Trial.Program.Globals.db.connectionString);
            dataAdapter = new SqlDataAdapter("select * from Cust", connection);
            dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
            int rows = dataSet.Tables[0].Rows.Count;          
            //MessageBox.Show("No. of Rows are : " + rows.ToString());
            int rowcount = rows + 1;
            txtCustNo.Text = rowcount.ToString();
        }


this code helps to generate the index number which is there to to add data next... :)

Retrieve Data from a Database ( Data Adapter / Data Reader) without using a DataGridView


//using System.Data.SqlClient; //header

using (SqlConnection connection = new SqlConnection(Trial.Program.Globals.db.connectionString))
using (SqlCommand command = new SqlCommand(" select itemName from Item ", connection))
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                           listBox1.Items.Add(reader["itemName"].ToString());
                        }
                    }
                    reader.Close();
                }
                connection.Close();
            }

here you can use a data reader(SqlDataReader) instead of using a data adapter(SqlDataAdapter).

Thursday, July 5, 2012

Live Running System Clock in C# form


public partial class parent : Form
{
        Timer clock;

        public parent()
        {
            InitializeComponent();    
        }

       private void parent_Load(object sender, EventArgs e)
       {
           clock = new Timer();
           clock.Interval = 1000;
           clock.Start();
           clock.Tick += new EventHandler(Timer_Tick);
       }

     
       public void Timer_Tick(object sender, EventArgs eArgs)
       {  
           if (sender == clock)
           {
              lblLiveUp.Text = DateTime.Now.ToString();
           }
       }
}

Make a Form a Parent (MDIParent) for a child form in C#

Type this inside the event which you call the child MDI form
from the parentMDI form.

Inside Parent Form:

            frmSearchCust frmCSearchCust = new frmSearchCust();
            frmCSearchCust.MdiParent = this;
            frmCSearchCust.StartPosition = FormStartPosition.CenterScreen;
            frmCSearchCust.Show();

Read from a database table (SQL) in C#

using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)
{
            //to read from DB
            string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Thisal Lekamge\Desktop\Shohan\new\ChainMan.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand(" select * from Item ", connection))
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            MessageBox.Show(reader["itemName"].ToString());
                            MessageBox.Show(reader["itemDescription"].ToString());
                        }
                    }
                    reader.Close();
                }
                connection.Close();
            }


}

Write to a SQL Database using C#

using System.Data.SqlClient;

private void btn_ok_Click(object sender, EventArgs e)
{
            //write to db
            string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Thisal Lekamge\Desktop\Shohan\new\ChainMan.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("INSERT INTO Item (itemName, itemDescription) VALUES (@itemName, @itemDescription);");

                cmd.CommandType = CommandType.Text;
                cmd.Connection = connection;

                cmd.Parameters.AddWithValue("@itemName", textBox3.Text);
                cmd.Parameters.AddWithValue("@itemDescription", textBox5.Text);

                connection.Open();

                cmd.ExecuteNonQuery();

                connection.Close();
              }

}

Where & How to create a global variable in for a Connection String in C#

Declare your Global Variable in "Program.cs" file


public static class Globals
{
            public static class db
            {
                public const string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Thisal Lekamge\Desktop\Shohan\new\ChainMan.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            }
 }


Use it as follows in other .cs files

Trial.Program.Globals.db.connectionString "

Here;



Trial is the name of the Visual Studio Project
Program stands as its a programme.

Wednesday, February 29, 2012

Advantages and Disadvantages of Decision Tables / Decision Trees

Decision Table(MATRIX) Advantages

Help the Analyst to ensure the completeness and the accuracy.

Decision Tree Advantages 


Easy to understand 
Map nicely to a set of business rules 
Applied to real problems 
Make no prior assumptions about the data 
Able to process both numerical and categorical data 

Decision Tree Disadvantages 

Output attribute must be categorical 
Limited to one output attribute 
Decision tree algorithms are unstable 
Trees created from numeric datasets can be complex

Thursday, January 19, 2012

C++ - Defining friendship in more than one class - Method Two


//Friends in multiple classes - Defining friendship in more than one class.
#include<iostream>
using namespace std;

//forward declaration of classes
class Circle;
class Square;

class Circle
{
char cColour[20];
public: Circle( char x[20])
{ strcpy(cColour,x);}
friend bool compare(Circle, Square);

};

class Square
{
char sColour[20];
public: Square( char y[20])
{ strcpy(sColour,y);}
friend bool compare(Circle, Square);
};

bool compare(Circle p, Square q)
{
int cmp;
cmp = strcmp(p.cColour,q.sColour);
if (cmp==0)
return true;
else
return false;


}


void main()
{
Circle cir("REED");
Square sqr("RED");
if (compare (cir,sqr))
cout<<"same"<<endl;
else
cout<<"diff"<<endl;

system("pause");
};

C++ - Defining friendship in more than one class - Method One


//Friends in multiple classes - Defining friendship in more than one class.
#include<iostream>
using namespace std;

//forward declaration of classes
class Circle;
class Square;

class Circle
{
char cColour[20];
public: Circle( char x[20])
{ strcpy(cColour,x);}
friend void compare(Circle, Square);
};

class Square
{
char sColour[20];
public: Square( char y[20])
{ strcpy(sColour,y);}
friend void compare(Circle, Square);
};


void compare(Circle p, Square q)
{
int cmp;
cmp = strcmp(p.cColour,q.sColour);

if (cmp == 0)
cout<<"Same Colour"<<endl;
else
cout<<"Diff Colour"<<endl;
};

void main()
{
Circle cir("REED");
Square sqr("RED");
compare (cir,sqr);
system("pause");
};