Monday, 15 October 2012

ASP.Net C# Retrieving values to a list from SQL server

Adding values to a ASP.Net ComboBox(No data binding) and Retrieving data to a List from the database


This problem started when I had a problem data binding a DataTable object to a ComboBox in C# WinForms application. I have been using Java Swing framework for a while and I always used a List or an ArrayList and loops to add values in to "JComboBox"es.
So I wanted to do the same thing with WinForms :D

This tutorial discuss the following

  • Connecting to the database
  • Retrieving DB values to a list
  • Loading List values to a ComboBox without data binding
  • Loading selection values of ComboBox from database
  • Getting values according to the selected value in ComboBox


Instead of adding some few code chunks. I will add a full project, so that you can build it from scratch yourself.

To demonstrate a common problem I will take 2 ComboBoxes and 2 Labels added on to a WinFrom.

1. Create a new Windows Forms Application. Make sure you give it a proper name and save it in a nice location :D. After that you will see some thing close to this 



also you will be able to see a blank form like this happily sitting on the designer


Double click on the from so the From_Load method can be automatically generated.
(or just add the damn thing manually)




























Rebuild and run the project so that you can be happy about no errors ...


2. OK, since we are happy with the Form, lets add two Labels and 2 ComboBoxes in to the from.








3. Its DB time now. Fire up the SQL server and create the following table...
(Passion is the database, and sampleTable is the table name. The IDENTITY(2, 1) make the table auto increment table values. 2 is the starting point and 1 means increments one by one )



CREATE TABLE Passion..sampleTable
(
sampleID INT PRIMARY KEY IDENTITY(2,1),
sampleValue VARCHAR(50)
)


lets add the following data in to the table 

INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues0');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues1');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues2');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues3');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues4');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues5');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues6');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues7');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues8');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues9');
INSERT INTO Passion..sampleTable(sampleValue) VALUES('SampleValues10');



4. Its time for the crazy connection string now(this always drives me nuts). So to add the connection string, right click on the project and add an "Application Configuration File". If you keep the default name(App.config), the project will look like this. :D






5. Double click the App.config file and add a connection string to this file.
The code looks like the below...


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
    <add name="PassionConnectionString" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Passion;Integrated Security=True"
     providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>



here's the breakdown of the above code :


  • name="PassionConnectionString" is the name that we can use to access this connection string from the c# code. Also, since we can add multiple connection strings, we can identify each connection string with this distinct name.
  • Data Source=localhost\SQLEXPRESS is the server path localhost\SQLEXPRESS is the default locally running server path.
  • Initial Catalog=Passion Passion is the name of the database, the relevant table exist in.


