.net Remoting

I found this article a bit easy and easily understandable and the one which you can perform and get a feel of learning Remoting.

Remoting is the process through which we can access any remote object from one application domain to another application domain.

For creating remote object the class object must be inherited by MarshalByRefObject class.

Application domain is the runtime environment of application, For MicrosoftWord, domain is MS office, For .NET programme, .NET runtime environment.

Terms Used in Remoting

Proxy: To avoid conjunction in networking. Main work is task Distributing.There are two type of proxy.

Transparent proxy (There is no physical existence , Created by IIS server)
Real Proxy (Physical Existence)

Channel: Channel provides the medium for transfer data from one location to another location. There are two types of channel.

TCP(work with Predefined root Connection oriented)
HTTP (No need predefined root)
Formatters: Change the data in an appropriate format that it can traverse through channels.

There are two types of formatters
Binary
SOAP(Simple Object Access Protocol)
Sink: Sink is used for security point of view. Before sending the data, the Data will be encrypted. Some additional bit will be added with the data to secure the data.

There are two types of sink
Envoy sink
Server Context Sink
Object Mode On Server: Two Types of Object Mode .

SingleCall
Singleton
For creating Remoting we have to create 3 applications:

class Library (Of which Remote Object will be created)
Server Application (Console Application)
Client Application (Window Application)
RemoteClass

using System;

using System.Collections.Generic;

using System.Text;

namespace remoteclass

{

public class xx:MarshalByRefObject

{

public int sum(int a, int b)

{

return a + b;

}

}

}

Remote Server

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

namespace remoteserver

{

class Program

{

static void Main(string[] args)

{

TcpChannel ch=new TcpChannel(8085);

ChannelServices.RegisterChannel(ch);

RemotingConfiguration.RegisterWellKnownServiceType(typeof

(remoteclass.xx),”rahul”,WellKnownObjectMode.Singleton);

Console.Write(“Sever is Ready……..”);

Console.Read();

}

}

}

When user run this Remote Server application.

Figure 1: Server Application.

Remote Client

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

namespace remoteclient

{

public partial class Form1 : Form

{

//TcpChannel ch = new TcpChannel();

remoteclass.xx obj = new remoteclass.xx();

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, System.EventArgs e)

{

//ChannelServices.RegisterChannel(ch);

obj = (remoteclass.xx)Activator.GetObject(typeof(remoteclass.xx),

“tcp://localhost:8085/rahul”);

int x = Int32.Parse(textBox1.Text);

int y = Int32.Parse(textBox2.Text);

textBox3.Text = (obj.sum(x, y)).ToString();

}

}

}

When user run the application.

Figure 2: Client Application.

Leave a Comment

Word counts in a Text file

namespace WordsCount
{
class Program
{
static void Main(string[] args)
{
WordCount obj = new WordCount();
// read the text file
StreamReader reader = new StreamReader(@”D:\Test.txt”);

// pass the file as the string of input
string readthisline = reader.ReadToEnd();

// Console.WriteLine(obj.CountWords(readthisline));
obj.CountWords(readthisline);
Console.ReadLine();
}
}

class WordCount
{
public string CountWords(string input)
{
// ignore these words, remove these things from the final input string.
char[] delims = new char[] { ‘ ‘, ‘.’, ‘,’, ‘;’,'”‘,’?',’(‘,’)',’:'};

// prepare the words from the string
string[] wordlist = input.Split(delims, StringSplitOptions.RemoveEmptyEntries);

// this is the final word list to be counted after removing the extra things.
SortedList words = new SortedList();

//Dictionary words = new Dictionary(wordlist.Length);

// count the repetitions of the words
foreach (string item in wordlist)
{
// check for upper and lower cases as well
if (!words.ContainsKey(item.ToLower()))
// find the word and add to the list.
words.Add(item.ToLower(), 1);
else
// increment the word count.
words[item.ToLower()]++;
}
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair kvp in words)
{
sb.Append(kvp.Key + “: ” + kvp.Value + “\r\n”);
Console.WriteLine(“The word is {0} and repitions {1}”, kvp.Key,kvp.Value);
}
//foreach (string item in words.Keys)
// sb.Append(item + “: ” + words[item] + “\r\n”);
return sb.ToString();
}
}

}

Leave a Comment

Interview @ Goldman Sachs , Bangalore

