Connect C# with MySql

This article is to show the step wise process of how to connect C# to MySql, I will be using MySql Connect/Net for this. Later I will show how to execute INSERT, UPDATE, DELETE and SELECT commands, this will include only setting up the connection.

Getting Started

First make sure you have downloaded and installed the MySql Connector/Net from the MySQL official website. In this article, I will use the Connector/NET version 6.1.6.

I felt the need of this when I was developing a windows form application and wanted to connect it to a database on my website. In this article I’m assuming that you have a cpanel on web and a database in it, you can also install MySql on your system.

Our first step will be “Adding Reference and Creating the MySQL Connector DLL from the Project”.

First we need to add a reference to ‘mysql’, we can do this by navigating to solution explorer and then right-click on the reference folder and then look for MySql.Data under .net tab

In order to use the application on other computers that don’t have the connector installed, we will have to create a DLL from the reference. To do so, we right click the reference name in our project, and set the copy local to true in its properties:

Now we are done with adding the reference and now we can start our actual coding.

We will start by adding a namespce

using MySql.Data.MySqlClient;

I have created a simple form with a button in it, our connection will be established when the button is clicked i.e. we will write our code in the OnClicked event of the button. My form looks some what like this.

Now comes the actual coding part.

We will have to create the connection string first.

To establish a connection, you must specify the computer you are connecting to, that has MySQL installed. To indicate the computer you are connecting to, use the Data Source, theDataSource, the Host, the Server, the Addr, the Address, or the Network Address attribute of the connection string. If you are connecting to a local database (installed in the same computer where the application is running), you can omit specifying the name of the computer. Otherwise, you can assign localhost to this attribute. To specify the database you want to connect to, the connection string includes an attribute named Database or Initial Catalog.

To specify the user name, use the User Id, the Uid, theUser name, or the Username attribute and for password use the PASSWORD or the PWD (remember that the attributes are not case-sensitive) attribute.

Here is a sample connection string :

string cs = @”server=YOUR_SERVER_NAME;userid=YOUR_USERNAME;
password=YOUR_PASSWORD;database=DATABASE_NAME”;

Now the code under the button clicked event.

That’s all. Debug your application, i have added the connection open in try catch block so if the connection established it will show a message boc which says “Connection Established”.

Cheers.

C# – Metro Style App – Message Dialog

After the release date of Windows 8 i.e 26th October developers have gone crazy about developing metro style applications. I have been developing for windows earlier also and MessageBox was the most used control, but in metro style apps i didn’t found that, so here is a simply article which will guide you through the use of message box in metro style apps which are referred as Popups here. The message box here are fully user defined, we can add the commands to the message box and also add action along it. Here is a step wise instruction.

First step is to create a new Metro Style Blank App Project.

A blank project will open in front of you, we will add our code into ‘MainPage.xaml.cs‘, in the following project I will add the message box under the ‘OnNavigatedTo‘ event so that as soon as the Application is opened the message box will appear.

Now we will add a namespace for message box in metro style apps.

using Windows.UI.Popups;

Now its time to write down our actual code. Here is a code snippet.

First line create a new object for MessageDialog which is saved in a var md. MessageDialog has an argument which is the message box text which is displayed when the message box appears.

var md = new MessageDialog(“Are you sure you want to exit”);

Second line adds a new command to the message box i.e. ‘Yes’,  new UICommand creates an object for a new command and new UICommandInvokedHandler adds the action to the corresponding command, here the action we have added is: Application.Current.Exit(); this closes the application.

md.Commands.Add(new UICommand(“Yes”, (UICommandInvokedHandler) =>
{
Application.Current.Exit();
}));

Third line adds another command i.e. ‘No’. This will cause nothing to the application and the application will continue.

md.Commands.Add(new UICommand(“No”));

Debug the app to see the result.

Here is the source code. Enjoy.

Image Browser Windows 8 – First Simple App

This is a very first app we are going to create for windows 8, its a Image Browser, we will create it using a FlipView control in windows 8. The FlipView control lets people flip through views or items one at a time. Flip buttons appear on mouse hover and let people flip to the next or previous item.

First step is to create a new Metro Style Blank App Project.

Now the project is created and the ‘MainPage.xaml’ is opened in the main window or you can open it from the solution explorer. Firstly we will add FlipView control which can be done by using the toolbox on left or writing some xaml code. The code for adding a FlipView is written below, we have used HorizontalAlignment and VerticalAlignment so that our control comes in center of the screen.

