Cricinfo Live Scores

Monday, June 16, 2008

Using strings and enum - C# .NET

private enum CarTypes

{
Lotus = 0,
Morgan = 1,
Atom = 2
}

private void button1_Click(object sender, EventArgs e)
{
CarTypes myCarType = CarTypes.Morgan;
textBox1.Text = Enum.GetName(typeof(CarTypes), myCarType) + ", " + myCarType.ToString() + ", " + (myCarType==CarTypes.Morgan).ToString();

myCarType = (CarTypes)Enum.Parse(typeof(CarTypes), "Atom");
textBox1.Text += "\r\n" + Enum.GetName(typeof(CarTypes), myCarType) + ", " + myCarType.ToString() + ", " + (myCarType == CarTypes.Atom).ToString();

myCarType = (CarTypes)Enum.Parse(typeof(CarTypes), "loTus", true);
textBox1.Text += "\r\n" + Enum.GetName(typeof(CarTypes), myCarType) + ", " + myCarType.ToString() + ", " + (myCarType == CarTypes.Lotus).ToString();
}

I have collected this from internet

Thursday, June 5, 2008

Assembly Questions

  1. How is the DLL Hell problem solved in .NET?
    Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  2. What are the ways to deploy an assembly?
    An MSI installer, a CAB archive, and XCOPY command.
  3. What is a satellite assembly?
    When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  4. What namespaces are necessary to create a localized application?
    System.Globalization and System.Resources.
  5. What is the smallest unit of execution in .NET?
    an Assembly.
  6. When should you call the garbage collector in .NET?
    As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.
  7. How do you convert a value-type to a reference-type?
    Use Boxing.
  8. What happens in memory when you Box and Unbox a value-type?
    Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

ADO.NET and Database Questions

  1. What is the role of the DataReader class in ADO.NET connections?
    It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.

  2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
    SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
  3. What is the wildcard character in SQL?
    Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
  4. Explain ACID rule of thumb for transactions.
    A transaction must be:
    1. Atomic - it is one unit of work and does not dependent on previous and following transactions.
    2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
    3. Isolated - no transaction sees the intermediate results of the current transaction).
    4. Durable - the values persist if the data had been committed even if the system crashes right after.
  5. What connections does Microsoft SQL Server support?
    Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
  6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
    Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
  7. What does the Initial Catalog parameter define in the connection string?
    The database name to connect to.
  8. What does the Dispose method do with the connection object?
    Deletes it from the memory.
    To Do: answer better. The current answer is not entirely correct.
  9. What is a pre-requisite for connection pooling?
    Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Debugging and Testing Questions

  1. What debugging tools come with the .NET SDK?
    1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch.
    2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.
  2. What does assert() method do?
    In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  3. What’s the difference between the Debug class and Trace class?
    Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
  4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
    The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.
  5. Where is the output of TextWriterTraceListener redirected?
    To the Console or a text file depending on the parameter passed to the constructor.
  6. How do you debug an ASP.NET Web application?
    Attach the aspnet_wp.exe process to the DbgClr debugger.
  7. What are three test cases you should go through in unit testing?
    1. Positive test cases (correct data, correct output).
    2. Negative test cases (broken or missing data, proper handling).
    3. Exception test cases (exceptions are thrown and caught properly).
  8. Can you change the value of a variable while debugging a C# application?
    Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.

XML Documentation Questions

  1. Is XML case-sensitive?
    Yes.
  2. What’s the difference between // comments, /* */ comments and /// comments?
    Single-line comments, multi-line comments, and XML documentation comments.
  3. How do you generate documentation from the C# file commented properly with a command-line compiler?
    Compile it with the /doc switch
    .

Events and Delegates

  1. What’s a delegate?
    A delegate object encapsulates a reference to a method.
  2. What’s a multicast delegate?
    A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

Method and Property Questions

  1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
    Value. The data type of the value parameter is defined by whatever data type the property is declared as.
  2. What does the keyword “virtual” declare for a method or property?
    The method or property can be overridden.
  3. How is method overriding different from method overloading?
    When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
  4. Can you declare an override method to be static if the original method is not static?
    No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)
  5. What are the different ways a method can be overloaded?
    Different parameter data types, different number of parameters, different order of parameters.
  6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
    Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

Class Questions

  1. What is the syntax to inherit from a class in C#?
    Place a colon and then the name of the base class.
    Example: class MyNewClass : MyBaseClass
  2. Can you prevent your class from being inherited by another class?
    Yes. The keyword “sealed” will prevent the class from being inherited.
  3. Can you allow a class to be inherited, but prevent the method from being over-ridden?
    Yes. Just leave the class public and make the method sealed.
  4. What’s an abstract class?
    A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.
  5. When do you absolutely have to declare a class as abstract?
    1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
    2.
    When at least one of the methods in the class is abstract.
  6. What is an interface class?
    Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
  7. Why can’t you specify the accessibility modifier for methods inside the interface?
    They all must be public, and are therefore public by default.
  8. Can you inherit multiple interfaces?
    Yes. .NET does support multiple interfaces.
  9. What happens if you inherit multiple interfaces and they have conflicting method names?
    It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
    To Do: Investigate
  10. What’s the difference between an interface and abstract class?
    In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
  11. What is the difference between a Struct and a Class?
    Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.

General Questions

# Does C# support multiple-inheritance?
No.

# Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).

# Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

# Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.

# What’s the top .NET class that everything is derived from?
System.Object.

# What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

# What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

# What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

# Can you store multiple data types in System.Array?
No.

# What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

# How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

# What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.