6. We can call this connection string any time we like. But its a good idea to use this connection string and create a connection object class to get a connection object instead of writing connection code every single time (this was taught to me in the uni, I did'mt come up with idea).

So, lets add a new class called ConnectionManager to the project. After that the solution should look like the following.





7. Now that we have created the class, we need to add some code in to it. 
Notice the part with the Connection string name :D 

class ConnectionManager
    {
        public static SqlConnection NewCon;
        public static string ConStr = System.Configuration.ConfigurationManager.ConnectionStrings["PassionConnectionString"].ConnectionString;

        public static SqlConnection GetConection()
        {
            NewCon = new SqlConnection(ConStr);
            return NewCon;
        }
    }


When you create the class like this, you will see some parts with errors. To get rid of them you will need to right click the project and add a reference to System.Configuration under the .NET tab first and also import System.Data.SqlClient

Clean and build the project and check to see if there are errors. No errors ? happyyyyyyyyyyyy :D 

8. Lets create a data access class in this project. The data access class can contain all the code and queries to access the actual data from the database. 
It should be noted that, some of the methods I use (for example, like writing sql in a C# file) might not be the best way of doing something, if you feel that you have a better way of doing it, well go nuts...)

So, lets create the class DBAccess




since we are work with data and also going to work with lists import the following in to the class


  • System.Collections.Generic;
  • System.Data;
  • System.Data.SqlClient;



9. Les leave the DBAccess class for a little bit. As we need to load up some objects to the list. Lets create a class for the object we are going to load.
Lets call it the SampleClass



10. Add the following code the the SampleClass



 class SampleClass
    {
        public int ID { get; set; }
        public string Variable { get; set; }

        public override string ToString()
        {
            return Variable.ToString();
        }
    }

I try to match the data types with the value types retrieving from the database. At the end of the day, we are going to assign the values from database to this object.

Notice the override, this is used like this, because, when the values and IDs are assigned to the ComboBox and when a particular item from the ComboBox is selected, we can get this ID. So, we can retrieve data according to a selected ComboBox item.


11. OK, Lest get back to DBAccess class. Now I'm going to add 2 methods retrieving 2 lists. Then we can do some experiments with this :D
Change the DBAccess class to look like this


class DBAccess
    {
//we can assign this the object from connection manager
        SqlConnection conn;

//assigning the connection object
        public DBAccess()
        {
            conn = ConnectionManager.GetConection();
        }

//heres the method for the first list
        public List<SampleClass> getList()
        {
            if (conn.State.ToString() == "Closed")
            {
                conn.Open();
            }

            SqlCommand cmd = conn.CreateCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from Passion..sampleTable";
            SqlDataReader dr = cmd.ExecuteReader();

//the list to store the objects we retrieve
            List<SampleClass> outputList = new List<SampleClass>();
            while (dr.Read())
            {
                SampleClass c1 = new SampleClass();
//[" <--->"] contains table column name
                c1.ID = Convert.ToInt32(dr["sampleID"]);
                c1.Variable = Convert.ToString(dr["sampleValue"]);
                outputList.Add(c1);
            }

//DON'T forget to close the connection
            conn.Close();
            return outputList;
        }

        public List<SampleClass> getList2()
        {
            if (conn.State.ToString() == "Closed")
            {
                conn.Open();
            }

            SqlCommand cmd = conn.CreateCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from Passion..sampleTable";
            SqlDataReader dr = cmd.ExecuteReader();

            List<SampleClass> outputList = new List<SampleClass>();
            while (dr.Read())
            {
                SampleClass c1 = new SampleClass();
                c1.ID = Convert.ToInt32(dr["sampleID"]);
                c1.Variable = Convert.ToString(dr["sampleValue"]);
                outputList.Add(c1);
            }

//DON'T forget to close the connection
            conn.Close();
            return outputList;
        }      
    }




12. Since we have the lists working. lets add the code to make the front end work.
So, double click Both ComboBoxes to generate box selection methods. Then fill the code to match with the following


public partial class Form1 : Form
    {
        DBAccess dba = new DBAccess();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FillBombo1();
            FillBombo2();
        }

        /// <summary>
        /// loads items from the list to the ComboBox
        /// </summary>
        private void FillBombo1()
        {
            List<SampleClass> lisSet = dba.getList();

            foreach (SampleClass item in lisSet)
            {
                comboBox1.Items.Add(item);
            }
        }

        private void FillBombo2()
        {
            List<SampleClass> lisSet = dba.getList2();

            foreach (SampleClass item in lisSet)
            {
                comboBox2.Items.Add(item);
            }
        }


        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Add the selected items ID to the label
            label2.Text = (comboBox2.SelectedItem as SampleClass).ID.ToString();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            label1.Text = (comboBox1.SelectedItem as SampleClass).ID.ToString();
        }
    }

Remember to change the variable names according to yours and also to import things you need, like the collections and generics.

Clean build and run the project

then you will see the form working fine :D






That's the end of our project

Now lets have some fun.
Comment the conn.Close() method of the first list class.
Now, run the project and notice that the ComboBox relevant to OTHER list, is not working properly (its empty).
So, I think you can get some idea about the connection and how data pass ;)

Cheers









Thursday, 16 August 2012

ASP.Net C# Zoom effect asp.net button

How to add effects to an asp.net button



