Tuesday 31 January 2012

How to extract words from a string in C# (Split string)

This is incredibly easy in C#. First of all, you need to have a string from which you want to extract words. A word is a string separated by spaces. To do that, just say:

string s = "Welcome to my blog!";

Now, when I use the split command, it will return an array of individual strings. So, the implementation will be:

string[] words = s.Split(" ",StringSplitOptions.RemoveEmptyEntries);

As a result, words will have "Welcome", "to", "my", "blog!" in it.

Thursday 26 January 2012

Google Chrome versus Mozilla Firefox

Well, they said that Mozilla firefox is the most efficient browser. I wasn't satisfied. Hence, I went to check. I am a big fan of Google Chrome. However, I recently learnt that chrome collects browsing information. That didn't sound good to me and hence I switched to Mozilla Firefox. On the download page, it said that it is the most efficient browser. I downloaded it, but initially I had some issues. It lagged a bit when I used it on my laptop. However, when I used it on my university's mac (with Windows 7 installed) it was smooth. Hence I was suspicious. I had to check. I closed all applications, refreshed the page few times and fired up Mozilla Firefox and Google Chrome.

I opened up www.sciencedaily.com in both the browsers. I fired up Task Manager only to find that Google chrome had three simultaneous processes and firefox had one. This probably means that it is doing multi-threading a lot and has a lot of external handlers. It is a good practice though when you are programming something like a web browser. However, I counted the memory allocated and firefox had like 88,000 and Google Chrome had in total something like 50,000. I was surprised.

Then, to satisfy myself that Firefox is better, I opened two tabs in both chrome and firefox. In one tab, I opened the google home page and in another I opened up www.sciencedaily.com. This time, I hoped chrome to jump up. The task manager showed that chrome had four processes, one more than last time I had seen and firefox still had one process. In terms of memory, firefox allocated something like 120,000 and chrome took something like 90,000. I was even more surprised. My quick analysis at that point was that the memory print of chrome increases rapidly with increase in number of tabs while in same conditions, that of firefox increases at relatively slower rate.

In the third test, in which I seriously hoped firefox to win, I opened up four tabs as follows:
1. Tab 1: www.google.com
2. Tab 2: www.sciencedaily.com
3. Tab 3: www.bing.com
4. Tab 4: news.google.com

This time, firefox really won. Its memory print was around 143,000 while at the same time, that of chrome was around 150,000. Yayy! Victory at last!

So, well, what does this tell to average computer user? I will still be using firefox. However, if I quickly want to check something like a definition or address, I'd use chrome. However, for tab intensive stuff like research and like that, I will be using firefox.

FYI:
Chrome: 12.0.742.122
Firefox: 5.0

Tuesday 24 January 2012

How do I do threading in C#?


Threading in C# is no big deal. It has the easiest implementation I've ever seen. First of all, you need to have a method that you want to execute on a different thread. For this instance, I'll put method called Calculate(). Now, this method has to be a void. However, it can take any amount of parameters. So, it can be:

public void Calculate()

or

public void Calculate(int x, int y)

Now that we know what to execute, we need to create a thread with this method. This is done by:

Thread t = new Thread(Calculate());

I can now run the thread by typing:

t.Start();

See Also: How do I do threaded programming in Java?

How do I do threaded programming in Java?


My favorite concept in any programming language is Threading. It is awesome. This time, I'll get started straight away!

First of all, before making a thread in java, you need a runnable. Runnable is basically like a piece of code that you want to execute as a separate thread. There are two ways to create a runnable. You can do it by making an anonymous class such as:

Runnable r = new Runnable(){

public void run(){


//Your code goes here...


}
}
However, this is not a good practice. Hence, it is advised to create a separate class which implements the Runnable interface like:


public class MyNewRunnable implements Runnable{


MyNewRunnable(){


}


public void run(){
//Your code here...
}
}

In this manner, you can pass any parameters for processing the information using the class constructor. For instance, if you are making a runnable for downloading files, you can pass url of the file through the class constructor. Now, once you have created your runnable, you need a thread in which you have to put the runnable. Then you run the thread, the run method of runnable gets executed. For runnable r, you can make a thread as follows:

Thread t = new Thread(r);

Then, you can start the thread by typing:

t.start();

