Monday, November 5, 2007

Encrypt web.config aps.net2.0

There are two types of encryption possible
i) DataProtectionConfigurationProvider - windows data protection api(DAPI)
ii) RSAProtectedConfigurationProvider - RSA protected configuration provider

it's a single step process using 'aspnet_regiis.exe' utility

ex:
goto vs command prompt

Decryption
type aspnet_regiis.exe {-pdf} section physical_dir
OR
type aspnet_regiis.exe {-pd} section -app virtual_dir

like
type aspnet_regiis.exe -pdf appSettings c:\website1
OR
type aspnet_regiis.exe -pd appSettings -app c:\Inetpub\wwwroot\website1

Source :

Encryption
type aspnet_regiis.exe {-pef/-pe} section physical_dir {-porv} provider
OR
type aspnet_regiis.exe {-pef/-pe} section virtual_dir {-porv} provider

like
type aspnet_regiis.exe -pe appSettings c:\website1 -porv "DataProtectionConfigurationProvider"
OR
type aspnet_regiis.exe -pef appSettings c:\Inetpub\wwwroot\website1 -porv "RSAProtectedConfigurationProvider"

Friday, October 26, 2007

Download Picasa Gallery

This utility help in downloading images and creating a similar structure as in picasa[dot]google[dot]com galleries.

A very basic and simple app. Least of all, handles your mistakes. so be sure your entering the right gallery address and that you are connect to web.
You can provide multiple gallery addresses separated by ','.
Requires .net 2.0

Download


Feedback and Feature request are welcome. just comment onto this post

Friday, October 19, 2007

How to protect ur code

Obfuscation

Obfuscated code is source code that is (usually intentionally) very hard to read and understand. Some languages are more prone to obfuscation than others. C, C++ and Perl are most often cited as easily obfuscatable languages. Macro preprocessors are often used to create hard to read code by masking the standard language syntax and grammar from the main body of code. The term shrouded code has also been used.

There are also programs known as obfuscators that may operate on source code, object code, or both, for the purpose of deterring reverse engineering.

Obfuscating code to prevent reverse engineering is typically done to manage risks that stem from unauthorized access to source code. These risks include loss of intellectual property, ease of probing for application vulnerabilities and loss of revenue that can result when applications are reverse engineered, modified to circumvent metering or usage control and then recompiled. Obfuscating code is, therefore, also a compensating control to manage these risks. The risk is greater in computing environments such as Java and Microsoft's .NET which take advantage of just-in-time (JIT) compilation technology that allow developers to deploy an application as intermediate code rather than code which has been compiled into machine language before being deployed.

for dot net there a tool called 'Dotfuscator' which provides ways to protect ur code from being disassembled in a human eye readalbe format, the way reflector.exe does disassabled all the dll & exe.

Example :- open reflector.exe in reflector itself. U'll see that all names will be displayed as '[]', and u'll not be able to link and find references between classess.
the logic behind having '[]' is to replaces all named things with '?'.

refer :

Based on these way there are also belief that developer can speed up the code upload in case of scripting languages by removing white space charaters form the code.
You can make a short program which will read all files with specifc extension like '.js' and edit the file, before deploying them.

Creational Design Pattern

Singleton

The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, you really have to make it a singleton.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.



C# (using generics)

This example is thread-safe with lazy initialization.

///
/// Generic class implements singleton pattern.
///

///
/// Reference type.
///

public class Singleton where T : class, new()
{
///
/// Get the Singleton Instance.
///

public static T Instance
{
get { return SingletonCreator._instance ; }
}

class SingletonCreator
{
static SingletonCreator() { }

internal static readonly T _instance = new T();
}
}

C# (using generics and reflection)

This example is thread-safe with lazy initialization. In addition, this example is suit for classes which have private constructor.

///
/// Generic class implements singleton pattern.
///

///
[CLSCompliant(true)]
public static class Singleton where T : class, new()
{
private static T _instance;

static Singleton() {
Type type = typeof(T);
BindingFlags searchPattern = BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance;
ConstructorInfo constructor = type.GetConstructor(searchPattern,
null,
Type.EmptyTypes,
null);

_instance = (T)constructor.Invoke(new object[0]);
}

///
/// Get the singleton instance of the type.
///

public static T Instance {
get { return _instance; }
}
}

public class Session
{
private Session() {
}
}

