Tuesday, September 28, 2004

How to prevent memory leak in C#.NET?


If you are letting .NET to manage memory, it will do a good job of memory management. If you start messing with the GC then you get into big trouble.

.NET's GC does not collect items right away, it lingers around in case the block is needed somewhere else. It collects when it thinks it should.

Don't mess with memory management unless you have a really, really good reason to. The Dispose method is used to release unmanaged resources that aren't handled by the garbage collector, like some streams and graphics operations. If you are using these, then you'll want to call the Dispose method when you're done with the object. The object itself will remain in memory until it's collected, but the unmanaged resources associated with it will be freed.

Note: For most streams, the Dispose method will probably be replaced by the Close method, which does the same thing.



With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Delegate: A neat example!

Delegate: A neat example!

Suppose your daughter is grounded: she's not allowed to use the phone.
If she picks up the phone, both mom and dad want to know about it.

Slap this code on her and she could wind up in big trouble!


using System;

namespace Grounded {

class Mother {

public void subscribe() {

Console.WriteLine("Mother Subscribing");

Daughter.onPhoneCall += new Daughter.OnPhoneCallHandler(Notify);

}

public void Unsubscribe() {

Console.WriteLine("Mother Unsubscribing");

Daughter.onPhoneCall -= new Daughter.OnPhoneCallHandler(Notify);

}

public void Notify() {

Console.WriteLine("Mother Notified");

}

}

class Father {

public void subscribe() {

Console.WriteLine("Father Subscribing");

Daughter.onPhoneCall += new Daughter.OnPhoneCallHandler(Notify);

}

public void Unsubscribe() {

Console.WriteLine("Father Unsubscribing");

Daughter.onPhoneCall -= new Daughter.OnPhoneCallHandler(Notify);

}

public void Notify() {

Console.WriteLine("Father Notified");

}

}


class Daughter {

public delegate void OnPhoneCallHandler();

public static event OnPhoneCallHandler onPhoneCall;

public void PlaceCall() {

Console.WriteLine("Daughter placed call");

if(onPhoneCall != null) {

onPhoneCall();

}

}

}


class Class1 {

static void Main(string[] args) {

Father f = new Father();

Mother m = new Mother();

Daughter d = new Daughter();

m.subscribe();

f.subscribe();

d.PlaceCall();

m.Unsubscribe();

f.Unsubscribe();

d.PlaceCall();

}

}

}

Tuesday, September 21, 2004

Xcopy Deployment

Xcopy command is used to easily copy all the files of a .Net application to
a target installation directory... For applications that do not require any
further registration Xcopy is command is the simplest way to distribute your
.Net applications...

Do note that Xcopy command does not copy the hidden and system files... Also
note that Xcopy creates files with the archive attribute set, whether or not
this attribute was set in the source file...If you have a disk that contains
files in subdirectories and you want to copy it to a disk that has a
different format, you should use the Xcopy command instead of Diskcopy.
Since the Diskcopy command copies disks track by track, it requires that
your source and destination disks have the same format. Xcopy has no such
requirement. In general, use Xcopy unless you need a complete disk image
copy or you wish to copy the system files.

With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

App Config File not being picked up

Some times you would have done nearly everything right in the windows
application but still on trying to access configuration file you would get
back null or nothing... Well the problem might be the name that you have
used for the config file...

You should know that for a windows based application to pick up app.config
file following should be taken care of...
1.) The app.config name should match your assembly name... i.e. if you have
myassembly.dll then the config file name should be myassembly.config...

2.) Also you should know that the config file is picked up for the main or
the application which is the starting point... So your app.config file
should be attached to that...


With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

When using the SqlDataReader, how can I tell how many records where found?

When using the SqlDataReader, how can I tell how many records where found?

The SqlDataReader provides a means of reading a "forward-only" stream of rows from a SQL Server database. Hence the number of rows read from the database is not known until the last row is read.

This is the same type of problem we had back in classic ADO where the Recordset's RecordCount was always -1 for a server-side, forward-only cursor. The solution in classic ADO was to use a static or keyset cursor. Or use a client-side cursor location, which always used a static cursor. However in ADO.NET 1.0, there is no such thing as a server-side, static or keyset cursor. There is only the server-side, forward-only DataReader. Or there is the client-side, static DataSet (in classic ADO "terms").

You can work-around this issue by either