# What class is underneath the SortedList class?
A sorted HashTable.

# Will the finally block get executed if an exception has not occurred?­
Yes.

# What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

# Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).

# Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

Wednesday, June 4, 2008

Google Search Tricks, Tips and Hints (Collected)

Basic Searches

[blue widgets] Finds pages with the words blue and/or widgets on them, in the title, or used in the anchor text to link the page. Words may not be near each other (this is known as proximity).
[
"blue widgets"] Finds pages with the words blue and widgets on them, in the title, or used in the anchor text to link the page. The words must be next to each other and in the exact same order. This type of query is known as an exact phrase match.
[
blue or widgets] Finds pages with the words blue or widgets on them, in the title, or used in the anchor text to link the page.
[
blue and widgets] Finds pages with the words blue and widgets on them, in the title, or used in the anchor text to link the page. Both words must occur in one of the cases, but can occur in any order.
[
blue -widgets] Finds pages with the words blue on them, in the title, or used in the anchor text to link the page. The page, title and anchor text must not have the word widgets in them It’s very important that the minus sign [-] be next to the word without a space. This is known as a negative search term.
[
blue ~widgets] Finds pages with the word blue on them, in the title, or used in the anchor text to link the page. It also returns documents with synonyms for the word next to the tilde [~] (in this case widgets) on the page, in the title or in the anchor text to the page.
[
define: blue] This will give you definitions for the word [blue] and links to pages with definitions.