Written Test(.Net)
I dont remember the exact questions but i can give u brief idea what were the questions like.
I have given the test as the .Net guy.
As they are using JAVA for the rest of the project, but they are using .Net for Front end (Web , windows application).
Few concepts or questions or toppics
-As the reuirement was for UI, front end so all the questions were revolving around that.
-Dataset
-DataAdaptor
-Fill()
-Outproc(SQL Server , state server)
-DebugListner
-Trace
-Application run mode (define- Debug/Trace)
-Gridview (ButtonField,CommandField)
-Viewstate
-Property to get a column from Dataset.
-Prepare well on Threading
-Prepare well on Delegates
-Design Patterns
-BinaryTextWriter
-How to get the root node of a dataset.

Leave a Comment

Dispose

Dispose is the method, which we call usually when we want the object to be garbage collected. If u r calling Dispose() on inbuilt classes like Form, It’ll call a method Finalize() method, which will usually used to cleanup any resources used with in the form. With in this Finalize method, we call the garbage collector to recycle the memory. So, when u r using dispose method, it is used to mark the object to Garbage Collectable. Calling the Dispose dose’t means, that object will b garbage collected immidiately. GC will monitor the Managed memory for objects Marked 4 garbage collectable. The recycling of memory depends on when the GC will pay the visit.
Purely the Dispose method is not used for reseting the values in the object. It is used to mark the Object to b collected by the GC

Leave a Comment

Serialization

WHAT IS SERIALIZATION?
Serialization is the process of converting an object or a con-nected graph of objects into a contiguous stream of bytes. Deserialization is the process of converting a contiguous stream of bytes back into its graph of connected objects. The ability to convert objects to and from a byte stream is an incredibly useful mechanism. Here are some examples:
• An application’s state (object graph) can easily be saved in a disk file or database and then restored the next time the application is run. ASP.NET saves and restores session state by way of serialization and deserialization.
• A set of objects can easily be copied to the system’s clipboard and then pasted into the same or another application. In fact, Windows® Forms uses this procedure.
• A set of objects can be cloned and set aside as a backup while a user manipulates the main set of objects.
• A set of objects can easily be sent over the network to a process running on another machine. The Microsoft® .NET Framework remoting architecture serializes and deserializes objects that are marshaled by value.
Why would you want to use serialization? The two most important reasons are
• to persist the state of an object to a storage medium so an exact copy can be recreated at a later stage, and
• to send the object by value from one application domain to another.

Leave a Comment

Garbage Collection

Garbage collection in .NET
By Amit Kukreja and Reshmi Nair

.Net is the much hyped revolutionary technology gifted to the programmer’s community by Microsoft. Many factors make it a must use for most developers. In this article we would like to discuss one of the primary advantages of .NET framework – the ease in memory and resource management.

Every program uses resources of one sort or another-memory buffers, network connections, database resources, and so on. In fact, in an object-oriented environment, every type identifies some resource available for a program’s use. To use any of these resources, memory must be allocated to represent the type.

The steps required to access a resource are as follows:

1. Allocate memory for the type that represents the resource.
2. Initialize the memory to set the initial state of the resource and to make the resource usable.
3. Use the resource by accessing the instance members of the type (repeat as necessary).
4. Tear down the state of the resource to clean up.
5. Free the memory.

The garbage collector (GC) of .NET completely absolves the developer from tracking memory usage and knowing when to free memory.

The Microsoft� .NET CLR (Common Language Runtime) requires that all resources be allocated from the managed heap. You never free objects from the managed heap-objects are automatically freed when they are no longer needed by the application.

Memory is not infinite. The garbage collector must perform a collection in order to free some memory. The garbage collector’s optimizing engine determines the best time to perform a collection, (the exact criteria is guarded by Microsoft) based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.

However for automatic memory management, the garbage collector has to know the location of the roots i.e. it should know when an object is no longer in use by the application. This knowledge is made available to the GC in .NET by the inclusion of a concept know as metadata. Every data type used in .NET software includes metadata that describes it. With the help of metadata, the CLR knows the layout of each of the objects in memory, which helps the Garbage Collector in the compaction phase of Garbage collection. Without this knowledge the Garbage Collector wouldn’t know where one object instance ends and the next begins.

Garbage Collection Algorithm

Application Roots

Every application has a set of roots. Roots identify storage locations, which refer to objects on the managed heap or to objects that are set to null.

For example:

� All the global and static object pointers in an application.
� Any local variable/parameter object pointers on a thread’s stack.
� Any CPU registers containing pointers to objects in the managed heap.
� Pointers to the objects from Freachable queue
The list of active roots is maintained by the just-in-time (JIT) compiler and common language runtime, and is made accessible to the garbage collector’s algorithm.

Implementation

Garbage collection in .NET is done using tracing collection and specifically the CLR implements the Mark/Compact collector.

This method consists of two phases as described below.

Phase I: Mark
Find memory that can be reclaimed.