public class Program
{
private static void Main() {
Session instanceA = Singleton.Instance;
Session instanceB = Singleton.Instance;

// Are they the same?
Console.WriteLine(instanceA == instanceB); // true
}
}

Source :

Thursday, September 13, 2007

File Types for asp.net web app

A web site Application can have multiple files of multiple file type. Many of these are managed by Asp.Net and many by IIS itself. File types that are managed by the Asp.Net are mapped to AspNet_isapi.dll in IIS. The file types that are not mapped to AspNet_isapi.dll are not managed by asp.net but by IIS only.

Here is a list of all the file types that are managed by Asp.Net.

.asax – The common most example is the Global.asax file. This normally contains code that is derived from HttpApplication class. The file contains application level event that are raised by application like Application start, application end etc. The file has to be kept in the root folder of the application.

.ascx – This file type is used to create web user control. The file can reside in either root folder on in a sub-directory.

.ashx – The file type is used to create generic handler by implementing the IHttpHandler interface.

.asmx – This file type is used to create a web service.

.aspx – The most common file for a asp.net web application. The file type is used for creating web pages.

.axd – This is a handler file for administration of web site request. Trace.axd is the best example for this file. The file is maintained in the root of the application.

.browser – This file type is kept only in the App_Browsers (which is a sub directory in the root of the application.) The file is used to identify the features of the client browser.

.config – the common example is the web.config file. The file can be kept in the root directory and also the sub directory. The file contains XML which defines the setting for the application. The config file in the sub directory represents setting for that directory only.

.cs, .vb (Not sure if any more are supported) – In App_code folder and as a code behind for aspx file. The file contains the source code of the file that will be compiled at the run time only for the first time it runs.

.dll – this is the compiled code or referenced assembly. The dll’s are kept in the bin folder in the root directory.

.pdb - it is a symbol file for the respective dll. used for debugging from within a running(live) app.

.master – used for the master page file in the application. It is used in defining the master design of the web site.

.mdf, .mdb, .ldb – These are the data files that are kept in the App_data folder.

.msgx, .svc – This file type is used for messaging framework service file.

.rem – Used for the remoting handler file.

.resources, .resx – The file type is used by the resource file where the resource string for images, localizable text etc are kept.

.sitemap – this file has to be kept in the root of the application. It contains the structure of the web site. We can then use the default site map provider to work with the sitemap file.

.skin - This file is kept in the App_Theme folder. This file is used for keeping consistent formatting of the web control through out the application.

.soap – This is a SOAP extension file.

Tuesday, July 31, 2007

ViewState transition

View state is page scoped and is valid for that page only. View state should not be transferred across pages.

The Viewstate structure
The Viewstate field is not crypted. But it has a 2 level coding:

* first all HTML punctuations, like "<", "+", "=" are encoded using a %nn notation. For instance, "+" is coded as "%2B" (where $2B is the Hex value of the ASCII code of ".")
* then the text is "base 64" encoded: to fit all 256 possible byte value in 7 bits, there is a transcoding from 8 to 7 bits.

The resulting decoded string follows a "compact xml" structure, where the elements are all between "<" and ">" and the elements of the tags are triples, pairs, lists arrays and indexes.

The IEBNF (Indented Extended BNF) grammar of this coding is


viewstate= element .
element = triple | pair | list | index .
triple= 't<' element ';' element ';' element '>' .
pair= 'p<' element ';' element '>' .
list= 'l<' { element ';' } .
index= 'i<' value '>' .
value= ANY_BUT ( ';' | '>' ) .

Refernces article


What happens if i do pass it on?

Similar to "ViewState" there are other option to save temporary data like "Cache", "AppDomain"


each one has its own use.
ViewState - Is good for page level data storage, where amount of data is small.
Cache - Is good for large amount of data
AppDomain - Is good for across client commuication.like sharing a specific details across all active clients.



From Another Article

Question: I set my page's EnableViewState property False; why is there still a __VIEWSTATE hidden form field?

ANSWER: A while back I wrote an article for MSDN online titled Understanding ASP.NET View State, and blogged about the article in this past entry. I recently noticed a comment in that blog entry from Matthias Cavigelli, asking:

When I disable the ViewState property of the page, I still have the hidden field __VIEWSTATE in the html code. Could you explain why it's still there although it's not enabled?

