MVC 3 Web grid sorting not working

I recently was working a lot with Web Grids, and there was this was one problem that kept coming up again n again, so I have decided to write an article for this.

Lets first see what my web grid code looked like when my sorting was NOT WORKING,

var myGrid = new WebGrid(source: Model.ABC);

@myGrid .GetHtml(

    columns: myGrid .Columns(  
    myGrid .Column("User Name", format: @<text>@item.Username</text>),  
    myGrid .Column("Password", format: @<text>@item.Password</text>),

))

While testing I found that sorting on Password column worked but when I tried sorting on Username column it just didn’t work !

SOLUTION:

After a little googling and going over stackOverflow QA I finally found the actual problem.

This happens because the grid column names must correspond to your fields or db columns. The Method which generates URL in grid header compares “sort” from url query string with bounded columns and with grid column name. These must be exactly the same.

So because I had used “User Name” and not “Username”, sorting on my username column did not work.

Corrected code : Use **columnName:, **to specify column names and **header: **to specify table header

var myGrid = new WebGrid(source: Model.ABC);

    @myGrid .GetHtml(

    columns: myGrid .Columns(  
    myGrid .Column(header: "User Name", columnName: "Username" , format: @<text>@item.Username</text>),  
    myGrid .Column(header: "Password", columnName: "Password" ,format: @<text>@item.Password</text>),

))

Hope this helps you too !

How to change WordPress Address and Site Address

There are 3 ways in which you can change the WordPress Address URL and Site Address URL, but first let us know what these URL actually mean.

The “WordPress Address URL” setting is the address you want people to type in their browser to reach your WordPress blog.
The “Site Address URL” setting is the address where your WordPress core files reside.

Method 1. First method is simply by going to your General Settings tab and changing the URL(s)

WordPress address (URL) & Site address (URL)

Method 2. Edit wp-config.php file [Using ftp]

It is possible to set the site URL manually in the wp-config.php file. Add these two lines to your wp-config.php, where “example.com” is the correct location of your site. You won’t be able to edit them on the General settings page anymore when using this method.

{code type=php}