When the garbage collector starts running, it makes the assumption that all objects in the heap are garbage. In other words, it assumes that none of the application’s roots refer to any objects in the heap.

The following steps are included in Phase I:

1. The GC identifies live object references or application roots.
2. It starts walking the roots and building a graph of all objects reachable from the roots.
3. If the GC attempts to add an object already present in the graph, then it stops walking down that path. This serves two purposes. First, it helps performance significantly since it doesn’t walk through a set of objects more than once. Second, it prevents infinite loops should you have any circular linked lists of objects. Thus cycles are handles properly.

Once all the roots have been checked, the garbage collector’s graph contains the set of all objects that are somehow reachable from the application’s roots; any objects that are not in the graph are not accessible by the application, and are therefore considered garbage.

Phase II: Compact

Move all the live objects to the bottom of the heap, leaving free space at the top.

Phase II includes the following steps:
1. The garbage collector now walks through the heap linearly, looking for contiguous blocks of garbage objects (now considered free space).
2. The garbage collector then shifts the non-garbage objects down in memory, removing all of the gaps in the heap.
3. Moving the objects in memory invalidates all pointers to the objects. So the garbage collector modifies the application’s roots so that the pointers point to the objects’ new locations.
4. In addition, if any object contains a pointer to another object, the garbage collector is responsible for correcting these pointers as well.
After all the garbage has been identified, all the non-garbage has been compacted, and all the non-garbage pointers have been fixed-up, a pointer is positioned just after the last non-garbage object to indicate the position where the next object can be added.

Finalization

.Net Framework’s garbage collection implicitly keeps track of the lifetime of the objects that an application creates, but fails when it comes to the unmanaged resources (i.e. a file, a window or a network connection) that objects encapsulate.

The unmanaged resources must be explicitly released once the application has finished using them. .Net Framework provides the Object.Finalize method: a method that the garbage collector must run on the object to clean up its unmanaged resources, prior to reclaiming the memory used up by the object. Since Finalize method does nothing, by default, this method must be overridden if explicit cleanup is required.

It would not be surprising if you will consider Finalize just another name for destructors in C++. Though, both have been assigned the responsibility of freeing the resources used by the objects, they have very different semantics. In C++, destructors are executed immediately when the object goes out of scope whereas a finalize method is called once when Garbage collection gets around to cleaning up an object.

The potential existence of finalizers complicates the job of garbage collection in .Net by adding some extra steps before freeing an object.

Whenever a new object, having a Finalize method, is allocated on the heap a pointer to the object is placed in an internal data structure called Finalization queue. When an object is not reachable, the garbage collector considers the object garbage. The garbage collector scans the finalization queue looking for pointers to these objects. When a pointer is found, the pointer is removed from the finalization queue and appended to another internal data structure called Freachable queue, making the object no longer a part of the garbage. At this point, the garbage collector has finished identifying garbage. The garbage collector compacts the reclaimable memory and the special runtime thread empties the freachable queue, executing each object’s Finalize method.

The next time the garbage collector is invoked, it sees that the finalized objects are truly garbage and the memory for those objects is then, simply freed.

Thus when an object requires finalization, it dies, then lives (resurrects) and finally dies again. It is recommended to avoid using Finalize method, unless required. Finalize methods increase memory pressure by not letting the memory and the resources used by that object to be released, until two garbage collections. Since you do not have control on the order in which the finalize methods are executed, it may lead to unpredictable results.

Garbage Collection Performance Optimizations

� Weak references
� Generations

Weak References

Weak references are a means of performance enhancement, used to reduce the pressure placed on the managed heap by large objects.

When a root points to an abject it’s called a strong reference to the object and the object cannot be collected because the application’s code can reach the object.

When an object has a weak reference to it, it basically means that if there is a memory requirement & the garbage collector runs, the object can be collected and when the application later attempts to access the object, the access will fail. On the other hand, to access a weakly referenced object, the application must obtain a strong reference to the object. If the application obtains this strong reference before the garbage collector collects the object, then the GC cannot collect the object because a strong reference to the object exists.

The managed heap contains two internal data structures whose sole purpose is to manage weak references: the short weak reference table and the long weak reference table.

Weak references are of two types:
� A short weak reference doesn’t track resurrection.
i.e. the object which has a short weak reference to itself is collected immediately without running its finalization method.

� A long weak reference tracks resurrection.
i.e. the garbage collector collects object pointed to by the long weak reference table only after determining that the object’s storage is reclaimable. If the object has a Finalize method, the Finalize method has been called and the object was not resurrected.