<FlipView HorizontalAlignment=”Center”  VerticalAlignment=”Center”>

</FlipView>

FlipView control can contain many FlipViewItem in it, which will flipped once at a time, inside the FlipViewItem we define what is to be displayed, since we are making a image gallery we will use Image control inside every FlipViewItem we add. Here is the complete snippet of the code.

I have added three images as a sample, you can add as many as u can or u can bind the image control programmatically to retrieve ‘n’ number of images. You might have noticed the beauty of Windows 8 SDK, i haven’t used any C# code and i have a nice light weight image browser. Debug the app.

Ask for source code. Cheers :)

 

 

 

CheckBox Selection Limit in ASP.NET

CheckBox control is the very common control of HTML, unlike radio buttons it can select multiple items on a webpage. CheckBox control in ASP.NET has many properties some of them are listed below.

Property Description
AutoPostBack Specifies whether the form should be posted immediately after the Checked property has changed or not. Default is false
CausesValidation Specifies if a page is validated when a Button control is clicked
Checked Specifies whether the check box is checked or not
InputAttributes Attribute names and values used for the Input element for the CheckBox control
LabelAttributes Attribute names and values used for the Label element for the CheckBox control
runat Specifies that the control is a server control.  Must be set to “server”
Text The text next to the check box
TextAlign On which side of the check box the text should appear (right or left)
ValidationGroup Group of controls for which the Checkbox control causes validation when it posts back to the server
OnCheckedChanged The name of the function to be executed when the Checked property has changed

In this article I will teach you how to limit the number of selected items among all the checkbox on a webpage. First step, create a “ASP.NET Empty Web Application“.

As we have started with an Empty Web Application we need to add a page now. Goto Project>Add New Item (Ctrl+Shift+A), a screen will popup add a web form from it name it ‘SelectionLimit.aspx’.

The explorer will have SelectionLimit.aspx open for you with some default code, add a Check Box List either from toolbox or writing the code. Since we need to limit the number of selections we need to call a function or submit our form every time a selection is made in check box list, for this we will use the property AutoPostBack and set this to “true” we need to call a function on every Post Back so we will trigger an event on selection changed. To do this go to properties on right bottom corner.

As soon as you double click the SelectedIndexChanged, “SelectionLimit.aspx.cs” will show up where you will write code.

we will have two functions there

protected void Page_Load(object sender, EventArgs e), and

protected void MyCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)

since we have just added CheckBoxList and not added any items to it, so in the ‘Page_Load’ Function we will add items to CheckBoxList

and in the ‘MyCheckBoxList_SelectedIndexChanged’ function we will do the main coding part.

That is all, debug your page, u might have noticed in the ‘if’ condition I have used count > 2 i.e  I’m limiting the selection to two selections only i.e. only two items can be selected.

Source Code here.

 

KILL NON RESPONDING PROCESSES WITH THE HELP OF NOTEPAD/BATCH FILE

I really hate it when i have some Non-Responding tasks in my laptop, sometimes I’m unable to open task manager even and at that time i feel helpless. Here is a simple trick which will kill all the non-responding task easily, we will do it through a Batch File (.bat).

Step wise instruction is as follows:

1. Open NOTEPAD

2.Copy the code written below and paste it in opened notepad document…
TASKKILL /F /FI “STATUS eq NOT RESPONDING”

3.Save the file as nonreponding.bat (save it on desktop so it becomes more handy)

WHENEVER U NEED TO CLOSE NON RESPONDING PROCESSES ,JUST DOUBLE CLICK THIS FILE.

Macros Programming in Excel Sheet 2010

Macros programming in Excel has made it very easy to use, it provides a visual basic programming interface which is an easy task. Here is a step wise instruction on how to do it.

1)    Start Excel Sheet 2010

2)    Click on View tab

3)    Now click on dropdown Macros and select Record Macros in dropdown menu

4)    Name your Macro, in the sample I named it ‘MyMacro’. You can also set a shortcut key for it e.g I have used “Ctrl+w”. Now Press ok in the new window opened.

5)    Now again pull down dropdown menu of Macros and click on Stop Recording.

6)    Now select View Macros in dropdown menu of Macros.

7)    You will get a window showing all the macros like this

8)    Select your Macro as in our case its MyMacro and now click on edit.

