|
|
October 26 static void Main(string[] args) { bool isAnotherInstanceRunning; Object obj = new System.Threading.Mutex(true, "YourNameHere", out isAnotherInstanceRunning);
if (!isAnotherInstanceRunning) { Console.WriteLine("Another instance is already running."); } else { Console.WriteLine("Only this instance is already running."); GC.KeepAlive(obj); } Console.ReadLine(); } Explanation: A "mutex" (short for "mutual exclusion") is an operating-system object that can be used to keep processes from interfering with each other. Basically, the process that doesn't want to be interfered with will create a mutex, which the operating system will keep track of. Other processes will try to obtain the same mutex and will be blocked from executing if they do not do so. See any book on threading to learn more about this.
A popular and quick way to ensure that only one instance of your program is running is to have it create a mutex with a specific name, or bail out if it cannot do so (because another copy of it is already running and owns the mutex). October 19 MAKs (MultipleActivation) allow a predetermined number of
activations. This number depends on the type of agreement you have.The number of activations can be revised (at
the request of the customer or by Microsoft) to accommodate your regular usage.
On the other hand, One
retail product key can only be activated for 10 times. October 01 It means that the product key is actually built into the installer and you do not need a separate one to install it. September 22 In RegEdit, you can take a look in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs to get the list of shared dlls.
If application "A" installs a dll, then application "B" tries to install the same dll, instead of copying over it, Windows Installer (WI) will increment the reference count for that file.. When uninstalling app "A" (or "B"), WI will check the reference count to see if any other applications are still using that dll. If they are, then WI will decrement the counter by 1 and leave the dll behind. When that counter hits zero, the dll will be uninstalled by the next application that tries to remove it.
September 15
Two new
features to C# 4.0 are optional parameters and named parameters. Optional
parameters have been a part of VB.Net but it's now possible to do this in C#.
Instead of using overload methods, you can do this in C#:
private string Method1(string givenName,
string surname
= "Prakash", int
age = 23)
{
return givenName + "
" + surname;
}
The
second and third parameters, surname & age, both have default values. The
only parameter required is givenName. To call this method you can either write
this:
string name = null;
name = Method1("Ved");
That will
return Ved Prakash. You can also do this:
string name = null;
name = Method1 ("Prakash ", "Tejwani");
The value
returned is Prakash Tejwani. But what if you didn't want to specify a
surname but you did want to pass the age? You can do this by using named
parameters:
string name = null;
name = Method1 ("Shyam", age: 24);
These are
nice additions to the language. April 02 Overview
One of the fundamental concepts of object oriented
software development is polymorphism. The term polymorphism (from the Greek
meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to
something in different contexts - specifically, to allow a variable to refer to more than
one type of object.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes
A, B and C for the discussions in this text. A is the
super- or base class, B is derived from A and C is derived
from class B. In some of the easier examples, we will only refer to a part of
this class hierarchy.
Inherited Methods
A method Foo() which is declared in the base class A
and not redeclared in classes B or C is inherited in the two
subclasses
using System;
namespace Polymorphism
{
class A
{
public void Foo() {
Console.WriteLine("A::Foo()"); }
}
class B : A {}
class Test
{
static void
Main(string[] args)
{
A a = new A();
a.Foo(); // output --> "A::Foo()"
B b = new B();
b.Foo(); // output -->
"A::Foo()"
}
}
}
The method Foo() can be overridden in classes B and C:
using System;
namespace Polymorphism
{
class A
{
public
void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
public
void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
static void
Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}
There are two problems with this code.
- The output is not really what we, say from Java, expected. The method
Foo() is a non-virtual method. C# requires the use of the keyword
virtual in order for a method to actually be virtual. An example using
virtual methods and polymorphism will be given in the next section.
|
- Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is
required on 'Polymorphism.B.Foo()' because it hides inherited member
'Polymorphism.A.Foo()'
|
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they
are explicitly declared to override the virtual base class method with the
override keyword.
using System;
namespace Polymorphism
{
class A
{
public virtual
void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
public override
void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
static void
Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "B::Foo()"
}
}
}
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only
supports method overriding, but also method hiding. Simply put, if a method is not
overriding the derived method, it is hiding it. A hiding method has to be declared using
the new keyword. The correct class definition in the second listing is
thus:
using System;
namespace Polymorphism
{
class A
{
public void Foo() {
Console.WriteLine("A::Foo()"); }
}
class B : A
{
public new void Foo()
{ Console.WriteLine("B::Foo()"); }
}
class Test
{
static void
Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived
method. In order to declare such a method, both keywords virtual and
new have to be used in the method declaration:
class
A
{
public void Foo() {}
}
class B : A
{
public virtual new void Foo() {}
}
A class C can now declare a method Foo() that either overrides or
hides Foo() from class B:
class
C : B
{
public override void Foo() {}
// or
public new void Foo() {}
}
Conclusion
- C# is not Java.
- Only methods in base classes need not override or hide derived methods. All methods
in derived classes require to be either defined as new or as
override.
- Know what your doing and look out for compiler warnings.
Connection Pooling:
1. When is the connection pool created :
When
a connection is opened for the first time a connection pool is created
and the pool is determined by the exact match of the connection string
in the connection. Each connection pool is associated with a distinct
connection string. When a new connection is requested, if the
connection string is not an exact match to an existing pool, a new pool
is created.
2. When is the connection pool destroyed :
When
process who created the connections is closed, the pool is destroyed.
Like if you are working with windows applications, then as soon as you
close your window application, the pool will be destroyed.
3. What happens when all the connections in the connection pool are consumed and a new connection request comes :
If
the maximum pool size has been reached and no usable connection is
available, the request is queued. The connection pooler satisfies these
requests by reallocating connections as they are released back into the
pool. Connections are released back into the pool when you call Close
or Dispose on the Connection.
4. How can I enable connection pooling ?
For
.Net applications it is enabled by default. Well, to make sure the same
we can use the Pooling=true; in the connection string for the
SQLConnection Object.
5. How can I disable connection pooling?
ADO.NET Data Providers automatically use connection pooling turned on. If you want to turn this functionality off:
In an SQLConnection object, Add this to the connection string: Pooling=False;
In An OLEDBConnection object, add this: OLE DB Services=-4;
This way, the OLE DB data provider will mark your connection so that it does not participate in connection pooling.
March 30 When clients access an ASP.NET page, there are basically two ways to provide them with the information they need:
- the ASP.NET page can either obtain information from
server resources, such as from data that has been persisted to a
database, or
- the ASP.NET page can obtain information from within the application.
Retrieving information from a resource outside the application will
require more processing steps, and will therefore require more time and
resources on the server than if the information can be obtained from
within the application space.
If the information that will be sent to the browser has already been
prepared by a previous request, the application will be able to
retrieve that information faster if it has been stored in memory,
somewhere along the request/response stream.
Known as caching, this technique can be used to temporarily
store page output or application data either on the client or on the
server, which can then be re-used to satisfy subsequent requests and
thus avoid the overhead of re-creating the same information.
Caching is particularly suitable when you expect to return the same information in the same format for many different requests.
ASP.NET provides the following types of caching that can be used to build highly responsive Web applications:
- Output caching, which caches the dynamic response generated by a request.
- Fragment caching, which caches portions of a response generated by a request.
- Data caching, which allows developers to programmatically retain arbitrary data across requests.
OutputCache
Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page.
<%@ OutputCache Duration = "#ofseconds" Location = "Any | Client | Downstream | Server | None" VaryByControl = "controlname" VaryByCustom = "browser | customstring" VaryByHeader = "headers" VaryByParam = "parametername" %>
Attributes
| Duration
| The time, in seconds,
that the page or user control is cached. Setting this attribute on a
page or user control establishes an expiration policy for HTTP
responses from the object and will automatically cache the page or user
control output.
NOTE: This attribute is required. If you do not include it, a parser error occurs.
|
| Location
| One of the OutputCacheLocation enumeration values. The default is Any.
IMPORTANT: This attribute is required when you
output cache ASP.NET pages and user controls. A parser error occurs if
you fail to include it.
|
| VaryByControl
| A semicolon-separated
list of strings used to vary the output cache. These strings represent
fully qualified names of properties on a user control. When this
attribute is used for a user control, the user control output is varied
to the cache for each specified user control property.
NOTE: This attribute is not supported for @ OutputCache directives in ASP.NET pages.
|
| VaryByCustom
| Any text that represents custom output caching requirements. If this attribute is given a value of browser, the cache is varied by browser name and major version information. If a custom string is entered, you must override the HttpApplication.GetVaryByCustomStringglobal.asax file. method in your application's
|
| VaryByHeader
| A semicolon-separated
list of HTTP headers used to vary the output cache. When this attribute
is set to multiple headers, the output cache contains a different
version of the requested document for each specified header.
NOTE: Setting the VaryByHeader attribute enables caching items in all HTTP/1.1 caches, not just the ASP.NET cache. This attribute is not supported for @ OutputCache directives in user controls.
|
| VaryByParam
| A
semicolon-separated list of strings used to vary the output cache. By
default, these strings correspond to a query string value sent with GET method attributes, or a parameter sent using the POST
method. When this attribute is set to multiple parameters, the output
cache contains a different version of the requested document for each
specified parameter. Possible values include none, *, and any valid query string or POST parameter name.
IMPORTANT: This attribute is required when you
output cache ASP.NET pages and user controls. A parser error occurs if
you fail to include it. If you do not want to specify a parameter to
vary cached content, set the value to none. If you want to vary the ouput cache by all parameter values, set the attribute to *.
|
Remarks
Setting values for the page output cache is the same as manipulating the SetExpires and SetCacheability methods of the Response.Cache onject. Setting the VaryByParam attribute when creating a user control implements partial-page caching for that control.
If a Web Forms page requires authorization to be viewed by a user, the output cache sets the Cache-Control header to private. For more information on all of these subjects, see Caching ASP.NET Pages.
Syntax Example
The below code snippet demonstrates how you can set the duration ( in seconds ) that a page or user control is output cached.
<%@ OutputCache Duration = "10" VaryByParam = "none" %>
The next example demonstrates how you can instruct the output cache
to cache a page or user control based on parameter values passed by a
form's GET or POST method. Each HTTP request that
arrives with a different parameter is cached for ten seconds. Any
subsequent requests with the same parameter values are satisfied from
the cache until the entry expires.
<%@ OutputCache Duration = "10" VaryByParam = "myParam1; myParam2" %> Application variables were under-used on my site, but not for long! I
realized recently that a list box that I was populating with data from
my database changed very rarely.So why should every visitor to the
site have to cause an identical database query? The simple answer is to
take advantage of Application variables. Think of the "Application" in
this case being IIS - the server. Once set, Application variables are
available to all pages on your site. But it's important to remember
that they are gone forever if the server is restarted. Using Application variables is easy - all you need are statements like:// to set the data
Application ( 'Data' ) = 'something';
// to use the data
Response.Write ( 'data is ' + Application ( 'Data' ) );
|
|
| Perhaps one of the most common questions among
people learning C# is this: What is a delegate? In this article, I
describe what a delegate is and show you several examples so you can
get up to speed on it as soon as possible.
Essentially,
a delegate is an object that contains a reference to a method. This
method can be either a static method for a class or a member method for
a particular instance.
This might sound vague, so let's look at a specific example. Or, if
you're in a hurry or already understand things like pointers in other
languages, you can skip to the last section of this article called The Quick Answer.
First example: Form events
Here's an example of where you would encounter such a thing. Suppose
you have a form with a button on it. Inside the form's class, you have
a method that handle's the button's click. That is, this method runs
when you click the button.
Behind the scenes, how does the .NET code know to call your handler
method? The form stores a reference to this method. The type of
variable used for this storage is a delegate.
Now suppose you create a second instance of this same form class,
and when your program runs, you display both instances. You now have
two forms on the screen that are the same, and you have two instances
of your form class. When you click the button on the second form, the
method for the second instance runs. How does the .NET code know to run
the handler for the particular instance? The answer is the delegate can
store a reference to a method for a particular class instance.
Let's be more specific. Create a new C# windows application with a
single form. Put a TextBox control and a Button control on the form.
Add a handler for your button's OnClick event, which displays a message
box showing the text in the TextBox control.
Here's the code that does this, assuming the TextBox control is
called TextBox1 and the button is called Button1. (I removed the
unneeded using statements).
using System; using System.Windows.Forms;
namespace DelegateApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { MessageBox.Show(textBox1.Text); } } }
When you run this, type something into the TextBox control, and
click the button, you'll see a message box open showing you what you
typed. Then close the program and return to Visual Studio.
Now let's add code to open two windows. From Solution Explorer, open
the Program.cs file. Add the following two lines shown in blue bold.
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 x = new Form1(); x.Show(); Application.Run(new Form1()); }
This code will open another copy of your form. Save the file and run
your program. Now you'll see two forms that look the same. In one form
type abc into the text box. In the second form, type def. Return to the first (abc) form, and click the button. What you see should be no surprise; the message box shows abc. Close the message box, and go to the second form. Click the button. Again, no surprise: The message box shows def. Now close the message box and the two forms.
Internally, each instance of the form class holds a variable that's
a delegate pointing to the method for the respective instance. When the
event fires and your event handler code runs, the code runs for its
respective instance. In other words, the delegate holds not only a
reference to your event handler method, but also a reference to the
particular instance for the method. (Technically, there's only one copy
of the code; internally, the runtime lets your method know which
instance the method is associated with.)
That's all a delegate is: A variable that holds a method of a class,
and, optionally, an instance. Or, more formally, a delegate is an
object that contains a reference to a method and optionally a reference
to an instance.
Second example: Class methods
A delegate doesn't have to be associated with a particular instance.
In the previous example, you saw that the delegate stored a method that
went with a particular instance of the form class. You can also store a
method that goes with an entire class, that is, a static method.
A delegate is an object that holds a reference to a method, and, optionally, a specific instance.
An event handler is an example of a delegate being used. When you
create code for a button's click handler, the form saves a delegate
containing your handler and the form instance. When the button gets
clicked, the form calls your handler by calling the delegate. When your
handler gets called, the method is associated with the specific form
instance.
Delegates are of specific types. When you declare a delegate type,
you specify the footprint for methods that the delegate can store. For
example, if you declare a delegate type like so:
public delegate string mydel(int number);
then you are saying that delegate objects of this type can hold a
pointer to a method that takes an integer as a parameter and returns a
string.
This only declares the type, however. To create the delegate itself, you create it as you would any other object, like so:
mydel del1 = obj1.myfunc;
where myfunc is the name of a method that takes an integer as a
parameter and returns a string. The following is a complete example
that demonstrates this.
using System; using System.Collections.Generic; using System.Text;
public class MyClass { int x; public MyClass(int x1) { x = x1; } public string myfunc(int n) { return (n * x).ToString(); } }
public delegate string mydel(int number);
class Program { static void Main(string[] args) { MyClass obj1 = new MyClass(10); MyClass obj2 = new MyClass(20);
mydel del1 = obj1.myfunc; mydel del2 = obj2.myfunc; Console.WriteLine(del1(50)); Console.WriteLine(del2(20)); } }
Delegates can be chained together so that they called in sequence. You use the += syntax like so:
mydel del1 = obj1.myfunc; del1 += obj2.myfunc;
When you invoke the del1 delegate, first obj1.myfunc will get
called, and then obj2.myfunc will get called. (In this example, the
myfunc method doesn't do anything besides return a string, so calling
the methods in sequence doesn't make much sense. More likely you would
chain together methods that actually do some work.)
Now here's a sample that demonstrates a delegate storing a static method:
using System; using System.Collections.Generic; using System.Text;
public class MyClass { public static int staticFunc(int n) { return n * 2; } }
public delegate int anotherdel(int number);
class Program { static void Main(string[] args) { anotherdel del1 = MyClass.staticFunc; Console.WriteLine(del1(50)); } }
You can see in this code that the delegate anotherdel is declared, and then an instance of the delegate, del1,
is created. Since staticFunc is a static method, I simply access it
through MyClass directly. Finally, notice also that when I declared the
delegate type, I don't specify whether it holds static or member
methods; it can, in fact, hold either.
Conclusion
One thing I didn't mention is that when you create a delegate, you are creating an instance of the .NET class called Delegate. Now that you have a feel for what exactly delegates are, take a look at the MSDN help entry for Delegate, as well as the entry on MulticastDelegate (which supports chaining).
|
March 14
Visual Basic was Object-Based, Visual Basic .NET is Object-Oriented,
which means that it's a true Object-Oriented Programming Language. Visual Basic .NET
supports all the key OOP features like Polymorphism, Inheritance, Abstraction and Encapsulation. It's
worth having a brief overview of OOP before starting OOP with VB.
Why Object Oriented approach?
A major factor in the invention of Object-Oriented approach is to remove some of the
flaws encountered with the procedural approach. In OOP, data is treated as a
critical element and does not allow it to flow freely. It bounds data closely to the functions
that operate on it and protects it from accidental modification from outside functions.
OOP allows decomposition of a problem into a number of entities called objects
and then builds data and functions around these objects. A major advantage of OOP
is code reusability.
Some important features of Object Oriented programming are as follows:
-
Emphasis on data rather than procedure
-
Programs are divided into Objects
-
Data is hidden and cannot be accessed by external functions
-
Objects can communicate with each other through functions
-
New data and functions can be easily added whenever necessary
-
Follows bottom-up approach
Concepts of OOP:
-
Objects
-
Classes
-
Data Abstraction and Encapsulation
-
Inheritance
-
Polymorphism
Briefly on Concepts:
Objects
Objects are the basic run-time entities in an object-oriented software. Programming
problem is analyzed in terms of objects and nature of communication between them.
When a program is executed, objects interact with each other by sending messages.
Different objects can also interact with each other without knowing the details of
their data or code.
Classes
A class is a collection of objects of similar type. Once a class is defined,
any number of objects can be created which belong to that class.
Data Abstraction and Encapsulation
Normally, in a Class,
variables used to hold data (like the age of a dog) is declared as
Private. Functions
or property routines are used to access these variables. Protecting the data
of an object from outside functions is called Abstraction or Data Hiding. This
prevents accidental modification of data by functions outside the class.
Putting all the data and related functions in a
Class is called Encapsulation. Data
cannot be accessible to the outside world and only those functions which are
stored in the class can access it.
Inheritance
Inheritance is the process by which objects can acquire the properties of objects
of other class. In OOP, inheritance provides reusability, like, adding additional
features to an existing class without modifying it. This is achieved by deriving a
new class from the existing one. The new class will have combined features of both
the classes.
Polymorphism
Polymorphism means the ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends on the
data types used in the operation. Polymorphism is extensively used in implementing Inheritance.
Advantages of OOP
Object-Oriented Programming has the following advantages over conventional approaches:
-
OOP provides a clear modular structure for programs which makes it good for defining
abstract datatypes where implementation details are hidden and the unit has a clearly
defined interface.
-
OOP makes it easy to maintain and modify existing code as new objects can be created
with small differences to existing ones.
-
OOP provides a good framework for code libraries where supplied software components
can be easily adapted and modified by the programmer. This is particularly useful
for developing graphical user interfaces.
Instead of Trigger in SQL Server
CREATE TRIGGER myTrigger ON [dbo].[Dept] instead of update AS begin declare @n1 decimal select @n1=id from inserted update dept set name='aa' where id=@n1 end
Reflection: GetType()
& TypeOf()
All .NET assemblies contain vivid type information which
describes the structure of every internal and external type (this can be
verified by loading an assembly into ildasm.exe and clicking the ctrl-m
keystroke). On a related note, many methods in the .NET base class libraries
require you to pass in type information for a given item. When you need to
obtain type information for a given method invocation, you have numerous
approaches. First, all types inherit the public System.Object.GetType() method:
// Obtain type information from a variable.
SomeType c = new SomeType();
Type t = c.GetType();
INeedYourTypeInfo(t);While this works, it is overkill to
create a type simply to call the inherited GetType() method. To streamline the
process, the C# language offers the typeof operator. The benefit is you are not
required to create the item in question, rather simply specify the name of the
type as an argument:
// Obtain type information via typeof.
INeedYourTypeInfo(typeof(SomeType));
ref Vs out parameters
"out" parameters are output only parameters meaning they can only pass back a value from a function. We create a "out" parameter by preceding the parameter data type with the out modifier. When ever a "out" parameter is passed only an unassigned reference is passed to the function.
class ParameterTest
{
static void Mymethod(out int Param1)
{
Param1=100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(out Myvalue);
}
}
"ref" parameters are input/output parameters meaning they can be used for passing a value to a function as well as to get back a value from a function. We create a "ref" parameter by preceding the parameter data type with the ref modifier. When ever a "ref" parameter is passed a reference is passed to the function.
class ParameterTest
{
static void Mymethod(ref int Param1)
{
Param1=Param1 + 100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(ref Myvalue);
}
}
boxing & unboxing
class Test
{
static void Main() {
int i = 1;
object o = i; // boxing: value type to object type
int j = (int) o; // unboxing: object type to value type
}
}
Overloading Vs overriding
Method overloading means having two or more methods with the same name but different signatures in the same scope. These two methods may exist in the same class or another one in base class and another in derived class.
Generally, you should consider overloading a method when you have required same reason that take different signatures, but conceptually do the same thing.
Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class.
CLR - CTS - CLS
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program.
The Common Language Runtime is the underpinning of the .NET Framework. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.
Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.
Common Language Specification (CLS) is an agreement among language designers and class library designers to use a common subset of basic language features that all languages have to follow.
sessionState modes
<sessionState mode="Off|InProc|StateServer|SQLServer"
cookieless="true|false"
timeout="number of minutes"
stateConnectionString="tcpip=server:port"
sqlConnectionString="sql connection string"
stateNetworkTimeout="number of seconds"/>
Required Attributes
|
Attribute
|
Option
|
Description
|
|
mode
|
|
Specifies where to store the session state.
|
|
|
Off
|
Indicates that session state is not enabled.
|
|
|
InProc
|
Indicates that session state is stored locally.
|
|
|
StateServer
|
Indicates that session state is stored on a remote server.
|
|
|
SQLServer
|
Indicates that session state is stored on the SQL Server. |
Optional Attributes
|
Attribute
|
Option
|
Description
|
|
cookieless
|
|
Specifies whether sessions without cookies should be used to identify client sessions.
|
|
|
true
|
Indicates that sessions without cookies should be used.
|
|
|
false
|
Indicates that sessions without cookies should not be used. The default is false.
|
|
timeout
|
|
Specifies the number of minutes a session can be idle before it is abandoned. The default is 20.
|
|
stateConnectionString
|
|
Specifies the server name and port where session state is stored remotely. For example, "tcpip=127.0.0.1:42424". This attribute is required when mode is StateServer.
|
|
sqlConnectionString
|
|
Specifies the connection string for a SQL Server. For example, "data source=localhost;Integrated Security=SSPI;Initial Catalog=northwind". This attribute is required when mode is SQLServer.
|
|
stateNetworkTimeout
|
|
When using StateServer mode to store session state, specifies the number of seconds the TCP/IP network connection between the Web server and the state server can be idle before the session is abandoned. The default is 10. |
Remarks
To use StateServer mode
- Make sure ASP.NET state service is running on the remote server that will store session state information. This service is installed with ASP.NET and is located by default at <Drive>:\systemroot\Microsoft.NET\Framework\version\aspnet_state.exe.
- In the application's Web.config file, set mode=StateServer and set the stateConnectionString attribute. For example, stateConnectionString="tcpip=dataserver:42424".
To use SQLServer mode
- Run InstallSqlState.sql (installed by default in <Drive>:\systemroot\Microsoft.NET\Framework\version) on the computer running SQL Server that will store the session state. This creates a database called ASPState with new stored procedures and ASPStateTempApplications and ASPStateTempSessions tables in the TempDB database.
- In the application's Web.config file, set mode=SQLServer and set the sqlConnectionString attribute. For example, sqlConnectionString="data source=localhost;Integrated Security=SSPI;Initial Catalog=northwind".
Example
The following example specifies several session state configuration settings.
<configuration>
<system.web>
<sessionState mode="InProc" cookieless="true" timeout="20"/>
</sessionState>
</system.web>
</configuration>
Authentication Modes
Authentication is the process of obtaining identification credentials from a user (such as name and password), and validating those credentials against some authority.
It sets the authentication policies of the application. Possible modes are "Windows", "Forms", "Passport" and "None"
"None" No authentication is performed.
"Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to its settings for the application. Anonymous access must be disabled in IIS.
"Forms" You provide a custom form (Web page) for users to enter their credentials, and then you authenticate them in your application. A user credential token is stored in a cookie.
"Passport" Authentication is performed via a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites.
<location path="Default.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Shared and Private Assembly
A private assembly is an assembly that is available to particular applications where they are kept. And cannot be references outside the scope of the folder where they are kept.
In contrast, Shared Assemblies are the assemblies that are accessible globally/shared across the machine to all the applications. For using the shared assemblies you need to register the assembly with a strong name in the global assembly cache (GAC) using gacutil.exe. GAC can be found on all the computers with .Net framework installed.
Oracle Vs SQL Server
The dialect of SQL supported by Microsoft SQL Server 2000 is called Transact-SQL (T-SQL). The dialect of SQL supported by Oracle 9i Database is called PL/SQL. PL/SQL is more powerful language than T-SQL. This is the brief comparison of PL/SQL and T-SQL:
|
Feature
|
PL/SQL(Oracle)
|
T-SQL(SQL Server)
|
|
Indexes
|
B-Tree indexes, Bitmap indexes, Partitioned indexes, Function-based indexes, Domain indexes
|
B-Tree indexes
|
|
Tables
|
Relational tables, Object tables, Temporary tables, Partitioned tables, External tables, Index organized tables
|
Relational tables, Temporary tables
|
|
Triggers
|
BEFORE triggers, AFTER triggers, INSTEAD OF triggers, Database Event triggers
|
AFTER triggers, INSTEAD OF triggers
|
|
Procedures
|
PL/SQL statements, Java methods, third-generation language (3GL) routines
|
T-SQL statements
|
|
Arrays
|
Supported
|
Not Supported |
The SQL Server 2000 advantages:
- SQL Server 2000 is cheaper to buy than Oracle 9i Database.
- SQL Server 2000 holds the top TPC-C performance and price/performance results.
- SQL Server 2000 is generally accepted as easier to install, use and manage.
The Oracle 9i Database advantages:
- Oracle 9i Database supports all known platforms, not only the Windows-based platforms.
- PL/SQL is more powerful language than T-SQL.
- More fine-tuning to the configuration can be done via start-up parameters.
Stored Procedures Vs Functions
Unlike stored procedures,
- You cannot perform UPDATE, INSERT or DELETE statements in a function.
- Non-deterministic functions such as GetDate() cannot be used in functions.
- UDF must return a value.
Stored Procedure: CREATE PROCEDURE DBO.GetUserName @UseName varchar(50) =' ' output, @UID int =1 AS SELECT @UseName= FNAME+' ' + LNAME FROM USERS WHERE USERID=@UID return @@rowcount GO ---- Calling a SP: private string GetUserName(int UID) { string strConn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; SqlConnection conn = new SqlConnection(strConn); conn.Open(); SqlCommand cmd = new SqlCommand("GetUserName", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@UseName", SqlDbType.VarChar,50); cmd.Parameters[0].Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@UID",UID); cmd.ExecuteNonQuery(); conn.Close(); return cmd.Parameters[0].Value.ToString(); } ---- Calling a Query:
System.Data.DataSet objResultDS = new System.Data.DataSet();
SqlDataAdapter objDataAdapter = new SqlDataAdapter(“Select * from emp”,”Data Source=webserver;Initial catalog=360Feedback;uid=sa;pwd=sa”);
objDataAdapter.Fill(objResultDS);
XML Serialization
Serialization allows program to persist objects by storing then in files. In this case, into XML files. XML has become the standard for storage in the recent years and it’s good to see that with XML serialization built into the .NET framework
Reflection
It enables us to get some information about object in runtime. That information contains data of the class. Also it can get the names of the methods that are inside the class and constructors of that object. To write a C# .Net program which uses reflection, the program should use the namespace System.Reflection. To get type of the object, the typeof operator can be used. There is one more method GetType(). This also can be used for retrieving the type information of a class. The Operator typeof allow us to get class name of our object and GetType() method uses to get data about object?s type.
Webservice Vs Remoting
Unlike Remoting
- Web services are a stateless programming model, which means each incoming request is handled independently. In addition, each time a client invokes an ASP.NET Web service, a new object is created to service the request. The object is destroyed after the method call completes. To maintain state between requests, you can either use the same techniques used by ASP.NET pages, i.e., the Session and Application objects, or you can implement your own custom solution. However it is important to remember that maintaining state can be costly with Web services as they use extensive memory resources.
interface Vs abstract class
|
Feature
|
Interface
|
Abstract class
|
|
Multiple inheritance
|
A class may inherit several interfaces.
|
A class may inherit only one abstract class.
|
|
Default implementation
|
An interface cannot provide any code, just the signature.
|
An abstract class can provide complete, default code and/or just the details that have to be overridden.
|
|
Constants
|
Only Static final constants.
|
Both instance and static constants are possible.
|
|
Core VS Peripheral
|
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from IMovable interface.
|
An abstract class defines the core identity of a class and there it is used for objects of the same type.
|
|
Homogeneity
|
If the various implementations only share method signatures then it is better to use Interface.
|
If the various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
|
|
Speed
|
Requires more time to find the actual method in the corresponding classes.
|
Fast
|
|
Adding functionality
|
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
|
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. |
readonly Vs const
- With const, the value is computed at compile-time (initialization expression is evaluated at compile time and therefore must be composed of other constants). With readonly you may initialize it at runtime (initialization expression is evaluated at runtime).
- The implication is that members declared with const are static (so the static keyword would be redundant and therefore is forbidden in this context). Members declared as readonly may be initialized in constructor (static or instance one) and therefore may differ between objects, so the static keyword works as usual.
- const may be used in local context, whereas readonly only for class/struct members.
static Vs private constructor
1. Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with <new> keyword. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.
2. Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.
3. The static constructor for a class executes before any instance of the class is created.
- Private constructors are commonly used in classes that contain only static members. This helps to prevent the creation of an instance of a class by other classes when there are no instance fields or methods in that class.
- Private constructors are useful when you want to create an instance of a class within a member of the same class and not want to instantiate it out side the class.
- Private constructors are used to create an instance of a class within a member of a nested class of the same class.
Stored Procedure: CREATE PROCEDURE DBO.GetUserName @UseName varchar(50) =' ' output, @UID int =1 AS SELECT @UseName= FNAME+' ' + LNAME FROM USERS WHERE USERID=@UID return @@rowcount GO ---- Calling a SP: private string GetUserName(int UID) { string strConn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; SqlConnection conn = new SqlConnection(strConn); conn.Open(); SqlCommand cmd = new SqlCommand("GetUserName", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@UseName", SqlDbType.VarChar,50); cmd.Parameters[0].Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@UID",UID); cmd.ExecuteNonQuery(); conn.Close(); return cmd.Parameters[0].Value.ToString(); }
Crystal Report
Schema(*.xsd)
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="CompanyDS" targetNamespace="http://tempuri.org/CompanyDS.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/CompanyDS.xsd" xmlns:mstns="http://tempuri.org/CompanyDS.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Survey">
<xs:complexType>
<xs:sequence>
<xs:element name="SID" type="xs:int" />
<xs:element name="UID" type="xs:int" />
<xs:element name="UNAME" type="xs:string" />
<xs:element name="SNAME" type="xs:string" />
<xs:element name="DATE" type="xs:date" />
<xs:element name="ISACTIVE" type="xs:boolean" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
----
<CR:CrystalReportViewer AutoDataBind="False" ID="CrystalReportViewer1" runat="server"
Height="50px" Width="350px" />
-----
using System.Data;
//--SqlClient for SqlConnection and etc.
using System.Data.SqlClient;
//--for CrystalReports's ReportDocument.
using CrystalDecisions.CrystalReports.Engine;
private void GenerateReport()
{
string strConn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
//--Sql string
String strCmd = "SELECT S.SURVEY_ID [SID],S.USER_ID [UID],U.FNAME+' ' +U.LNAME [UNAME],S.SURVEY_NAME [SNAME],S.CREATED_DATE [DATE],S.ACTIVE [ISACTIVE] FROM SURVEYS S,USERS U WHERE S.USER_ID=U.USERID";
//--Opening Sql Connection
//string strConn = ConfigurationManager.AppSettings["Conn"];
SqlConnection sqlConn = new SqlConnection(strConn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strCmd, sqlConn);
//--this statement is very important, here the table name //should match with the XML Schema table name
da.Fill(ds, "Survey");
//--Closing Sql Connection
sqlConn.Close();
//--(Optional) I have used it to disable the properties
CrystalReportViewer1.DisplayGroupTree = false;
CrystalReportViewer1.HasCrystalLogo = false;
//--Initializing CrystalReport
ReportDocument myReportDocument;
myReportDocument = new ReportDocument();
myReportDocument.Load(Server.MapPath("MyCompanyRpt.rpt"));
myReportDocument.SetDataSource(ds);
//--Binding report with CrystalReportViewer
CrystalReportViewer1.ReportSource = myReportDocument;
CrystalReportViewer1.DataBind();
}
-----------------
SELECT * FROM EMPLOYEE, LEAVE
è If EMPLOYEE contains 5 records & Leave contains 3 records then the query returns 5X3=15 records.
è If EMPLOYEE contains 5 records & Leave contains 0 records then the query returns 5X0=0 records.
Select * from employee where (substring (name, 1, 1) in ('v')) and (substring (name,len(name),1) in ('h'))
è It fetches all emps whose name starts with ‘v’ and ends with ‘h’
SELECT DEPT.NAME, COUNT (*) FROM employee,DEPT WHERE employee.DEPTID=DEPT.ID GROUP BY DEPT.NAME HAVING COUNT(*)>1
-----------------
JOIN
Join is to query data from more than one table. Normally, there are five different joining schemes.
1. Cartesian product. If no joining condition is specified, every row in the first table with be matched to the every row of the second tables and so on for the second table and the third joining table. This should be avoided.
2. Equal-Join. Tables are joined based on some column equality condition.
3. Non-equal Join. Tables are joined based on some column inequality condition.
4. Outer-Join. Tables are joined and rows that do NOT meet the join condition are also returned.
5. Self-Join. Joining a table with itself.
The schemes 2 to 4 are described in details in the following.
Equal-Join
Use table prefix to qualify column names to remove column ambiguity.
For example,
SQL> SELECT empno, employee.name, employee.dept_no, dept.name
FROM employee, dept
WHERE employee.dept_no = dept.dept_no;
Non-equal-Join
Use Between-And clause in non-equal join queries.
For example, to answer the query "find the students whose mark falls in Grade A range" (assuming the student mark table only stores the raw marks (with values ranging from 0 from 100, and the grade_class table stores the low-end and high-end marks for each grade.), the query is:
SQL> SELECT a.name, a.matric_no, a.mark
FROM student_marks a, grade_class b
WHERE b.grade = 'A' AND
a.mark BETWEEN b.low_end AND b.high_end;
Outer-Join
Outer-join operator is the plus sign (+). Out join queries return the normal joining results plus the rows in two tables that do not meet the join condition.
For example, assume we have a module_taken table which keeps the relationship on what modules taken by which student, and a module table which keeps the module details.
The following statement returns the student matric no, and module names taken that student, and in addition to this, it also list the modules which are not taken by anyone.
SQL> SELECT a.matric_no, a.module_no, b.module_name
FROM module_taken a, module b
WHERE a.module_no (+) = b.module_no;
Assume module CS9999 is not taken by any student but is listed in the module table, then this module will also appear in the result, with empty value for matric_no.
Self-Join
To join the table with itself, a table must be given an alias to distinguish each other.
For example, the following statement retrieves all employees who have a manager (who don't have a boss :)).
SQL> SELECT worker.name || ' works for ' || mgr.name
FROM employee worker, employee mgr
WHERE worker.mgr_no = mgr.empno;
|  | |  |
|