What Matthias is referring to is the EnableViewState property, which is defined in the System.Web.UI.Control class (which means that all ASP.NET server controls have this property, including the Page class from which all ASP.NET Web pages are derived.) This property defaults to True, which means that, by default, a control should track its view state and save its view state during the SaveViewState stage of the page's lifecycle. By setting EnableViewState to false, a control is saying, "Don't bother recording my view state."

Setting EnableViewState to False on certain state-heavy controls is a good way to trim the size of a page's view state. Of course, you must take care when tweaking this property, since the state-heavy controls typically rely on the view state to maintain their functionality. Here's a good example of when you can set EnableViewState to False: when you have a DataGrid Web control on a page that simply displays data, and where the DataGrid's properties are not programmatically changed on postback. (Note: if this page does have postbacks you'll have to make sure to rebind the database data to your DataGrid on every postback.)

If your page does not perform any postbacks at all, having view state is a big waste. So, you might as well set the Page class's EnableViewState to False, so that no view state is saved for the entire page. Or so you'd think. If you set EnableViewState to False for the page, you'll still get a hidden __VIEWSTATE form field, although it will be pretty small. Why does this hidden form field exist at all?

To answer this question it is important to realize that view state really is paramount to Web Forms, not the Page class. (A Web Form is a server-side form tag, which is represented in the .NET Framework via the System.Web.UI.HtmlControls.HtmlForm class.) If a Web Form exists, there typically needs to be a hidden __VIEWSTATE form field. But the Web Form does not know the complete view state of the page. The Page class, for instance, has a ViewState property, into which a page developer can store items into the view state. The Web Form, obviously, is ignorant about this. So there's this chicken-and-egg thing going on here - the Page knows how to completely represent the view state, but it's the Web Form that cares about it, not the Page. The end result is that the Page class is responsible for generating the hidden __VIEWSTATE form field, but it's the Web Form that knows whether or not this is needed.

To overcome this hurdle, the Page class needs some way to know whether or not the __VIEWSTATE form field needs to be emitted or not. To allow for this, the Page class provides a public RegisterViewStateHandler() method; if this method is called during the page lifecycle, a __VIEWSTATE hidden form field will be emitted, even if the Page class's EnableViewState property is set to False.

From a Web Form's perspective, it always needs to save view state. Well, this is the way the Web Form class was programmed by Microsoft. You can see this by examining the HtmlForm class's OnInit() method:

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Page.SetForm(this);
this.Page.RegisterViewStateHandler();
}

Personally, it would seem to make more sense to me to have Page.RegisterViewStateHandler() called only if Page.EnableViewState is true, but there may be a reason behind this that I haven't seen. Anywho, when the Web Form is rendered, it calls an additional two of the Page class's methods:

1. OnFormRender() - this adds the __VIEWSTATE hidden form field along with any registered hidden form fields or script blocks registered via Page.RegisterClientScriptBlock().
2. OnFormPostRender() - this adds any script blocks registered via Page.RegisterStartupScript() and any client-side arrays registered via Page.RegisterArrayDeclaration().

You may still be wondering why when the Page's EnableViewState is False that the __VIEWSTATE hidden form field has anything in it. Well, if you take a look at the Page class's SavePageViewState() method, you'll see:

internal void SavePageViewState()
{
if (!this._needToPersistViewState)
{
return;
}
Triplet triplet1 = new Triplet();
int num1 = this.GetTypeHashCode();
triplet1.First = num1.ToString(NumberFormatInfo.InvariantInfo);
triplet1.Third = this._registeredControlsThatRequirePostBack;
...
triplet1.Second = base.SaveViewStateRecursive();

this.SavePageStateToPersistenceMedium(triplet1);
}

So what you see her is the following: if _needToPersistViewState is False, then nothing is saved. Well, this flag is set to True when the Web Form calls Page.RegisterViewStateHandler(). So a Triplet is built up, with the first item containing the page's hash, the third item containing an ArrayList of Web controls that require a postback. Now, the second item is where the meat of the view state comes from - this is the sum of the view state of the controls in the page. But if EnableViewState is False for the page, SaveViewStateRecursive() returns null.

So even if you set the Page's EnableViewState to False, you'll still get a __VIEWSTATE hidden form field with the Page's hash and ArrayList of controls that require postback. I still don't see why this is needed, but there is likely a good reason.

Rounding Off decimal places

what is the output of the following statements :

Console.WriteLine(decimal.Round(Convert.ToDecimal("0.05"), 1)); --0.0--
Console.WriteLine(decimal.Round(Convert.ToDecimal("0.15"), 1)); --0.2--