define(‘WP_HOME’,’http://example.com’);
define(‘WP_SITEURL’,’http://example.com’);

{/code}


Method 3. Edit function.php file [Using ftp]

FTP to the site, and get a copy of the active theme’s functions.php file. You’re going to edit it in a simple text editor (like notepad) and upload it back to the site.

Add these two lines to the file, immediately after the initial “<?php” line.

{code type=php}

<?php
update_option(‘siteurl’,’http://example.com/blog’);
update_option(‘home’,’http://example.com/blog’);

{/code}

Feel free to write in if you are not  still not able to get it working !

 

Write to an Event Log using C#

Event logging provides a standard, centralized way for your applications to record important software and hardware events.

string eventSource, strlog, message;

eventSource = “YasserSource”;
strlog = “LogDetails”;
message = “This is my error message”;

// Creates an event source if it does not exists
if (!EventLog.SourceExists(eventSource)) {
EventLog.CreateEventSource(eventSource,strlog);
}

EventLog.WriteEntry(eventSource, message, EventLogEntryType.Error);

Be sure you include System.Diagnostics;

Redirect from OnException method to a View in MVC 3

All controller class should by default inherit the Controller class. And in the controller class we have the OnException() method. This method is called whenever an unhandled exception occurs in an action.

Below is the code using which we can redirect to a view using the OnException method. Also note that we can use the filterContext.Exception which we have stored in the Session on the error view to show a nice error message.

protected override void OnException(ExceptionContext filterContext)  
{
    this.Session["ExceptionMessage"] = filterContext.Exception; // Can use this exception message later on.

    filterContext.ExceptionHandled = true;

    filterContext.Result = this.RedirectToAction("Error", "Home"); // Redirect to error page.

    base.OnException(filterContext);  
}

Read appsettings and connectionStrings from web.config file using c#

Ok, in this tutorial we are going to read appSetting and connectionStrings that are defined in web.config.
For explanation’s sake lets have a sample web.config file first

<configuration>
    <appSettings>
        <add key="Mykey" value="Some Value" />
    </appSettings>
    <connectionStrings>
        <add name="localConnStr" value="Data Source=ys2012;Initial Catalog=myDB;User ID=sa;Password=123;" />
    </connectionStrings>
</configuration>

So in the above example I have defined 1 appSetting and 1 connectionString. Now below I have used the Configuration Manager Class to read appSettings as well as connectionStrings

1. Reading AppSetting

string value = ConfigurationManager.AppSettings["Mykey"].ToString();

2. Reading ConnectionString

string value = ConfigurationManager.ConnectionStrings["localConnStr"].ToString();

Give a common CSS to all input tags

You may want to give all input tags a common CSS. That is you want all your Text Fields, Password Fields, Radio button, Submit buttons etc… all to have a common CSS.

This can be done easily by simply including the below code in your CSS file as shown below. Here I am giving all my input tags a common font of 13px size and Calibri as font-family.

{code type=css}

input
{
font: 13px Calibri;
}

{/code}

Show text on image hover

Show text on image hover : It is a common requirement to show a text on hover of an image. I recently wanted to do the same. Below is the straight forward and simple solution for the same.

Using the title tag, we can easily do so, check the code below

{code type=html}

<img src=”http://yassershaikh.com/wp-content/uploads/2012/03/sp-studio-1.jpg” alt=”My Avatar” title=”I love Rock n Roll ! “></img>

{/code}

Example Image :

My Avatar

Hide Feedjit Feed in WordPress

Feedjit is clearly one of the best FREE traffic tracking widget available on the internet. You can install and use it with your WordPress blog or Blogger blog or on any other website. It is very simple to install and customize a Feedjit widget to a blog.

You may also want to hide your Feedjit Live Traffic widget !

Yet you want to still keep a track of the traffic you are getting using FEEDJIT. Can I do that ?

YES YOU CAN !

Firstly you need to register on Feedjit and get a script for your site. Go to  http://feedjit.com for that.

Once you have the code, your script should look like this…

{code type=html}

<script type=”text/javascript” src=”http://feedjit.com/serve/?vv=955&amp;tft=3&amp;dd=0&amp;wid=645c8d98500ad529&amp;pid=0&amp;proid=0&amp;bc=FFFFFF&amp;tc=000000&amp;brd1=012B6B&amp;lnk=135D9E&amp;hc=FFFFFF&amp;hfc=2853A8&amp;btn=C99700&amp;ww=200&amp;wne=1&amp;wh=Live+Traffic+Feed&amp;hl=0&amp;hlnks=0&amp;hfce=0&amp;srefs=0&amp;hbars=0″></script><noscript><a href=”http://feedjit.com/”>Feedjit Live Blog Stats</a></noscript>

{/code}

Now to use this script on your website, without actually showing the Feedjit Live Feed, you just need to surround it with a div tag and set its display property to none.

{code type=html}

<div style=”display:none;” >

<script type=”text/javascript” src=”http://feedjit.com/serve/?vv=955&amp;tft=3&amp;dd=0&amp;wid=645c8d98500ad529&amp;pid=0&amp;proid=0&amp;bc=FFFFFF&amp;tc=000000&amp;brd1=012B6B&amp;lnk=135D9E&amp;hc=FFFFFF&amp;hfc=2853A8&amp;btn=C99700&amp;ww=200&amp;wne=1&amp;wh=Live+Traffic+Feed&amp;hl=0&amp;hlnks=0&amp;hfce=0&amp;srefs=0&amp;hbars=0″></script><noscript><a href=”http://feedjit.com/”>Feedjit Live Blog Stats</a></noscript>

</div >

{/code}

Now once that is done, How do I now track my website traffic ?

Its simple ! Simply open a browser and type in

http://live.feedjit.com/live/yoursite.com/0/ and you are ready to go.

for eg : http://live.feedjit.com/live/yassershaikh.com/0/

OOPS Interview Questions and Answers

Q. What is Object Oriented Programming?
A. Object-oriented programming (OOP) is a programming paradigm using “objects” (data structures consisting of data fields and methods together with their interactions) to design applications and computer programs.


Q. What is an Object?
A. An object is an instance of a class.


Q. What is a Class?
A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.


Q. What is Encapsulation ?

  • Encapsulation implies that the non-essential details of an object are hidden from the user and an access its provided to its essential details.
  • Example : Computer games also use this feature. The user only needs to know how to play the game, the complex working of the game is hidden from the user.
  • Encapsulation is the feature that provides security to the data and the methods of a class.

Q. What is Abstraction ? 

  • Abstraction is a process of hiding unwanted details from the user.
  • Abstraction also means ignoring the non-essential details of an object and concentrating on its essential details.

Q. What is Inheritance ?

  • Inheritance enables you to extend the functionality of an existing class.
  • When you create a class that inherits another existing class, it will inherit the attributes and behavior of that class, plus it can also have new attributes and behavior that are specific to that class.
  • Advantage : Code-Resuability which result in saving time and energy.

Q. What is Polymorphism ?

  • Polymorphism – Poly stands for many and morph means form. So any thing that exists in more than one form is known as polymorph.
  • In oops, polymorphism means assigning a different meaning to an entity in different context.

Q. What are the different types of Inheritance ?
There are 5 types of inheritance,
a. Single Inheritence – One Super Class and One Sub class.
b. Multiple Inheritance – More than One Super Class and One Sub class
c. Multi Level Inheritance – A Class which is a Sub class of One class, becomes a Super class for another class.
d. Hierarchical Inheritance – One Super Class and many Sub classes
e. Hybrid Inheritance – Multiple and Multi level combined.


Q. What are the different types of Polymorphism ?
There are two types of polymorphism
1. Run Time Polymorphism
2. Compile time Polymorphism

To achive the Compile Time polymorphism there two ways

  • Function Overloading
  • Operator Overloading

To achieve the Run time Polymorphism we need to use

  • Virtual functions

Q. What is a Virtual Function ?

  • Virtual functions are normal member functions of a class, which can be over-ridden in the derived classes. The whole functionality can be replaced in the over-riding function.
  • In C#, the virtual functions will be declared with a keyword ‘virtual’ and the over-riding functions will be declared with ‘override’ key word.

Q. What is Serialization and De-Serialization?
Serialization is the process of converting an object into a series of bytes for transmitting or storing purpose. Deserialization is a process, where these same bytes are converted back into objects.


Q. What is an Abstract Class ?

  • Abstract class is a class which cannot be instantiated but it is inherited by derived classes. This class contains abstract as well as non-abstract methods and members.
  • Any concrete class (i.e not abstract) inheriting an abstract class MUST implement ALL inherited abstract method.

Q. What is an Interface ?

  • Interface is a contract for what a class MUST do, but it does not specify the way it should be done.
  • An interface contains only the signatures of methods (only the declaration). A class implementing the interface must implement all the members of the interface (i.e provide the definations for those methods).
  • Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be flexible.
  • Interfaces can inherit other (many) Interfaces.
  • A Class can implement many Interfaces.

Q. What is the difference between Abstract class and Interface ?

  • An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must be overriden in its derived class.
  • A class can inherit one or more interfaces, but only one abstract class.
  • An abstract class can have 0 abstract method.
  • Abstract class can have fields (such as int, string etc) , whereas Interface cannot.

Q. What are the different accessibility levels  that can be defined in .NET?
Private – Only members of class have access.
Protected – All members in current class and in derived classes can access the variables.
Friend (internal in C#) – Only members in current project have access to the elements.
Protected friend (protected internal in C#) – All members in current project  and all
members in derived class can access the variables.
Public – All members have access in all classes and projects.


Q. What is the difference between Class and Structure?

  • Structs are value types and classes are reference types. The general different is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.
  • A struct’s members are public by default while a class’ members are private by default
  • Classes are reference types and structs are value types.

Q. What does virtual keyword mean?

A. It signifies that the method/property can be overridden.


Q. What are static variables?

A static member cannot be referenced through an instance. Instead it is referenced through the class name.

An instance of a class will contain a separate copy for each instance, whereas for static, there will be only one copy for each static field.

If static keyword is applied to a class then all members of the class must be static.


Q. What is Finalize method in .NET?

Allows an object to try and free resources and perform other clean up operations before it is reclaimed by garbage collection.


Q. What is Dispose method in .NET?

Dispose method belongs to ‘IDisposable’ interface. If any object wants to release its unmanaged code, it is a good practice to implement the ‘IDisposable’ interface and then override the Dispose() method.


Q. What is the use of “Overrides” and “Overridable” keywords?

Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the child class to indicate that you are overriding a method


Q. Where are all .NET Collection classes located?

System.Collection namespace


Q. What is an ArrayList?

An ArrayList is a data structure. It stores data in an array that can be dynamically resized. Array list can hold item of different types. You can access any item in array using the INDEX value of the array position.


Q. What is a HashTable?

Hashtable optimizes lookups. This type is used in the C# language. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.


Hashtable hashtable = new Hashtable();
 hashtable[1] = "One";
 hashtable[2] = "Two";
 hashtable[13] = "Thirteen";

foreach (DictionaryEntry entry in hashtable)
 {
 Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
 }


Q. What are Collections in .NET

List
First, the List type provides you with an efficient and dynamically-allocated array. It does not provide fast lookup in the general case, which you will want to use Dictionary for. It is excellent when used in loops.


// Use the List type.
List<string> list = new List<string>();
list.Add("cat");
list.Add("dog");

foreach (string element in list)
{
 Console.WriteLine(element);
}
 

Dictionary
The Dictionary type in the base class library is one of the most important ones you need to use for your C# programs. It is an implementation of a hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET is well-designed.


// Use the dictionary.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("cat", 1);
dict.Add("dog", 4);

Console.WriteLine(dict["cat"]);
Console.WriteLine(dict["dog"]);

ArrayList
As shown in this program, the ArrayList is a collection found in System.Collections and it can store objects of any derived type. You don’t need to worry about the type of the elements, at least until you need to know their types to use them.


ArrayList list = new ArrayList();
list.Add("cat");
list.Add(2);
list.Add(false);

foreach (var element in list)
{
 Console.WriteLine(element);
}

Hashtable
Hashtable optimizes lookups. This type is used in the C# language. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type. First, you can create a new Hashtable with the simplest constructor. When it is created, the Hashtable has no values. We directly assign values with the indexer, which uses the square brackets [ ]. The example adds three integer keys with one string value each.


Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen";

foreach (DictionaryEntry entry in hashtable)
{
 Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

Stack
Stack is a LIFO collection. It provides a powerful and simple last-in-first-out data structure. This can help you develop parsers quickly and also replace complex recursive algorithms. Stack is a generic type.

LIFO:
The last element added (with Push) to Stack is the first one removed (with Pop).

Stack<int> stack = new Stack<int>();
stack.Push(100);
stack.Push(1000);
stack.Push(10000);
return stack;

Queues
Queue is a FIFO collection. It helps when you have elements that you need to process in a first-in, first-out order. It processes the elements that you received longest ago first. We look at several examples of using Queue<T>. We think about some of the logic used for processing help requests in a C# application.

First-In-First-Out:
The queue data structure implements this algorithm. Queue is a generic type with one type parameter.


// New Queue of integers
Queue<int> q = new Queue<int>();

q.Enqueue(5); // Add 5 to the end of the Queue.
q.Enqueue(10); // Then add 10. 5 is at the start.
q.Enqueue(15); // Then add 15.
q.Enqueue(20); // Then add 20.


Q. What is an ENUM?

It is used to define constants. Enums store special values. They make programs simpler. If you place constants directly where used, your C# program becomes complex. It becomes hard to change. Enums instead keep these magic constants in a distinct type. They improve code clarity. They alleviate maintenance issues.

An enum type is a distinct value type that declares a set of named constants.


Q. What is a nested Classes?

Nested classes are classes within classes. In sample below “ClsNested” class has a “Child
Nested” class nested inside it.

The class B here is enclosed inside the declaration of class A. Class B is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class A’s scope. In the main entry point, we create an instance of A, and also an instance of A.B. The instance of A does not contain an instance of B; the reverse is also the case.

Program that shows nested class B [C#]


class A
{
 public int _v1;

public class B
 {
 public int _v2;
 }
}

class Program
{
 static void Main()
 {
 A a = new A();
 a._v1++;

A.B ab = new A.B();
 ab._v2++;
 }
}


Q. What is Operator overloading in .NET?

It provides a way to define and use operators such as +, -, and / for user-defined classes or
structs. It allows us to define/redefine the way operators work with our classes and structs. This allows programmers to make their custom types look and feel like simple types such as int and string.


using System;

class Widget
{
 public int _value;

public static Widget operator +(Widget a, Widget b)
 {
 // Add two Widgets together.
 // ... Add the two int values and return a new Widget.
 Widget widget = new Widget();
 widget._value = a._value + b._value;
 return widget;
 }

public static Widget operator ++(Widget w)
 {
 // Increment this widget.
 w._value++;
 return w;
 }
}

class Program
{
 static void Main()
 {
 // Increment widget twice.
 Widget w = new Widget();
 w++;
 Console.WriteLine(w._value);
 w++;
 Console.WriteLine(w._value);

// Create another widget.
 Widget g = new Widget();
 g++;
 Console.WriteLine(g._value);

// Add two widgets.
 Widget t = w + g;
 Console.WriteLine(t._value);
 }
}

Output

1
2
1
3


Q. What is the significance of Finalize method in .NET?

For the majority of the objects that your application creates, you can rely on the .NET Framework’s garbage collector to implicitly perform all the necessary memory management tasks. However, when you create objects that encapsulate unmanaged resources, you must explicitly release the unmanaged resources when you are finished using them in your application. The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file, window, or network connection. Although the garbage collector is able to track the lifetime of an object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. For these types of objects, the .NET Framework provides the Object.Finalize method, which allows an object to clean up its unmanaged resources properly when the garbage collector reclaims the memory used by the object. By default, the Finalize method does nothing. If you want the garbage collector to perform cleanup operations on your object before it reclaims the object’s memory, you must override the Finalize method in your class.


Q. What is the use of DISPOSE method? 

Dispose method belongs to ‘IDisposable’ interface. We had seen in the previous section how bad it can be to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants to release its unmanaged code best is to implement I Disposable and override the Dispose method of I Disposable interface. Now once your class has exposed the Dispose method it is the responsibility of the client to call the Dispose method to do the cleanup.


Q. In what instances you will declare a constructor to be private?

When we create a private constructor, we cannot create object of the class directly from a client.
Therefore, you will use private constructors when you do not want instances of the class to be created by any external client. Example UTILITY functions in project will have no instance and be used with out creating instance, as creating instances of the class would be waste of memory.


Q. Can two catch blocks be executed?

No, once the proper catch section is executed the control goes finally to block. So there will not be any scenarios in which multiple catch blocks will be executed.


Q. What is the difference between System.String and System.StringBuilder

System. String is immutable; System.StringBuilder can have mutable string where a variety of operations can be performed.



Sachin’s 100th Century

It’s been a year and four days, but Sachin Tendulkar, the Little Master, has finally done it. He has scored 100 centuries in international cricket, an incredible sporting feat that may never be matched.

In the end, the historic milestone wasn’t reached in his backyard Mumbai. It wasn’t reached at Lord’s, the spiritual home of cricket. It wasn’t reached in the vast cauldron of the Melbourne Cricket Ground, either. It didn’t come against India’s great rival Pakistan, or the English or the Australians, or any other leading cricket-playing nations. It came against Bangladesh, in the Shere Bangla National Stadium, Dhaka.

Sachin Tendulkar on his way to his 100th century against Bangladesh, Thursday.

Tendulkar won’t care a jot about the venue or opposition. Any international century is special, and he’s just scored 100 of them. That’s 29 more centuries than his nearest challenger on the all-time list, Australia’s Ricky Ponting. This latest one is perhaps the sweetest, as it came when Tendulkar was facing an unfamiliar – and unfair — amount of criticism. The pressure was on.

But the pressure valve was emphatically released on Friday, March 16. The date will go down in history. Forget Pranab Mukherjee’s budget speech (if you can bear to), this was Sachin’s day. Millions of cricket fans – who had almost been more desperate for this moment than Tendulkar himself – watched as the Little Master’s score crept above 50, 60, 70, gulp, 80, then the unbelievably nervous 90s. Surely this was his moment. Please let this be his moment.

And it was.