Compound Searches
Using logical operators like [and] and [or] we can create complex searches. We can create extremely complex searches by combining logical operators using parenthesis. These complex searches can also be combines with ["] and [-] as well.
[
widgets (red OR blue)] Finds pages with the words widgets on them, in the title, or used in the anchor text to link the page. The words blue or red must be on the page, in the title or in the anchor text used to link to the page.
[
widgets (red AND blue)] Finds pages with the word widgets on them, in the title, or used in the anchor text to link the page. The words blue and red must be on the page, in the title or in the anchor text used to link to the page.
[
widgets (red AND blue) -green] Finds pages with the word widgets on them, in the title, or used in the anchor text to link the page. The words blue and red must be on the page, in the title or in the anchor text used to link to the page. The word green must not be on the page, in the title or in the anchor text used to link to the page.
Lets say you wanted to do a search for people who haven’t posted or updated their blog in a while, here’s how you would create that query [
"haven't (updated OR posted)" and blog]

Search Modifiers
Google has a series of search modifiers that allow you to perform very specific searches, these include [inanchor], [intext], [intitle], and [inurl]. In addition you can also add the word [all] in front of each term to include all of the words in the phrase. These modifiers can also be combined with the ["] , [-], and logical operators and be used to create complex queries.
[
inanchor:blue widgets] Returns pages where the words blue is used by other pages or websites to link to the page, and have the word widgets on the page, in the title, or in the anchor text used to link to the page.2
[allinanchor:blue widgets] Returns pages where the words blue and widgets are used by other pages or websites to link to the page.
[
intitle:blue widgets]Returns pages where the word blue is used in the title, and the word widgets is on the page, in the title, or in the anchor text used to link to the page.
[
allintitle:blue widgets]Returns pages with the words blue and widgets are in the title.
[
inurl:blue widgets]Returns pages where the word blue is used in the URL, and the word widgets is on the page, in the title, or in the anchor text used to link to the page.
[
allinurl:blue widgets]Returns pages with the words blue and widgets are in the URL.
Lets say you were looking for pages about cookbooks where people used the words celebrity to link to them here is a query you might construct [
cookbooks inanchor:celebrity]
Lets refine that query taking out all the bad, horrible, and terrible cookbooks with this query [
cookbooks -bad -horrible -terrible inanchor:celebrity]
Now lets refine it once more to find only cookbooks with recipes from your favorite movie star Alicia Silverstone in them [
cookbooks "alicia silverstone" -bad -horrible -terrible inanchor:celebrity]

Restrictive Searches
Google also has restrictive searches that allow you to limit the sites or information that you are searching for.
[
soccer site:whitehouse.gov] Will return only documents from the site whitehouse.gov with the word soccer on the page, in the title or in the anchor text that links to the page.
[
intitle:soccer site:whitehouse.gov] Will return only documents from the site whitehouse.gov with the word soccer in the title.
[
ipod $100..$150] Will return pages with the word IPod on the page, in the title, or anchor text linking to the page, and with dollar amounts between $100 and $150 on the page, in the title, or in the anchor text linking to the web page.
[
ipod $100..$150 "in stock"] Will return pages with the word IPod, and “in and stock” on the page, in the title, or anchor text linking to the page, and with dollar amounts between $100 and $150 on the page, in the title, or in the anchor text linking to the web page.
[
ipod $100..$150 "in stock" -shuffle (green OR blue)] Will return pages with the word IPod, and “in and stock” on the page, in the title, or anchor text linking to the page, and with dollar amounts between $100 and $150 on the page, in the title, or in the anchor text linking to the web page. The word shuffle must not be on the page, in the title or anchor text, and the page, title or anchor text must contain either the word green or blue.
[
telescope filetype:pdf] Will return only PDF files with the word telescope on the document, in the title or in the anchor text to the document. Filetypes can be any of the following: Adobe Portable Document Format (pdf), Adobe PostScript (ps), Lotus 1-2-3 (wk1, wk2, wk3, wk4, wk5, wki, wks, wku), Lotus WordPro (lwp), MacWrite (mw), Microsoft Excel (xls), Microsoft PowerPoint (ppt), Microsoft Word (doc), Microsoft Works (wks, wps, wdb), Microsoft Write (wri), Rich Text Format (rtf), Shockwave Flash (swf), Text (ans, txt).
[
telescope filetype:pdf intitle:dobsonian 2004..2005] Will return only PDF files with the word telescope on the document, in the title or in the anchor text to the document. The title must contain the word Dobsonian and the document will contain numbers from 2004 through 2005.
[
link:whitehouse.gov] Provides a completely random sampling of some sites that link to whitehouse.gov. There is no logic or reason to the sites displayed or the order they are displayed in. Many sites that link to you will not be displayed. This search is considered “broken”.
[
info:whitehouse.gov]Provides links to information and searches about the website whitehouse.gov.
[
cache:whitehouse.gov] Displays a copy of the page stored on Google’s server. This may vary from the actual page on the website.

Specialized Searches
Google has a number of specialized searches that search through a small subset of data for highly relevant results.
[
phonebook: gibson NY] Will return a sampling of business and residential listings with the word gibson in the name, town or street that are in New York.
[
bphonebook: gibson NY]Will return a business listings with the word gibson in the name, town or street that are in New York.
[
rphonebook: gibson NY]Will return a residential listings with the word gibson in the name that are in New York.
[
movie:Goblet of Fire] Will return pages about the Goblet of Fire, contain the words Goblet of Fire . Has links to reviews about the Goblet of Fire and movie show times.
[
movie: flux capacitor] Will return pages about movies with the words flux capacitor on them.
[
stocks:goog] Will return information about the stock with the symbol GOOG.
[
weather las vegas NV] Will give the local weather for Las Vegas Nevada.
[
fly JFK LAX] Links to flight information from JFK airport to LAX airport.
[
fly new york to los angeles] Link to flight information from New York to Los Angeles
[
jetblue 189] Provides a direct link to the status of Jet Blue Airlines flight 189.
[
frank zappa] Links to More information about Frank Zappa, albums, and other information. This is sometimes hit or miss depending on the artist.
[
related:whitehouse.gov] Returns links to other pages that are about similar topics or information. Some of these sites will have links that exist between them others will not. In some cases this may show direct competition, for example [related:walmart.com]
[
1600 pennsylvania avenue washington dc] This is an address search and provides a direct link to Google Map for the address.

Fact Searches
This category provides you with immediate answers to a specific narrow set of questions. It’s a bit of hit or miss here but here are some examples.
[
gdp malta] Gross Domestic Product of Malta
[
population malta] Population of Malta.
[
capital malta] The capital of Malta.
[
location malta] Rough idea of where Malta is located.
[
currency malta] What is the currency of Malta.
[
flag france] The flag of France. Note there was no flag shown for Malta.
[
anthem france] What is the national anthem of France.
[
state bird hawaii] What is the state bird of Hawaii.
[
state flower hawaii] State flower of Hawaii.
[
motto hawaii] what is the state motto of Hawaii.
[
size hawaii]
[
governor hawaii] The governor of Hawaii.
[
birthplace of walt disney] Where Walt Disney was born.

Math and Number Searches
[100+37+92+641-7] Works like a calculator to perform math operations.
[
how many teaspoons in a tablespoon] Provides the answer to measurement conversions.
[
convert 300 yen to dollars] Provides currency conversion
[
1Z9999W99999999999] Provides a link to UPS tracking information.
[
790187289080] Provides a link to Fed Ex tracking information.
[
0103 8555 7493 2721 4413] Provides a link to USPS tracking information.
[
1HD1BEK11BY123456]Provides a link to VIN (Vehicle Identification Number) information.
[
073333531084]Provides a link to UPC information for that product.
[
212] Provides a link to information about the area code 212.
[
202-456-1111]Provides a link to more information about the residence, business, or organization for that phone number.
[
patent 5123128]Provides a link to more information about patent number 5123128.
[
n199ud] Provides a link for more information about the FAA registration for the airplane with that registration number.
[
fcc IHDT5ZG1]Provides a link to information about the product with that FCC id number

Tuesday, June 3, 2008

Spring .NET 3 Tier Application Architecture


1. Introduction
This document will help to kick start the design of SPRIG .NET based applications. In this document we will describe about prototype application architecture and all details about the architecture.
2. Application Architecture
A common 3-tier application will be discussed in this document.
· UI
· Facade
· BO
· DAO
· NHibernate
· SQL Server 2005
2.1 UI
Here UI is implemented in ASP .NET 2.0. Very common design


We do have a list of names and from the list when one will be selected then its detail will be displayed in the side. Next, we can change and update information. We can delete a selected one and if we need we can add a new one to the list too.
2.2 Facade
Facade of this application is the gateway to the buisness part. For example we have the following code
using System;
using System.Collections;
using System.Text;
using Entity;
using BO;

namespace Common
{
public class Facade
{
private IssueBO m_IssueBO;

public IssueBO IssueBO
{
get { return m_IssueBO; }
set { m_IssueBO = value; }
}

public IList AllIssue()
{
return IssueBO.AllIssue();
}

public Issue IssueById(long lIssueId)
{

return IssueBO.IssueById(lIssueId);
}

public void SaveIssue(Issue oIssue)
{
IssueBO.SaveIssue(oIssue);
}

public void UpdateIssue(Issue oIssue)
{
IssueBO.UpdateIssue(oIssue);
}

public void DeleteIssue(long lIssueId)
{
IssueBO.DeleteIssue(lIssueId);
}

}
}

Here IssueBO is our buisness object. If we want to disable a service from the solution we can just comment it from the Facade class.
2.3 BO
Our buisness part is something like this
using System;
using System.Collections;
using System.Text;
using Entity;
using DAO;

namespace BO
{
public class IssueBO
{

private IIssueDAO m_IssueDAO;

public IIssueDAO IssueDAO
{
get { return m_IssueDAO; }
set { m_IssueDAO = value; }
}


public IList AllIssue()
{
return (IList)IssueDAO.LoadAll();
}

public Issue IssueById(long lIssueId)
{

return IssueDAO.LoadByID(lIssueId);
}

public void SaveIssue(Issue oIssue)
{
IssueDAO.Save(oIssue);
}

public void UpdateIssue(Issue oIssue)
{

IssueDAO.Update(oIssue,oIssue.Id);
}

public void DeleteIssue(long lIssueId)
{
IssueDAO.Delete(lIssueId);
}
}
}

We do have an Interface object which contains the DAO object for this buisness class.
2.4 DAO
Here One IBaseDAO interface is created which is a Generic solution.
using System;
using System.Collections.Generic;
using System.Collections;

namespace DAO
{
public interface IBaseDAO
{
IList LoadAll();
EntityT LoadByID(idT id);
IList Load(string hsqlQuery, object[] values);
void Save(EntityT fine);
void Update(EntityT fine, idT id);
void Delete(idT id);
NHibernate.ISessionFactory SessionFactory { set; }
}
}

An abstract BaseDAO implements the IBaseDAO interface generically.
using System;
using System.Collections.Generic;
using System.Text;
using Spring.Data.NHibernate;
using NHibernate;
using System.Collections;
using Entity;

namespace DAO
{
public abstract class BaseDAO : IBaseDAO
{
protected HibernateTemplate hibernateTemplate;

public BaseDAO()
{
}

public ISessionFactory SessionFactory
{
set
{
hibernateTemplate = new HibernateTemplate(value);
hibernateTemplate.TemplateFlushMode = TemplateFlushMode.Auto;
}
}

public virtual EntityT LoadByID(idT id)
{
EntityT entity = (EntityT)hibernateTemplate.Load(typeof(EntityT), id);
hibernateTemplate.Evict(entity);
hibernateTemplate.Flush();
return entity;
}

public virtual IList LoadAll()
{
return hibernateTemplate.LoadAll(typeof(EntityT));
}

public virtual IList Load(string hsqlQuery, object[] values)
{
return hibernateTemplate.Find(hsqlQuery, values);
}

public virtual void Save(EntityT fine)
{
IEntity entity = (IEntity)fine;
hibernateTemplate.Save(entity);
hibernateTemplate.Flush();
}

public virtual void Update(EntityT fine, idT id)
{
EntityT entity = (EntityT)hibernateTemplate.Load(typeof(EntityT), id );
hibernateTemplate.Evict(entity);
hibernateTemplate.Flush();
hibernateTemplate.Update((IEntity)fine);
hibernateTemplate.Flush();
}


public virtual void Delete(idT id)
{
EntityT entity = (EntityT)hibernateTemplate.Load(typeof(EntityT), id);
hibernateTemplate.Evict(entity);
hibernateTemplate.Flush();
hibernateTemplate.Delete(entity);
hibernateTemplate.Flush();
}

}
}

And following is a DAO which has an IIssueDAO interface to maintain constraints. IssueDAO implements the interface and extends the BaseDAO class.

using System;
using System.Collections.Generic;
using System.Text;
using Entity;

namespace DAO
{
public interface IIssueDAO : IBaseDAO
{
}

public class IssueDAO : BaseDAO, IIssueDAO
{
}

}

2.5 Nhibernate
Here is the issue.hbm.xml file.

namespace="Entity" assembly="Entity">
























Here is the Issue Entity


using System;
using System.Collections.Generic;
using System.Text;

namespace Entity
{
public class Issue:IEntity
{
private string m_Name;
private string m_Description;
private bool m_IsActive;
private long m_Id;

//These methods should be virtual for NHibernate Mapping

public virtual long Id
{
get { return m_Id; }
set { m_Id = value; }
}

public virtual string Name
{
get { return m_Name; }
set { m_Name = value; }
}

public virtual string Description
{
get { return m_Description; }
set { m_Description = value; }
}

public virtual bool IsActive
{
get { return m_IsActive; }
set { m_IsActive = value; }
}

}

}
Issue.hbm.xml and Issue Entity mapped to give the serive of ORM for Issue Table in the databse.

2.6 Sql Server 2005
Here is the Issue Table information for the database.


3. Spring .NET
Spring .NET is implemented using change in the web.config file. The structure of the file is maintained in this way.

Here in the spring folder there is
Aspects.xml, Bo.xml, Dao.xml, Facade.xml, Services.xml, Transaction.xml, Web.xml and web.config holds the total thing together.
Web.config file selects the above xml as its object context.
Projects contain the following library files too


3.1 Web.config
When aspx request comes from the browser to the application deployed server. Then it will be dispatched the spring.web part.

Then, aspx file will inject dependecy for its page. Next facade will inject dependency, next BO will inject dependency and set transaction manager for the DAO object.
3.2 Web.xml
Each aspx file will have the Facade Property. And all the service required for the web page will he given throgh the facade class.


Here is the content of spring/web.xml file. The Dependecy injection for the aspx page will be added.


3.3 Facade.xml
Here all those BO of the facade class will injected. And, facade is managed as singleton here. So that it can be treated as class service.


3.4 BO.xml
Here for a BO class there is a DAO property and it will have the Transaction object IssueDAOTx. It is the built in service for transaction management of spring .net application.


3.5 DAO.xml
Here is the DAO xml for the spring .net application. Here hmb files and the entity classes will be mapped. Hibernate properties and session factory is created here. Changing the database server is managed here. If we want to change the Database server from MSSQL to (Oracle, MySQL etc) then we need to change the dialect and the driver. And, we should have the database provider dll for the Nhibernate. Here we have used Spring.data.Nhibernate12.dll.


3.6 Transaction.xml
It contains all the transaction settings for the DAO classes.

3.7 Aspects.xml, Services.xml
Aspects will be used for incorporating customized AOP to the application. Services will contain the xml configuration for the web service part of the application.
4. Result

Output of the total solution architecture yields

:):):)::::::::::) I will try to improve my writing later