5 at 2nd decimal place is rounded to 1 if first decimal places is non-zero else zero
Why?



Explanation
The decimal.Round version that take 2 parameters
rounds midpoints to the even number (Banker's Rounding)
rather than rounding them away from zero

i.e
decimal.Round(0.05, 1); // 0.0
decimal.Round(0.15, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.35, 1); // 0.4
etc.

To get 'normal' rounding (midpoints are rounded away from zero)
you can use a overloaded version of the decimal.Round
method that takes a thrid parameter, which
specifies how to treat midpoints:

ie
decimal.Round(0.05, 1, MidpointRounding.ToEvent); // 0.0 Banker's Rounding

decimal.Round(0.05, 1, MidpointRounding.AwayFromZero); // 0.1

Monday, July 16, 2007

Basics

Value and Refference types
By default in C# everything is passed as value type.

Structs are value type and Classes are reference type. Value types are assigned memory in stack with an exception of In-Line value types asssigned in heap. Reference types are always assigned memory in heap.

value type means a copy of whatever is being passed either a reference type or a value type.



Interface - Abstract Class
What is an Interface?

An interface is a contract, a specification that concrete classes MUST follow. It defines method signatures but cannot have any implementations; the latter must be provided by the classes that implement the interface.
For example,
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}

what is an abstract class?

An Abstract class lets you define some behaviors and force your subclasses to provide others.
For example,
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}


Differences between Interfaces and Abstract classes ?

I. multiple inheritance

A class may implement several interfaces but can only extend one abstract class.

II. default implementation

An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.

III. adding functionality

If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.
If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

IV. is-a vs -able or can-do

Interfaces are often used to describe the abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

An abstract class defines the core identity of its descendants.


Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.


With abstract classes we can provide a default/general method implementation for all overridding classes whereas in case of interfaces, every implementing class must provide its own specific implementation.




Static (Type) or Instance Constructer
Static or Type Constructor :

used to provide a one way access to the class object. you can restrict the class intance to itself using a static constructer. it also provide ways to make singelton class or a clone function, which always returns the class object.
Only one class constructor per type is permitted.
It cannot use the vararg (variable argument) calling convention.

Instance Constructor :

is executed every time a new object is created and is specific to that object instance.
Multiple instance construtor are allowed with different parameter list (return type ie void and name are fixed).
It cannot use the vararg (variable argument) calling convention.
Instance constructors are not allowed to be a virtual type.




Ex :

using System;
class SomeClass {

private Int32 member1;
private static Int32 member2;

//Type constructor
static SomeClass(){}

//Instance constructor
public SomeClass(){} //default instance Constructor
public SomeClass(Int32 memberval){ member1 = memberval;}


}



Working Ex:

public class A

{

//Static Constructor of Class A

static A()

{

Console.WriteLine("Static Constructor of Class A");

}

//Constructor of Class A

public A()

{

Console.WriteLine("Constructor of Class A");

}

}

public class B: A

{

//Static Constructor of Class B

static B()

{

Console.WriteLine("Static Constructor of Class B");

}

//Constructor of Class B

public B()

{

Console.WriteLine("Constructor of Class B");

}

}

public class C: B

{

//Static Constructor of Class A

static C()

{

Console.WriteLine("Static Constructor of Class C");

}

//Constructor of Class C

public C()

{

Console.WriteLine("Constructor of Class C");

}

}

#endregion

class ConstructerDestructer

{

static void Main(string[] args)

{

C c = new C();

Console.ReadKey();

}

}



Output :

Static Constructor of Class C

Static Constructor of Class B

Static Constructor of Class A

Constructor of Class A

Constructor of Class B

Constructor of Class C





Interview

ref and out?
A ref parameter must be assigned a value by the CALLER before it is sent to the callee. An out parameter, on the other hand, is sent unassigned by the caller and must be assigned by the CALLEE


why cant i use static and const together?
All constants declarations are implicitly static, and the C# specification states that the (redundant) inclusion of the static modifier is prohibited.


Difference b/w const(compile time constant) and static readonly(set at run time, containing class is allowed to modify) ?


Can we const array of class/struct ?

const int constIntArray = 2; -valid-
int [] xconstIntArray = new int [] {2, 3, 4}; -valid-
const int [] xconstIntArray = new int [] {2, 3, 4}; -not valid- 'const can only be applied to a field or local whose value is known at compile time.'


