Example:
namespace ConsoleApplication5
{
class Sample
{
public int Age()
{
return 12;
}
}
class Program:Sample
{
public int Age()
{
return 56;
}
static void Main(string[] args)
{
Program pgm = new Program();
Console.WriteLine(pgm.Age());
Console.ReadLine();
}
}
}
Output:56
Warning Message: 'ConsoleApplication5.Program.Age()' hides inherited member 'ConsoleApplication5.Sample.Age()'. Use the new keyword if hiding was intended. C:\Documents and Settings\hemnam\My Documents\Visual Studio 2005\Projects\ConsoleApplication5\ConsoleApplication5\Program.cs
If you want to resolve this warning message put the 'New' keyword in the derived class.So automatically the warning message will goes off.
The reason behind, whenever if you use 'New' keyword it will hide the base class method.
1. In C#, derived classes can contain methods with the same
name as base class methods.
2. The base class method must be defined virtual.
If the method in the derived class is not preceded by
new or override keywords, the compiler will issue a warning
and the method will behave as if the new keyword were present.
3. If the method in the derived class is preceded with
the new keyword, the method is defined as being independent
of the method in the base class.
4. If the method in the derived class is preceded with
the override keyword, objects of the derived class will call
that method instead of the base class method.
5. The base class method can be called from within the
derived class using the base keyword. The override, virtual, and new keywords can also be
applied to properties, indexers, and events.
Sunday, November 23, 2008
Shall we have the method in drived class with the same name which is there in base class?
How to display date in textbox from the Calendar control
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
}
How to upload document from one document library into another document library
public void UploadChart()
{
try
{
String GenerateNo=”ABC_0001”;
String Vertical= Request.QueryString["Vertical"];
sourceWeb = mySite.OpenWeb();
destinationWeb = mySite.AllWebs[Vertical];
destinationWeb.AllowUnsafeUpdates = true;
destinationWeb.Update();
sourceDocuments = sourceWeb.Lists["List Template Gallery"];
destinationDocuments = destinationWeb.Lists["Chart"];
currentSourceDocument = sourceDocuments.Items.GetItemById(25);
fileBytes = currentSourceDocument.File.OpenBinary();
fileNameandExtn = currentSourceDocument.File.Name.Split(".".ToCharArray());
NameofDocument = fileNameandExtn[0] + "_" + GenerateNo + "." + fileNameandExtn[1];
ht1 = new Hashtable();
ht1.Add("ContractNumber", GenerateNo);
//GenerateNo is the method to generate number
relativeDestinationUrl = destinationDocuments.RootFolder.Url + "/" + NameofDocument;
destinationFile = ((SPDocumentLibrary)destinationDocuments).RootFolder.Files.Add(relativeDestinationUrl,fileBytes, ht1,OverwriteDestinationFile);
destinationFile.CheckIn("New Contract", SPCheckinType.MajorCheckIn);
}
catch (Exception ex)
{
//System.Diagnostics.EventLog.WriteEntry("Contract Details Exception", ex.Message);
}
finally
{
mySite.Dispose();
}
}
How to upload document into document library using C#.Net
String Continent = clistitem["Continent"].ToString();
fStream = FileUpload1.PostedFile.InputStream;
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
//storing the contents of the uploaded document
Bytes[] contents= new byte[fStream.Length];
fileName = FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf('\\') + 1);
Hashtable ht = new Hashtable();
ht.Add("Continent", Continent);
SPFile fff = files.Add(fileName, contents, ht, true);
myweb.AllowUnsafeUpdates = true;
myweb.Update();
How to loop through all the Groups
foreach (SPGroup grp in myweb.Groups)
{
if (!grp.Name.Contains("Admin"))
{
foreach (SPUser user in grp.Users)
{
lbUsers.Items.Add(user.Name);
}
}
}
Saturday, November 22, 2008
How to find one list item from the Listitems
SPDocumentLibrary ContractsLib;
SPListItemCollection contractsItems;
ContractsLib = (SPDocumentLibrary)myweb.Lists["Contracts"];
SPListItem clistitem;
String EmployeeNumber=Request.QueryString["EmployeeNumber "] != null)
{
SPListItemCollection contractsItems;
String strContractNumber = Request.QueryString["ContractNumber"];
ENumberQuery = new SPQuery();
// Belowed one line of code will help you to loop through all the items;
ENumberQuery.ViewAttributes = "Scope=\"Recursive\"";
ENumberQuery.Query = "
"
"" +"
"
"" +
"";
contractsItems = ContractsLib.GetItems(ENumberQuery);
clistitem = contractsItems[0];
Friday, November 21, 2008
How to connect MOSS(Sharepoint Server 2007) using c#.Net
Use the following namespace for your Project to utilise the Sharepoint classes, properties and methods.
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
Once you add the reference and namespace properly, intellisense will show you all the classes and methods properly.
mySite = new SPSite("http://Test-Sample:123/"); //You have to specify your site here.
SPWeb myweb = mySite.AllWebs["IT"]; //You have to speify the subsite here.
myweb.AllowUnsafeUpdates = true; //It will allow you to update listitem or List or anything from your code.
myweb.Update(); //It will update the web.
This code will be hardcoded. If you don't want to hardcode you can use the following code snippet
string Subsite = Request.QueryString["Subsite"]
mySite = new SPSite(this.Page.Request.Url.ToString());
SPWeb myweb = mySite.AllWebs[Subsite];
myweb.AllowUnsafeUpdates = true;
myweb.Update();
The above example is a good practice to implement it to your Project. In this project instead of subsite hardcoding, i used querystring to fetch the subsite from other forms. Based on the subsite value it will connect to your subsite.
Thursday, November 20, 2008
Polymorphism:
The declaration of the method name will be same, but passing parameter datatypes, order of parameters and number of parameters will be differentiate the methods.
In the belowed example, Add method is doing different operations. Here in this example i have implemented the Constructor Overloading also.
using System;
using System.Collections.Generic;
using System.Text;
namespace Polymorphism
{
class Sample
{
public Sample()
{
Console.WriteLine("Sample Constructor invoked");
Console.ReadLine();
}
public void Multiply()
{
int a, b, c;
a = 10;
b = 20;
c = a * b;
Console.WriteLine("C value is:" + c);
Console.ReadLine();
}
public void Exam()
{
Console.WriteLine("This is from base calss");
Console.ReadLine();
}
public virtual void display()
{
Console.WriteLine("Hello from Base class");
Console.ReadLine();
}
}
class Program:Sample
{
public Program()
{
Console.WriteLine("Program constructor involked");
Console.ReadLine();
}
public void Multiply(int a, int b)
{
int c = a * b;
Console.WriteLine("C value is:" + c);
Console.ReadLine();
}
public new void Exam()
{
Console.WriteLine("This is from Derived class");
Console.ReadLine();
}
public int Add(int n1, int n2)
{
return n1 + n2;
}
public float Add(float a1, float a2)
{
return a1 + a2;
}
public override void display()
{
Console.WriteLine("Hello from derived class");
Console.ReadLine();
}
static void Main(string[] args)
{
Program pgm = new Program();
pgm.display();
pgm.Exam();
pgm.Multiply(20, 30);
pgm.Multiply();
Console.WriteLine(pgm.Add(2.3f, 5.6f));
Console.WriteLine(pgm.Add(45, 67));
Console.ReadLine();
Sample obj = new Sample();
obj.Multiply();
obj.display();
obj.Exam();
Sample pgm1 = new Program();
pgm1.display();
pgm1.Exam();
pgm1.Multiply();
}
}
}
Wednesday, November 19, 2008
Interface Method and Property declaration Example
using System.Collections.Generic;
using System.Text;
namespace Interface
{
interface Maths
{
void add();//method declaration
void concatenate();//method declaration
//Property declaration
int Add
{
get;
set;
}
//Property declaration
string Concatenate
{
get;
set;
}
}
class Program:Maths
{
//method definition
public void add()
{
int a = 23;
int b = 45;
int c = a + b;
Console.WriteLine(c);
Console.ReadLine();
}
//method definition
public void concatenate()
{
string FirstName = "Hemnath";
string LastName = "Manoharan";
string Name = FirstName + LastName;
Console.WriteLine(Name);
Console.ReadLine();
}
//property definition
public int Add
{
get
{
return c=a+b;
}
set
{
c = value ;
}
}
public int c;//variable declaration
public int a = 12;//variable declaration
public int b = 23;//variable declaration
//property definition
public string Concatenate
{
get
{
return Total=s+g ;
}
set
{
Total = value ;
}
}
public string Total;//variable declaration
public string s = "Hem";//variable declaration
public string g = "nath";//variable declaration
static void Main(string[] args)
{
Maths mat;//instance for interface
Program obj = new Program();//Instance for class
mat = new Program();
Console.WriteLine(mat.Add);
Console.WriteLine(mat.Concatenate);//calling the interface property
Console.ReadLine();//calling the interface property
obj.add();//calling the interface mthod
obj.concatenate();//calling the interface mthod
}
}
}
Interface Definition with Example
- An Interface is a reference type and it contains only abstract members.
- Interface's members can be Events,Methods,Properties and Indexers.But the Interface contains only declaration for its members.
- Any implementation must be placed in class that realizes them.
- All member declaration inside interface are implicitly public.
Limitations:
- The Interface can't contain constants, data fields, constructors, destructors and static members.
- A very important point to be remembered about c# interfaces is, if some interface is inherited, the program must implement all its declared members. Otherwise the c# compiler throws an error.
using System;
using System.Collections.Generic;
using System.Text;
namespace Interface
{
interface Maths
{
int Add
{
get;
set;
}
string Concatenate
{
get;
set;
}
}
class Program:Maths
{
public int Add
{
get
{
return c=a+b;
}
set
{
c = value ;
}
}
public int c ;
public int a = 12;
public int b = 23;
public string Concatenate
{
get
{
return Total=s+g ;
}
set
{
Total = value ;
}
}
public string Total;
public string s = "Hem";
public string g = "nath";
static void Main(string[] args)
{
Maths mat;
mat = new Program();
Console.WriteLine(mat.Add);
Console.WriteLine(mat.Concatenate);
Console.ReadLine();
}
}
}
Now the above code has created a c# class Program(Class) that inherits from Maths (Interface) c# interface and implement all its members.
Tuesday, November 18, 2008
Limitations of Abstract Class and Abstract method
- Abstract class cannot be a
sealed
class. - Declaration of abstract methods are only allowed in abstract classes.
- An abstract method cannot be
private
. - The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as
protected
, it should beprotected
in its derived class. Otherwise, the compiler will raise an error. - An abstract method cannot have the modifier
virtual
. Because an abstract method is implicitly virtual. - An abstract member cannot be
static
.
Multiple Abstract Class
Example:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
public abstract class Class1
{
public void Add(int n1, int n2)
{
int n3;
n3= n1 + n2;
Console.WriteLine("N3:" + n3);
Console.ReadLine();
}
public abstract void Multiply(int x, int y);
}
public abstract class Program1 : Class1
{
string c;
public void Concatenate(string a, string b)
{
c = a + b;
Console.WriteLine(" C:" + c);
Console.ReadLine();
}
}
class Program : Program1
{
public static void Main(string[] args)
{
Program asd = new Program();
asd.Add(10, 20);
asd.Concatenate("Hem", "nath");
asd.Multiply(20, 100);
}
public override void Multiply(int e, int f)
{
int z;
z = e * f;
Console.WriteLine("Z:" + z);
Console.ReadLine();
}
}
}
In the above example,
absClass1
contains two methods Add
and abstract method Multiply
. The class Program
is derived from Program1
and the Multiply
is implemented there.
Simple Abstract Class- Definition with Example
Abstract Class:
Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract
'.
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
Example :
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
abstract class Class1
{
public void Add(int n1, int n2)
{
int n3;
n3= n1 + n2;
Console.WriteLine("N3:" + n3);
Console.ReadLine();
}
public abstract void Multiply(int x, int y);
}
class Program:Class1
{
string c;
int z;
public void Concatenate(string a, string b)
{
c = a + b;
Console.WriteLine(" C:" + c);
Console.ReadLine();
}
public static void Main(string[] args)
{
Program pgm = new Program();
pgm.Add(10, 20);
pgm.Concatenate("Hem", "nath");
pgm.Multiply(20, 100);
}
public override void Multiply(int e, int f)
{
z = e * f;
Console.WriteLine("Z:" + z);
Console.ReadLine();
}
}
}
In the above sample, you can see that the abstract class Class1
contains two methods Add
and Multiply
. Add
is a non-abstract method which contains implementation and Multiply
is an abstract method that does not contain implementation.
The class Program
is derived from Class
1 and the Multiply
is implemented on Program
. Within the Main
, an instance ( pgm) of the Program
is created, and calls Add
and Multiply
.
Partial Class Example and Definition
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
}
public partial class sub
{
int a,b,c;
public void method()
{
a=10;
b=20;
c=a+b;
}
}
public partial class sub
{
public void display()
{
method();
Console.WriteLine("C Value is :"+ c);
Console.ReadLine();
}
static void Main(string[] args)
{
sub sd=new sub();
sd.display();
sd.meth();
}
}
}
Class1.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Class1
{
}
public partial class sub
{
public void meth()
{
method();
Console.WriteLine("C value is:" + c);
Console.ReadLine();
}
}
}
- Partial Class name should be same in both Program.cs and Class1.cs file.
- We can use the method from one class file to another class file.
- Easily Debugging.
- Sharing the class is easy.
- Multiple developers can work at a time.
- But the compiler merges these 2 classes and it will compile.
- The assembly should unique for these 2 class files.
Monday, November 17, 2008
Partial Classes in Asp.Net
The newly introduced “partial” keyword can be used to split a single class, interface, or struct into multiple, separate files in ASP.NET (using C# as the language). This permits multiple developers to works on these files, which can later be treated as a single unit by the compiler at the time of compilation and compiled into MSIL code. Partial classes can improve code readability and maintainability by providing a powerful way to extend the behavior of a class and attach functionality to it. This article discusses partial classes and how to use them in our ASP.NET applications in a lucid language (with code examples, wherever necessary).
Partial Classes in ASP.NET
Using partial classes helps to split your class definition into multiple physical files. However, this separation does not make any difference to the C# compiler, as it treats all these partial classes as a single entity at the time of compilation and compiles them into a single type in Microsoft Intermediate Language (MSIL). ASP.NET 2.0 uses partial classes as the code-beside class (a new evolution of the code behind model). It is generated by ASP.NET 2.0 to declare all the server side controls you have declared in your ASPX file. The following is an example of a partial class definition:
using System;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
Following are the major benefits of using partial classes:
- Isolation of the business logic of an application from its user interface
- Facilitates easier debugging
Implementing Partial Classes
We can split one part of a class in one file and the other part in some other file using the partial keyword. The compiler merges these partial classes spread across one or more source files into a single compiled class at the time of compilation — provided all these partial types are available. The following code examples illustrate this better:
Employee1.cs
public partial class Employee
{
public void ReadData()
{
//Some code
}
}
Employee2.cs
public partial class Employee
{
public void SaveData()
{
//Some code
}
}
class Test
{
public static void
{
Employee employee = new Employee();
//Some Code
employee.ReadData();
//Some code
employee.SaveData();
}
}
Points to Be Noted
This section discusses some of the most important points that we should keep in mind when working with partial classes or types. Note that all partial types are defined using the keyword “partial”. Further, the “partial” keyword should precede the type signature definition. Note that the partial keyword applies to classes, structs, and interfaces, but not enums. It also does not apply to classes that extend the system classes or types. According to MSDN, “It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled”. The partial types for a specific type should be located in the same module or assembly.
Saturday, November 1, 2008
Data Caching:
For Data caching asp.net provides a cache object for Ex:cache["States"]=dsStates;
Caching:
In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.
Asp.net has 3 kinds of caching strategies Output Caching, Fragment Caching and Data Caching
Difference Between Response.Write and Response.Output.Write:
Satellite Assemblies:
These assemblies are used in deploying an Global application for different languages.
Public/Shared Assemblies:
Strong name has to be created to create a shared assembly.
This can be done using SN.EXE. The same has to be registered using GACUtil.exe(Global Assembly Cache).