Change the Default Location of the My Documents Folder

Change the Default Location of the My Documents Folder

To change the default location of the My Documents folder, follow these steps:
1.Click Start, and then point to My Documents.
2.Right-click My Documents, and then click Properties.
3.Click the Target tab.
4.In the Target box, do one of the following:
Type the path to the folder location that you want, and then click OK. For example, D:\My Stuff.

If the folder does not exist, the Create Message dialog box is displayed. Click Yes to create the folder, and then click OK.

-or-
Click Move, click the folder in which to store your documents, and then click OK twice.

If you need to create a new folder, click Make New Folder. Type a name for the folder, and then click OK twice.
5.In the Move Documents box, click Yes to move your documents to the new location, or click No to leave your documents in the original location.

Tuesday, April 1, 2008

SIX THINKING HATS

Edward de Bono´s SIX THINKING HATS

WHITE :: Facts, Data, Figures
BLACK :: Critic, Analysis
BLUE: Global, Agenda, Decision, Overview
GREEN: Creative, Growth, Ideas
RED: Emotions, Hunches, Feelings(Gut), Insticts
YELLOW: Logical, Positive

Saturday, March 29, 2008

Restrict Keys in vba textbox

Hi, when i went to work out with my VBA application then i faced a problem of restricting
key press in my price textbox. So, i went on searching and searching in the internet. And
at last found a solution to it. Take a look on it.