1) Increment a counter while looping throuh all of the rows, or

2) use two SELECT statements in your query. The first one returns the row count and the second one returns the actual rows. e.g. "SELECT COUNT(*) FROM myTableName; SELECT * FROM myTableName". Then you can use the NextResult method to move from the first to the second result set, or

3) Or use a DataSet instead of the SqlDataReader. Then use the DataSet's Table Rows count. e.g. oDataSet.Tables("Products").Rows.Count

For more information, see: http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q308050

#) Best Practices for Using ADO.NET
Learn about the best solutions for implementing and achieving optimal performance, scalability, and functionality in Microsoft ADO.NET applications


* Information about the .NET Framework data providers included with the .NET Framework.
* Comparisons between the DataSet and the DataReader, and an explanation of the best use for each of these objects.
* An explanation on how to use the DataSet, Commands, and Connections.
* Information about integrating with XML.
* General tips and issues.

more here..http://msdn.microsoft.com/library/defaultasp?url=/library/en-us/dnadonet/html/adonetbest.asp

#) What is the difference between a Recordset and Dataset?

A Recordset is a single set of data from a database, whereas a DataSet is a relational set of data. ADO.NET allows for DataSets to be populated from the database, but DataSets are not exclusively an ADO.NET construct. A single dataset may house related, but distinct sets of data. For example, a dataset may contain a table of information about a patient (think a patient recordset) and also a related table of all the medications the patient is taking. In ADO, you would need to treat these as different recordsets. In ADO.NET this is remarkably different. DataSets are also inherited as disconnected.


With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Obtaining installation state of Visual Studio .NET programmaticall

The following article describes how to obtain the installation state of Visual
Studio .NET programmatically.

Typically, you can examine a file or a registry entry to determine
whether you have a version of Microsoft Visual Studio .NET, or of any
program, already installed on your computer. You can also determine
the version information programmatically by using Microsoft Windows
Installer functions such as the MsiQueryProductState function. The
MsiQueryProductState function takes the product code as the input
parameter and then returns the installation state of the program.


http://support.microsoft.com/default.aspx?scid=kb;EN-US;884468


With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Friday, August 27, 2004

Pre-defined Visual Studio Command Aliases

A list of Visual Studio pre-defined commands

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxgrfpredefinedcommandlinealiases.asp


With Best Regards
Mitesh Mehta

Monday, August 23, 2004

Reading Text file with XML DOM object

Hi,
XML DOM has no limitations on the kind of file it can open, what is important is that the content be XML. In your case, for this document to be a valid XML Document, the root node is missing. So, you would have a two step process for processing this doc as XML DOM.
1. Using XML Dom, create the root node and read the TXT file into a filestream
2. Concat the TXT file to the root node created above.

Now coming to the caveats of DOM.
Remember, DOM creates a tree in mem. This tree is so huge that its nearly 10 times the size of the original doc, once in memory.
Secondly, DOM is slower any day to actual raw file processing i.e. using streams. FSO is a different story. For that the VBScript engine has to be loaded, and then the file loaded (Unless of course you are referring to a VBScript here :) )

My suggestion would be, load the file into the FSO as you are doing now, and use the RegularExpression object (available in both, .NET as well as VBScript 5.0 onwards) to select the text between the and tags. Don't go for DOM unless you are looking at some requirement in the future which might need this doc available for XML processing.

With Best Regards,
Mitesh V. Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Thursday, August 19, 2004

Transaction

Transactions in .Net

We talked about Transactions in .Net a few days back... We learnt that how
they can be automatic or manual...Now ,we will talk about Automatic
Transactions this whole week... Hopefully it will be interesting and
useful...

Automatic Transaction manages transaction boundaries for you... But again it
manages the boundaries on the basis of what you suggest it to do (you do
that by attributes which we will talk in a couple of days... ) The
transaction flows from one object to other as instructed... Within its
scope, it includes, the objects that are suppose to participate in
transactions and leaves out the objects that are not suppose to
participate...

Note: Nested transactions are not possible in Automatic model...

---------xxxxxx--------------------
Transaction Attribute for your class

We discussed that for our class to participate in transactions we need to do
certain things... Now we will talk about what those certain things have to
be...

One of the things that you need to do is to apply Transaction attribute to
your class... You would apply it just before your class declaration... It
would look something like:

[Transaction(TransactionOption.Supported)]

Now if you are familiar with COM+ transactions then TransactionOption has
values which are very similar to COM+ transaction options...

The TransactionOption values can be Disabled, NotSupported, Supported,
Required, RequiresNew... Out of these Required is the default...



With Best Regards
Mitesh Mehta
eMAIL : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta

Wednesday, August 11, 2004

Changing Reference to different version of external assembly










Changing Reference to different version of external assembly

Consider a scenario when your application is referencing version 1.0.1.1 of
"SomeAssembly" in GAC... Now you realize that there are some major bugs in
that assembly and you want your assembly to reference the new version of the
assembly (say 1.0.2.0) and you do not want to go ahead and recompile your
code for that... What would you do... Well here is the answer... You would
go and change the configuration file with similar updates to the ones I am
writing below...

<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asmv1">
<publisherPolicy apply="no"/>
<dependantAssembly>
<assemblyIdentity name="SomeAssembly"
publicKeyToken="whatever" />
<publisherPolicy apply="no"/>
<bindingRedirect oldVersion="1.0.1.1"
newVersion="1.0.2.0" />
</dependantAssembly>
</assemblyBinding>
</runtime>
</configuration>
Regards,
Mitesh v. Mehta

Snippet Compiler


Snippet Compiler










Snippet Compiler Here are its
features:



  • Compiles and runs single or multiple C#, VB.NET
    and ASP.NET snippets.

  • Optionally builds WinForm EXEs, console
    EXEs or DLLs.

  • The user can store a library of
    templates.

  • Displays compile errors and warning, including
    wave lines in editor with error/warning tooltips.

  • IntelliSense for static members and method
    signatures, as well as constructor signatures.

  • Imports VS.NET projects.
  • Conveniently sits in the notification
    area waiting to be useful.

  • Exports snippets to HTML/RTF.

Regards,
Mitesh v. Mehta


Common Type System - Value Types vs Reference Types










Common Type System - Value Types vs Reference Types

Value Types and Reference Types are two basic types of CTS... Value Types
are allocated on the stack and Reference Types are allocated on Managed
heap... How this thing work is that the value of the "Value Types" is
allocated on the stack where as in case of "Reference Types" the value i.e.
the object itself resides in the heap but there is a pointer to the object
in the memory...

Considering this differences value types are faster but consume the process
memory.... Managed type don't consume this process memory but then they
become slower... When value types are copied then the whole object is copied
on the heap, when reference types are copied then only the reference is
copied... Inshort, there are pros and cons to both and sometimes you have an
option to choose one of them in your development sometimes you don't
have....

Value types are usually native data types like int, float, string, char,
enums etc... Reference types mostly include classes and some other user
defined types...
Regards,
Mitesh v. Mehta



.NET Supporting Languages List...


.NET Supporting Languages List...









.NET Supporting Languages List...

Language Company URL
Perl ActiveState www.activestate.com/visualperl/
Python ActiveState www.activestate.com/visualpython/
RPG ASNA www.asna.com/avr_caviar_information.asp
APL Dyadic Systems www.dyadic.com/msnet.htm
Oberon ETH Zentrum www.oberon.ethz.ch/oberon.net/
Cobol Fujitsu www.adtools.com/dotnet/index.html
Fortran Fujitsu www.fs.fujitsu.com/products/fortran.html
Eiffel ISE dotnet.eiffel.com
Haskel Massey University www.mondrian-script.org
Mondrian Massey University www.mondrian-script.org
J# Microsoft msdn.microsoft.com/visualj/jsharp/beta.asp
Standard ML Microsoft Research research.microsoft.com/projects/sml.net
Scheme Northwestern University rover.cs.nwu.edu/~scheme/
Pascal QUT www.plasrc.qut.edu.au/ComponentPascal/
Fortran Salford Software www.salfordsoftware.co.uk/compilers/ftn95/dotnet.shtml
SmallScript SmallScript www.smallscript.net
SmallTalk SmallScript www.smallscript.net
Pascal TMT Development www.tmt.com/net/
Mercury University of Melbourne www.cs.mu.oz.au/mercury/dotnet.html

Regards,
Mitesh v. Mehta

Ensuring a single instance of your .Net application


Ensuring a single instance of your .Net application