I'd say that threading would help make your program more responsive. This is solely because of the fact that all the heavy processor hungry tasks are carried out in a separate thread and the UI thread is kept clean.

See Also: How do I do threading in C#?

Sunday 22 January 2012

How to make a login in ASP .NET C#

In this post, I will teach you guys about making a simple login using common page controls. First of all, you need two textboxes, one for username and another for password. I'll call them usernameTextBox and passwordTextBox for this example. Drag down a button and call it loginButton. Now, in the OnClick event of loginButton, you need to check if the provided combination of username and password is correct or not. You can only do this if you have username and passwords stored somewhere. It is recommended to use a database to do this. Create a AccountDetails table in your database. The table should have username and password fields, both as text (VARCHAR for SQL). The way login is going to work is that you select records from AccountDetails table who have the provided username and password. This query should return one row if the combination matches. If not, then it should return nothing. Here's the query you need to pass:

string query = "SELECT * FROM AccountDetails WHERE username='"+usernameTextBox.Text + "' AND pass='" + passwordTextBox.Text + "'";
Supply this query to the command object. This can be OleDbCommand or SqlCommand depending on your type of database. Invoke the ExecuteReader method of the command object and then check if the Read method of the DataReader object returns true. If it does then this means that the login is successful. If not, then login is invalid. Here's a sample code.

string connectionString = "...";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string queryString = "SELECT * FROM AccountDetails WHERE username='"+usernameTextBox.Text + "' AND pass='" + passwordTextBox.Text + "'";
OleDbCommand command = new OleDbCommand(queryString, conn);
OleDbDataReader reader = command.ExecuteReader();
if(reader.Read()){
//Login is successful.
}else{
//Login failed.
}
Thats it! Your ASP website should now have a wonderful login to allow geniune users. To extend its capabilities, store the username in a session and then in PageLoad event of rest of the pages which require login, check if the session contains something. If it is null, then the page should redirect to login page. Same if for log-out. In the PageLoad event of the login page, check if the session username contains something. If it does, then clear out the session and display some notification saying that the user has been logged out. Now, in your page, to which the user gets redirected after successful login, put a simple link to login.

Now, initially when user lands on the login page, the session username will be empty. However, on typing correct username and password, this session gets filled with the username of the logged user and he/she is redirected to some sort of dashboard page. When the user clicks on the log-out link, he/she gets redirected to the login page which first checks if there is anything in the session. Since the user has previously logged in, there will be a username inside that session. Login page clears it out and displays a message saying that the user has been logged out. I hope that was easy.

If you have any queries or doubts, feel free to comment below.
If you want to know how session works, click here to see my post on Sessions.

Friday 20 January 2012

Using Sessions in ASP .NET


Well, believe it or not, Session is the most important thing when it comes to web design. I used to hate it but now I am a big fan of it. Trust me. You will like it once you get hang of it. So, in this post, I will be teaching you about using them. First of all, a session is like a small memory pit where you can store values. Values in session are lost once the browser closes. However, they stay the same even if you change the page or open new tab. Hence, sessions are used to pass values from one page to another.

You can store an object in session. It can be int, double, string or any other FooClass object that you have defined. This is the main benefit of it. However, when taking values back, you need to make sure that you cast them back to its same original form. Here's how you store value in a session. Let me define some variables.

int i=2;
string s="Hello";
FooClass foo = new FooClass();
Now, I will store each of them in session. To store a value, you need to give a session name. This must be unique. You must remember this because you will have to use it to extract value out of session. Here's how you do it:

Session["someIntegerVariable"] = i;
Session["someStringVariable"] = s;
Session["someFooClassObject"] = foo;
Now that I have all of them in the session, I will extract them. Remember, I can only extract variable 'i' from 'someIntegerVariable' session and not 'someStringVariable' session.

int newI = (int)Session["someIntegerVariable"];
string newS = (string)Session["someStringVariable"];
FooClass = (FooClass)Session["someFooClassObject"];
Since session stores object only, you will have to cast the object back to its original form. In the code above, I have casted the object stored in 'someIntegerVariable' session back to its original form which is int.

Thats basically how you use sessions. It is widely used in tracking pages and variety of other purposes, especially when you have to keep something consistent between pages.

Best way to query database in Visual C#


Best way to query database in C#
Well, this is actually not an official way but my personal choice. In this instance, I will use an access database as an example.
While querying the database is a long process in C#, it becomes simplified once you use object orientation. First of all, here's the conventional way of querying the database:

string connectionString = "...";
OleDbConnection dbConnection = new OleDbConnection(connectionString);
dbConnection.Open();
string queryString = "SELECT * FROM Customers";
OleDbCommand dbCommand = new OleDbCommand(queryString,dbConnection);
//since this is select query...
OleDbDataReader dr = dbCommand.ExecuteReader();
//and then you do the reading process...


Now, if you have a lot of queries to run, then this would be really painful process to do again and again. Hence, it is better to put the process in a method like this:

public OleDbDataReader runSelectQuery(string queryString){
string connectionString = "...";
OleDbConnection dbConnection = new OleDbConnection(connectionString);
dbConnection.Open();
//using the query string...
OleDbCommand dbCommand = new OleDbCommand(queryString,dbConnection);
//since this is select query...
OleDbDataReader dr = dbCommand.ExecuteReader();
//and then you do the reading process...
return dr;
}


The method takes in the select query string and returns the data reader which can then be used to extract the data. To make this more efficient, make a class and put the above method as static. Also, make the connectionString a global variable so that it if you need to change it, then you only have to change it in one place. In the end, the code would look like this:

public class QueryClass{

private static string connectionString = "...";

public static OleDbDataReader runSelectQuery(string queryString){
OleDbConnection dbConnection = new OleDbConnection(connectionString);
dbConnection.Open();
//using the query string...
OleDbCommand dbCommand = new OleDbCommand(queryString,dbConnection);
//since this is select query...
OleDbDataReader dr = dbCommand.ExecuteReader();
return dr;
}
}


Later, to access the method, you'll just have to do:

OleDbDataReader reader = QueryClass.runSelectQuery("SELECT * FROM Customers");

Comment below if you have any queries regarding the code.

Thursday 19 January 2012

Displaying tabular data in Visual C# using ListView

ListView is extremely useful in displaying tabular data in C#. Yet, it is an easy to use control.

  1. Drag the control onto your form and note its name. In this instance, I am going to use ListView1 as name.
  2. You will have to add columns to it now. This is how you do it.
    ListView1.Columns.Add("ColumnName");
    If you have 5 columns, then you will have to do it five times.
  3. Now, you will have to have each row that you want to insert as a single dimension string array. Number of items in this array should be equal to number of added columns. If it's not, then rest of string elements will not show up. 
  4. Add the string array to a ListViewItem. For that, you will have to create a ListViewItem first. ListViewItem's constructor would allow you to pass the string array to it. Do it by typing:
    ListViewItem li = new ListViewItem(stringarray);
  5. Now add the ListViewItem to the ListView by typing:
    ListView1.Items.Add(li);
  6. Thats it! Run your application and you'll have your table beautifully displayed in tabular format. 

Introduction to code efficiency and The Big O Notation



The big O notation explains how efficient the code is. It is like measurement scale for code efficiency. If you go in details, it can become complex. However, in this post, I'll explain how to get a rough idea of your code's efficiency.


To roughly calculate it, you need to know size of your problem which is 'n' in this case. Look through your code, and analyze the loops that you have. Basically, loops are the determining factor. If your code has 100 loops (not nested) then the efficiency is O(n). No matter what the number is, if your code has no nested loops, then the efficiency is still O(n). However, if you have one single nested loop, then efficiency is n2. Nested loops decrease efficiency of code. This is simply depicted by the fact that n2 is greater than n.

To write efficient code, it should be your goal to reduce number of nested loops. To do this, the best way is to reuse values that have been previously generated. My way to do this is by using connected methods. I will be discussing more about this in next posts. You can also exit loops when you have met your aim. In this case, while loop is preferred but if you have more than one condition, you should exit the loop when they are met just to save iterations.

If you wish to know more about the big O notation, read the article written by Rob Bell

Wednesday 18 January 2012

Welcome!

Welcome to Code Ninjutsu.

Code Ninjutsu is about art of writing efficient code. In this blog, we shall discuss methods to write efficient code. I shall also teach tricks that you can perform in different programming languages to get the most out of your code. We shall also see how algorithm works and methods to make it more efficient. We have a lot to talk about. Till then, you can watch videos on my youtube channel:

http://www.youtube.com/user/themanthandave

Later then!

Manthan Dave