So, suppose there is a situation where we need to have a zoom effect in an asp.net button ( that button in asp.net controls thinggies ...).
Its a known fact that new css allows you to add zoom and other crazy effects to you buttons, but asp.net button is not exactly a html button ( thats why its called an asp.net button I guess). So if you just add an asp button and try to call that button ID from the css using #<id>,
well, it wont work.
WHYYYYY???
simple, just drag and drop an asp.net button in to a web form and press view in browser, right click and check out the page source..
the button id is not the same as the one in the source, now its a computer generated ID. That means, its not a good idea to use #<id> to select the button from the style sheet.
but its not the end of the world,
instead, we can use  CLASSES :D

let me add some example code...

here is a sample css class for the button:
**Remember this doesn't work with IE yet

.buttonStuff
{
    width:60px;
    height:30px;
    font-weight: bold;
    background-color: Silver; 
    border-radius: .75em; 

    -webkit-transition: all.35s;/*Safari and Google chrome*/
    -moz-transition: all .35s; /* Firefox 4 */
    -o-transition: all .35s; /* Opera */

}

.buttonStuff:hover
{
    font-weight: bold;
    background-color: Red;  
    width:80px;
    height:40px;
}



this is how you call that class from the button:

 <asp:Button ID="Button1" class = "buttonStuff" runat="server" Text="Button" onclick="Button1_Click"  />

Now, this button will have rounded edges and when you hover over it, it'zoom it self etc.

in buttonStuff class, border-radius is the curve of the button.
-webkit-ransition: all .35s meas, do the "animating" to ALL the changes, when going in to the other state, here the hover is a different state, in this state button size is a different, font color, background color are different, these changes will apply smoothly in.35 seconds when the above line is added.

so try it out,

all you have to do is,

1. add an asp.net button to you aspx page.
2. add those 2 classes to the style sheet
3. call the style sheet from the page (if its not already called)
4. add that class to the button.

then you are done :D 


Monday, 16 January 2012

ASP.Net C# Passing values from a grid view