Private Sub txtMasterPrice_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case Asc("0") To Asc("9")
Case Asc("-")
If InStr(1, txtMasterPrice.Text, "-") > 0 Or txtMasterPrice.SelStart > 0 Then
KeyAscii = 0
End If
Case Asc(".")
If InStr(1, txtMasterPrice.Text, ".") > 0 Then
KeyAscii = 0
End If
Case Else
KeyAscii = 0
End Select
End Sub

Saturday, March 22, 2008

VBA: 255 string length problem

I had a very strange experience with my VBA application of MIS.
Two days past away but there was no solution for this problem.
The problem was my query length was crossing 255 characters length
and i was receiving error in the vba.

But, most interesting thing after a long investigation i discovered that
actually string length is not fixed to 255. Actually vba does not have
such kind of problems.

The problem was that i was using debugger to go through my logic paths
as i always do when testing application result; i was just investigating
my string length the debugger.

And, every time it was limited to 255 chars. Very unusual! When i get bored
and let the program to run for anything then i saw that my operation was
successful.

So, i come to the solution there is no problem with string length in VBA. Actually
debugger is not able to show you the string value over 255 chars.

It was a happy moment for me. So much pain i had gone through for that string......

Happy Programming.

Author
Kazi Masudul Alam
Software Engineer

Wednesday, March 19, 2008

xml and xsl

So, after a long time again in my little newspaper.

XSL stands for EXtensible Stylesheet Language.

The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML-based style sheet language.

XSLT stands for XSL Transformations. In this tutorial you will learn how to use XSLT to transform XML documents into other formats, like XHTML.

Let us go for """xsl:template""" . It is a very nice tool of xsl which takes a lot of pressure out of
your head. I will show you some smart implementation of this.

Here are 3 source files. You can download and run the xml in your browser. Go through it carefully and learn about the "template-match" http://www.w3schools.com/xsl/default.asp.
And compare it with the source files. It will be a nice experience.

topic.xml
topic.xsl
ui.xsl

Sunday, March 16, 2008

Struts 2: Basic Application

You can learn struts-2 from http://www.roseindia.net.

Here is a basic application for struts 2 the startup application for

Download the source code from here

Saturday, March 1, 2008

Design Pattern (GOF): Structural Pattern : Bridge

Definition

Decouple an abstraction or interface from its implementation so that the two can vary independently.

Where to use & benefits

Examples

If you have a question database, you may want to develop a program to display it based on the user selection. The following is a simple example to show how to use a Bridge pattern to decouple the relationship among the objects.

import java.util.*;

//abstraction
interface Question {

public void nextQuestion();
public void priorQuestion();
public void newQuestion(String q);
public void deleteQuestion(String q);
public void displayQuestion();
public void displayAllQuestions();
}

//implementation
class QuestionManager {

protected Question questDB; //instantiate it later
public String catalog;

public QuestionManager(String catalog) {
this.catalog = catalog;
}

public void next() {
questDB.nextQuestion();
}

public void prior() {
questDB.priorQuestion();
}

public void newOne(String quest) {
questDB.newQuestion(quest);
}

public void delete(String quest) {
questDB.deleteQuestion(quest);
}

public void display() {
questDB.displayQuestion();
}

public void displayAll() {
System.out.println("Question Catalog: " + catalog);
questDB.displayAllQuestions();
}
}


