For an example,
StringVar textToDisplay := "Title for the Cross-Tab" + Chr(13) + "Period from Year X to Year Y"
int[] intArray = new int[] { 3, 1, 4, 5, 2 };Of course, this is not efficient for large arrays.
Array.Sort<int>( intArray );
Array.Reverse( intArray );
<%@ Page Language="C#" AutoEventWireup="true" Codebehind="SortSample.aspx.cs" Inherits="SampleApplication.SortSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sort Ascending /Descending Order by Generic</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace SampleApplication.
{
public partial class SortSample: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
char[] charArray = new char[] { 'r', '1', 'f', 'c', 'x' };
string[] stringArray = new string[] { "array item 1", "array item 2", "array item 3", "array item 4", "array item 5" };
ArraySorter<int>.SortDescending(intArray);
ArraySorter<char>.SortDescending(charArray);
ArraySorter<string>.SortDescending(stringArray);
BindDropDownList(DropDownList1, intArray);
BindDropDownList(DropDownList2, charArray);
BindDropDownList(DropDownList3, stringArray);
}
private static void BindDropDownList(BaseDataBoundControl ddl, Array arr)
{
if(ddl !=null && arr !=null && arr.Length>0)
{
ddl.DataSource = arr;
ddl.DataBind();
}
}
static public class ArraySorter<T> where T : IComparable
{
static public void SortDescending(T[] array)
{
Array.Sort<T>(array, s_Comparer);
}
static private readonly ReverseComparer s_Comparer = new ReverseComparer();
private class ReverseComparer : IComparer<T>
{
public int Compare(T object1, T object2)
{
return -((IComparable)object1).CompareTo(object2);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatternConsole
{
/// <summary>
/// The 'Product' abstract class
/// </summary>
abstract class Page
{
}
/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class SkillsPage : Page
{
}
/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class EducationPage : Page
{
}
/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ExperiencePage : Page
{
}
/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class IntroductionPage : Page
{
}
/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ResultsPage : Page
{
}
/// <summary>
/// The 'Creator' abstract class
/// </summary>
abstract class Document
{
private List<Page> _pages = new List<Page>();
// Constructor calls abstract Factory method
public Document()
{
this.CreatePages();
}
public List<Page> Pages
{
get { return _pages; }
}
// Factory Method
public abstract void CreatePages();
}
/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Resume : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new SkillsPage());
Pages.Add(new EducationPage());
Pages.Add(new ExperiencePage());
}
}
/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Report : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new IntroductionPage());
Pages.Add(new ResultsPage());
}
}
class AbstractFactory
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Note: constructors call Factory Method
Document[] documents = new Document[2];
documents[0] = new Resume();
documents[1] = new Report();
// Display document pages
foreach (Document document in documents)
{
Console.WriteLine("\n" + document.GetType().Name + "--");
foreach (Page page in document.Pages)
{
Console.WriteLine(" " + page.GetType().Name);
}
}
// Wait for user
Console.ReadKey();
}
}
}
Happy Coding!!!
if (singleton == null)
{
singleton = new Singleton(); // lazy instantiation
Console.WriteLine ("Singleton instantiated");
}
public sealed class Singleton
{
//private static Singleton singleton;
private static readonly Singleton singleton = new Singleton(); // eager instantiation
static Singleton()
{
Console.WriteLine ("Singleton instantiated");
}
private Singleton() {} // private constructor
public static Singleton GetInstance()
{
//if (singleton == null)
//{
// singleton = new Singleton();
// Console.WriteLine ("Singleton instantiated");
//}
return singleton;
}
}
<%@ Page Language="C#" AutoEventWireup="true" Codebehind="DesignPatternTest.aspx.cs"
Inherits="DesignPatternTest.SingletonSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Singleton</title>
</head>
<body>
<form id="form1" runat="server">
<div>
See the above Singleton output
</div>
</form>
</body>
</html>
using System;
namespace DesignPatternTest
{
public partial class SingletonSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Constructor is protected
// Prevented from using 'new' keyword
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if (s1 == s2)
Response.Write("s1 & s2 are the same instance");
s1.x = 100;
Response.Write("<br>s1.x=" + s1.x);
s2.x = 200;
Response.Write("<br>s2.x=" + s2.x);
// Updates to x are updating same instance
Response.Write("<br>s1.x=" + s1.x);
Response.Write("<br>s2.x=" + s2.x);
}
}
public class Singleton
{
// Variable
public int x = 0;
// Fields
private static Singleton instance;
// Empty Constructor
protected Singleton() { }
// Methods
public static Singleton Instance()
{
// Uses "Lazy initialization"
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
Happy Coding!!!
Step 2 : Now add handler for
<style type="text/css">
.normalrow
{
background-color:white;
}
.hightlighrow
{
background-color:#cccccc;
}
</style>
RowCreated
event for the grid and add the attributes for onmouseover
and onmouseout
javascript events.Use the technology!!!
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='hightlighrow'");
e.Row.Attributes.Add("onmouseout", "this.className='normalrow'");
}
}
function AllowNumbersOnly(evt)
{
// Allow numbers only in the Textbox.
var e = event evt; // for trans-browser compatibility
var charCode = e.which e.keyCode;
if (charCode > 31 && (charCode < 48 charCode > 57))
return false;
return true;
}
<INPUT id="txtChar" onkeypress="return AllowNumbersOnly(event)" type="text" name="txtChar">
TextBox.Attributes.Add("onkeypress", "javascript:return AllowNumbersOnly(event);");
What is an Object?
An object is an instance of a class. It can be uniquely identified by its name and it defines a state which is represented by the values of its attributes at a particular time.An object can be considered a "thing" that can perform a set of activities. The set of activities that the object performs defines the object's behavior.
The state of the object changes according to the methods which are applied to it. We refer to these possible sequences of state changes as the behavior of the object. So the behavior of an object is defined by the set of methods which can be applied on it.
Objects can communicate by passing messages to each other.
What is inheritance?
Inheritance is the mechanism which allows a class A to inherit properties of a class B. We say "A inherits from B''. Objects of class A thus have access to attributes and methods of class B without the need to redefine them.
If class A inherits from class B, then B is called superclass of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the superclass.
However, subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass.
In the literature you may also find other terms for "superclass" and "subclass". Superclasses are also called parent classes or base classes. Subclasses may also be called child classes or just derived classes.
Inheritance Example
Like a car, truck or motorcycles have certain common characteristics- they all have wheels, engines and brakes. Hence they all could be represented by a common class Vehicle which encompasses all those attributes and methods that are common to all types of vehicles.
However they each have their own unique attributes; car has 4 wheels and is smaller is size to a truck; whereas a motorcycle has 2 wheels. Thus we see a parent-child type of relationship here where the Car, Truck or Motorcycle can inherit certain Characteristics from the parent Vehicle; at the same time having their own unique attributes. This forms the basis of inheritance; Vehicle is the Parent, Super or the Base class. Car, Truck and Motorcycle become the Child, Sub or the Derived class.
What is a Virtual Functions in class?
A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions.
A virtual function has a different functionality in the derived class according to the requirement. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods (polymorphism).
The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.
What is Encapsulation in Object Oriented Programming (OOPS) Languages?
Encapsulation is the procedure of covering up of data and functions into a single unit. Encapsulation (also information hiding) consists of separating the external aspects of an object which are accessible to other objects, from the internal implementation details of the object, which are hidden from other objects.
A process, encapsulation means the act of enclosing one or more items within a (physical or logical) container (Class).
Object-oriented programming is based on encapsulation. When an objects state and behavior are kept together, they are encapsulated. That is, the data that represents the state of the object and the methods (Functions and Subs) that manipulate that data are stored together as a cohesive unit.
The object takes requests from other client objects, but does not expose its the details of its data or code to them. The object alone is responsible for its own state, exposing public messages for clients, and declaring private methods that make up its implementation. The client depends on the (hopefully) simple public interface, and does not know about or depend on the details of the implementation.
For example, a HashTable object will take get() and set() requests from other objects, but does not expose its internal hash table data structures or the code strategies that it uses.
Explain the advantages of Encapsulation in Object Oriented Programming Languages.
Benefits of Encapsulation in oops: Encapsulation makes it possible to separate an objects implementation from its behavior to restrict access to its internal data. This restriction allows certain details of an objects behavior to be hidden. It allows us to create a "black box" and protects an objects internal state from corruption by its clients.
Encapsulation is a technique for minimizing interdependencies among modules by defining a strict external interface. This way, internal coding can be changed without affecting the interface, so long as the new implementation supports the same (or upwards compatible) external interface. So encapsulation prevents a program from becoming so interdependent that a small change has massive ripple effects.
The implementation of an object can be changed without affecting the application that uses it for: Improving performance, fix a bug, consolidate code or for porting.
Limitations and Restrictions of Interface
The essential idea to remember is that an interface never contains any implementation. The following restrictions and imitations are natural consequences of this:
You're not allowed any fields in an interface, not even static ones. A field is an implementation of an object attribute.
You're not allowed any constructors in an interface. A constructor contains the statements used to initialize the fields in an object, and an interface does not contain any fields!
You're not allowed a destructor in an interface. A destructor contains the statements used to destroy an object instance.
You cannot supply an access modifier. All methods in an interface are implicitly public.
You cannot nest any types (enums, structs, classes, interfaces, or delegates) inside an interface.
What is the difference between abstract class and interface?
We use abstract class and interface where two or more entities do same type of work but in different ways. Means the way of functioning is not clear while defining abstract class or interface. When functionality of each task is not clear then we define interface. If functionality of some task is clear to us but there exist some functions whose functionality differs object by object then we declare abstract class.
We can not make instance of Abstract Class as well as Interface. They only allow other classes to inherit from them. And abstract functions must be overridden by the implemented classes. Here are some differences in abstract class and interface.
An interface cannot provide code of any method or property, just the signature. We dont need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. An abstract class can provide complete code of methods but there must exist a method or property without body.
A class can implement several interfaces but can inherit only one abstract class. Means multiple inheritance is possible in .Net through Interfaces.
What is a static class?
We can declare a static class. We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We can not create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.
Here are some more features of static class:
What is static member of class?
A static member belongs to the class rather than to the instances of the class. In C# data fields, member functions, properties and events can be declared static. When any instances of the class are created, they cannot be used to access the static member.
To access a static class member, use the name of the class instead of an instance variable
Static methods and Static properties can only access static fields and static events.
Like: int i = Car.GetWheels;
Here Car is class name and GetWheels is static property.
Static members are often used to represent data or calculations that do not change in response to object state.
What is the difference between value parameter and reference parameter?
A value parameter is used for "in" parameter passing, in which the value of an argument is passed into a method, and modifications of the parameter do not impact the original argument. A value parameter refers to its own variable, one that is distinct from the corresponding argument. This variable is initialized by copying the value of the corresponding argument.
A reference parameter is used for "by reference" parameter passing, in which the parameter acts as an alias for a caller-provided argument. A reference parameter does not itself define a variable, but rather refers to the variable of the corresponding argument. Modifications of a reference parameter impact the corresponding argument.
What is the use of parameter array?
A parameter array enables a many-to-one relationship: many arguments can be represented by a single parameter array. In other words, parameter arrays enable variable length argument lists.
A parameter array is declared with a params modifier in C#. There can be only one parameter array for a given method, and it must always be the last parameter specified. The type of a parameter array is always a single dimensional array type. A caller can either pass a single argument of this array type, or any number of arguments of the element type of this array type.
What is a constant?
A constant is a class member that represents a constant value: a value that can be computed at compile-time.
Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies. The example
class Constants {
public const int A = 1;
public const int B = A + 1;
}
shows a class named Constants that has two public constants.
Happy Programming!!!
What is the difference between indexers and properties in C#?
Comparison Between Properties and IndexersIndexers are similar to properties. Except for the differences shown in the following , all of the rules defined for property accessors apply to indexer accessors as well.
What type of class cannot be inherited?
A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note that a struct is implicitly sealed; so they cannot be inherited.
How do I use an alias for a namespace or class in C#?
Use the using directive to create an alias for a long namespace or class. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in. Sample code: // Namespace:
using act = System.Runtime.Remoting.Activation;
// Class:
using list = System.Collections.ArrayList;
...
list l = new list(); // Creates an ArrayList
act.UrlAttribute obj; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute obj
Can an abstract class have non-abstract methods?
An abstract class may contain both abstract and non-abstract methods. But an interface can contain only abstract methods.
Explain some features of interface in C# or Comparison of interface with class.
An interface cannot inherit from a class.
An interface can inherit from multiple interfaces.
A class can inherit from multiple interfaces, but only one class.
Interface members must be methods, properties, events, or indexers.
All interface members must have public access (the default).
By convention, an interface name should begin with an uppercase I.
Name two ways that you can prevent a class from being instantiated.
Ways to prevent a class from instantiated:
What's the difference between override and new in C#?
his is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance:
public class Base
{
public virtual void SomeMethod()
{
}
}
public class Derived : Base
{
public override void SomeMethod()
{
}
}
...
Base b = new Derived();
b.SomeMethod();
will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.
Now, if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code like this:
public class Base
{
public virtual void SomeOtherMethod()
{
}
}
public class Derived : Base
{
public new void SomeOtherMethod()
{
}
}
...
Base b = new Derived();
Derived d = new Derived();
b.SomeOtherMethod();
d.SomeOtherMethod();
Will first call Base.SomeOtherMethod , then Derived.SomeOtherMethod . They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
Explain Abstract, Sealed, and Static Modifiers in C#
C# provides many modifiers for use with types and type members. Of these, three can be used with classes: abstract, sealed and static.
Which interface(s) must a class implement in order to support the foreach statement?
Required interface for foreach statement: A class must implement the IEnumerable and IEnumerator interfaces to support the foreach statement.
How do I call one constructor from another in C#?
You use : base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether you want to call a constructor in the base class or in this class.
What is the difference between struct and class in C#?
Structs vs classes in C#
Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.
Happy programming!!!
Net remoting replaces DCOM. Web Services that uses remoting can run in any Application type i.e. Console Application, Windows Form Applications, Window Services etc. In CLR Object Remoting we can call objects across network.
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).
Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.
There are a number of styles of remote access:
SingleCall:
Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished. This (essentially stateless) model can be made stateful in the ASP.NET environment by using the ASP.NET state service to store application or session state.
Singleton:
All incoming requests from clients are processed by a single server object.
Client-activated object:
This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
Lease-Based Lifetime :
Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure
.Net Remoting takes a Lease-base Lifetime of the object that is scaleable
Call Context :
Additional information can be passed with every method call that is not part of the argument with the help of SOAP Header
Distributed Identities :
If we pass a reference to a remote object, we will access the same object using this reference.
By implementing ILease interface when writing the class code.
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
Use the Soapsuds tool.
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
It’s an application that’s running and had been allocated memory.
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
One.
Happy Programming!!!
using System;
class ParameterTest
{
static void Mymethod(int Param1)
{
Param1=100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(Myvalue);
}
}
using System;
class ParameterTest
{
static void Mymethod(out int Param1)
{
Param1=100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(out Myvalue);
}
}
Outputusing System;
class ParameterTest
{
static void Mymethod(ref int Param1)
{
Param1=Param1 + 100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(ref Myvalue);
}
}
Output
using System;
class ParameterTest
{
static int Sum(params int[] Param1)
{
int val=0;
foreach(int P in Param1)
{
val=val+P;
}
return val;
}
static void Main()
{
Console.WriteLine(Sum(1,2,3));
Console.WriteLine(Sum(1,2,3,4,5));
}
}
Foreign key :
Unique Key :
Surrogate Key / Artificial Key / Identity key:
What's the difference between a primary key and a unique key?