Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

ISAPI (Internet Server Application Programming Interface) filter

Internet Server Application Programming Interface (ISAPI) is an API developed to provide the application developers with a powerful way to extend the functionality of Internet Information Server (IIS). ISAPI filters always run on an IIS server, filtering every request until they find one they need to process. The ability to examine and modify both incoming and outgoing streams of data makes ISAPI filters powerful and flexible.

Developing a CGI(Common Gateway Interface) program involves creating an EXE with C, C++, and/or Perl programming languages. This EXE file will be executed and terminated for every request received, causing an excessive memory usage, whenever users hit the same page over and over again!

This excessive memory usage that could bring the server completely down, has been solved under ISAPI extensions. An ISAPI extension is a regular DLL file that exposes 3 special functions that is called by the calling process (i.e., IIS) and therefore, will be loaded to memory once, no matter how many clients are going to use it at the same time.

Since the ISAPI extension and the calling process (IIS) live at the same address space, they could contact each other, directly. This means a great potential to bring the whole IIS down, and in some cases, the entire web server! Take a look at the following figure:

Both ISAPI filters and ISAPI extensions can only be developed using C/C++. Visual Studio comes with wizards that make ISAPI development fast and easy.

Uses of ISAPI filters

ISAPI filters can be registered with IIS to modify the behavior of a server. Filters can perform the following tasks:

Change request data (URLs or headers) sent by the client.
Control the user name and password used with anonymous or basic authentication.
Modify or analyze a request after authentication is complete.
Perform custom authentication.
Handle encryption and compression.

NOTE: ISAPI filters DLLs cannot be requested explicitly, like ISAPI extensions can.

References :
http://msdn.microsoft.com/en-us/library/ms524610.aspx
http://www.codeproject.com/KB/ISAPI/isapi_extensions.aspx


Globalization and Localization

Ms. Asha Bora has done some studies on Globalization and Localization.. Lets see what she has to say..

Globalization and localization are very important features of .Net framework, which is very useful and about which every programmer should be aware of while creating an application. If I want my application to be used by everyone then I have to make my interface in a language which everyone can understand or say in a global language. But at the same time it is not possible that everyone in the world knows a particular language. So, in order to make those people use the application, I have to publish it in their regional language or say in their local language, this is known as localization .

From the introduction of the article you must have understood the basic meaning of globalization and localization. Now let’s see a proper definition of it in terms of a programmer.

This very important feature is used by .Net to make our programs universal. Now if we talk in term of programming then GLOBALIZATION can be defined as the process of designing and developing an application that function for multiple cultures and regions, irrespective of the language and regional differences and LOCALIZATION is the process of customizing your application for a given culture and locale. It consists primarily of translating the user Interface according to a culture. Culture will decide date display settings (like, mm/dd/yyyy or dd/mm/yyyy), currency display formats etc.

Now, the process by which we can make sure that our program will be localized is known as Internationalization or Globalization. In simpler terms, Globalization can be defined as the set of activities which will ensure that our program will run in regions with different languages and cultures.

Thus, globalization is related to intrinsic (basic) code changes to support such changes we use Resource files etc. Whereas, localization is the process of using a particular culture and regional info so that the program uses the local languages and culture. This means translating strings into a particular local language. This covers putting language specific strings in the resource files. Globalization starts in the main construction phase along with the code development. Localization generally comes later.

Now let’s see how we define the culture and region code.

We all know that languages depend upon the geographical location. For example, French is spoken in France as well as in Canada (besides many other countries). But linguistically speaking, Canadian French is quite different from French spoken in France. Similarly, there are linguistic differences between US English and British English. Therefore, the language needs to be associated with the particular region where it is spoken, and this is done by using locale (language + location).

For example
: fr is the code for French language. fr-FR means French language in France. So, fr specifies only the language and FR specifies the region France whereas fr-FR is the locale. Similarly, fr-CA defines another locale implying French language and culture in Canada. If we use only fr, it implies a neutral culture (i.e., location neutral).