Passing values from a grid view (ASP.net C#)


When working in asp.net, I usually use gridViews to show and manipulate data. Well, it’s a good clean and easy way to get ad manipulate data from a db.
But suppose you select a value from a gridView and when you select it say… some sort of a key, it should pass into another page.
In this tutorial we will look at creating a simple data base table, creating a connection, getting data to a grid view and passing it to another page :D
Believe it or not, it’s not as hard as it sounds.

Well, first things first

Create a data base using ms sql server management studio express (wow that’s a long name …)
Go to the MSSMSE, log in to it and by right clicking the Databases folder, create a new database called
myTesting

now you will be able to see the newly created database. 
Select it and then click on the new query so that you can write sql for the database :D

Then you can write the following queries,

/*this is how we comment in sql*/

create table sampleTable(
id  int primary key identity (0, 1),
name varchar(100),
age int,
country varchar(100)
)

the create table  statement will create a table with the name sampleTable with attributes id, name,
age and country. In the table you can see data types as int and varchar.
id is set as the primary key
identity is a special feature in mssql server (as I remember, some of the other databases doesn't support that). It is defined as identity (SEED, INCREMENT). SEED means the starting value and INCREMENT means the value that it is incremented from. With this, we can make the identity auto increment.



run this query and see if the table is working properly, you will see an empty table
select * from sampleTable

Now insert some values in to the table....
note that I'm not inserting any values in to the id column because it will auto increment.

insert into sampleTable(name, age, country) values ('sampleName0', 13, 'sampleCountry0')
insert into sampleTable(name, age, country) values ('sampleName1', 16, 'sampleCountry1')
insert into sampleTable(name, age, country) values ('sampleName2', 17, 'sampleCountry2')
insert into sampleTable(name, age, country) values ('sampleName3', 17, 'sampleCountry3')
insert into sampleTable(name, age, country) values ('sampleName4', 18, 'sampleCountry4')
insert into sampleTable(name, age, country) values ('sampleName5', 19, 'sampleCountry5')
insert into sampleTable(name, age, country) values ('sampleName6', 13, 'sampleCountry6')


Run this query and you will see all the data in the table
select * from sampleTable

Run this and you will see only the name, age and country columns from sampleTable
select name, age, country from sampleTable

Run this and you will see all rows from the table where the age is greater than 17
select * from sampleTable
where age > 17



( if you don’t know how to run a query, all you have to do is highlight the relevant part of the query, and press execute… for example, if you want to run a select query , highlight select * from sampleTable and the press execute)

Now that creation of tables is complete, let us go to visual studio.

Start a new web site in C#, because I am bored, I keeping the name as the default one "WebSite1"

Now make a new page in the web site,
right click on the root that is in shown in the solution explorer, 

select Add New Item 

select Web Form (make sure you select visual c#, in Installed Templates)
Now change the name to TestingForm.aspx
click Add 


Now you will be able to see the page in the solution explorer.


ok, so lets do some cool stuff.

Now add a  gridView controller to the to the page.
(well you can do it in design or source view)

Now it should look like this in the design view.


Now, click on that > like thing in the data gridView and in the choose data source drop select <new data source >

select SQL data base
make the datasoruce name as appropriate.





select new connection 


select Microsoft SQL Server and press continue 





Now in the new window, for the server name TYPE, localhost\SQLEXPRESS ( server and instance name, change as appropriate ).
after entering the server name is entered, select the database. now press Test Connection

If the connection is successful, press OK



now you will be able to see the data connection press NEXT






Keep notice the data connection name and press Next





Leave them as they are and press next







press test query and you will see all the data that was inserted in to the db, press finish




Now run the application by right clicking and selecting view in browser ...







notice all the data is visible in the grid view






now go back to the TestingForm and in the gridView go to edit columns







add a HyperLinkField









Give it a name






Now, lets create a new web form called TestingForm2 , we will pass the selected gridView value from the TestingForm to this TestingForm2.





You can see the new page in the solution explorar








Now add a new Label to the newly created TestingForm2










Now lets get back to the TestingForm.aspx and edit that gridView, go inside it and select the link field and add the new TestingForm2.aspx  the NavigateURL










Select the TestingForm2.aspx so it is added as the navigation url







See  .... you can see the TestingForm2.aspx in the NavigateURL, press OK






Now, you can see the links in blue color that means, they are active so they can navigate to another page.








Right click the TestingForm and select view in browser and check out the page ...











Press the Go link in TestingForm and you will notice that you have navigated to TestingForm2









Now in the TestingForm2 you can only see the label, no values passed yet








Now go back to the TestinForm.aspx and edit the gridView as the following.
We edited the NavigateURL before,
now
set DataNavigateUrlFields to "id"
and set DataNavigateUrlFormatString to TestingForm2.aspx?id={0}
that is
<place to navigate>?<passingvalue>={0}










Now go to the code behind of the TestingForm2








not set the Label1's text to the values that were passed to the query string from the other page.
id is the identifying value we set ( you should see the code view of the gridView to get a better understanding of this).







Now run the page again
and press the Go link
















you can see the value passed to the other page





WOW that was long ... if this works, help ur self to a nice cup of tea :D :D

Hope this helps,
Cheers



Saturday, 14 January 2012

MS SQL server default instance

How to install SQL Severver Management Studio Express
(using a proper server instance to connect to the server)

Before installing this make sure you have installed the visual studio pack that was downloaded from the MSDN site or the dreamspark site.

go and search in the google for sql server management studio express and you will be able to download it easily and for free ( EXPRESS editions are free)




I am not going to talk about downloading the software much. Its not that difficult
well then install it keeping everything as default, of course change if necessary, make sure to remember the server instance name.  

well after you install the software, when you run it for the first time, you will see a window like this,
you should enter the server name and instance.




Soooo, if you haven't changed any thing in the installation and kept every thing as default, the default server instance shout be SQLEXPRESS
so you should put, <server name>\<server instance>
localhost is when the server is in your own machine 

so the server name is 
localhost\SQLEXPRESS

then press connect



after you connect to the database server it should give a window as below.




 If you like to create a new database, right click on the Databases folder and create a new database

hope this helps
cheers


Thursday, 12 January 2012

ASP.Net C# session object


How to pass values to a session (ASP.net C#)

When working on ASP.net web pages or any other web programming for that matter, there comes a point we need to pass values or objects between web pages.
There are several ways of doing this, as examples
We can use the view state string that passes values as a string in the page or
We can use a cookie which is not more than a text file that stores data in the client side computer or
We can use a session variable.

In this tutorial we look at how to work with a session variable
All you have to do is, create a session variable, pass the values in to it and retrieve when necessary.

So here’s the way to do it :D




Creation of a session

Suppose there is an integer variable and you want to assign it to the session object.

//integer variable
int intVar = 10;

//below the int variable is assigned to the session
//remember you can even add an object to a session
//the <userID> is the session variable name and it is written within double quotes and it’s the name
//access the session object
Session[“userID”] = intVar;




Accessing the session variable

To check this, you should go to another page or some where
And in the code behind we can assess the variable using the following code.

Make sure you get the code working inside a page load method or something like that

//remember you have to cast it to an int type.
//if you passed another object, as an example a User type object, then cast it to User type

int passedVariable  = (int)Session[“userID”];




As an example of the usage of this ( in my opinion) we can create a session object in the log in page and pass it to the master page if we need to change the master page according to the authentication level and every time we need to check for authentication or authentication level, in every page load, check the session variable and see if its null or not.
If you want to log out set the session as null.

(Please note that this is one of the ways of doing it and it might not be the best way, if you have any better way of working with sessions or log ins please be kind enough to share them with me)

Hope that helps
Cheers

Restoring HP laptop to the factory state

Restoring your HP laptop to the factory state
(When boot loader is deleted, in other words  when F11 doesn't work)

NOTE 
I have written this tutorial in a way that some people might not understand, if you don't understand don't follow the tutorial because it might make your computer go to a state where you cannot use it at all.
Remember what ever you do, back up your data before starting the process


Background to the problem
After 2 sent backs costing almost a month my HP machine was finally repaired.

In the communication process I found out that, if you don't send the HP laptop in the original factory state, they will consider it as a breaking of warranty conditions (GREAT!!!).
So if you hadn't created recovery disks, and if you lost your boot loader because you installed another copy of windows or if you have installed linux (even Ubuntu with WUBI). Your boot up or recovery keys like F11 might not work. 

So, now you have to use the recovery partition to restore the machine to the factory settings, but how do you access the recovery partition ?
Well,

Strategy
The strategy here is to create a separate partition, copy the content of the recovery partition to the and set it as the ACTIVE partition, once you do that, it’ll make the computer boot from that partition, Thus making the recovery process start.


Necessary items
You will need a bootable windows CD or some sort of a boot up disk to go to a terminal (or a command prompt) remember, you can’t do this when you are inside windows, you have to boot from a separate disk.



Process
1.       Make sure all the folders are visible, if not go to folder options and make all the files even hidden files and machine files visible. (in your recovery partition otherwise how can you copy paste?)
2.       If you don’t already have a partition you have to create a new partition
3.       If you are using windows vista or 7
       right click on computerà manageàdisk management
4.       Using the disk management tool create a new partition large enough to keep the stuff of the recovery partition
5.       Now copy all the stuff of recovery partition to the newly created partition ( make sure they look exactly the same)
6.       Now, load the bootable disk and boot the computer using them ( a windows DVD or a boot disk)
7.       Go to a command prompt
8.       Now, what you have to do is find the find the relevant disk, find the relevant partition and make it active
9.       The commands you will be are the following
A.      diskpart ( this will move for the disk partitioning )
B.      list disk (displays a list of disks available)
C.      select disk 0 (use one of the numbers from list disk)
D.      list partition (displays a list of available partitions)
E.       list partition 1 (select the appropriate partition)
F.       active (this will make the partition active)
G.     exit ( exit from partition)
H.      exit ( exit from disk)


 10.       Now, just restart the computer and it will boot from the newly created active partition.


Hope this helps 
cheers