What is a delegate? Comparision with function pointers?

A delegate is a data structure that refers to a static method or to an object instance and an instance method of that object.
function pointer can only reference static functions, a delegate can reference both static and instance methods.( In the latter case, the delegate stores not only a reference to the method’s entry point, but also a reference to the object instance for which to invoke the method.)


AppDomain & WebServices?

Assembly(physical) & Namespaces(logical)?

Assembly(contains verious modules) & Module(smallest executable part in a assembly)?

Can i generate and load a Assembly at runtime?
yes, use System.Reflection.Emit



Comparision b/w Equals and ReferenceEquals?

if ReferenceEquals true, then Equals true; but vice versa is always not true. ReferenceEquals compare the object pointed to whereas Equals(String) compare value. In case of object type Equals comparision, it compares the object pointed to.

ex:

public static void ReferenceValue(object a1, object a2){

if(object.ReferenceEquals(a1,a2))

Console.WriteLine("Reference Equals");

else

Console.WriteLine("Reference Not Equals");

if(object.Equals(a1,a2))

Console.WriteLine("Value Equals");

else

Console.WriteLine("Value Not Equals");}



string a = "luck"; string b = "luck"; string c = "l"; int s = 1;

Program.ReferenceValue(a, b); // 'Reference Equals' , 'Value Equals'

Program.ReferenceValue(a, c); // 'Reference Not Equals' , 'Value Not Equals'

Program.ReferenceValue(a, s); // 'Reference Not Equals' , 'Value Not Equals'

a = Console.ReadLine(); // enter 'luck'

Program.ReferenceValue(a, b); // 'Reference Not Equals' , 'Value Equals'

Console.ReadKey();

Console.Clear();

a = Console.ReadLine(); //enter 'luck'

b = Console.ReadLine(); //enter 'luck'

Program.ReferenceValue(a, b); // 'Reference Not Equals' , 'Value Equals'

Console.ReadKey();



Virtual Function?

Ex:

using System;
namespace SomeCorpProject
{
public class BaseBusinessObject
{
public BaseBusinessObject() {
}
public override string ToString() {
return "BaseBusinessObject";
}
}
}

using System;
namespace SomeCorpProject
{
public class NCapacitor : BaseBusinessObject
{
public NCapacitor()
{
}
}

public class Capacitor : BaseBusinessObject
{
public Capacitor() {
}
public override string ToString() {
return "Capacitor";
}
}
}

using System;
namespace SomeCorpProject
{
class Class1 {
[STAThread]
static void Main(string[] args) {
BaseBusinessObject bizObj = new Capacitor();
System.Console.WriteLine(bizObj.ToString());
BaseBusinessObject NbizObj = new NCapacitor();
System.Console.WriteLine(NbizObj.ToString());
}
}
} What will happen when this code is compiled and run?

