Gradient Datagridview Columns Header C#

Unfortunately datagridview does not support gradient columns header , there’s a work around it : first thing we need to do is to handle the CellPainting Event of the Datagridview .
put this segment of code on the top of code page of the Form

//to use brushes , and graphics
using System.Drawing;
using System.Drawing.Drawing2D;

in the CellPainting Event of the datagridview post the following code

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1) // only Columns Header
            {
                //A gradient Brush to fill header area
                Brush gradientBrush = new LinearGradientBrush(e.CellBounds, Color.Navy, Color.White, 90);
                // using the graphics object obtained from event arguments to paint on the cell
                e.Graphics.FillRectangle(gradientBrush, e.CellBounds);
                // disposing the brush(to free memory)
                gradientBrush.Dispose();
                //painting the rest of cell content to the cell
                e.PaintContent(e.CellBounds);
                //disabling the CLR from rehandling the Event
                e.Handled = true;
            }
        }

ADO.Net Connection Class

Introduction ..

in order to connect to any data source you will often need some information about that source , such as it’s location and it’s way of connectivity .

also you will be needing a tool to connect and disconnect from that data source

ADO.Net Connection Class ..
ADO.Net encapsulate all of the data source connectivity in one class called  ”Connection” , according to data providers you should respectively choose your appropriate class ;

For Example if you’re working with MS SQL Server Database (Version 7.0 and higher) you want to use “SqlConnection” Class which resides in the System.Data.SqlClient namespace

Note : through this series of articles we will be working with Visual Studio (2005/2008/2010) and SQL Server (2005 /2008)

Creating an Instance of The Connection Class ..

Open Your Visual Studio and then From The menu bar choose  File >> New >> Project >> C# >> Windows Application

Switch to Code View (F7 Default)  and at the top section of the code page make sure you type the following line :
using System.Data.SqlClient;

Now you we are ready to create our first connection (SqlConnection) ; if you are willing to connect to a database other than MS SQL server you want to use a different namespace .

Drag a button from your toolbox into the form and then double click it and it the Button_Click event handler type the following code :

SqlConnection myFirstConnection = new SqlConnection();
right now we have created an instance from the SqlConnection Class called myFirstConnection , but our connection object has no idea on which server to go , or which database to interact with so we need to configure it , we can do that be configuring it’s ConnectionString Property ; connection string basically is a string that has all the information needed for establishing a connection with the database such as the server name/IP , the database name and  security options  such as user name & password , etc .

assuming that our server name is Pharaoh and our database called northwind our connection string should look like this :

myFirstConnection.ConnectionString= "Server=Pharaoh;Database=northwind;Integrated Security=true;";

the last part of the connection string “Integrated Security=true;” is simply because we don’t have a SQL Login and we are using Windows Authentication otherwise we would have to provide a valid SQL Server Username and password

now we can open our connection and interact with the database simply we Call the “Open” method of the connection

myFirstConnection.Open();
//Don't Forget to Close the Connection
myFirstConnection.Close();

Note : if you try to open an already opened connetion you will get an exception ; such an issue can be handled by checking the Connection state first
if(myFirstConnection.State != ConnectionState.Open)
{
myFirstConnection.Open();
}

our next article will discuss how to query the database and retrieve data and doing Regular CRUD operations

Hashing a Passwords using MD5 & SHA1

Instead of saving passwords in a plain text format in the database it’s better hashing them one thing to consider is hashing is not encrypting which means once you hashed the password you will never see the original one (theoretically)

for example if you hash the word “Pharaoh”  using MD5 you will get “……………..”

now all we need to do is to compare the hash of the user input to the hash stored in the database instead of comparing the actual password string ..

First We Need to use the Following Namespace

using System.Security.Cryptography;
then in any Class/Form/Page Paste the Following Method

string hashMD5(string password)
{
MD5 Cryptor = MD5.Create();
byte[] PasswordBytes = Encoding.ASCII.GetBytes(password);
byte[] HashedBytes = Cryptor.ComputeHash(PasswordBytes);
string HashedString = Encoding.ASCII.GetString(HashedBytes);
return HashedString;
}

well the first line we Created an MD5  Service Provider then , on the second line we converted our password to a byte array because MD5 provider need it in that format then we declared another byte array to store the result of hashing and finally we converted that byte array back to a string and returned it .

here’s another method using SHA1
string hashSHA1(string password)
{
SHA1 Cryptor = SHA1.Create();
byte[] PasswordBytes = Encoding.ASCII.GetBytes(password);
byte[] HashedBytes = Cryptor.ComputeHash(PasswordBytes);
string HashedString = Encoding.ASCII.GetString(HashedBytes);
return HashedString;
}

For More Information About Hashing Click Here or or respectively you could check SHA1′s Page Here
and MD5 Here

Manual Paging ASP.Net GridView

Introduction … !Paging

using SqlDataSource With the GridView Control gives you a lot of advantages , on the other hand if you are an old school ADO/ADO.Net programmer you would encounter scenarios where you wanna bind your gridview with your own datatable . the most obvious problem you will encounter that after binding the datatable with gridview and set AllowPaging = true and try to navigate between pages ; ASP.Net Will Raise the following Exception :

