Call Hierarchy : A handy feature in Visual Studio 2010

Suppose we have a solution that contains different dependent projects. We can face 2 most common situation here:

Situation 1: We have a method that we need to change by modifying the definition of that method or just we want to check that which other methods are calling this method.

Situation 2: We have a method that contains so many lines of codes and we need to check that inside this method which all other methods are calling as method is too large and we don’t want to go line by line for this.

Before VS 2010, for situation 1, we need to search the method name in whole solution then we can find the call of this solution in search window but the drawback of this approach is that if you have overloaded methods then in search result all methods will display and you need to take extra care for that.

Now in VS 2010, Microsoft provided a beautiful menu and context command to help these situations. Below are the steps to use these helpful commands:

  1. First you need to open your solution.
  2. Now open the file, where the method is located and needs to be checked.
  3. Go to View > Call Hierarchy
  4. Call Hierarchy window will open on bottom side, in this window choose My Solution from drop down. (You can also choose Current Project, Current Document depending upon your needs.)
  5. Now right click the method name in file opened and click on “View Call Hierarchy” from context menu.
  6. Your Call Hierarchy window will populate with details like Calls To “Method Name” and Calls From “Method Name” you can just expand these nodes and check all the incoming and outgoing call from this particular method.

Enjoy this new feature 🙂

 

Advertisements

Resolved: Could not load file or assembly ‘Microsoft.SharePoint.Search, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’ or one of its dependencies…

I have a solution that contains SharePoint dll’s reference. Whenever I run the solution, start page get crash and show me this error.

“Could not load file or assembly ‘Microsoft.SharePoint.Search, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’ or one of its dependencies. An attempt was made to load a program with an incorrect format.”

Well every time I run the project it creates Microsoft.SharePoint.Search.dll and Microsoft.SharePoint.Search.xml inside the bin folder and it creates the problem. Well there are lots many things have written on web regarding this problem. I follow all these things but could not get rid of this error. Finally I decided to fix this problem according to my way. So below are the steps to fix this problem permanently.

1.       Inside solution explorer (Visual Studio), select the project and right click on that.

2.       From context menu, click on properties.

3.       When properties page opens, Click on Build Events.

4.       Under Post – build event command line, copy and  paste below lines

cd $(TargetDir)

del Microsoft.SharePoint.Search.dll

del Microsoft.SharePoint.Search.xml

Now save the project, build the project and run. Now above mentioned error will never irritate you. 🙂

Resolved: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.

During my SharePoint project i need to clean up the site for better performance.  So first thing i started to delete the closed web parts from web part pages. As there were so many web part pages in the application so i decide to write a web application that can delete the closed web parts after run. Well when i run the application i got “The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.” error  on delete operations. I knew that this error was due to the fact that Web Page Security Validation was turned on that site and it was restricting me to delete the web part from my application. I can change the settings from Central Administration by turning off the security validation for that site but it’s not a good practices as any malicious code can harm your site as the security validation was off for that site. So i decide to handle this thing pro grammatically from my code so that it only disable security validation of web for a moment when only my code will run otherwise it will be on and protect my web from harmful activities. Well so here is the solution i applied.

Microsoft.SharePoint.Administration.SPWebApplication webApp = web.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;

// Insert your code for adding/deleting/updating here

webApp.FormDigestSettings.Enabled = true;

That’s it and i was back for deleting closed web parts 🙂

Common errors with SharePoint 2010 development using Visual Studio 2010 in x64 architecture: Resolved