9)    You will get a new window as shown in figure below, this window is the visual basic programming interface, this Interface show different components as project explorer, property window, code window.

You will see:

Sub MyMacro

End Sub

place your code between these two lines.

10) Press Alt+F11 to go back to the excel sheet (You can always switch between programming interface and excel sheet with Alt+F11)

11) Now again Select View Macros from the Macros drop down menu and just click on run after selecting your Macro from the View Macro window to see the effect of your work. In  this sample we have coded to change the text in UPPERCASE, you can code it according to your requirement.

Enjoy programming Macros for Excel.

 

How to use AdRotator in ASP.NET?

AdRotator is a control in asp.net which is concerned with advertisements, it basically displays a sequence of ad images. This control uses an XML file to store the ad information. The XML file must begin and end with an <Advertisements> tag. Inside the <Advertisements> tag there may be several <Ad> tags which defines each ad (we will see a sample XML in this article).

In this article i will tell you how to use AdRotator in your page. First step, create a “ASP.NET Empty Web Application“.

As we have started with an Empty Web Application we need to add a page now. Goto Project>Add New Item (Ctrl+Shift+A), a screen will popup add a web form from it name it ‘AdRotator.aspx’.

We should also add an XML file which will contain ad information. Goto Project>Add New Item (Ctrl+Shift+A), select ‘Data’  from left and add a XML file, name it ‘AdRotator.xml’.

Now we will write our XML file, it begins and ends with an <Advertisements> tag. Inside the <Advertisements> tag there may be several <Ad> tags which defines each ad. The predefined elements inside the <Ad> tag are listed below:

Element Description
<ImageUrl> Optional. The path to the image file
<NavigateUrl> Optional. The URL to link to if the user clicks the ad
<AlternateText> Optional. An alternate text for the image
<Keyword> Optional. A category for the ad
<Impressions> Optional. The display rates in percent of the hits

But before we add content to our XML file we need to have ad images, so create a new folder in solution explorer and name it ‘Images’ and drag your ad images to it. Code Snippet for XML file is shown below.

Now, from the solution explorer open AdRotator.aspx page it will contain some default code, we will add the AdRotator control now either by dragging it from Toolbox or writing its code, we will also use some attributes for it like AdvertisementFile (Specifies the path to the XML file that contains ad information )and Target (Specifies where to open the URL ).

This was all, Debug your project and see it working. I have just added 3 images so many a times you may see the same image add more images and see it rolling, other than advertisement this can also be used as an banner for your website and many more.

Click Here for source code.

 

 

Windows 8 development, Getting Started

Windows 8 the hot topic in Operating System market, though it is not yet launched but its preview versions are doing a great job among the developers. It has launched three versions till date, Developer Preview, Consumer Preview and Release Preview. Windows App Store in windows 8 is the major attraction. In this article I will guide you to start developing applications for Windows 8.

Starting with development, we need some developer tools for windows 8:

  • Visual Studio 11 or Visual Studio 12 RC
  • Windows 8 SDK
  • App Certification Kit

Well if you use Visual Studio 12 RC it contains all the developer tools, though Visual Studio 12 RC cannot be installed on consumer preview for this you need Developer preview or Release preview.

Create new project, Under templates section you will see Windows Metro Style:

There are three types of app which can be developed.

  • Blank App – It is the minimal application for windows metro style framework. It is used to create basic applications.
  • Grid App – This can be used to create multi-page project for navigating multiple layers of content with item details displayed on a detailed page. This can be used to create a panoramic view also.
  • Split App – This defines two different section where you can create a project for navigating among master list of items while viewing their details on the same page.
For this article I’m using Blank App Type. Fig below will clear everything I’m talking about.

Now the new project is created, and the MainPage.xaml will show in the main window, other files can be browsed from the solution explorer. We have a ToolBox on the left from which various controls can be drag and dropped to the design view of the MainPage.xaml or we can directly write some xaml code to add the control. As this is this first app we are going to make, we will simply add a TextBlock and add some text to it which will be shown when the app is loaded. The Fig below will show you the code snippet:

Consider the first line, here MyFirstApp is the name space and MainPage is the class. We have added a control TextBlock and added few attributes like HorizontalAlignment and VerticalAllignment, we have set both of them to Center so that our text comes in center. And now you are done with your very first and Simple App. This can be debugged in various modes like debug in the Local Machine, Simulator and Remote Machine. I prefer debugging it in Simulator. It will look something like this.

Here is the Source Code.