//further implementation
class QuestionFormat extends QuestionManager {

public QuestionFormat(String catalog){
super(catalog);
}

public void displayAll() {

System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~");
super.displayAll();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
}
}

//decoupled implementation
class JavaQuestions implements Question {

private List questions = new ArrayList();
private int current = 0;

public JavaQuestions() {
//load from a database and fill in the container
questions.add("What is Java? ");
questions.add("What is an interface? ");
questions.add("What is cross-platform? ");
questions.add("What is UFT-8? ");
questions.add("What is abstract? ");
questions.add("What is Thread? ");
questions.add("What is multi-threading? ");

}

public void nextQuestion() {
if( current <= questions.size() - 1 )
current++;
}

public void priorQuestion() {
if( current > 0 )
current--;
}

public void newQuestion(String quest) {
questions.add(quest);
}

public void deleteQuestion(String quest) {
questions.remove(quest);
}

public void displayQuestion() {
System.out.println( questions.get(current) );
}

public void displayAllQuestions() {
for (String quest : questions) {
System.out.println(quest);
}
}
}


class TestBridge {
public static void main(String[] args) {

QuestionFormat questions = new QuestionFormat("Java Language");

questions.questDB = new JavaQuestions();//can be hooked up with other question class
//questions.questDB = new CsharpQuestions();
//questions.questDB = new CplusplusQuestions();

questions.display();
questions.next();

questions.newOne("What is object? ");
questions.newOne("What is reference type?");

questions.displayAll();
}
}

Author
Kazi Masudul Alam

Wednesday, February 27, 2008

Design Pattern (GOF): Structural Pattern : Builder

Definition

Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in one application. Also known as Wrapper pattern.

To reuse classes and make new class compatible with existing ones. For example, A clean system is already designed, you want to add more job in, the Extra interface uses adapter pattern to plug in the existing system.

Example

interface Clean {
public void makeClean();
}
class Office implements Clean{
public void makeClean() {
System.out.println("Clean Office");
}
}
class Workshop implements Clean{
public void makeClean() {
System.out.println("Clean Workshop");
}
}

interface Extra extends Clean{
public void takeCare();
}
class Facility implements Extra{
public void makeClean() {
System.out.println("Clean Facility");
}
public void takeCare() {
System.out.println("Care has been taken");
}
}
In order to reuse Workshop and Office classes,
we create an adapter interface Extra and
add new job takeCare in the system.

class Test {
static void Jobs (Extra job) {
if (job instanceof Clean)
((Clean)job).makeClean();
if (job instanceof Extra)
((Extra)job).takeCare();
}
public static void main(String[] args) {
Extra e = new Facility();
Jobs(e);
Clean c1 = new Office();
Clean c2 = new Workshop();
c1.makeClean();
c2.makeClean();
e.makeClean();
}
}
Author
Kazi Masudul Alam

Sunday, February 24, 2008

Returning more than one value from a function

A function can only have one return value. In Access 2, there were a couple of ways to work around this limitation:
  • Use a parameter to define what you want returned. For example:
    Function MultiMode(iMode As Integer) As String
    Select Case iMode
    Case 1
    MultiMode = "Value for first Option"
    Case 2
    MultiMode = "Value for second Option"
    Case Else
    MultiMode = "Error"
    End Select
    End Function
  • Another alternative was to pass arguments whose only purpose was so the function could alter them:
    Function MultiArgu(i1, i2, i3)
    i1 = "First Return Value"
    i2 = "Second Return Value"
    i3 = "Third Return Value"
    End Function

VBA (Access 95 onwards) allows you to return an entire structure of values. In database terms, this is analogous to returning an entire record rather than a single field. For example, imagine an accounting database that needs to summarize income by the categories Wages, Dividends, and Other. VBA allows you to declare a user-defined type to handle this structure:

    Public Type Income
Wages As Currency
Dividends As Currency
Other As Currency
Total As Currency
End Type

You can now use this structure as the return type for a function. In a real situation, the function would look up your database tables to get the values, but the return values would be assigned like this:

    Function GetIncome() As Income
GetIncome.Wages = 950
GetIncome.Dividends = 570
GetIncome.Other = 52
GetIncome.Total = GetIncome.Wages + GetIncome.Dividends + GetIncome.Other
End Function

To use the function, you could type into the Immediate Window:

    GetIncome().Wages

(Note: the use of "Public" in the Type declaration gives it sufficient scope.)

Programmers with a background in C will instantly recognize the possibilities now that user-defined types can be returned from functions. If you're keen, user-defined types can even be based on other user-defined types.


Collection
Kazi Masudul Alam

Changing Array Size

When you want to declare array in VBA and change the array size
you can go like this.

Dim list1() as String

When you want to first use it, set the size:

Redim List1(10)

When you want to change size and lose the contents

Redim List1(20)

If you want to increase size and retain the contents

Redim Preserve List1(30)

Author
Kazi Masudul Alam

OOA/OOD/OOP

Object-Oriented Analysis

  • It's general, and thus reusable.
  • Information access is enough. Objects that don't need information can't get to it. Objects that do need information can get to it (i.e., either they have it, or they have an instance variable that points to an object that has it.)
  • Responsibility, control, and communication is distributed. One object doesn't do everything. Makes it easier to reuse, easier to develop and manage.
  • Minimize assumptions of language or system. Try to describe the world, not a program.
  • Define objects not functions or managers. Objects are nouns.
  • Don't include things you don't need, even if it is part of the real world. Sure, everything is made up of molecules, but you probably don't need a molecules class.
  • Good hierarchy is always linked by IsA relationships.
  • Attributes and services should be factored out as high in the hierarchy as possible.
  • It should be easy to add on to, and thus reusable.
  • There should be little or no redundancy.
  • Again, objects are NOUNS.