Now, in order to change the current culture, we have to change two properties of the CultureInfo class- UICulture and Culture.

ASP.NET can set the UICulture and Culture properties for the page to the language and culture values that are passed by the browser. Alternatively, you can set the UICulture and Culture properties explicitly, either declaratively or in code. You can also set the values declaratively in
Web.config file under the property and these two properties can be set using the overloaded constructor of the class and then we can use this class to change the culture of the currently executing program.

UICulture: gets/sets the user interface culture for the currently executing thread. This property helps the runtime to load the resource strings from a specific resource. This property can take neutral cultures as well as locales.
  • Thread.CurrentThread.CurrentUICulture = new CultureInfo(“fr”); OR
  • Thread.CurrentThread.CurrentUICulture = new CultureInfo(“fr-CA”);
Culture: gets/sets the region specific culture and formats of currency, dates etc. This needs language as well as location.
  • Thread.CurrentThread.CurrentCulture = new CultureInfo(“fr-CA”); // we have given locale
  • Thread.CurrentThread.CurrentCulture = new CultureInfo(“fr”); // wrong, will not work
In my next article I will talk about “How to implement Globalization in our application”.

References:

  • http://msdn.microsoft.com/en-us/library/ms227427.aspx
  • http://www.codeproject.com/Kb/aspnet/localizationByVivekTakur.aspx

Jagged Arrays

Our dear friend Ms.Asha Bora has done some studies on the wonderful Jagged Arrays..
Lets see what she has to say..

In this Article I will be discussing about Jagged Arrays. Many of us who are working as a Programmer may not be knowing about it, as I didn't knew it. One of my friends told me about Jagged Arrays. So I thought that I should explore myself on this topic so that people like me can know more about it..

.Net supports two types of Arrays:
Single dimensional arrays(Linear)
Multi-dimensional arrays - These are of two type : Rectangular Arrays and Jagged Arrays

What are Jagged Arrays?

A jagged Array is nothing but a multidimensional array, whose elements are arrays. The elements of an array can be of different dimensions and sizes. A jagged array is also known as “array of arrays”. Following is an example to show the declaration and initialization of jagged array:

i. Declaration : int[][] jaggedArray = new int[3][];
       Over here‘3’shows the number of rows in the array.

ii. Initialization: There are many ways to initialize a jagged array. In the given example each of the element is a single dimensional array.

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[3];


We can also do initialization of the arrays without knowing its size.
For Example :

int[][] jaggedArray2 = new int[][]
{
   new int[] {1,3,5,7,9},
   new int[] {0,2,4,6},
   new int[] {11,22,33}
}
;

We can also do this in the below given way. Notice that we cannot omit the new operator from the elements initialization because there is no default initialization for the elements..

int[][] jaggedArray3 =
{
   new int[] {1,3,5,7,9},
   new int[] {0,2,4,6},
   new int[] {11,22,33}
};

NOTE: A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null. The length property of the array returns the number of arrays contained in the jagged array.

The following C# example will tell us how we can iterate in a jagged array.

class JaggedArray_Test
{
static void Main()
{
// Declare the array of two elements:
int[][] jaggedarr = new int[2][];

// Initialize the elements:
jaggedarr [0] = new int[5] { 3, 9, 15, 21, 27 };
jaggedarr [1] = new int[4] { 6, 12, 18, 24 };

// Display the array elements:
for (int i = 0; i < jaggedarr.Length; i++)
{
System.Console.Write("Element({0}): ", i);

for (int j = 0; j < jaggedarr [i].Length; j++)
{
System.Console.Write("{0}", jaggedarr [i][j]);
System.Console.Write(“ ”);
}
System.Console.WriteLine();
}
}
}
OUTPUT will be: Element(0) 3 9 15 21 27
Element(1) 6 12 18 24

Difference between multidimensional arrays (also known as rectangular arrays) and jagged arrays:

In a multi-dimensional array we have to declare both dimensions. Suppose we want to store the number of months and the days of each month in an array. If we create a multidimensional array then we have to give a fixed size to both the number of rows and column (To store the number of days for the month).But since each month has different number of days thus declaring the fixed size will lead to wastage of memory. Thus in this case we can use jagged arrays, as we don’t need to declare the second dimension of the array. It is enough to declare just the number of rows (to store number of months) in jagged array. The column or say the size of each linear array will vary as per the requirement.

THUS WE CAN SAY Jagged arrays have certain advantages over rectangular arrays. Jagged arrays are more space efficient, since not all rows (in a two-dimensional array) must have the same number of columns. In addition, since each row has its own one-dimensional array, we can easily pass an individual row to a method that requires a one-dimensional array parameter.
We will find working with jagged arrays much easier if you keep in mind that a jagged array is really an array of arrays.

References :
 http://msdn.microsoft.com/en-us/library/2s05feca(VS.80).aspx
 http://www.odetocode.com/Articles/253.aspx
 http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=128


String Equality and Interning

In the previous article on “Strings : Java and C#”, I had discussed the concept of strings, and some common functions for string manipulation. This time, I will be mainly talking on string equality, and about string interning.

So, Lets start with string equality first.. But before starting, keep in mind.. that java or C#.. Strings are nothing but references.

Now.. Because of the transparent optimizations performed by runtime, its very necessary to know when 2 strings are equal. Strings can be compared by comparing string instances, object instances, and their values. The default comparison operations in both C# and Java compare the string's values instead of the object references.

Lets try to understand this by the following C# program.

using System;

public class StringTest
{


public static void Main(string[] args)
{

char[] c = new char[] {'H','e','l','l','o'};
string[] strings = new string[4];
strings[0] = "Hello";
strings[1] = "World";
strings[2] = "Hello";
strings[3] = new string(c);

Console.WriteLine("-----[ Comparing strings using ==
operator of System.String ]-----");
for (int i =0; i < strings.Length; ++i){
for (int j = i+1; j < strings.Length; ++j){

Console.WriteLine("{0} = {1} {2}",i,j,strings[i] ==
strings[j]);
}
}


Console.WriteLine("-----[ Comparing strings using ==
operator of System.Object ]-----");
for (int i =0; i < strings.Length; ++i){
for (int j = i+1; j < strings.Length; ++j){

Console.WriteLine("{0} = {1}{2}",i,j,
(object)strings[i] ==
(object)strings[j]);
}
}


Console.WriteLine("-----[ Comparing String using the Equals
method ]-----");
for (int i =0; i < strings.Length; ++i){
for (int j = i+1; j < strings.Length; ++j){

Console.WriteLine("{0} = {1}{2}",i,j,
strings[i].Equals(strings[j]));
}
}
}
}

The output of above code is :

-----[ Comparing strings using == operator of System.String ]-----
0 = 1 False
0 = 2 True
0 = 3 True
1 = 2 False
1 = 3 False
2 = 3 True
-----[ Comparing strings using == operator of System.Object ]-----
0 = 1False
0 = 2True
0 = 3False
1 = 2False
1 = 3False
2 = 3False
-----[ Comparing String using the Equals method ]-----
0 = 1False
0 = 2True
0 = 3True
1 = 2False
1 = 3False
2 = 3True

In C#, the == operator of the System.Object method compares the references of the objects and returns true if the two references point to the same object, and false otherwise. The == operator is overloaded in the System.String class to compare the value of the strings instead of the actual objects they refer to. Therefore, in example above, strings[3] == strings[0] returns true because they have the same string value. However, when both strings[0] and strings[3] are cast to the object and then compared using the == operator, they return false. This is because strings[3] points to a different string object.

C# also has the Equals method, which is similar in behavior to the == operator. Notice in the output of above code that comparing strings using the Equals method and the overloaded == operator gives the same results.

Java programmers must be particularly careful when dealing with the == operator and C# strings.

