Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Showing posts with label programming in C#. Show all posts
Showing posts with label programming in C#. Show all posts

DateTime Formatting In VSTS

DateTime Formatting In VSTS : How to Format Date and Time in various manner ?


Private Sub Page_Load(sender As Object, e As System.EventArgs)

  Response.Write("Default: " System.DateTime.Now "<br>")
  Response.Write("Local Time: " System.DateTime.Now.ToLocalTime() "<br>")
  Response.Write("Long Date: " System.DateTime.Now.ToLongDateString() "<br>")
  Response.Write("Long Time: " System.DateTime.Now.ToLongTimeString() "<br>")
  Response.Write("Short Date: " System.DateTime.Now.ToShortDateString() "<br>")
  Response.Write("Short Time: " System.DateTime.Now.ToShortTimeString() "<br>")
  Response.Write("ToString Default: " System.DateTime.Now.ToString() "<br>")
  Response.Write("Universal Time: " System.DateTime.Now.ToUniversalTime() "<br>"' returns a datetime, which can still be formatted
  
  ' Using Format Strings
  Response.Write("d - Short Date: " System.DateTime.Now.ToString("d") "<br>")
  Response.Write("D - Long Date: " System.DateTime.Now.ToString("D") "<br>")
  Response.Write("t - Short Time: " System.DateTime.Now.ToString("t") "<br>")
  Response.Write("T - Long Time: " System.DateTime.Now.ToString("T""<br>")
  Response.Write("f - Full date/time (short time): " System.DateTime.Now.ToString("f") "<br>")
  Response.Write("F - Full date/time (long time): " System.DateTime.Now.ToString("F") "<br>")
  Response.Write("g - General: " System.DateTime.Now.ToString("g""<br>")
  Response.Write("G - General: " System.DateTime.Now.ToString("G") "<br>")
  Response.Write("M/m - Month day: " System.DateTime.Now.ToString("M") "<br>")
  Response.Write("u - Universal Sortable: " System.DateTime.Now.ToString("u") "<br>")
  Response.Write("Y/y - Year month: " System.DateTime.Now.ToString("y") "<br>")

  ' Custom Format Strings
  Response.Write("d, day of month: " & System.DateTime.Now.ToString(" d""<br>"' can't use just "d"
  Response.Write("dd, zero-padded day of month: " & System.DateTime.Now.ToString("dd""<br>")
  Response.Write("ddd, abbreviated day of week: " & System.DateTime.Now.ToString("ddd""<br>")
  Response.Write("dddd, full day of week: " & System.DateTime.Now.ToString("dddd""<br>")

  Response.Write("h, hour: " & System.DateTime.Now.ToString(" h""<br>"' can't use just "h"
  Response.Write("hh, hour, zero padded " & System.DateTime.Now.ToString("hh""<br>")
  Response.Write("H, hour, 24-hr " & System.DateTime.Now.ToString(" H""<br>"' can't use just "H"
  Response.Write("H, hour, 24-hr, zero padded " & System.DateTime.Now.ToString("HH""<br>")
  
  Response.Write("m, minute: " & System.DateTime.Now.ToString(" m""<br>"' can't use just "m"
  Response.Write("M, month: " & System.DateTime.Now.ToString(" M""<br>"' can't use just "M"
  Response.Write("MM, month, zero padded: " & System.DateTime.Now.ToString("MM""<br>"
  Response.Write("MMM, month abbreviated: " & System.DateTime.Now.ToString("MMM""<br>"
  Response.Write("MMMM, month full name: " & System.DateTime.Now.ToString("MMMM""<br>"
  
  Response.Write("y, year (omits century): " & System.DateTime.Now.ToString(" y""<br>"' can't use just "y"
  Response.Write("yy, 2-digit year, zero padded: " & System.DateTime.Now.ToString("yy""<br>"
  Response.Write("yyyy, 4-digit year, zero padded: " & System.DateTime.Now.ToString("yyyy""<br>"
End Sub 'Page_Load


Algorithm Complexity -3

BIG O NOTATION
In mathematics, computer science, and related fields, big O notation  (also known as Big Oh notation, Landau notation, Bachmann–Landau notation, and asymptotic notation) describes the limiting behavior of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions. Big O notation allows its users to simplify functions in order to concentrate on their growth rates: different functions with the same growth rate may be represented using the same O notation.

Although developed as a part of pure mathematics, this notation is now frequently also used in the analysis of algorithms to describe an algorithm's usage of computational resources: the worst case or average case running time or memory usage of an algorithm is often expressed as a function of the length of its input using big O notation. This allows algorithm designers to predict the behavior of their algorithms and to determine which of multiple algorithms to use, in a way that is independent of computer architecture or clock rate. Because Big O notation discards multiplicative constants on the running time, and ignores efficiency for low input sizes, it does not always reveal the fastest algorithm in practice or for practically-sized data sets. But the approach is still very effective for comparing the scalability of various algorithms as input sizes become large.

A description of a function in terms of big O notation usually only provides an upper bound on the growth rate of the function. Associated with big O notation are several related notations, using the symbols o, Ω, ω, and Θ, to describe other kinds of bounds on asymptotic growth rates. Big O notation is also used in many other fields to provide similar estimates.


Formal definition

Let f(x) and g(x) be two functions defined on some subset of the real numbers. One writes
f(x)=O(g(x))\mbox{ as }x\to\infty\,
if and only if, for sufficiently large values of x, f(x) is at most a constant multiplied by g(x) in absolute value. That is, f(x) = O(g(x)) if and only if there exists a positive real number M and a real number x0 such that
|f(x)| \le \; M |g(x)|\mbox{ for all 
}x>x_0.
In many contexts, the assumption that we are interested in the growth rate as the variable x goes to infinity is left unstated, and one writes more simply that f(x) = O(g(x)).
The notation can also be used to describe the behavior of f near some real number a (often, a = 0): we say
f(x)=O(g(x))\mbox{ as }x\to a\,
if and only if there exist positive numbers δ and M such that
|f(x)| \le \; M |g(x)|\mbox{ for }|x - a| <
 \delta.
If g(x) is non-zero for values of x sufficiently close to a, both of these definitions can be unified using the limit superior:
f(x)=O(g(x))\mbox{ as }x \to a\,
if and only if
\limsup_{x\to a} 
\left|\frac{f(x)}{g(x)}\right| < \infty.

 Example

In typical usage, the formal definition of O notation is not used directly; rather, the O notation for a function f(x) is derived by the following simplification rules:
  • If f(x) is a sum of several terms, the one with the largest growth rate is kept, and all others omitted.
  • If f(x) is a product of several factors, any constants (terms in the product that do not depend on x) are omitted.
For example, let f(x) = 6x4 − 2x3 + 5, and suppose we wish to simplify this function, using O notation, to describe its growth rate as x approaches infinity. This function is the sum of three terms: 6x4, −2x3, and 5. Of these three terms, the one with the highest growth rate is the one with the largest exponent as a function of x, namely 6x4. Now one may apply the second rule: 6x4 is a product of 6 and x4 in which the first factor does not depend on x. Omitting this factor results in the simplified form x4. Thus, we say that f(x) is a big-oh of (x4) or mathematically we can write f(x) = O(x4).
One may confirm this calculation using the formal definition: let f(x) = 6x4 − 2x3 + 5 and g(x) = x4. Applying the formal definition from above, the statement that f(x) = O(x4) is equivalent to its expansion,
|f(x)| \le \; M |g(x)|
for some suitable choice of x0 and M and for all x > x0. To prove this, let x0 = 1 and M = 13. Then, for all x > x0:
\begin{align}|6x^4 - 2x^3 + 5| &\le 6x^4 +
 |2x^3| + 5\\
                                      &\le 6x^4 + 2x^4 + 5x^4\\
                                      &= 13x^4,\\
                                      &= 13|x^4|\end{align}
so
 |6x^4 - 2x^3 + 5| \le 13 \,|x^4 |.

Usage

Big O notation has two main areas of application. In mathematics, it is commonly used to describe how closely a finite series approximates a given function, especially in the case of a truncated Taylor series or asymptotic expansion. In computer science, it is useful in the analysis of algorithms. In both applications, the function g(x) appearing within the O(...) is typically chosen to be as simple as possible, omitting constant factors and lower order terms.
There are two formally close, but noticeably different, usages of this notation: infinite asymptotics and infinitesimal asymptotics. This distinction is only in application and not in principle, however—the formal definition for the "big O" is the same for both cases, only with different limits for the function argument.

Infinite asymptotics

Big O notation is useful when analyzing algorithms for efficiency. For example, the time (or the number of steps) it takes to complete a problem of size n might be found to be T(n) = 4n2 − 2n + 2.
As n grows large, the n2 term will come to dominate, so that all other terms can be neglected — for instance when n = 500, the term 4n2 is 1000 times as large as the 2n term. Ignoring the latter would have negligible effect on the expression's value for most purposes.
Further, the coefficients become irrelevant if we compare to any other order of expression, such as an expression containing a term n3 or n4. Even if T(n) = 1,000,000n2, if U(n) = n3, the latter will always exceed the former once n grows larger than 1,000,000 (T(1,000,000) = 1,000,0003= U(1,000,000)). Additionally, the number of steps depends on the details of the machine model on which the algorithm runs, but different types of machines typically vary by only a constant factor in the number of steps needed to execute an algorithm.
So the big O notation captures what remains: we write either
\ T(n)= O(n^2)
or
T(n)\in O(n^2)
and say that the algorithm has order of n2 time complexity.
Note that "=" is not meant to express "is equal to" in its normal mathematical sense, but rather a more colloquial "is", so the second expression is technically accurate (see the "Equals sign" discussion below) while the first is a common abuse of notation.

 Infinitesimal asymptotics

Big O can also be used to describe the error term in an approximation to a mathematical function. The most significant terms are written explicitly, and then the least-significant terms are summarized in a single big O term. For example,
e^x=1+x+\frac{x^2}{2}+O(x^3)\qquad\hbox{as}\ 
x\to 0
expresses the fact that the error, the difference \ e^x - (1 + x + x^2/2), is smaller in absolute value than some constant times | x3 | when x is close enough to 0.

Properties

If a function f(n) can be written as a finite sum of other functions, then the fastest growing one determines the order of f(n). For example
f(n) = 9 \log n + 5 (\log n)^3 + 3n^2 + 2n^3 
\in O(n^3)\,\!.
In particular, if a function may be bounded by a polynomial in n, then as n tends to infinity, one may disregard lower-order terms of the polynomial.
O(nc) and O(cn) are very different. The latter grows much, much faster, no matter how big the constant c is (as long as it is greater than one). A function that grows faster than any power of n is called superpolynomial. One that grows more slowly than any exponential function of the form cn is called subexponential. An algorithm can require time that is both superpolynomial and subexponential; examples of this include the fastest known algorithms for integer factorization.
O(logn) is exactly the same as O(log(nc)). The logarithms differ only by a constant factor (since log(nc) = clogn) and thus the big O notation ignores that. Similarly, logs with different constant bases are equivalent. Exponentials with different bases, on the other hand, are not of the same order. For example, 2n and 3n are not of the same order.
Changing units may or may not affect the order of the resulting algorithm. Changing units is equivalent to multiplying the appropriate variable by a constant wherever it appears. For example, if an algorithm runs in the order of n2, replacing n by cn means the algorithm runs in the order of c2n2, and the big O notation ignores the constant c2. This can be written as  c^2n^2 \in O(n^2) . If, however, an algorithm runs in the order of 2n, replacing n with cn gives 2cn = (2c)n. This is not equivalent to 2n in general.
Changing of variable may affect the order of the resulting algorithm. For example, if an algorithm's running time is O(n) when measured in terms of the number n of digits of an input number x, then its running time is O(log x) when measured as a function of the input number x itself, because n = Θ(log x).

Product

 f_1 \in O(g_1) \text{ and } f_2\in O(g_2)\, 
\Rightarrow f_1  f_2\in O(g_1  g_2)\,
f\cdot O(g) \in O(f g)

Sum

 f_1 \in O(g_1) \text{ and }
  f_2\in O(g_2)\, \Rightarrow f_1 + f_2\in O(|g_1| + |g_2|)\,
This implies f_1 \in O(g) \text{ and } f_2 \in
 O(g) \Rightarrow f_1+f_2 \in O(g) , which means that O(g) is a convex cone.
If f and g are positive functions, f + O(g) \in O(f + g)

Multiplication by a constant

Let k be a constant. Then:
\ O(k g) = O(g)if k is nonzero.
f\in O(g) \Rightarrow kf\in O(g).

Multiple variables

Big O (and little o, and Ω…) can also be used with multiple variables.
To define Big O formally for multiple variables, suppose f(\vec{x})and g(\vec{x})are two functions defined on some subset of \mathbb{R}^n. We say
f(\vec{x})\mbox{ is }O(g(\vec{x}))\mbox{ as 
}\vec{x}\to\infty
if and only if
\exists C\,\exists M>0\mbox{ such that } 
|f(\vec{x})| \le C |g(\vec{x})|\mbox{ for all }\vec{x} \mbox{ with } 
x_i>M \mbox{ for all }i.
For example, the statement
f(n,m) = n^2 + m^3 + \hbox{O}(n+m) \mbox{ as }
 n,m\to\infty\,
asserts that there exist constants C and M such that
\forall n, m>M\colon |g(n,m)| \le C(n+m),
where g(n,m) is defined by
f(n,m) = n^2 + m^3 + g(n,m).\,
Note that this definition allows all of the coordinates of \vec{x}to increase to infinity. In particular, the statement
f(n,m) = \hbox{O}(n^m) \mbox{ as } 
n,m\to\infty\,
(i.e., \exists C\,\exists M\,\forall n\,\forall
 m\dots) is quite different from
\forall m\colon f(n,m) = \hbox{O}(n^m) \mbox{ 
as } n\to\infty
(i.e., \forall m\,\exists C\,\exists M\,\forall
 n\dots).

Matters of notation

Equals sign

The statement "f(x) is O(g(x))" as defined above is usually written as f(x) = O(g(x)). Some consider this to be an abuse of notation, since the use of the equals sign could be misleading as it suggests a symmetry that this statement does not have. As it is said, O(x) = O(x2) is true but O(x2) = O(x) is not.Knuth describes such statements as "one-way equalities", since if the sides could be reversed, "we could deduce ridiculous things like n = n2 from the identities n = O(n2) and n2 = O(n2)."
For these reasons, it would be more precise to use set notation and write f(x) ∈ O(g(x)), thinking of O(g(x)) as the class of all functions h(x) such that |h(x)| ≤ C|g(n)| for some constant C. However, the use of the equals sign is customary. Knuth pointed out that "mathematicians customarily use the = sign as they use the word 'is' in English: Aristotle is a man, but a man isn’t necessarily Aristotle."

 Other arithmetic operators

Big O notation can also be used in conjunction with other arithmetic operators in more complicated equations. For example, h(x) + O(f(x)) denotes the collection of functions having the growth of h(x) plus a part whose growth is limited to that of f(x). Thus,
g(x) = h(x) + O(f(x))\,
expresses the same as
g(x) - h(x) \in O(f(x))\,.

 Example

Suppose an algorithm is being developed to operate on a set of n elements. Its developers are interested in finding a function T(n) that will express how long the algorithm will take to run (in some arbitrary measurement of time) in terms of the number of elements in the input set. The algorithm works by first calling a subroutine to sort the elements in the set and then perform its own operations. The sort has a known time complexity of O(n2), and after the subroutine runs the algorithm must take an additional 55n3 + 2n + 10 time before it terminates. Thus the overall time complexity of the algorithm can be expressed as
T(n)=O(n^2)+55n^3+2n+10.\
This can perhaps be most easily read by replacing O(n2) with "some function that grows asymptotically slower than n2 ". Again, this usage disregards some of the formal meaning of the "=" and "+" symbols, but it does allow one to use the big O notation as a kind of convenient placeholder.

 Declaration of variables

Another feature of the notation, although less exceptional, is that function arguments may need to be inferred from the context when several variables are involved. The following two right-hand side big O notations have dramatically different meanings:
f(m) = O(m^n)\,,
g(n)\,\, = O(m^n)\,.
The first case states that f(m) exhibits polynomial growth, while the second, assuming m > 1, states that g(n) exhibits exponential growth. To avoid confusion, some authors use the notation
g \in O(f)\,,
rather than the less explicit
g(x) \in O(f(x))\,.

 Complex usages

In more complex usage, O(...) can appear in different places in an equation, even several times on each side. For example, the following are true for n\to\infty
(n+1)^2 = n^2 + O(n)\
(n+O(n^{1/2}))(n + O(\log n))^2 = n^3 + 
O(n^{5/2})\
n^{O(1)} = O(e^n).\
The meaning of such statements is as follows: for any functions which satisfy each O(...) on the left side, there are some functions satisfying each O(...) on the right side, such that substituting all these functions into the equation makes the two sides equal. For example, the third equation above means: "For any function f(n) = O(1), there is some function g(n) = O(en) such that nf(n) = g(n)." In terms of the "set notation" above, the meaning is that the class of functions represented by the left side is a subset of the class of functions represented by the right side.



Export GridView To Word/Excel/PDF/CSV in ASP.Net


To retrieve the records from a table fom within a database is perfectly easy via the gridview server control which can be bound via some queries specific to the requirements.

However what ought to be done when we have to export the data into a Word/Excel/PDF/CSV format ?

Does it seem tough. May be but here in we go with the simple though tricky codes :

protected void btnExportWord_Click(object sender, EventArgs e)

{

Response.Clear();

Response.Buffer = true;

Response.AddHeader("content-disposition",

"attachment;filename=GridViewExport.doc");

Response.Charset = "";

Response.ContentType = "application/vnd.ms-word ";

StringWriter sw= new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.AllowPaging = false;

GridView1.DataBind();

GridView1.RenderControl(hw);

Response.Output.Write(sw.ToString());

Response.Flush();

Response.End();

}

Int32.Parse(), Convert.ToInt32(), and Int32.TryParse() A Comparison

Int32.parse(string)
-------------------------

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent.
When s is null reference, it will throw ArgumentNullException.
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.


Example:
------------------

string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException


Convert.ToInt32(string)
----------------------------------

Convert.ToInt32(string s) method converts the specified the string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
When s is null reference, it will return 0 rather than throw ArgumentNullException
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException

Example:
result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException



Int32.TryParse(string, out int)
---------------------------------------------

Int32.Parse(string, out int) method converts the specified the string representation of 32-bit signed integer equivalent to out variable, and returns true if it parsed successfully, false otherwise. This method is available in C# 2.0
When s is null reference, it will return 0 rather than throw ArgumentNullException.
If s is other than integer value, the out variable will have 0 rather than FormatException.
When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

Example:-
-------------
success = Int32.TryParse(s1, out result); //-- success => true; result => 1234
success = Int32.TryParse(s2, out result); //-- success => false; result => 0
success = Int32.TryParse(s3, out result); //-- success => false; result => 0
success = Int32.TryParse(s4, out result); //-- success => false; result => 0


Convert.ToInt32 is better than Int32.Parse, since it return 0 rather than exception. But, again according to the requirement this can be used. TryParse will be best since it handles exception itself always.

Open Web Page in a new window

The following HTML code will enable you to open a web page in a new window:


A HREF="http://www.yourdomain.com" TARGET="_blank"


If you're linking to a lot of other web sites within your web page and would like to open all of your links in a new window, this HTML code is for you.

The following HTML code will enable you to open all of your links in a new window. Place this code between your HEAD tag within your HTML:

base target="main"

Multicast Delegate

A delegate (object) which simultaneously executes more than one method dynamically can be called as a multicast delegate.

In all of my previous examples, I attached a delegate to one and only one method every time. Now, we are going to assign more than one method to the same delegate. In other words, the moment "invoke()" gets executed, all the methods (addresses of methods) attached to the delegate get executed.

Let us see an example of this:



'multi-cast delegate


Public Class Form7




Delegate Sub Calculate()


Dim obj As New Sample01(10, 20)


Dim deleg As Calculate




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


deleg = AddressOf obj.Add


deleg = System.Delegate.Combine(deleg, New Calculate(AddressOf obj.Multiply))


'deleg.Invoke()


deleg()


End Sub


End Class



From the above, the most important lines are the following:



deleg = AddressOf obj.Add


deleg = System.Delegate.Combine(deleg, New Calculate(AddressOf obj.Multiply))



The first line says that the "Add" method must be assigned to the "deleg" object. The second line says that another method, "Multiply," must be assigned to the "deleg" object, to keep existing.

Finally, all the methods in the delegate get executed using the following line:

deleg()

Delegates To Methods Returning Values


In
all of the previous examples, I concentrated only on methods which do not return any values. Now, let us concentrate on delegates which can be used to call methods returning values (say, functions in a class).

Let us add one more class as follows:



Public Class Sample03


Private _x As Integer


Private _y As Integer




Public Sub New()




End Sub




Public Sub New(ByVal a As Integer, ByVal b As Integer)


_x = a


_y = b


End Sub




Public Property X() As Integer


Get


Return _x


End Get


Set(ByVal value As Integer)


_x = value


End Set


End Property




Public Property Y() As Integer


Get


Return _y


End Get


Set(ByVal value As Integer)


_y = value


End Set


End Property




Public Function GetSum() As Integer


Return (Me.X + Me.Y)


End Function




Public Function GetProduct() As Integer


Return (Me.X * Me.Y)


End Function




End Class



The above class contains two methods, "GetSum()" and "GetProduct()," which return values of type integer. To access those methods using delegates, you can code as follows:


'delegates to functions


Public Class Form5


Delegate Function Calculate() As Integer




Dim delegCalc As Calculate


Dim obj As New Sample03(10, 20)




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


delegCalc = AddressOf obj.GetSum


MessageBox.Show("Sum = " & delegCalc())


'MessageBox.Show("Sum = " & delegCalc.Invoke())


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


delegCalc = AddressOf obj.GetProduct


MessageBox.Show("Product = " & delegCalc())


'MessageBox.Show("Product = " & delegCalc.Invoke())


End Sub




End Class


"Callback"
is one of the most important features of delegates. Let us start with an example. To make things easier to understand, I added a new class as follows:



Public Class Sample04




Delegate Sub FactorFound(ByVal FactorValue As Integer)




Private _x As Integer




Public Sub New()




End Sub




Public Sub New(ByVal a As Integer)


_x = a


End Sub




Public Property X() As Integer


Get


Return _x


End Get


Set(ByVal value As Integer)


_x = value


End Set


End Property




Public Sub FindFactors(ByVal delgFoundFactor As FactorFound)


For i As Integer = 1 To _x


If _x Mod i = 0 Then


delgFoundFactor(i)


End If


Next


End Sub




End Class



The most important method from the above class is the following:



Public Sub FindFactors(ByVal delgFoundFactor As FactorFound)


For i As Integer = 1 To _x


If _x Mod i = 0 Then


delgFoundFactor(i)


End If


Next


End Sub



The method accepts a parameter of type "delegate" which is declared at module level as follows:


Delegate Sub FactorFound(ByVal FactorValue As Integer)


That means the calling program can execute the "FindFactors" method by passing the address of another method. The address, which is passed to "FindFactors," can be invoked within the same "FindFactors" method.

In simple words, the calling program executes "FindFactors" by giving permission to the "FindFactors" method to execute (internally inside "FindFactors") another method (address) passed to it.

The following sample can be considered a caller for this demonstration:



'implementing callback methods using delegates


Public Class Form6




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Me.ListBox1.Items.Clear()


Dim obj As New Sample04(Me.TextBox1.Text)


obj.FindFactors(AddressOf FactorAvailable)


End Sub




Private Sub FactorAvailable(ByVal FactorValue As Integer)


Me.ListBox1.Items.Add(FactorValue)


End Sub


End Class



From the above, you can observe that "FactorAvailable" is passed to the "FindFactors" method. The "FactorAvailable" method gets executed with the following statement in the "FindFactors" method:



delgFoundFactor(i)

Delegates With Parameters

In my previous example, you were introduced to simple delegates. Now, I shall extend the same with parameters.

To help us understand "delegates with parameters," I added a new class as follows:



Public Class Sample02


Private _x As Integer


Private _y As Integer




Public Sub New()




End Sub




Public Sub New(ByVal a As Integer, ByVal b As Integer)


_x = a


_y = b


End Sub




Public Property X() As Integer


Get


Return _x


End Get


Set(ByVal value As Integer)


_x = value


End Set


End Property




Public Property Y() As Integer


Get


Return _y


End Get


Set(ByVal value As Integer)


_y = value


End Set


End Property




Public Sub Increment(ByVal IncrementValue As Integer)


_x += IncrementValue


_y += IncrementValue


End Sub




Public Sub Add()


MessageBox.Show("Sum = " & (Me.X + Me.Y))


End Sub




Public Sub Multiply()


MessageBox.Show("Product = " & (Me.X * Me.Y))


End Sub


End Class



You can observe that a new method, "Increment" (which accepts a parameter), is added. Let us try to access it using delegate. The following is the code:



'delegate with parameters


Public Class Form4




Delegate Sub Calculate()


Delegate Sub IncreaseValues(ByVal value As Integer)




Dim delegCalc As Calculate


Dim delegIncrease As IncreaseValues




Dim obj As New Sample02(10, 20)




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


delegCalc = AddressOf obj.Add


delegIncrease = AddressOf obj.Increment


delegIncrease(100)


delegCalc()


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


delegCalc = AddressOf obj.Multiply


delegIncrease = AddressOf obj.Increment


delegIncrease(100)


delegCalc()


End Sub




End Class



Let us try to understand this step by step. Consider the following first:



Delegate Sub IncreaseValues(ByVal value As Integer)



"IncreaseValues" is a delegate type of class now. However, it only accepts methods (which can be executed later) with just one parameter of type integer.



Dim obj As New Sample02(10, 20)


delegIncrease = AddressOf obj.Increment



As the "Increment" method accepts a parameter of type integer, it can be assigned to the delegate object we declared earlier.

Finally, the method gets executed with a value of 100 using the statement:



delegIncrease(100)



A delegate declaration can have multiple parameters, not only one. And further, those parameters could be of any type, from primitive data types to reference types!


Delegates Basics

A delegate allows us to encapsulate a reference to a method inside an object -- a delegate object, to be precise. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Before trying to understand the above, let us work with a simple example. The following is a sample class:


Public Class Sample01

Private _x As Integer

Private _y As Integer


Public Sub New()


End Sub


Public Sub New(ByVal a As Integer, ByVal b As Integer)

_x = a

_y = b

End Sub


Public Property X() As Integer

Get

Return _x

End Get

Set(ByVal value As Integer)

_x = value

End Set

End Property


Public Property Y() As Integer

Get

Return _y

End Get

Set(ByVal value As Integer)

_y = value

End Set

End Property


Public Sub Add()

MessageBox.Show("Sum = " & (Me.X + Me.Y))

End Sub


Public Sub Multiply()

MessageBox.Show("Product = " & (Me.X * Me.Y))

End Sub

End Class



The above class has two private fields ("_x" and "_y") which are only accessible within the class, and not outside the class. Further, it has two public properties and two public methods, "Add" and "Multiply." Note that public members are accessible even outside the class.

To test the above class, add a new form with two buttons and a label. Modify your code to match the following:


'without using delegates

Public Class Form1


Dim obj As New Sample01(10, 20)


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

obj.Add()

End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

obj.Multiply()

End Sub


End Class


There is nothing new in the above form. We are simply instantiating an object based on the "Sample01" class and calling its methods. We will do the same in the next section, but with "Delegates."

In the previous section, a class named "Sample01" was introduced. The following is a simple "delegate" way of coding:


'sample of using delegate


Public Class Form2




Delegate Sub Calculate()


Dim obj As New Sample01(10, 20)




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Dim delg As New Calculate(AddressOf obj.Add)


delg.Invoke()


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


Dim delg As New Calculate(AddressOf obj.Multiply)


delg.Invoke()


End Sub


End Class



Let us try to understand it step by step. First of all we have the following:


Delegate Sub Calculate()


The line says that "Calculate" is a delegate. Even though its signature looks like a method, it is actually a class. Consider "Calculate" to be a named class of yours having its own functionality to invoke "methods of other objects dynamically."

Further proceeding we have the following:


Dim obj As New Sample01(10, 20)


It is simply an instantiation. Further on we have the following:


Dim delg As New Calculate(AddressOf obj.Add)


As previously described, "Calculate" is a class. And now, "delg" is an instance of the class "Calculate," which is "authorized" to access and execute the method named "obj.Add()".

The "obj.Add()" method gets executed when the following statement is invoked:


delg.Invoke()


Finally, a delegate is simply an object which can execute methods of other objects dynamically at run time.

To make all of this simpler, the above can also be written as follows:



'Without creating instances of a delegate and without using invoke


Public Class Form3




Delegate Sub Calculate()


Dim obj As New Sample01(10, 20)


Dim deleg As Calculate




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


deleg = AddressOf obj.Add


deleg()


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


deleg = AddressOf obj.Multiply


deleg()


End Sub


End Class

Retrieving SMTP, FTP, POP3 Information

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dt As DataTable = getPropertyStruct()
Dim dr As DataRow
Dim searcher As New ManagementObjectSearcher("root\MicrosoftIISv2", "SELECT * FROM IIsSmtpService")
For Each queryObj As ManagementObject In searcher.Get()

dr = dt.NewRow
dr("Name") = "DisplayName"
dr("value") = queryObj("DisplayName")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "PathName"
dr("value") = queryObj("PathName")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "Started"
dr("value") = queryObj("Started")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "State"
dr("value") = queryObj("State")
dt.Rows.Add(dr)


dr = dt.NewRow
dr("Name") = "SystemName"
dr("value") = queryObj("SystemName")
dt.Rows.Add(dr)

Next
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
Catch err As ManagementException
Response.Write(err.Message)
End Try
End Sub

To retrieve information about SMTP, we need to work with the class “IIsSmtpService.” Similarly, to work with FTP, we need to work with “IIsFtpService,” and so on.

IIS Information Retrieval Via IIsWebVirtualDirSettng


We can dig still further, but with a different class, as shown in the following program.A yet another waay to dig into the IIS informaticas.



Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dt As DataTable = getStruct()
Dim dr As DataRow
Dim searcher As New ManagementObjectSearcher("root\MicrosoftIISv2", "SELECT * FROM IIsWebVirtualDirSetting")
For Each queryObj As ManagementObject In searcher.Get()
dr = dt.NewRow
dr("AppPoolId") = queryObj("AppPoolId")
dr("Name") = queryObj("Name")
dr("Path") = queryObj("Path")
dr("EnableDirBrowsing") = queryObj("EnableDirBrowsing")
dt.Rows.Add(dr)
Next
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
Catch err As ManagementException
Response.Write(err.Message)
End Try
End Sub


To get further in-depth information about the virtual directories, we need to work with the class “IIsWebVirtualDirSettng.” It also has a lot of properties. I selected only the most important ones. I am using another routine to form a structure, to store that property information. The routine is as follows.

Private Function getStruct() As DataTable
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("Name"))
dt.Columns.Add(New DataColumn("Path"))
dt.Columns.Add(New DataColumn("AppPoolId"))
dt.Columns.Add(New DataColumn("EnableDirBrowsing"))
Return dt
End Function

All the columns are indirectly nothing but the properties and the rest is the same as I explained in the first section.

Retrieval Of Virtual Directories In IIS

Retrieving all virtual directories present in IIS using ASP.NET 2.0

This is a bit different from the above coding style. First of all, let us look at the program.

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dt As DataTable = getVirtualRootStruct()
Dim dr As DataRow
Dim searcher As New ManagementObjectSearcher("root\MicrosoftIISv2", "SELECT * FROM IIsWebVirtualDir")
For Each queryObj As ManagementObject In searcher.Get()
dr = dt.NewRow
dr("AppRoot") = queryObj("AppRoot")
dr("Caption") = queryObj("Caption")
dr("Description") = queryObj("Description")
dr("Name") = queryObj("Name")
dr("Status") = queryObj("Status")
dt.Rows.Add(dr)
Next
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
Catch err As ManagementException
Response.Write(err.Message)
End Try
End Sub
To get the virtual directory information, we need to work with the class “IIsWebVirtualDir”. It has got a lot of properties. I just selected only the most important ones. I am using another routine to form a structure, to store that property information. The routine is as follows.


Private Function getVirtualRootStruct() As DataTable
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("AppRoot"))
dt.Columns.Add(New DataColumn("Caption"))
dt.Columns.Add(New DataColumn("Description"))
dt.Columns.Add(New DataColumn("Name"))
dt.Columns.Add(New DataColumn("Status"))
Return dt
End Function

IIS Information Retrieval 1

IIS Information Retrieval Via “IIsWebService,” which gives you much ore information than the previous class which was “IIsWebInfo” class.

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dt As DataTable = getPropertyStruct()
Dim dr As DataRow
Dim searcher As New ManagementObjectSearcher("root\MicrosoftIISv2", "SELECT * FROM IIsWebService")
For Each queryObj As ManagementObject In searcher.Get()

dr = dt.NewRow
dr("Name") = "Name"
dr("value") = queryObj("Name")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "DisplayName"
dr("value") = queryObj("DisplayName")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "PathName"
dr("value") = queryObj("PathName")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "Started"
dr("value") = queryObj("Started")
dt.Rows.Add(dr)


dr = dt.NewRow
dr("Name") = "State"
dr("value") = queryObj("State")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "Status"
dr("value") = queryObj("Status")
dt.Rows.Add(dr)

dr = dt.NewRow
dr("Name") = "SystemName"
dr("value") = queryObj("SystemName")
dt.Rows.Add(dr)

Next
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
Catch err As ManagementException
Response.Write(err.Message)
End Try
End Sub