“The type or namespace name ‘SharePoint’ does not exist in the namespace ‘Microsoft’ (are you missing an assembly reference?”

(Even you add Microsot.SharePoint.dll reference in your project and import the namespace in code but while building the solution you will get above mentioned annoying error.)

OR

“FileNotFoundException was unhandled: The Web application at http://localhost/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.”

(When you initialize the SPSite class in your code the above mentioned error will thrown. Well some people suggest that in place of localhost you should use machine name or ip of the machine but trust me I used all tricks but even then I couldn’t get rid of above mentioned error)

The above two problems are most annoying when you develop an application for SharePoint 2010 using Visual Studio 2010. Well no problems below are the solution of above two problems. Before writing the code just check for two things that are by default set by Visual Studio 2010 and need to change.

  • Right Click on your project (Not your solution).
  • Click on Properties.
  • On project properties page, Click on Application tab.
  • Under Target Framework select .NET Framework 3.5 in drop down list.
  • Click on save button in toolbar.
  • Now click on Build tab.
  • In Platform Target, select x64 option.
  • Click on save and close the project properties page.

Build and run the application and it would work fine now 🙂

Resolved: COM DLL is not showing in COM Library after Registering on Windows Server 2008 x64

Well I had to implement a payment gateway at my server. My server was built on x64 architecture and had Windows Server 2008 installed. Well according to the document I had to put my COM dll inside c:\windows\system32 folder and then from Run command I had to register this dll like “regsvr32 c:\windows\system32\MyCOM.dll”.

Well I done above mentioned procedure successfully now I want to use this dll in my C# project so I create a project and go for add reference but even after successful registration my COM dll was not showing inside COM tab. I tried all possible way to add reference of this dll without any luck. I tried un-register, register as well as browsing this dll to add reference but nothing could help out me. So after doing some goggling and research I came to know that in x64 architecture there is a folder inside “c:\windows\” i.e. SysWOW64. This folder is specially designed for old 32 bit programs. Well if you are registering the old 32 bit COM dll or other 32 program then you should put the dll inside SysWOW64 folder and then register them from that location it will then use RegSvr32.exe of SysWOW64 folder for normal 64 bit dlls and other 64 bit programs u should put dlls inside System32 folder and run RegSvr32.exe from System32 folder.

Get HTML of a web page using C#.NET

Below i am using a function that takes a web page full url as string and return back HTML of that page as string. You can
use this returned HTML in your code as per your requirement.

Step 1:
First import 2 namespaces that are required by this function to work.

using System.IO;
using System.Net;

Step 2:
Copy & Paste this function in your code behind.

public string GetHTML(string strURL)
{
HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create(strURL);
wbrq.Method = “GET”;
HttpWebResponse wbrs = (HttpWebResponse)wbrq.GetResponse();
StreamReader sr = new StreamReader(wbrs.GetResponseStream());
strResult = sr.ReadToEnd();
sr.Close();
return strResult;
}

Step 3:
Call this function as per your requirement.

string strHtml=this.GetHTML(“http://www.google.com”);

Happy Programming 🙂

Programming Tips for .NET Guys !

1. How to handle single quote (‘) during insertion and updation ?

Suppose there is a text box in form and you want to handle single quote ( ‘ ) during insertion and updation.

string StrValue=this.TextBox1.Text;
StrValue=StrValue.Replace(“‘”,”””);

2. How to handle maximum length in multi line text box ?

Suppose there is a multi line text box in form and you want to handle maximum length during insertion and updation.

int MaxLength=this.TextBox1.Text.Length;
if(MaxLength>=100)
MaxLength=100;
string StrMaxLength=this.TextBox1.Text.SubString(0,MaxLength);

3. How to do date time search in string mode ?

Suppose there is a text box in form and you want to search a date in grid using text entered in text box.

DateTime ScheduledDate=Convert.ToDateTime(this.TextBox1.Text);
string StrScheduledDate= ScheduledDate.ToString(MM,dd,yyyy);

Static Classes and Static Class Members in Microsoft.NET

Static Classes and Static Class Members

  

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class.

The data and functions do not change regardless of what happens to the object.

Static Classes

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword.

Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object.

The main features of a static class are:

They only contain static members.

They cannot be instantiated.

They are sealed.

They cannot contain Instance Constructors.

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created.

If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.

Static class members are declared using the static keyword before the return type of the member.

Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member.

 

Properties and Indexers in Depth

All the object-oriented languages support encapsulation, inheritance and polymorphism. What is different about C# is that it supports additional features like properties, events, indexers, delegates, etc. That is why C# is often termed as a modern object-oriented (OO) language. In this article we will discuss two modern OO concepts—properties and indexers.

Properties
Properties provide an interface for the data members of a class. Using properties, values can be stored and retrieved from the data members. So, what is the big deal about that? Even methods do the same thing. What’s good here is that we can access a property as if we are accessing a data member. Manipulating data using properties is done through get and set accessors. In the following example we have defined a property Size for a data member size.

class sample
{
            private int size ;
            public int Size
            {
                        get
                        {
                                     return size ;
                        }
                        set
                        {
                                     if ( value > 10 )
                                                 Console.WriteLine ( “Invalid Size” ) ;
                                     else
                                                 size = value ;
                        }
    }
}

The get accessor is invoked when we retrieve the value of the property, whereas the set accessor is invoked when we assign a value to the property. For example,

            sample s = new    sample( ) ;
            s.Size = 10 ;
            int i = s.Size ;

Here, the statement s.Size = 10 would invoke the set accessor. The value 10 would get collected in value. value is a keyword and is an implicit parameter of the set accessor. In the set accessor we have assigned the contents of value to the size data member. Before that we have validated the value assigned by the user to the property. Thus a property gives the syntactical convenience of a data member as well as the functionality of a method. We can write any program logic and throw exceptions in a property. It can be overridden and can be declared with any modifiers. The statement int i = s.Size would invoke the get accessor which returns the value of the size data member. The returned value would get collected in i.

Generally a property is associated with a data member. But this is not necessary. The get accessor can return a value without accessing a data member. For example, we can write a get property that returns system time without using a data member. The data type of a property can be a preliminary data type or a user-defined data type.

Indexers
An indexer is a new syntax that allows us to use an object as if the object itself is an array. This syntax is used if the class contains an array as a data member. An indexer allows access to the array elements within the class using the [ ] operator with an object. In one sense, we overload the [ ] operator. Unlike arrays, indexers allow usage of non-integer subscripts as well. Below, we see a program in which an indexer takes a string as a subscript.

using System ;
namespace stringindexer
{
   class sample 
   {
                        string[ ] english = new string[ ] {“Sunday”, “Monday”, “Tuesday”,
“Wednesday”, “Thursday”, “Friday”, “Saturday”} ;
                        string[ ] hindi = new string[ ] {“Itwar”, “Somwar”, “Mangalwar”,
“Budhwar”, “Guruwar”, “Shukrawar”, “Shaniwar”} ;
            public string this [string c]
            {
                        get
                        {
                                     for ( int i = 0 ; i < english.Length ; i++ )
                                                 {
                                                             if ( String.Compare ( c, english [ i ],
 true ) == 0 )
                                                             return hindi [ i ] ;
                                                 }
                                                 return “Not Found”;
                                     }
                                     set
                                     {
                                                 for ( int i = 0 ; i < english.Length ; i++ )
                                                 {
                                                             if ( String.Compare ( c, english [ i ],
 true ) == 0 )
                                                             {
                                                                         hindi [ i ] = value ;
                                                                         break ;
                                                             }
                                                 }
                                     }
                        }
   }
 
            class Class1
   {
                        static void Main ( string[ ] args )
                        {
                                     sample s = new sample( ) ;
                                     Console.WriteLine ( s[“Monday”] ) ;
                                     s[“Monday”] = “Som” ;
                                     Console.WriteLine ( s[“Monday”] ) ;
                        }
   }
}

In this example, the user would provide a string representing a weekday in English. The get accessor of the indexer would return the corresponding name in Hindi, whereas, set accessor would store the specified name in Hindi for the corresponding weekday in English. For example, s[“Monday”] should return “Somwar”. Similarly, s[“Monday”] = “Som” should set “Som” as Monday’s equivalent Hindi name. To implement this, we have declared two arrays of strings—english and hindi as data members of class sample. In Main( ), we have instantiated an object of sample and called the get accessor through the statement Console.WriteLine ( s [ “Monday” ] ) ;

“Monday” would get collected in c in the get accessor. If the specified weekday is available in the english array we have returned its Hindi equivalent from the hindi array. We have done a case insensitive comparison by mentioning true as a third parameter of the Compare( ) method.

Next, we have called the set accessor through the statement s [ “Monday” ] = “Som” ;

The string “Monday” would get collected in c. We have stored the name “Som”, which is available in the implicit parameter value, in the hindi array.

Indexers are nameless. It means that unlike properties we cannot assign name to an indexer. We use the this reference for writing indexers. Indexers may be overloaded. We can write one indexer for a 1-D array and another for a 2-D array in the same class. Needless to say, a 2-D indexer is accessed using [ , ] syntax.

Although indexers allow us to use an object as an array, we cannot use it in a foreach loop like an array. This is because foreach works only with collections. Writing an indexer does not qualify a class to be a collection.

It is not possible to write indexers for jagged arrays because a statement such as public int this [ int index1] [ int index2 ] results in an error.

Lastly, indexers cannot be declared as static because of the simple reason that the this reference is not available in static methods.

Partial Classes in Depth

Partial classes permit splitting a single class, interface, or struct into multiple, separate files. There are several advantages to splitting these elements into many files, including permitting more than one developer to work on the same class.
OR
partial classes mean that your class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.

The partial keyword also means that it’s possible to split generated code into two parts: the part that’s generated, and another part that provides a convenient location for you and me to add customizations.

One of the greatest benefits of partial classes is that it allows a clean separation of business logic and the user interface (in particular the code that is generated by the visual designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway.

Partial classes will also make debugging easier, as the code is partitioned into separate files.

Using Partial Classes
Listing 1 contains two class definitions written in VB.NET, with the second class definition starting with the partial keyword. Both class definitions may reside in two different physical files. Functionally, Listing 1 is equivalent to Listing 2.

Listing 1
‘—File1.vb—
Public Class Class1
Public Sub method1()

End Sub
End Class

File2.vb
Partial Public Class Class1
Public Sub method2()

End Sub
End Class
Listing 2
‘—File1.vb—
Public Class Class1
Public Sub method1()

End Sub
Public Sub method2()

End Sub
End Class
So, what are the uses for partial classes?

Here are some good reasons to use partial classes:
They allow programmers on your team to work on different parts of a class without needing to share the same physical file. While this is useful for projects that involve big class files, be wary: If you find your class file getting too large, it may well signal a design fault and refactoring may be required.
The most compelling reason for using partial class is to separate your application business logic from the designer-generated code. For example, the code generated by Visual Studio 2005 for a Windows Form is kept separate from your business logic (we will discuss this in a later section). This will prevent developers from messing with the code that is used for the UI. At the same time, it will prevent you from losing your changes to the designer-generated code when you change the UI.

Rules for Partial Classes
Elements That Can Use the Partial Keyword
The partial keyword can be applied to a class, a struct (structure in VB), and an interface. All of the parts make up the whole, and you can split the parts into as many source files as you’d like.
The partial class cannot be applied to an enumeration or a delegate, although a delegate is really a class.

Defining Parts in the Same Namespace
If you define two classes with the same name in different namespaces, the result is a different class, even if each class uses the partial keyword. For multiple parts to be part of the same whole, each part must reside in the same namespace.

Assigning Accessibility
All parts must have the same accessibility modifier. For example, if one part is public, all parts should be public. If any part has the sealed modifier applied, all parts are considered sealed. (Sealed is equivalent to NotInheritable in VB.)

Specifying Generalization and Realization
Only one part needs to provide the name of any parent classes, but all parts inherit from the same parent (this is referred to as generalization). If all parts are specific to a parent class, then all of the parts must agree.
Each part can specify different interfaces—called realization—but in the end the final type must implement (or realize the union of) all of the interfaces defined by thee parts.

Finally, the partial keyword must precede one of the three words class, struct, or interface in C#, or Class, Structure, or Interface in Visual Basic.NET. All parts must reside in the same module or assembly (.exe or .dll).

*Generic can be defined as partial classes, but the class name and all generic parameters must match on all of the parts.*