Object-Oriented Design

  • Implementable. You can see how you'd write code from here.
  • Complete. It's obvious that the OOA is right because everything you need to do is (1) covered in the OOD and (2) matches the OOA.
  • Removes unnecessary middlemen. If A needs to reach B, but can only do it through C...think about allowing A to reach B directly.
The idea is that the OOD is where you patch the pieces together, where you make sure that messages are caught, important information is known at the right places, that all the important services are accounted for.

Object-Oriented Programming

  • NEVER change a reused class! Use subclasses.
Collection
Kazi Masudul Alam
Software Engineer

Wednesday, February 20, 2008

Excel VBA Variables Lifetime & Scope


In Excel, when coding in VBA, we can use what are know as variables to store information. These variables (as the name suggests) can be varied and changed to store different data information. As soon as a variable loses scope it loses its stored value.

Excel VBA Variables Levels

There are 3 levels at which we can dimension (Dim) variables. These are;

1) Procedure-Level
2) Module-Level
3) Project-Level, Workbook Level, or Public Module-Level

Each of these levels differ in scope and lifetime. This is discussed below

Procedure-Level Variables

These are probably the best known and widely used variables. They are dimensioned (Dim) inside the Procedure itself. See Example below;

Sub MyMacro ()
Dim lRows as Long
'Code Here
End Sub

All variables dimensioned at this level are only available to the Procedure that they are within. As soon as the Procedure finishes, the variable is destroyed.

Module-Level Variables

These are variables that are dimensioned (Dim) outside the Procedure itself at the very top of any Private or Public Module. See Example below;

Dim lRows as Long

Sub MyMacro ()

'Code Here
End Sub

All variables dimensioned at this level are available to all Procedures that they are within the same Module the variable is dimensioned in. Its value is retained unless the Workbook closes or the End Statement is used.

Project-Level, Workbook Level, or Public Module-Level

These variables are dimensioned at the top of any standard public module, like shown below;

Public lRows as Long

All variables dimensioned at this level are available to all Procedures in all Modules. Its value is retained unless the Workbook closes or the End Statement is used.

Author

Kazi Masudul Alam

Tuesday, February 19, 2008

JavaScript Events

JavaScript Events are items that transpire based on an action. A document event is the loading of an HTML document. A form event is the clicking on a button. Events are objects with properties.

Event Properties

  • x -Mouse x coordinate when the event happened.
  • y -Mouse y coordinate when the event happened.

JavaScript defines five types of events which are form, image, image map, link, and window events. Events are associated with HTML tags. The definitions of the events described below are as follows:

Form Events

  • blur - The input focus was lost.
  • change - An element lost the focus since it was changed.
  • focus - The input focus was obtained.
  • reset - The user reset the object, usually a form.
  • select - Some text is selected
  • submit - The user submitted an object, usually a form.

Image Events

  • abort - A user action caused an abort.
  • error - An error occurred.
  • load - The object was loaded.

Image Map Events

  • mouseOut - The mouse is moved from on top a link.
  • mouseOver - The mouse is moved over a link.

Link Events

  • click - An object was clicked.
  • mouseOut - The mouse is moved from on top a link.
  • mouseOver - The mouse is moved over a link.

Window Events

  • blur - The input focus was lost.
  • error - An error occurred.
  • focus - The input focus was obtained.
  • load - The object was loaded.
  • unload - The object was exited.
Author
Kazi Masudul Alam

Introduction to AJAX

Description: Everybody till now must have atleast heard about AJAX (Asynchronous JavaScript And XML). This example will give you an idea about how you can implement simple AJAX interaction in your web application.

Purpose of using AJAX

The main purpose of using AJAX is to asynchronously get the information from the server and update only that area of the web page where this information fetched needs to be displayed, avoiding refresh of the entire page. The other advantage of this is, the web page can hold minimal required data and retrieve rest as needed based of events.

How is all this possible.

Its possible by writing a JavaScript code in your web application, which uses XMLHttpRequest object to communicate with the server and get the data asynchronously.

The first step is to create and configure the XMLHttpRequest object.

  • Currently there are two implementations of this object, ActiveXObject is Internet ExplorerXMLHttpRequest works with other browsers. So a check is made before creating the object, like this,

    var httpRequest;
    specific, and
    if (window.ActiveXObject) // for IE
    {
    httpRequest
    = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) // for other browsers
    {
    httpRequest
    = new XMLHttpRequest();
    }
  • Now configure the object by setting the HTTP method, GET or POST, the URL of the server side element, like a servlet or cgi script, which this object will communicate with, and the third parameter is a boolean value which decides whether the interaction should be synchronous or asynchronous, where true means asynchronous.

    httpRequest.open("
    GET", url, true);
  • Then set the name of the JavaScript function, which will handle the callback from the server side element.

    httpRequest.onreadystatechange
    = function() {processRequest(); } ;
  • Now make the call,

    httpRequest.send(
    null);

Second step is to handle the response from the server which is always in XML form.

The server element can return the actual data in XML form or the formatted HTML code. This processing is done in the JavaScript function, which is specified as the callback function. The first thing to do in this method is to check the XMLHttpRequest object's readyState, value 4 indicates that the call is complete. Then check for the status, which is the HTTP status code, value 200 means HTTP is successful. Following is how the method looks,

function processRequest()
{
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
//process the response
}
else
{
alert("
Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
}
}
}