[STAThread]
static void Main()
{
bool ok;
m = new System.Threading.Mutex(true, "YourNameHere", out ok);
if (! ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1());
GC.KeepAlive(m);
}
Regards,
Mitesh Mehta
http://cc.1asphost.com/miteshvmehta/

Know about Data Protection API (DPAPI)


Know about Data Protection API (DPAPI)









What is the Data Protection API? The DPAPI is used to hide secrets like
connection strings and user credentials that are typically stored in a
config file. Instead of storing the plain text, you can use DPAPI to encrypt
and decrypt the secrets at a machine or user specific level.

Read and learn more at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsecure/html/windataprotection-dpapi.asp
Regards,
Mitesh v. Mehta



Network Ports Used by Key Microsoft Server Products.


Network Ports Used by Key Microsoft Server Products.









I found this nice link from http://www.only4gurus.com/ which also gives one .pdf files containing the list of Network Ports Used by Key Microsoft Server Products and their explaination.
Thanks and Regards,
Mitesh V. Mehta

KnowledgeBase: Remoting at a Glance.


KnowledgeBase: Remoting at a Glance.









Remoting at a Glance.

An
end-to-end picture of remoting is as follows. The host application is
loaded and registers a channel and port on which to listen for incoming
calls. The configuration file, if any, is read and an object’s remoting
information is loaded—the host application can now map a URI to the
physical assembly and instantiate the object when required. The client
application also registers the same channel and then attempts to create
a new instance of the remote class. The remoting system handles the
request for a new instance by providing a proxy object in place of the
actual object on the server. The actual object is either created
immediately for CAOs or on the first method call for Singleton/Singlecall objects—the
remoting framework takes care of this for you automatically. When the
client calls a method on the proxy object, the information is sent
across the channel to the remote object. The remoting system will then
pass back the results of the method across the channel in the same
manner

- C# .NET - Web Developers Guide

Regards,
Mitesh v. Mehta


Tuesday, July 27, 2004

namespaces & assemblies


namespaces & assemblies









The import statement enables access to a namespace in an external library or within the current script. The syntax is very simple:


  import namespaceName;

where namespaceName
is the name of the required namespace. There is always the question as
to where the computer should search for the given namespace. A
namespace is a collection of classes that typically offer related
features or functions. An assembly, on the other hand, is a physical
file, deployed during installation of the .NET framework, or other
applications. File extensions
.dll or .exe are a clear indication of assemblies. Usually, your namespaces will be implemented in .dll files. What's the relationship between the .dll file name and the namespace name? Generally speaking, none. A single namespace can be distributed among several .dll files. Also, a single .dll file can include multiple namespaces. In practice, though, the name of the .dll is usually the name of the namespace, and the jsc.exe compiler does support this practice with the /autoref compilation switch.






Mitesh Mehta



Thursday, July 22, 2004

Data Structures in C#


Data Structures in C#










This six-part series that focuses on important data structures and their
use in application development. Also examines both built-in data structures
present in the .NET Framework, as well as essential data structures we'll have
to build ourselves.


Part 1: An Introduction
to Data Structures


Focuses on defining what data
structures are, how the efficiency of data structures is analyzed, and why this
analysis is important.


Part 2: The Queue,
Stack, and Hashtable


Examines three of the most
commonly studied data structures: the Queue, the Stack, and the
Hashtable.


Part 3: Binary Tress and
BSTs


Looks at a common data
structure that is not included in the .NET Framework Base Class Library:
binary trees.


Part 4: Building a
Better Binary Search Tree


Examination of AVL trees and
red-black trees, which are two different self-balancing, binary search tree data
structures, skip list data structure, an ingenious data structure that turns a
linked list into a data structure that offers the same running time as the more
complex self-balancing tree data structures


Part 5: From Trees to
Graphs


All about graphs, one of the
most versatile data structures.


Part 6: Efficiently
Representing Sets


Data structures for implementing general and disjoint sets. A set is an
unordered collection of unique items that can be enumerated and compared to
other sets in a variety of ways.



Regards,
Mitesh Mehta
Microsoft Certified Professional
miteshvmehta@gmail.com

Some Questions On .Net


Some Questions On .Net









7.How to get updated data if datasource changes after filling dataset from datasource?
First
of all, a dataset should be used only when the data is not expected to
change very often. To get data that has been changed in the datasource
itself, means simply re-querying the datasource and re-filling the
dataset.