Note that in Java the equals method functions the same way as the == operator of C#. The equals method is defined on java.lang.Object, and by default it compares the object references. However, the java.lang.String class overrides the equals method and compares the String values.

Coming to string interning now..

String Interning is a method of storing only one copy of each distinct string value, which must be immutable.
Simply stated: string interning keeps a hashtable of strings while running an application. If a string with the same contents is created, no new heap allocation happens but instead a reference to the existing (identical) string is returned.

String interning is supported by most of the modern object-oriented programming languages, including Python, Ruby (with its symbols), Java and .NET languages.

The single copy of each string is called its 'intern' and is typically looked up by a method of the string class, for example String.intern() in Java, and in C# as well.

String equality and interning is very much related to each other.. Lets see how..

Both Java and C# support String interning, so both the JVM and the CLR create only one object from a String that has the same value. This is an optimization feature so that different String references pointing to the same literal value are internally stored as pointing to the same String object. Interning saves RAM at the expense of more CPU time to detect and replace duplicate Strings. There is only one copy of each String that has been interned, no matter how many references point to it. Because Strings are immutable, the intern process is free to further save space, for example, by not creating a separate String literal for "yoddha" when it exists as a substring of some other literal such as "tech yoddha". It also speeds up the String equality compares. Interned Strings will compare faster even if you use equals instead of ==.

The intern Gotcha

All String literals present at compile time are automatically interned. It is only Strings generated on the fly as the program runs that might not be interned. A nasty side effect of this behaviour is that a program will work fine for some simple cases, but fail on complex ones. The problem comes if you used == to test for String equality where you should have used equals. The wrong code will still work much of the time because most String literals are naturally interned.

Manual Interning

It can be implemented by using intern() method. But its not advised to try and implement interning manually.. The big problem with intern is once you intern a String, you are stuck with it in RAM until the program ends. It is no longer eligible for garbage collection, even if there are no more references to it. If you want a temporary interned String, you might consider interning manually.

However, in the most recent JVMs, the interned string cache is now usually implemented in soft references fashion, so that interned strings may become eligible for garbage collection as soon as they are no longer strongly referenced.

Further References :

• http://book.javanb.com/NET-For-Java-Developers-Migrating-To-Csharp/ 0672324024_ch12lev1sec2.html


• http://mindprod.com/jgloss/interned.html


• http://javatechniques.com/



Strings : Java and C#

In this article, I would be discussing with you the concept of strings.. and what does modern programming languages like Java and C# have in store for String manipulation.

Let's first start with understanding “what is a String".

A string is basically a sequence or a string of Unicode characters. It is one of the most common data types that a programmer deals with. Input validation, text analysis and file conversions are several direct applications of string manipulation.

In some languages such as C, strings are treated as character arrays. Whereas, Java and C#, works with complete strings and treat them as objects.

Let’s now move on to discuss the implementation of strings in java and C#.

Strings in Java :

For string manipulation in java, in java.lang package we have a class called String which extends Object class. String objects are created so as to store character sequences. It may contain null as well.

String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class can extend it. The java.lang.String class differs from other classes. One difference being that the String objects can be used with the += and + operators for concatenation.

A simple String can be created using a string literal enclosed inside double quotes as shown :

String str = "Tech Yoddha";

Or by passing some characters to the constructor like this :

String str = new String("Tech Toddha");

Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.

If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Such strings are said to be interned, meaning that they share a unique String object. The String class maintains a private pool where such strings are interned.

I will be discussing more on String Interning in my upcoming article. As of now, lets continue with String creation..

Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (""), using the string concatenation operator (+).

String class contains many useful methods for string manipulation. Lets see some of the them :

boolean equals(Object obj) and boolean equalsIgnoreCase(String str) : The comparison using equals() is case-sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase( ).

Example:

String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> “+s1.equalsIgnoreCase(s4));

• int length() : This function returns an int which is the number of characters present in a String variable.

Example:

String str = "Tech yoddha";
System.out.println("Length : "+str.length);
//output : 11