The GridView ‘GridView1′ fired event PageIndexChanging which wasn’t handled.

that’s fairly normal because the gridview have no idea what to do , or how to navigate to the next page

Solutions ::

Simple Handle The following event for the gridview (PageIndexChanging)

and type the following code

GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource =myTable;
GridView1.DataBind();

Simply Changing The Page Index and Rebinding The Control Will Do The Trick

Full Example:: (will need the NorthWind Database)

Create a new website  ; in your default page drag a gridview into your page and set AllowPaging = true

then switch to code view and at the top page type the following line:

using System.Data.SqlClient;

then in the Page_Load Event handler type the Following Code

//Checking if the page is loading for the first time
if(!isPostBack)
{
string conString  = "Server=localhost;Database=Northwind;Integrated Security=true;";
SqlDataAdapter myAdapter = new SqlDataAdapter("Select * From Products",conString);
Datatable ProductsTable = new Datatable();
myAdapter.Fill(ProductsTable);
gridview1.DataSource=ProductsTable;
gridview1.DataBind();
// Must Persist the Datatable to a Session variable so that we don't have to re-Select the Data
Session["myTable"] = ProductsTable;
}

and then in the gridview1_PageIndexChanging event handler type the following code

// Changing the Page Index and Retriveing The Datatable From the Session Variable
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource =(Datatable)Session["myTable"];
GridView1.DataBind();
Tags: ,

Ternary Operators C#

Ternary Operators ….

Basically ternary operators are just an inline if statements ..

Consider the following  Pseudo code segment

bool isAdmin = getUserStatus();
string outPutMessage = "";
if (isAdmin)
{
outPutMessage =  "You Are An Administrator";
}
else
{
outPutMessage =  "You Are A Normal User";
}
MessageBox.Show(outPutMessage);

Assuming that getUserStatus() is a Method that returns a boolean value representing the user role true = admin , false = user , so that piece of code is absolutely fine but we usually see that pattern of code if some condition assign some value , else assign another value to be totaly honest it can be alot of work sometimes

well c# gives us the options to use ternary Operators the Previous piece of code can be rewritten like the following ::
bool isAdmin = getUserStatus();
string outPutMessage = isAdmin ? "You Are Admin" : "You Are User";
MessageBox.Show(outPutMessage);

we simply told the Compiler if the value of the variable isAdmin is true then assign the Value “You Are Admin” to the outPutMessage Variable and if it’s false then Assign “You Are User” to it .

Also the Code Can be Shortened to look like this
string outPutMessage = getUserStatus() ? "You Are Admin" : "You Are User";
MessageBox.Show(outPutMessage);

Note …

Ternary Operators are great for saving time and a lot of typing but sometimes they can decrease Readability..

When should you use database constraints….?

Consider the following diagram. It’s a map of the flow of data from your user, which eventually makes its way into the database.

Validation Layers

Since we’re getting input from a user, and they’re the one that can fix invalid data, we validate data at the top layer. There’s usually no getting around this. In fact, for the best user experience on the web, you’re going to perform some JavaScript validation. Then you’ll probably validate it again on the server, in case they have JavaScript disabled.

At this point, unless there is a bug in your code, you’re sure that the data is valid. You may not know if it’s referentially valid. Validating the input a third time in the database is probably overkill. It’s also a potential performance bottleneck.

Yes, there are many times when this doesn’t apply. For example, when multiple systems are interacting with the same database, and one counts on the data in a certain format. The only way to guarantee you get data in a format you expect is to constrain it at the database level.

In general, I avoid strict constraints at the database level. The biggest reason is that it requires your to synchronize all of your validators. They all have to agree on the same set of restrictions, or the code will fail. That goes against the LEAN and Agile philosophies. When I want to allow negative numbers in my integer field, it’s much easier to simply change it in my application. This is amplified if you have to talk to a DBA to make changes.

Another reason to avoid constraints is that they can’t always understand the data like the application can. For example, should a constraint attempt to ensure that valid email addresses are entered? If you’re storing a persons age, do you constrain it so that it can’t go above 500? 200? 100?

iStock_000005716223XSmall

Now let’s assume that there is a bug in your application code, and you didn’t have a trusty constraint to stop it. You now have invalid data in your database. The good news is that you now have the potential to clean it up, or adapt your code to deal with it. The bad news is that if that value is used in a calculation that could have bad side effects, you could have big problems.

As with anything, there is no hard and fast rule for every situation, but we can at least make some general guidelines.

Think LEAN. Anything that doesn’t provide value to the customer is waste. Think Agile, requirements change, be adaptable.

TOP 10 Things Girls Need To Know When Dating a Programmer!

TOP 10 Things Girls Need To Know When Dating a Programmer!

So you’re dating a Programmer, a Techy or an IT Guy…

Here’s some Goldies you need to take into consideration and This will save you lots of headache and sleepless nights talking to your self and saying .. WHY THE HELL MY GUY DOESN’T UNDERSTAND ME!!!