(BaseBusinessObject overrides object.ToString)
---------The word "Capacitor" will be written to the console.(overrides BaseBusinessObject's object.ToString)
---------The word "BaseBusinessObject" will be written to the console.(doesnt overrides BaseBusinessObject's object.ToString)

Properties

Properties
Properties can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. For example, the get may be public to allow read-only access from outside the type, and the set may be private or protected.
A property may be declared as a static property using the static keyword. This makes the property available to callers at any time, even if no instance of the class exists.
A property may be marked as a virtual property using the virtual keyword. This allows derived classes to override the property behavior using the override keyword.
A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. Lastly, a property can be declared abstract, meaning there is no implementation in the class, and derived classes must write their own implementation.

*It is an error to use a virtual, abstract, or override modifier on an accessor of a static property

Abstract Properties
-------------------
A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.
If the abstract class contains only set accessor, we can implement only set in the derived class.
The following program shows an abstract property in action.

using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}

Static Properties
-----------------
C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also.
The following program shows a class with a static property.

using System;
class MyClass
{
private static int x;
public static int X
{
get {return x;}
set {x = value;}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}
Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.
Properties & Inheritance
------------------------
The properties of a Base class can be inherited to a Derived class.

using System;
class Base
{
public int X
{
get{Console.Write("Base GET");return 10;}
set{Console.Write("Base SET");}
}
}
class Derived : Base
{}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}
The above program is very straightforward. The inheritance of properties is just like inheritance any other member.

Properties & Polymorphism
-------------------------
A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

using System;
class Base
{
public virtual int X
{
get{Console.Write("Base GET");return 10;}
set{Console.Write("Base SET");}
}
}
class Derived : Base
{
public override int X
{
get{Console.Write("Derived GET");return 10;}
set{Console.Write("Derived SET");}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}

Variable argument methods

Variable argument methods
sometimes a general purpose requirements is to provide a variable number of parameters to a common logical unit. 'params' keyword in c# helps you perform such sometiems difficult tasks.

only care that should be take while passing variable argument is the type of variable. if you fix the type, then it might become easy but it wont fulfill the variable argument feature.
we will discuss both options :

fixed argument type :

void Ex(params string[] args)
{
foreach(string ar in args)
{
Console.WriteLine(ar);
}
}

Ex("a","d","r","t");


different argument types :

void Ex(params object[] args)
{
foreach(object ar in args)
{
Console.WriteLine(ar);
}
}
//the implementation will be similar to printf function in c

Ex(1, 'a', "text");

ps: problem comes when you need to work on the args and compute some result, which needs the actual conversion on the args to their original type. to do that we need to pass the args type in sequence with actual args sequence, as a string.

void Ex(string sequentialArgsTypeList, params object[] args)
{
//convert each arg based on its corresponding type defined in 'sequentialArgsTypeList'
}
//the implementation will be similar to printf function in c

Ex("int,string,Employee", ob1, ob2, ob3);

VS Debugging tips

Debugging made easy
Visual studio provides a very good way to debug your code whether its running in production or test




Build the report in debug mode.
Copy pdb (Symbol file) and dll and place then in the product you want to debug. The dll copied should be used by the product.
run Product

In VS - Click 'Debug' menu - Select 'Attach to process'
Select your product running services/exe form the process list (if its not visible select 'Show processes from all users' checkbox)
click 'Attach'

Click 'Tools' menu - Select 'Options'
Expand 'Debugging' option in the right panel
Select 'Symbol' option.
Add a symbol option and give the full path of the pdb file.

Apply breakpoint at appropriate places

Now whenever the product tries to access the dll (copied) it will stop at your specified breakpoints)

Thursday, February 1, 2007

A to Z of embedding resources

extarct resources from a dll

a question comes to mind how to view the embedded resources of a dll.

one way is to type WebResource.axd source location on the browser address bar and then either u'll get a download dialog or the file content in the browser.

another option (which might interesting for dev's) is to extract the resources from the dll itself.the below code only extracts the embedded resources.

void ExtractAssemblyResource()

{

// EmbeddedResources should be a class in the dll from which you want to extract the resources//

Assembly executingAssembly = Assembly.GetAssembly(typeof(EmbeddedResources));

//get the fully qualified resource names//


foreach (string resourceName in executingAssembly.GetManifestResourceNames())

{

//extract the file name from the '.' separated resource name

string[] resourcePart = resourceName.Split('.');

int startIndex = 0;

int indexCal = resourcePart.Length - 2;

foreach (string part in resourcePart)

{


if (indexCal-- > 0)

{

startIndex += part.Length + 1;

}

else

{

break;

}

}

string resource = resourceName.Substring(startIndex);

Console.WriteLine(resource);

//create stream from the resource and write a byte stream to a locale file//


Stream resourceStream = executingAssembly.GetManifestResourceStream(resourceName);

FileInfo aResource = new FileInfo(resource);

FileStream fAResource = aResource.OpenWrite();

byte[] content = new byte[resourceStream.Length];

resourceStream.Read(content, 0, content.Length);

fAResource.Write(content, 0, content.Length);

resourceStream.Close();

fAResource.Close();


}

}


common class for web resource
//provides functions to retrieve WebResourceUrl for the EmbeddedResources

public class Resources

{

private Page caller = null;

public Resources(Page page)

{

caller = page;

}

public void GetResourceUrl(string sourcePath)

{

if(caller != null)

GetResourceUrl(caller, sourcePath);

}

public static string GetResourceUrl(Page caller, string sourcePath)

{

return caller.ClientScript.GetWebResourceUrl(typeof(Resources), sourcePath);

}

}



//define constants for all the EmbeddedResources, specifying their location

public class ResourceConstants

{

public const string ARROW = "WebResources.arrow.jpg";

public const string BOXINGDAYGIFTICON = "WebResources.BoxingDayGiftIcon.gif";

}



ps: dont forget to change the build action property for the images, from content to EmbeddedResource



public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

img1.Src = Resources.GetResourceUrl(Page, ResourceConstants.BOXINGDAYGIFTICON);

}

}