• int compareTo(String str) and int compareToIgnoreCase(String str) : This method is used to compare two strings.
It returns 0 if both strings are same,
It returns a negative value if first string is less than the second string and
It returns a positive value if first string is greater than the second string.

Example:

String smaller = "abc";
String greater = "bcd";
If(greater.compareTo(smaller) >0)
System.out.println(greater+" is greater than "+smaller);
else
System.out.println(greater+" is lesser than "+smaller);
// output: bcd is greater than abc

• String replace(char oldChar, char newChar) : This method is used to replace a character with another character throughout the string.

Example:


String s1 = "java" , s2 ;
s2=s1.replace('a','#');
Now a in java is replaced by #. So s2 is referring to j#v#.

• boolean startsWith(String prefix) and boolean endsWith(String suffix) : These two methods are used to check respectively whether the string starts with or ends with a particular character combination.

• String trim() : This method is used to remove leading and trailing spaces from a string object.

There are lot more functions in String class for string manipulation like indexOf(), split(), substring(), toUpperCase(), toLowerCase(), charAt() etc.

You can also use StringBuilder and StringBuffer classes for manipulating strings.

Strings in C# :


C# or Java, the basic concept of string remains the same.

Like Java, in C# also, the string type represents a string of Unicode characters. Here, we have System.String class which we can use for string manipulation.

Lets discuss over String class in C# now.

But before that, I want to tell you something about string and String in C#. Many people think that string with a small 's' is different than String with capital 'S'. But actually string is an alias for System.String in the .NET Framework. That means string is same as String.
So, keep in mind that whether you write string or String, to C# compiler both means the same.

Lets continue with class String now..

The methods and features of System.String is similar to java.lang.String, but there are a few different things here.

In C#, Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.

The + operator concatenates strings like this :

string a = "good " + "morning";

The [] operator accesses individual characters of a string:

char x = "test"[2]; // x = 's';

String literals are of type string and can be written in two forms, quoted and @-quoted.