10. The Health of our Computer/Mobile is as important as your Future Child… Stop Nagging!

9. We use a different logic than other guys you’ve dated, this is true: 1+1=2 and this is Also True: 1+1=10 … STOP TRYING TO Analyze How we think! (and BTW in the Programming World… LOGIC WORKS!!!!!)

8. Our Information & Knowledge DO EXPIRE… Believe it or not… We need to Work hard to Survive… SO STOP TALKING ABOUT it!! (I wrote “it” intentionally in small letters, we wouldn’t dare to say the whole sentence in ALL CAPITAL)..

7. We Do LOVE other Guys Like Scott Hanselman, Bill Gates and Scott Guthrie but that doesn’t Mean that we’re GAY or weirdoes… STOP Being JEALOUS!

6. Technology is IMPORTANT TO US and so is using it in our relationship… So Sending an E-Greeting Card IS Considered ROMANTIC for us… CANDLE DINNER MY APPS!

5. We’ve Made Peace with our Parents Long time ago.. Stop Trying to Teach us Manners!

4. We Don’t Cheat.. Because more likely we will barely have time for Two Women in our Lives (One being our Mother)… STOP DOUBTING… YES I NORMALLY WORK LATE!

3. We Don’t Lie… We may seem Dump & Reclus in how we do things; that’s because we’re used to something called ROLLBACK TRANSACTION => we can undo things as if it NEVER HAPPENED!!!! That’s 100% TRUE!

2. Our Brains has an Advanced Problem Solving Skills, For us as long as there is a Solution SOMEWHERE, THERE IS NO PROBLEM! … STOP THE DRAMA!

1. We Love in Binary… it’s either 1 or 0 … so IF We say “I love You “… THAT”S THE ONLY WAY WE KNOW HOW TO SAY IT!

ADO.Net Introduction

Introduction ..

As a Developer it’s one of my daily tasks to perform database operations such as read data from database and update data back to the database and handle all sorts of data manipulation operations such as searching and exporting sets of data into another formats , etc .

What’s ADO.Net .. ?

ADO.Net is a rich set of Classes Provided Within Microsoft’s .Net to Handle Database connectivity and manipulation also it’s not limited to databases only , it can be used to handle most data sources such as spreadsheet files and XML files.

ADO.Net is the Successor of the Previous Version(ADO (ActiveX Data Objects)) but it’s developed extensively
Why ADO.Net .. ?

ADO.Net enable Developers to handle complex database (or any data source ) tasks with great ease and

flexibility without worrying about networking or threading or the infrastructure about database systems connectivity

ADO.Net is a part of the BCL (Basic Class Library of the .Net FrameWork) and it’s located in System.Data namespace

ADO.Net Data Providers ..

ADO.Net is Structured into multiple namespaces according to data sources providers :

for example:

The System.Data.SqlClient namespace is used for connecting and handling MS SQL Server Version 7.0 and higher and The System.Data.OracleClient namespace is used for connecting or Oracle Database Servers also there’s neutral Namespaces such as System.Data.OleDB namespace which can be used to connect to almost any data source such as MS SQL Server , Oracle , MS Access , IBM DB2 , Excel Files , etc

So why should i use System.Data.SqlClient over System.Data.OleDB when connecting to MS SQL Server Database  ?


Well  the answer is simple because Specific Data Providers such as System.Data.SqlClient often provide more specific functionality and performance Improvements over general data providers such as System.Data.OleDB

You can also implement your own database provider classes Through inheriting from System.Data.Common classes and extending them .

In the next few articles we will get to know about  ADO.Net in greater detail .

Tags: , ,

Incorrect usage of UNION and ORDER BY

Incorrect usage of UNION and ORDER BY

A common problem when using the UNION command in MySQL is when you want to order the sets of data differently. If you do it incorrectly, you will see the error message:

Incorrect usage of UNION and ORDER BY

To solve the problem, wrap each individual SELECT statement in parenthesis as follows:

(SELECT col1,col2,col3 FROM table1)
UNION
(SELECT cola,colb,colc FROM table2)

Nice and simple, all you have to do is remember the brackets!

MySQL – Introduction

DatabaseMySQL is currently the most popular open source database server in existence. On top of that, it is very commonly used in conjunction with PHP scripts to create powerful and dynamic server-side applications.

MySQL has been criticized in the past for not supporting all the features of other popular and more expensive DataBase Management Systems. However, MySQL continues to improve with each release (currently version 5), and it has become widely popular with individuals and businesses of many different sizes.
What is a Database?
A database is a structure that comes in two flavors: a flat database and a relational database. A relational database is much more oriented to the human mind and is often preferred over the gabble-de-gook flat database that are just stored on hard drives like a text file. MySQL is a relational database.

In a relational structured database there are tables that store data. The columns define which kinds of information will be stored in the table. An individual column must be created for each type of data you wish to store (i.e. Age, Weight, Height). (more…)

© 2010 Programming online. All rights reserved.
Free WordPress Themes
freshlife WordPress Themes Theme Junkie