What is it?
Web Resource is a way to embedded all your less frequently changed items like images, css, js etc into a common dll and use it accross projects, intead of adding them individually to each project.

via web resource, you can embedded almost any type of resource like xhtml etc. but the ways to access them may vary.

the project i was doing, has absolute image path(~/images/icon_edit.gif) all over the place i.e. ASPX, CSS, JavaScript. the best and most reliable way to embbed resource is to prepare a separate dll only for the resource and use it whenever required.

enough of talking........lets start of with some solid work........

Create a Web Application Project (in case of console app, you have to force a dll out)
Clean up the project (just so that there is no junk i.e cs file)

Add a *.cs file to the project (EmbeddedResource.cs)

Add a folder (images) which contains a hierarchical arranged images. Select images and change there Property- 'Build Action' to 'Embedded Resource'.

Now comes the cumbersome part of making entries in the Assembly.info and creating a class to refer constant paths. best way out is to create a small program which can scan through a specific directory and all the sub-directory and generate a string for each file found (easier said then done)

entry for a single resource in

Assembly.info
------- [assembly: WebResource("XYZ.Resources.images.holidays.BoxingDayGiftIcon.gif", "image/gif")]

WebResource is under System.Web.UI.WebResourceAttribute

ResourceName i.e XYZ.Resources.images.holidays.BoxingDayGiftIcon.gif, defines the location of the resource in the assembly(dll). the string path is a collection of 3 parts i.e. Assembly Name + Folder name + Resource Name.
Here
'XYZ.Resources' is the assembly name
images - holidays are the folder separated by a '.'
boxingdaygifticon.gif is the resource name

ContentType i.e the type of the resource, in this case it is image/gif. we also used 'image/ico' , 'image/jpg'

ps : to check weather the resource has been added, use .net reflector to locate the above entry in the dll. if the entry is there, then the resource has been added.

EmbeddedResource.cs
------

public class EmbeddedResource
{
public static class Images
{
public static class Holidays
{
public const string BOXINGDAYGIFTICON = "XYZ.Resources.images.holidays.BoxingDayGiftIcon.gif";
}
}
}

now you are read with the dll. just include it in the project where required and assign the resource path by using the System.Web.UI.ClientScriptManager to GetResourceUrl (which provides a WebResource Url and various other things like registering client script, registering startup client script etc) to the appropriate control properties.


the toughest part of making all your existing absolute path to point to WebResource would be the entries in CSS.


*the next would be to extract the WebResource from the dll.

Thursday, January 18, 2007

Add images as Web Resources

Adding a image programmatically to UpdateProgress (ajax)

First, create a class called MyTemplate.

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace YourNamespace
{
public class MyTemplate : TemplateControl, ITemplate
{
private string template;

public MyTemplate(string template)
{
this.template = template;
}

public void InstantiateIn(Control container)
{
LiteralControl lc = new LiteralControl(this._template);
container.Controls.Add(lc);
}
}
}


sample aspx code------


create a Asp UpdatePanel
create Content Template
create a empty Update Progress having id="OpenProgress"




Second, in the calling code, set your Template based property like so.---------

string imageTemplateString = "\";
OpenProgress.ProgressTemplate = new CustomTemplate(string.Format(imageTemplateString, "Loading. Please wait...", LoadingImageUrl));

where LoadingImageUrl return the image web resource


Removing images from CSS and adding it from CS


CSS with images(absolute path)-----

function ShowHideGroups(thisImage)
{
if(isExpanded)
thisImage.src = "iamges/minus_icon.gif";
else
thisImage.src = "images/plus_icon.gif";
}

CSS without images(absolute path)-----

var minusIcon;
var plusIcon;

function ShowHideGroups(thisImage)
{
if(isExpanded)
thisImage.src = minusIcon;
else
thisImage.src = plusIcon;
}

CodeBehind----


from the pages where your are accessing the *.js file which contains the function. Add following lines to register the images before registering the javascript


string iconInitTemplate = "";
string iconInitScript = string.Format(iconInitTemplate,
Page.ClientScript.GetWebResourceUrl(typeof(PermissionType), "images/minus_icon.gif"),
Page.ClientScript.GetWebResourceUrl(typeof(PermissionType), "images/plus_icon.gif"));

Page.ClientScript.RegisterStartupScript(typeof(PermissionTypePage), "initIcons", iconInitScript);