Quoted string literals are enclosed in double quotation marks ("):
"good morning" // a string literal

@-quoted string literals start with @ and are enclosed in double quotation marks. For example:
@"good morning" // a string literal

The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
@"c:\Docs\Source\a.txt"
// rather than "c:\\Docs\\Source\\a.txt"

To include a double quotation mark in an @-quoted string, double it:
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

You may try this example :

// keyword_string.cs
using System;
class test
{
public static void Main( String[] args )
{
string a = "\u0068ello "; // \u0068 is the unicode
representation for letter “h”.

string b = "world";
Console.WriteLine( a + b );
Console.WriteLine( a + b == "hello world" );
}
}

Rest all the functions are more or less same as that in java.lang.String class.

Thus, we learnt the basic concept of Strings.. and how they are implemented in C# and java.. and also discussed a few places where C# String class varies from java String class.

References :
  • http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
  • http://msdn.microsoft.com/en-us/library/362314fe.aspx
  • http://www.java2s.com/Tutorial/Java/0040__Data-Type/equalsandequalsIgnoreCase.htm

Generics and Legacy Code

My previous article “Generics in Java” was a mere introduction to the generics. You can say that it was just the tip of the ice burg. This time we will go a bit inside generics and discuss about the issues in integrating generic and non-generic code..

Imagine we have an ArrayList, of type Integer, and we're passing it into a method from a class whose source code we don't have access to. Will this work?

// a Java 5 class using a generic collection
import Java.util.*;
public class TestLegacy {
public static void main(String[] args) {
List myList = new ArrayList();
// type safe collection
myList.add(4);
myList.add(6);
Adder adder = new Adder();
int total = adder.addAll(myList) ;
// pass it to an un-typed argument
System.out.println(total);
}
}

The older, non-generics class we want to use:

import Java.util.*;
class Adder {
int addAll(List list) {
// method with a non-generic List argument,
// but assumes (with no guarantee) that it will be Integers
Iterator it = list.iterator();
int total = 0;
while (it.hasNext()) {
int i = ((Integer)it.next()).intValue();
total + = i;
}
return total;
}
}
Yes, this works just fine. You can mix correct generic code with older non-generic code, and everyone is happy.

In that example, method wasn't doing anything except getting the Integer (using a cast) from the list and accessing its value. So, there was no risk to the caller's code, but the legacy method might have blown up if the list passed in, contained anything but Integers (which would cause a ClassCastException).

But now imagine that you call a legacy method that doesn't just read a value but adds something to the ArrayList? Will this work?

import java.util.*;
public class TestBadLegacy {
public static void main(String[] args) {
List myList = new ArrayList();
myList.add(4);
myList.add(6);
Inserter in = new Inserter();
in.insert(myList); // pass List to legacy code
}
}
class Inserter {
// method with a non-generic List argument
void insert(List list) {
list.add(new Integer(42)); // adds to the incoming list
}
}

Sure, this code works. It compiles, and it runs. The insert() method puts an Integer into the list that was originally typed as , so no problem.

But…what if we modify the insert() method like this:

void insert(List list) {
list.add(new String("42")); // put a String in the list passed in
}

Will that work? Yes, sadly, it does! It both compiles and runs. No runtime exception.

How can that be?

Remember, in the older legacy code i.e. before java 5, you were allowed to put anything into a collection. So, in order to support your legacy code, Java 5 compiler is forced to let you to compile your new type safe code, even though your new code invokes an old method of some pre-generics class, which was totally unaware of the type safety.

In the above example with the legacy insert() method that adds a String, the compiler generated a warning:

javac TestBadLegacy.java
Note: TestBadLegacy.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Remember that compiler warnings are NOT considered a compiler failure. The compiler generated a perfectly valid class file from the compilation, but it was kind enough to tell you by saying, in so many words, "I seriously hope you know what you are doing because this old code has NO respect (or even knowledge) of your typing, and can do whatever the heck it wants to your precious ArrayList<>."

The reason the compiler produces a warning is because the method is ADDING something to the collection! In other words, the compiler knows there's a chance the method might add the wrong thing to a collection the caller thinks is type safe.

There's one Big Truth you need to know to understand why it runs without problems—the JVM has no idea that your ArrayList was supposed to hold only Integers. The typing information does not exist at runtime! All your generic code is strictly for the compiler. Through a process called "type erasure," the compiler does all of its verifications on your generic code and then strips the type information out of the class bytecode. At runtime, ALL collection code—both legacy and new Java 5 code you write using generics—looks exactly like the pre-generic version of collections. None of your typing information exists at runtime. In other words, even though you WROTE

List myList = new ArrayList();

By the time the compiler is done with it, the JVM sees what it always saw before Java 5 and generics:

List myList = new ArrayList();

The compiler even inserts the casts for you—the casts you had to do to get things out of a pre-Java 5 collection.

Always keep in mind, even though you are using generics, no type information is available at runtime. The fact is, you don't NEED runtime protection…until you start mixing up generic and non-generic code.

The only advice we have is to pay very close attention to those compiler warnings:


javac TestBadLegacy.java

Note: TestBadLegacy.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

This compiler warning isn't very descriptive, but the second note suggests that you recompile with -xlint:unchecked. If you do, you'll get something like this:


javac -Xlint:unchecked TestBadLegacy.java

TestBadLegacy.java:17: warning: [unchecked] unchecked call to
add(E) as a member of the raw type java.util.List
list.add(new String("42"));
^
1 warning

When you compile with the -Xlint:unchecked flag, the compiler shows you exactly which method(s) might be doing something dangerous. In this example, since the list argument was not declared with a type, the compiler treats it as legacy code and assumes no risk for what the method puts into the "raw" list.


Just remember that the moment you turn that type safe collection over to older, non-type safe code, your protection vanishes. Again, pay very close attention to compiler warnings, and be prepared to see issues like we just discussed….

References:

• Sun Certified Programmer for Java 5 Study Guide by Kathy Sierra and Bert Bates.