These two tables simply contain pointers to objects allocated within the managed heap. Initially, both tables are empty. When you create a WeakReference object, an object is not allocated from the managed heap. Instead, an empty slot in one of the weak reference tables is located; short weak references use the short weak reference table and long weak references use the long weak reference table.

Consider an example of what happens when the garbage collector runs. The diagrams (Figure 1 & 2) below show the state of all the internal data structures before and after the GC runs.

Now, here’s what happens when a garbage collection (GC) runs:

The garbage collector builds a graph of all the reachable objects. In the above example, the graph will include objects B, C, E, G.
The garbage collector scans the short weak reference table. If a pointer in the table refers to an object that is not part of the graph, then the pointer identifies an unreachable object and the slot in the short weak reference table is set to null. In the above example, slot of object D is set to null since it is not a part of the graph.
The garbage collector scans the finalization queue. If a pointer in the queue refers to an object that is not part of the graph, then the pointer identifies an unreachable object and the pointer is moved from the finalization queue to the freachable queue. At this point, the object is added to the graph since the object is now considered reachable. In the above example, though objects A, D, F are not included in the graph they are treated as reachable objects because they are part of the finalization queue. Finalization queue thus gets emptied.
The garbage collector scans the long weak reference table. If a pointer in the table refers to an object that is not part of the graph (which now contains the objects pointed to by entries in the freachable queue), then the pointer identifies an unreachable object and the slot is set to null. Since both the objects C and F are a part of the graph (of the previous step), none of them are set to null in the long reference table.
The garbage collector compacts the memory, squeezing out the holes left by the unreachable objects. In the above example, object H is the only object that gets removed from the heap and it’s memory is reclaimed.
Generations
Since garbage collection cannot complete without stopping the entire program, they can cause arbitrarily long pauses at arbitrary times during the execution of the program. Garbage collection pauses can also prevent programs from responding to events quickly enough to satisfy the requirements of real-time systems.

One feature of the garbage collector that exists purely to improve performance is called generations. A generational garbage collector takes into account two facts that have been empirically observed in most programs in a variety of languages:
1. Newly created objects tend to have short lives.
2. The older an object is, the longer it will survive.

Generational collectors group objects by age and collect younger objects more often than older objects. When initialized, the managed heap contains no objects. All new objects added to the heap can be said to be in generation 0, until the heap gets filled up which invokes garbage collection. As most objects are short-lived, only a small percentage of young objects are likely to survive their first collection. Once an object survives the first garbage collection, it gets promoted to generation 1.Newer objects after GC can then be said to be in generation 0.The garbage collector gets invoked next only when the sub-heap of generation 0 gets filled up. All objects in generation 1 that survive get compacted and promoted to generation 2. All survivors in generation 0 also get compacted and promoted to generation 1. Generation 0 then contains no objects, but all newer objects after GC go into generation 0.

Thus, as objects “mature” (survive multiple garbage collections) in their current generation, they are moved to the next older generation. Generation 2 is the maximum generation supported by the runtime’s garbage collector. When future collections occur, any surviving objects currently in generation 2 simply stay in generation 2.

Thus, dividing the heap into generations of objects and collecting and compacting younger generation objects improves the efficiency of the basic underlying garbage collection algorithm by reclaiming a significant amount of space from the heap and also being faster than if the collector had examined the objects in all generations.

A garbage collector that can perform generational collections, each of which is guaranteed (or at least very likely) to require less than a certain maximum amount of time, can help make runtime suitable for real-time environment and also prevent pauses that are noticeable to the user.

Myths Related To Garbage Collection

GC is necessarily slower than manual memory management.
Counter Explanation:
Not necessarily. Modern garbage collectors appear to run as quickly as manual storage allocators (malloc/free or new/delete). Garbage collection probably will not run as quickly as customized memory allocator designed for use in a specific program. On the other hand, the extra code required to make manual memory management work properly (for example, explicit reference counting) is often more expensive than a garbage collector would be.

GC will necessarily make my program pause.
Counter Explanation:
Since garbage collectors usually stop the entire program while seeking and collecting garbage objects, they cause pauses long enough to be noticed by the users. But with the advent of modern optimization techniques, these noticeable pauses can be eliminated.

Manual memory management won’t cause pauses.
Counter Explanation:
Manual memory management does not guarantee performance. It may cause pauses for considerable periods either on allocation or deallocation.

Programs with GC are huge and bloated; GC isn’t suitable for small programs or systems.
Counter Explanation:
Though using garbage collection is advantageous in complex systems, there is no reason for garbage collection to introduce any significant overhead at any scale.

I’ve heard that GC uses twice as much memory.
Counter Explanation:
This may be true of primitive GCs, but this is not generally true of garbage collection. The data structures used for GC need be no larger than those for manual memory management.