The third step is to process the response received.

The response is stored in responseText of the XMLHttpRequest object. The response is always in the XML form and the object representation of this XML is stored in responseXML
Following code shows how this is done.

of the XMLHttpRequest object. This XML can be parsed in the JavaScript itself using the DOM API to obtain the actual data.
//The method getElementsByTagName, gets the element defined by the given tag
var profileXML
= httpRequest.responseXML.getElementsByTagName("Profile")[0];

//The node value will give you actual data
var profileText
= profileXML.childNodes[0].nodeValue;

Once we get the actual data, now the last step is to update the HTML.

The way to do that is by modifying the DOM (Document Object Model) of the HTML page. This can be done within JavaScript using the DOM API. JavaScript can get access to any element in the HTML DOM and modify it after the HML is loaded. This ability to dynamically modify the HTML DOM object within JavaScript plays very important role in AJAX interaction. The document.getElementById(id) method is used to get reference of the element in DOM. Where id, is the ID attribute of the element you want to modify. In this example the element is DIV with the ID attribute "profileSection".
Following code shows how to modify this DOM element with the data received,

//Create the Text Node with the data received
var profileBody
= document.createTextNode(profileText);

//Get the reference of the DIV in the HTML DOM by passing the ID
var profileSection
= document.getElementById("profileSection");

//Check if the TextNode already exist
if(profileSection.childNodes[0])
{
//If yes then replace the existing node with the new one
profileSection.replaceChild(profileBody, profileSection.childNodes[
0]);
}
else
{
//If not then append the new Text node
profileSection.appendChild(profileBody);
}

How does web page interact with this JavaScript

To tie this interaction with your web page, you need to first identify the part of your web page which will be updated dynamically and mark it with DIV tag and provide it an id, like,

="profileSection">



Identify what event will update the marked area, like clicking on a link, mouseover a image etc. trap this events using JavaScript and call the JavaScript function which creates the XMLHttpRequest object.

What does server side element need to take care of?

While sending the response back the server should set the Content-Type to text/xml, since the XMLHttpRequest object will process this type of request. Also you can set the Cache-Control to no- cache to avoid the browser caching the response locally. The server should always send back data in XML format. The data should be a valid XML format and parse able by the JavaScript. If your data contains characters not friendly with the XML parsers, use the CDATA section in your XML

Author
Kazi Masudul Alam

Deployment of WebLogic Server Applications

Weblogic directory structure or deployment of weblogic server application, the best article is

Deployment of Weblogic Server Application

JBoss Directory Structure

The binary distribution unpacks into a top-level JBoss install directory, often referred to as the JBOSS_DIST directory. There are four sub-directories immediately below this:

NOTE: Some directories are dynamically created when you start JBoss. Some directories may not exist in older versions.

  • bin: contains various scripts and associated files. This is where the run and shutdown scripts, which start and stop JBoss, reside.
  • client: stores configuration and jar files which may be needed by a Java client application or an external web container. You can select archives as required or use jbossall-client.jar.
  • docs: contains useful information
    • docs/dtd: contains the XML DTD used in JBoss for reference (these are also a useful source of documentation on JBoss configuration specifics).
    • examples: contains optional configurations:
      • bindingmanager: example configuration for the binding service for running multiple copies on jboss with different ports on the same machine.
      • jca: example JCA configuration files for setting up datasources for different databases (such as MySQL, Oracle, Postgres) and access to legacy EIS systems.
      • jms: example configurations for different jbossmq persistence, state manager and connection factorys
        • standalone: a script to make a minimal jbossmq server configuration
      • jmx: additional and legacy management deployments
      • netboot: a web application used when netbooting jboss
      • remoting: an early access of the remoting service from JBoss4
      • tomcat: scripts for installing different versions of Tomcat
      • varia: additional services
        • loadbalancer: a deployment for running jboss as a http loadbalancer
  • lib: jar files which are needed to run the JBoss microkernel. You should never add any of your own jar files here.
  • server: each of the subdirectories in here is a different server configuration. The configuration is selected by passing the option -c to the run script.
    • : a server configuration started with the -c option
      • conf: configuration files including the bootstrap services in jboss-service.xml
        • props: default users/roles properties files for the jmx console (from 4.0.2)
        • xmdesc: XMBean descriptors for those MBeans with extended descriptions
      • lib: static jar files for the services
      • deploy: services and applications that are hot deployed
      • data: data files that survive reboot
      • tmp: temporary files that do not survive reboot
      • work: work files for Tomcat
    • minimal: a minimal jndi and jmx kernel
    • default: the default configuration (does not include clustering or corba)
    • all: all services including clustering and corba
      • farm: deployments in here are hot deployed across the cluster
      • deploy-hasingleton: deployments in here are only run on one node in the cluster at a time

When one application will be deployed it can be deployed in \\server\\deploy or it can deployed in \\server\\deploy

Deployment Structure

Enterprise Archive Contents

Enterprise Archive (.ear) component follows the standard directory structure defined in the J2EE specification.

Directory Structure of .ear archive

/

.war and .jar files

|_Meta-inf

-----|_ application.xml

In the .ear file .war,.jar and application.xml file are packaged in the above format.

Enterprise Archive Contents

Web component follows the standard directory structure defined in the J2EE specification.

Directory Structure of Web Component

/

index.htm, JSP, Images etc..

|_Web-inf

-----web.xml

-----|_ classes

-----|_ servlet classes

-----|_ lib

----- jar files


/Kazi Masudul Alam
Software Engineer