Leave a Comment

Application Domain

Inorder to set the default domain for a website in case of Basic Authentication:

//set the default domain
DirectoryEntry site = new DirectoryEntry(“IIS://localhost/W3SVC/” + newWebSiteID + “/ROOT”);
site.Invoke(“Put”, new object[] { “DefaultLogonDomain”, “CodeLeacher”});
site.Invoke(“SetInfo”);
site.CommitChanges();

October 22, 2008
IIS Enums
Posted by Mohamed Fahmy under IIS | Tags: IIS6 |
No Comments
Here are all the enum values needed for the IIS6 development:

public enum AccessPermissions

{

Read = 1,

Write = 2,

Execute = 4,

Source = 16,

Script = 512,

NoRemoteRead = 4096,

NoRemoteWrite = 1024,

NoRemoteExecute = 8192,

NoRemoteScript = 16384,

NoPhysicalDir = 32768

}

public enum SiteStatus

{

Starting = 1,

Started = 2,

Stopping = 3,

Stopped = 4,

Pausing = 5,

Paused = 6,

Continuing = 7

}

public enum AppPoolStatus

{

Starting = 1,

Started = 2,

Stopping = 3,

Stopped = 4

}

public enum AuthenticationTypes

{

Anonymous = 1,

Basic = 2,

Integrated = 4,

Digest = 16,

Passport = 64

}

public enum AppPoolIdentity

{

LocalSystem = 0,

LocalService = 1,

NetworkService = 2,

UserDefined = 3

}

public enum ASPNET

{

v1_1_4322 = 1,

v2_0_50727 = 2

}

October 22, 2008
Creating FTP site on IIS6 programitacally using C#
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: C#, IIS6 |
No Comments
Inorder to create FTP site on IIS6

public void CreateFTPSite(string serverName, string siteName, string siteID)

{

try

{

//Create website on IIS

DirectoryEntry root = new DirectoryEntry(”IIS://” + serverName + “/msftpsvc”);

DirectoryEntry newSite = root.Children.Add(siteID, “IIsFTPServer”);

newSite.Properties["ServerComment"][0] = “codeleacher.com”;

newSite.CommitChanges();

root.CommitChanges();

SetSingleProperty(“IIS://” + serverName + “/msftpsvc/”+siteID.ToString(), “ServerBindings”, ”:2122:”);

private static void SetSingleProperty(string metabasePath, string propertyName, object newValue)

{

try

{

DirectoryEntry path = new DirectoryEntry(metabasePath);

PropertyValueCollection propValues = path.Properties[propertyName];

if (null == propValues.Value)

propValues.Value = “foo”;

string oldType = propValues.Value.GetType().ToString();

string newType = newValue.GetType().ToString();

if (newType == oldType)

{

path.Properties[propertyName][0] = newValue;

path.CommitChanges();

}

else

Console.WriteLine(” Failed in SetSingleProperty; type of new value does not match property”);

}

catch (Exception ex)

{

if (“HRESULT 0×80005006″ == ex.Message)

Console.WriteLine(” Property {0} does not exist at {1}”, propertyName, metabasePath);

else

Console.WriteLine(“Failed in SetSingleProperty with the following exception: \n{0}”, ex.Message);

}

}

}

catch (Exception ex)

{

throw new Exception(“Error”);

}

}

September 27, 2008
Add users to the IIS_WPG group using C#.Net
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: Directory Services, IIS6, IIS_WPG |
1 Comment
The following function adds a user to the IIS_WPG group using the ntrights.exe utility by Microsoft. Note that in order for this function to work you have to have the ntrights utility downloaded. To download it check Microsoft’s wensite:

http://www.microsoft.com/downloads/details.aspx?FamilyID=9D467A69-57FF-4AE7-96EE-B18C4790CFFD&displaylang=en

public static void AddUserToWPG(string currentFolderPath, string user)
{
try
{
Process process = new Process();
//run the script
process.StartInfo.FileName = System.Environment.SystemDirectory + @”\net.exe”;
process.StartInfo.Arguments = string.Format(” localgroup \”{0}\” {1} /add”, wpgGroup, user);
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = true;
process.Start();
process.WaitForExit();

process.StartInfo.FileName = Path.Combine(currentFolderPath, “ntrights.exe”);
process.StartInfo.Arguments = string.Format(” +r \”seTcbPrivilege\” -u \”{0}\”", user);
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = true;
process.Start();
process.WaitForExit();
}
catch
{
throw new Exception(“your message”);

}

}

September 27, 2008
Change the ASP.Net version of a website on IIS6 using C#.Net
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: ASP.NET, Directory Services, IIS6 |
1 Comment
Sometimes, while creating a website pragmatically, you wish to change the ASP.Net version the site is using. The following function change the ASP.Net version a website is using to ASP.Net 2.0

public static void UpdateASPNetVersion(string siteidentifier, string virtualDirectoryName)
{
//get virtual directory and site name for m context parameters
string targetSite = “W3SVC/” + siteidentifier + “/ROOT”;
string targetVDir = virtualDirectoryName;
Process process = new Process();
//run the script
process.StartInfo.FileName = Path.GetDirectoryName(System.Environment.SystemDirectory) + @”\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe”;
process.StartInfo.Arguments = string.Format(” -s {0}/{1}”, targetSite, targetVDir);
process.StartInfo.CreateNoWindow = false;
process.Start();
process.WaitForExit();
}

You can of course change the ASP.Net version to any other version by choosing a different directory.

September 27, 2008
Check if a TCP port is already in use by IIS6 using C#.Net
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: Directory Services, IIS6, TCP Port |
No Comments
The following function checks if a port is already in use by the IIS. Such function can be used to validate ports before creating a website. The function simply attempts to open a connection to the specified port. In case there was an exception, that means that it is not used.

public static bool IsPortUsed(int port)
{
try
{
TcpListener tcp = new TcpListener(port);
tcp.Start();
tcp.Stop();
return true;
}
catch (SocketException)
{
return false;
}
}

September 27, 2008
Get a Website Identifier from IIS6 using C#.Net
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: Directory Services, IIS6 |
No Comments
This function retrieves a website identifier from the IIS. Sometimes, you need a website identifier in order to connect to it and install something under it pragmatically. This function simply connects to the IIS and retrieve all the sub directories and then start searching for the desired website by its name and then return its identifier.

public static int GetWebSiteIdentifier(string server, string siteName)
{
int siteIdentifier = 0;
try
{
DirectoryEntry root = new DirectoryEntry(“IIS://” + server + “/W3SVC”);
foreach (DirectoryEntry entry in root.Children)
{
if (string.Compare(entry.SchemaClassName, “IIsWebServer”, true) == 0 && string.Compare(entry.Properties["ServerComment"].Value.ToString(), siteName, true) == 0)
siteIdentifier = Int32.Parse(entry.Name);
}
}
catch
{
throw new Exception(“your message”);
}

return siteIdentifier;

}

September 27, 2008
Creating an Application Pool on IIS6 using C#.Net
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: Directory Services, IIS6 |
No Comments
The following function creates an application pool on IIS6. The function creates an application pool and sets its identity with the specified user name and password.

public static void CreateAppPool(string serverName, string poolName, string userName, string password, bool enableRecylce)
{
DirectoryEntry AppPool = null;
DirectoryEntry root = null;
try
{
root = new DirectoryEntry(“IIS://” + serverName + “/W3SVC/AppPools”);

//create app pool
AppPool = root.Invoke(“Create”, “IIsApplicationPool”, poolName) as DirectoryEntry;

//set app pool identity
AppPool.InvokeSet(“AppPoolIdentityType”, new Object[] { AppPoolIdentityType.SpecificUser });
AppPool.InvokeSet(“WAMUserName”, new Object[] { userName });
AppPool.InvokeSet(“WAMUserPass”, new Object[] { password });
AppPool.InvokeSet(“AppPoolAutoStart”, new Object[] { true });

//set recycling options
if (!enableRecylce)
AppPool.InvokeSet(“PeriodicRestartTime”, new Object[] { 0 });

AppPool.Invoke(“SetInfo”);
AppPool.CommitChanges();
}
catch
{
throw new Exception(“your message”);
}
finally
{
AppPool.Dispose();
root.Dispose();
}
}

September 27, 2008
Check if a website exists on IIS6 using C#.Net
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: Directory Services, IIS6 |
No Comments
The following function checks if a website with the same name exists or not on the IIS. What it actually does, is that it connects to the IIS and retrieve all sub directories and then start searching for the specified website.

public static bool IsWebSiteExistsOnIIS(string serverName, string siteName)
{
DirectoryEntry site = null;
try
{
site = new DirectoryEntry(“IIS://” + serverName + “/W3SVC”);
foreach (DirectoryEntry entry in site.Children)
{
if (entry.Properties["ServerComment"].Value != null &&
entry.Properties["ServerComment"].Value.ToString() == siteName)
return true;
}
return false;
}
finally
{
site.Dispose();
}
}

Notice that the website name is saved in the “ServerComment” property and not the “name”. The “name” property holds the website Identifier.

September 27, 2008
Create website on IIS6 using C#.Net
Posted by Mohamed Fahmy under C#.Net, IIS | Tags: C#.Net, Directory Services, IIS6 |
[7] Comments
The following function creates a website on IIS6 with C#.Net using directory services:

public static void CreateWebSiteOnIIS(string serverName, string siteName, int port, int? sslPort, string sitePath, string appPoolName, AuthTypes authenticationType)
{

try
{
//Create website on IIS
DirectoryEntry root = new DirectoryEntry(“IIS://” + serverName + “/W3SVC”);
int newWebSiteID = (int)root.Invoke(“CreateNewSite”, new object[] { siteName, new object[] { “:” + port.ToString() + “:” }, sitePath });
DirectoryEntry newSite = new DirectoryEntry(“IIS://” + serverName + “/W3SVC/” + newWebSiteID);

//Set SSL port
if (sslPort != null)
{
newSite.Invoke(“Put”, new object[] { “SecureBindings”, “:” + sslPort + “:” });
}

//update application pool
newSite.Invoke(“Put”, new object[] { “AppPoolId”, appPoolName });

//update the authentication type of the website
newSite.Invoke(“Put”, new object[] { “AuthFlags”, authenticationType });
newSite.Invoke(“Put”, new object[] { “AccessRead”, true });

//save changes
newSite.Invoke(“SetInfo”);
newSite.CommitChanges();
root.CommitChanges();

//Start the new site
newSite.Invoke(“Start”, null);
newSite.Dispose();
root.Dispose();
}
catch
{
throw new Exception(“Error”);
}
}

You can choose any other authentication type for your website by selecting a different Authentication type from the following enum

public enum AuthTypes
{
AuthAnonymous = 1,
AuthBasic = 2,
AuthNTLM = 4,
AuthMD5 = 16,
AuthPassport = 64
}

Leave a Comment

Interview @ HU(Health Unity) softwares

I got a chance to appear for an interview for this company called HU(Health Unity) softwares.
Its a small company , but the interview was full of questions and they asked be some really good questions, good food for my brains.
They asked questions from their real time project experience.
1. .net runtime architecture.
2. Who iis process asp.net web request.
3. Is it possible to make an application without having IDE on your machine.
4. If your machine is having OS and IIS installed on it , can i deploy an application.
5. How to deploy an application
6. What is application domain
7. How we create application domain
8. How many app domain gest created whne we create a virtual directory.
9. Virtual directory is having a cofig file and a child underneath is having a config file , how to make virtual config file override the settings of child config file.
10. If an application A is having A.dll where B.dll is present in bin folder of A.
- How A will know B.dll has to use.
- How B.dll will be installed in GAC.
- What is GAC.
- If B.dll is modified how A will come to know.
- If B.dll is there in GAC and changes are made to B.dll present in bin folder, which dll will be taken by A, how to modify it.
11. What is SP.
12. How to call SP from C#.
13. ADO.net architecture.
14. Ado.net classes.
15. Diff b/w queries and SP.
16. Advantages of SP.
17. Indexes in SQL.
18. How indexes work.
19. Diff types of indexes.
20. Types of session storing mode(in proc and out proc)
21. State and SQL server (diff)
22. How session values are stored in State server(config files)
23. Diff b/w application and session.
24. What all are the events fired when web request is made.
25. Difference b/w CTS and CLS.
26. How GC works,
27. Generation in GC.
28. How heap and queue works while garbage collecting an object.
29. If an error occurs in using block will object be disposed.
30. Can we force a class to use using block .
31. Contracts in WCF.
32. Overriding in WCF
33. Diff b/w .net remoting , web service and WCF.
34. Why web service?
35. How to assign a global variable in application event.
36. Xpath,xquer,xmlreader,xmlwritter.
37. Diff b/w dataset and recordset.

Leave a Comment

10 Worst Stock Market Crashes

10 Worst Stock Market Crashes

10th Worst Stock Market Crash (1932 – 1933): This crash required the longest recovery time of all the 10 crashes. The combination of the tech bubble bursting and the September 11th terrorist attack served a deadly blow to the stock market, but relative to markets past, this was a minor one. Date Started: 1/15/2000 Date Ended: 10/9/2002

Total Days: 999 Starting DJIA: 11,792.98 Ending DJIA: 7,286.27 Total Loss: -37.8%

9th Worst Stock Market Crash (1916 – 1917): This market suffered about a 40% loss. Date Started: 11/21/1916 Date Ended: 12/19/1917 Total Days: 393 Starting DJIA: 110.15 Ending DJIA: 65.95 Total Loss: -40.1%

8th Worst Stock Market Crash (1939 to 1942): It was one of the most grueling. It took nearly 3 years to recover from this crash! With the attack on Pearl Harbor, the markets had a very tough time. Date Started: 9/12/1939 Date Ended: 4/28/1942

Total Days: 959 Starting DJIA: 155.92 Ending DJIA: 92.92 Total Loss: -40.4%

7th Worst Stock Market Crash (1973-1974): Another long market crash -one that many people still remember (think Vietnam and the Watergate scandal). This crash lasted for 694 days before bottoming out. Date Started: 1/11/1973 Date Ended: 12/06/1974 Total Days: 694 Starting DJIA: 1051.70 Ending DJIA: 577.60 Total Loss: -45.1%

6th Worst Stock Market Crash (1901 – 1903): This is the oldest crash to make the list (DJIA records are not available before 1900). Date Started: 6/17/1901 Date Ended: 11/9/1903 Total Days: 875 Starting DJIA: 57.33 Ending DJIA: 30.88 Total Loss: -46.1%

The 5th worst stock market Crash (1919 – 1921): This crash followed a post war boom (Stock prices rose 51%). After the crash bottomed out in August of 1921, this decade saw tremendous growth in the stock market and the economy (often called the roaring twenties). Date Started: 11/3/1919 Date Ended: 8/24/1921

Total Days: 660 Starting DJIA: 119.62 Ending DJIA: 63.9 Total Loss: -46.6%

The 4th worst stock market crash in U.S. History Although this is the shortest market crash observed, it was a deadly one. Investors saw almost half their money disappear in just two months. This crash started the “Great Depression.” Date Started: 9/3/1929 Date Ended: 11/13/1929

Total Days: 71 Starting DJIA: 381.17 Ending DJIA: 198.69 Total Loss: -47.9%

3rd Worst Stock Market Crash (1906 – 1907): This crash was called the “Panic of 1907.” The U.S. Treasury department bought 36 million dollars worth of government bonds to offset the decline Date Started: 1/19/1906 Date Ended: 11/15/1907

Total Days: 665 Starting DJIA: 75.45 Ending DJIA: 38.83 Total Loss: -48.5%

2nd Worst Stock Market Crash (1937 – 1938): Just when investors thought the market was finally good again, following a recovery of almost half of the great depression losses, the market plunged again due to war scare and Wall street scandals. Date Started: 3/10/1937 Date Ended: 3/31/1938

Total Days: 386 Starting DJIA: 194.40 Ending DJIA: 98.95 Total Loss: -49.1%

Worst Stock Market Crash Ever: 1932 Stock Market Crash: Investors lost 86% of their money over this 813 day beast. This market crash combined with the 1929 crash, made up the great depression. The full recovery didn’t take place until 1954. Date Started: 4/17/1930 Date Ended: 7/8/1932

Total Days: 813 Starting DJIA: 294.07 Ending DJIA: 41.22 Total Loss: -86.0%

Leave a Comment

IBP Petrol Pump- Theives

I found these patrol bunk guys the biggest fraud ever.
It’s not the first time i found them cheating but its always the case.
I am talking about IBP Petrol Bunk, RT Nagar,MLA layout.
If you will ask them to put petrol for Rs100, in fraction of seconds they will show you the meter reading as Rs 00 and immediately it will reach Rs 30 or Rs 50 and they will indulge you in some matter like “your fuel tank is having dust you should clean it and other junk as well” and suddenly you will find that 30,50 bucks petrol has been put they haven’t even started and then you will say i asked for more and they will set it back to Rs 00 and fuel another Rs 70.

Today, i scolded the guy that you haven’t put a single drop of petrol and how come it reached Rs 30 and then he started telling i havn’t started yet then i told him how come it became Rs 30 and then he started giving some excusses and again i set the meter to Rs 00 and added exact Rs 100 petrol.

So, this way i got fully confirmed that they are cheating on us.

Please make sure that you pay full attention while filling the fuel.

Sometime 3 or 4 attendent will come and 1 will ask for money someone will talk about fuel tank and buy the time you would have gone.

I have been observing this issue from quite a while , i found my milage going down and fuel tank also showing less petrol and but i couldn’t figure it out.

But last weekend i got a chance to speak to one of my friend regarding this and i finally decided to shout this time.

so its an appeal to all the petrol bunk owners kindly ask you employees not to cheat the innocent people of our country.

Solution to this problem could be :-
-pay proper attentin while getting your vehicle fueled.
-vehicle manufacturer should fix digital fuel reading so that you can easily make out the fuel added.
-shout at the attendent at petrol bunk if you will observe it.

JAGO GRAHAK JAGO!

Leave a Comment

Older Posts »