Wednesday, December 31, 2008

Cleaning the Transaction Logs in SQL Server2005

To Back up the transaction log file :
BACKUP LOG TO DISK = ''
Eg.
BACKUP LOG TestDB TO DISK='C:\TestDB1.bak'

To Shrink the transaction log file:

DBCC SHRINKFILE (, ) WITH NO_INFOMSGS

How to clean the transaction Log in SQL Server

use master
go
dump transaction with no_log
go
use
go
DBCC SHRINKFILE (, 100) -- where 100 is the size you may want to shrink it to in MB, change it to your needs
go
-- then you can call to check that all went fine
dbcc checkdb()

(or)

To Truncate the log file:

Backup the database
Detach the database, either by using Enterprise Manager or by executing : *Sp_DetachDB [DBName]*
Delete the transaction log file. (or rename the file, just in case)
Re-attach the database again using: *Sp_AttachDB [DBName]*
When the database is attached, a new transaction log file is created.
To Shrink the log file:

Backup log [DBName] with No_Log
Shrink the database by either:

Using Enterprise manager :- Right click on the database, All tasks, Shrink database, Files, Select log file, OK.

Using T-SQL :- *Dbcc Shrinkfile ([Log_Logical_Name])*

You can find the logical name of the log file by running sp_helpdb or by looking in the properties of the database in Enterprise Manager.

Monday, November 24, 2008

Replace the First Charater in SQL

Query for replacing the first character only.

--select replace(left('Mahesh',1),left('Mahesh',1),'H') + right('Mahesh',len('Mahesh') - 1)

Thursday, October 30, 2008

Generics in .NET 2.0

What Are Generics?
Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler makes sure that the types used with it are consistent for type safety. Generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, they are very different in their implementation.

The short answer is this: "without generics, it is very difficult to create type-safe collections".

Creating Our First Generic Type:

public class Col {
T t;
public T Val{get{return t;}set{t=value;}}
}


public class ColMain {
public static void Main() {
//create a string version of our generic class
Col mystring = new Col();
//set the value
mystring.Val = "hello";

//output that value
System.Console.WriteLine(mystring.Val);
//output the value's type
System.Console.WriteLine(mystring.Val.GetType());

//create another instance of our generic class, using a different type
Col myint = new Col();
//load the value
myint.Val = 5;
//output the value
System.Console.WriteLine(myint.Val);
//output the value's type
System.Console.WriteLine(myint.Val.GetType());

}
}


When we compile the two classes above and then run them, we will see the following output:

hello
System.String
5
System.Int32

Generic Collections:

User.cs


namespace Rob {
public class User {
protected string name;
protected int age;
public string Name{get{return name;}set{name=value;}}
public int Age{get{return age;}set{age=value;}}
}
}


Main.cs

public class M {
public static void Main(string[] args) {
System.Collections.Generic.List users = new System.Collections.Generic.List();
for(int x=0;x<5;x++) {
Rob.User user = new Rob.User();
user.Name="Rob" + x;
user.Age=x;
users.Add(user);
}

foreach(Rob.User user in users) {
System.Console.WriteLine(System.String.Format("{0}:{1}", user.Name, user.Age));
}
System.Console.WriteLine("press enter");
System.Console.ReadLine();

for(int x=0;x System.Console.WriteLine(System.String.Format("{0}:{1}", users[x].Name, users[x].Age));
}

}
}


Output

Rob0:0
Rob1:1
Rob2:2
Rob3:3
Rob4:4
press enter

Rob0:0
Rob1:1
Rob2:2
Rob3:3
Rob4:4

Thursday, August 7, 2008

Website to download latest free e-books

www.free-ebooks-download.org
Website to download latest free e-books on C#, vb.net, asp.net, 2.0, ado.net, sql 2005, web services, ajax, .net framework, compact framework, xml, sharepoint, exchange server, seo, crystal reports and more.. All free ebooks download, Hurry!

Monday, July 28, 2008

SQL Stored Procedure,Triggers, Cursors.

Stored Procedure:
Pre-Compiled set of SQL Statments..
Increases Performance
Reduces Network Traffic

Syntax:
Create Procedure Proc_name(param list)
As
Begin
// SQL Statements
End


Trigger:
Equivalent to event raising, ie, doing certain action based on events like insert, update...

syntax:
create trigger trg_name
As
begin
// sql statements
end

Cursor:
cursors are used when row by row processing is needed.
syntax
DECLARE cur_name CURSOR
FOR
SELECT username
FROM table

OPEN cur_name

FETCH NEXT FROM cur_name
INTO @usrID

WHILE @@FETCH_STATUS = 0
BEGIN

FETCH NEXT FROM cur_nmae
INTO @usrID

END

CLOSE cur_name
DEALLOCATE cur_name

Wednesday, July 23, 2008

Create A VB InputBox in C#

The below link will help out to know about the Inputbox in C#:

http://www.knowdotnet.com/articles/inputbox.html

Sunday, July 20, 2008

Object Oriented Architecture Modeling

Why architecture with OO methods?
OO methods provide a set of techniques for analyzing, decomposing, and modularizing software system architectures. In general, OO methods are characterized by structuring the system architecture on the basis of its objects (and classes of objects) rather than the actions it performs
Main purpose of these design concepts is to manage software system complexity by improving software quality factors. This provides the following benefits
• Helps to focus on large-scale system design
• Separation of design concerns
• Can identify good domain-specific architectures
• Design abstraction
• Have a common language
o Managerial basis for cost estimation & process mgmt
o Reuse
o Consistency and dependency analysis
o Technical basis for design

OO Modeling of an Solution:
• Identifying Objects of Interest from the Model
• Associating Attributes with Objects of Interest
• Specify how the objects, and interactions and interrelationships among the objects, will effect a solution to the problem

Types Model
(a) Textual Models
These are textual descriptions of both individual objects and systems of objects.

(b) Graphical Models
These graphically represent the characteristics of individual objects or systems of objects.

(c) Class-Responsibility-Collaboration Cards (CRC Cards)

Where do Objects come from?
The following are potential sources of objects:
• The model itself, e.g.:
o Written documents
paragraph, the nouns, pronouns, noun phrases, adjectives, adjectival phrases, adverbs, and adverbial phrases will suggest candidate objects.
o Graphical model certain objects may be implied by such things as nodes and communication among the nodes.
• The information supplied by the OORA(Object Oriented Requirement Analysis) process
• The mind of the software engineer
• A study of existing objects in an object library
• Technical references, e.g., books and articles

Object Modeling using UML
There are three prominent aspects of the modeled system that are handled by UML:

• Functional Model
It describes the functionality of the system from the user's Point of View.
It’s through Use Case Diagrams.
• Object Model
It showcases the structure and substructure of the system using objects, attributes, operations, and associations.
It’s through Class Diagrams.
• Dynamic Model
It showcases the internal behavior of the system.
It’s through Sequence Diagrams, Activity Diagrams and Statechart Diagrams

Use Case model
• Provide an overview of all or part of the usage requirements for a system or organization in the form of an model or a business model
• Communicate the scope of a development project
• Model the analysis of the usage requirements in the form of a system use case model

Use Cases are used primarily to capture the high level user-functional requirements of a system. The Use Case model is about describing “what” the system will do at a high-level and with a user focus for the purpose of scoping the project and giving the application some structure.

Class Diagram
It shows the classes of the system, their inter-relationships, and the operations and attributes of the classes. Class diagrams are used to:
• Explore domain concepts in the form of a domain model
• Analyze requirements in the form of a conceptual/analysis model
• Depict the detailed design of object-oriented or object-based software

Object Sequence Diagram
Object Sequence Diagrams are about deciding and modeling HOW our system will achieve WHAT we described in the Use Case model.
It’s a dynamic modeling technique. UML sequence diagrams are typically used to:
• Validate and flesh out the logic of a usage scenario.
• Explore the design because they provide a way to visually step through invocation of the operations defined by the classes.
• To detect bottlenecks within an object-oriented design. By looking at what messages are being sent to an object, and by looking at roughly how long it takes to run the invoked method, you quickly get an understanding of where need to change the design to distribute the load within the system. In fact some CASE tools even enable to simulate this aspect of the software.
• Gives a feel for which classes in the application are going to be complex, which in turn is an indication that may need to draw state chart diagrams for those classes

Activity Diagram
This is used to explore the logic of the following
• A complex operation
• A complex business rule
• A single use case
• Several use cases
• A business process
• Software processes

Deployment Diagram
Deployment diagrams show the hardware for the system, the software that is installed on that hardware, and the middleware used to connect the disparate machines to one another. A deployment model is to:

• Explore the issues involved with installing the system into production.
• Explore the dependencies that your system has with other systems that are currently in, or planned for, the production environment.
• Depict a major deployment configuration of a business application.
• Design the hardware and software configuration of an embedded system.
• Depict the hardware/network infrastructure of an organization.

Disable the Right click option in the Webpage

1. write the below function in the script tag:
function click(e)
{
if (document.all)
{
if (event.button==2event.button==3)
{
oncontextmenu='return false';
}
}
if (document.layers)
{
if (e.which == 3)
{
oncontextmenu='return false';
}
}
}
if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
function handleKeyDown()
{
if (window.event.keyCode == 116)
{
event.keyCode=0;
event.returnValue=false;
}
}
document.onkeydown = handleKeyDown;

2. In Body Tag:

call the funtion in the events as follows:
oncontextmenu="return false"
ondragstart="return false"
onselectstart="return false"


3. write this inside the script tag:

function click(e) {
if (document.all) {
if (event.button==2event.button==3) {
oncontextmenu='return false';

}
}

if (document.layers) {
if (e.which == 3) {
oncontextmenu='return false';
}
}
}

if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;

function handleKeyDown() {
if (window.event.keyCode == 116) {
event.keyCode=0;
event.returnValue=false;
}
}
document.onkeydown = handleKeyDown;

Friday, July 18, 2008

What's the difference between char,nvarchar,ntext and nvarchar(max) ? (SQL2005)

see the below link:

http://geekswithblogs.net/claeyskurt/archive/2006/02/04/68161.aspx

SQL Server : Sum of 2 querries which has already sum function

There are 2 ways for summing the 2 sub querries:
Method : 1
select
(select SUM(substring(SP_Product, 5, 2) * SP_Opening) AS Muliplied from tblStock_Packed_Factory
where SP_Oil = 'Cocounut'and SP_Product like '%kg' and Len(SP_Product)=8 )
+
(select SUM(substring (SP_Product, 5, 3) * SP_Opening) AS Muliplied from tblStock_Packed_Factory
where SP_Oil = 'Cocounut'and SP_Product like '%kg' and Len(SP_Product)=9 ) AS Muliplied
------------
Method: 2
select Sum(tmp.Muliplied) As Muliplied
From (
select SUM(substring (SP_Product, 5, 2) * SP_Opening) AS Muliplied from tblStock_Packed_Factory
where SP_Oil = 'Cocounut'and SP_Product like '%kg' and Len(SP_Product)=8
union
select SUM(substring (SP_Product, 5, 3) * SP_Opening) AS Muliplied from tblStock_Packed_Factory
where SP_Oil = 'Cocounut'and SP_Product like '%kg' and Len(SP_Product)=9 ) as tmp

Deleting the listbox selected value through Javascript

Javascript:
function removeOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
if(selectbox.options[i].selected)
selectbox.remove(i);
}
}

HTML:








Thursday, July 17, 2008

Reading the Mails from the Outlook 2003 using C# .NET

The following demostrates how to retreive data from items within an Outlook folder (called "MySubFolderName" under the Inbox folder) using .NET:

First add a reference to the Outlook COM object your project:

1. In VS.NET right click on References and choose Add Reference.
2. Select the COM tab Choose "Microsoft Outlook 11.0 Object Library" (this is for MS Office 2003 - I think 10.0 is for Office XP) and click Select.
3. Click OK.
Note that you can access any Outlook/Exchange object types, eg Appointments, Notes, Tasks, Emails etc - just use intellisense to select which one (eg Microsoft.Office.Interop.Outlook. ... - see definition of variable called 'item' below).

Here's the code:

Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;

try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null,null,false, false);

inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
subFolder = inboxFolder.Folders["MySubFolderName"]; //folder.Folders[1]; also works
Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());

for(int i=1;i<=subFolder.Items.Count;i++)
{
item = (Microsoft.Office.Interop.Outlook.PostItem)subFolder.Items[i];
Console.WriteLine("Item: {0}", i.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}" item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Categories: {0}", item.Categories);
Console.WriteLine("Body: {0}", item.Body);
Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
}

Note:If the Problem comes then change the PostItem into MailItem

Programmatically Complete PDF Form Fields using VB and the iTextSharp DLL

Use the below link to get the Idea:

http://www.vbdotnetheaven.com/UploadFile/scottlysle/PdfGenVB06162007031634AM/PdfGenVB.aspx

Caching in ASP .NET

ASP.NET supports multiple levels of caching:
1. Output caching
2. Fragment caching
3. Data caching


Benefits:
Can increase performance by reducing trips to the database


Challenges:
Requires correct design and enough memory to be effective


ASP.NET provides built-in caching support that enables re-use of work:
1. Full Page Caching (Vary by params, language, user-agent)
2. Partial Page Caching (Enables portions of pages to be cached)
3. Web Service Caching (Vary by parameters and methods)
4. Cache Engine: Extensible Cache API (Enables arbitrary objects to be cached)

Cache Dependencies:
1. File Based dependencies
2. Key Based dependencies
3. Time Based dependencies

How to do Caching:
Cache the content of an entire ASP.NET page
–Declarative:
<%@ OutputCache Duration="60" VaryByParam="None"%>
–Programmatic:
•Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
•Response.Cache.SetCacheability(HttpCacheability.Public)
•Response.Cache.SetSlidingExpiration(True)

Example of Output Cache:
<%@ OutputCache Duration="20" VaryByParam="none" %>

Output Cache

Now :<%= Now() %>


The content of the page will be same till 20 Sec.
of the creation of cache of this output.





Tuesday, July 1, 2008

Javascript : To check the URL Validation







URL:





Finding the Control in the Grid

To find the control whether is existing in the grid:
----------------------------------------------------

TextBox txtcomments;
txtcomments=(TextBox)e.Item.FindControl("txtcomments");
txtcomments.Attributes.Add("Onchange","javascript:fncallcheck("+txtcomments.ClientID+")");

String Array

For String array:
------------------

string[] strhistry = (string[])childdr["fldWFHistory"];

Place Holder

For Place Holder:
------------------

StringBuilder str = new StringBuilder();
str.Append("");
str.Append("strhistry[i].ToString()");
placecomments.Controls.Add(new LiteralControl(str.ToString()));

Formating the Date in C# .NET

The Date mm/dd/yyyy Can be changed in to dd/mm/yyyy using the below format:

String.Format("{0:dd/MM/yyyy}",Convert.ToDateTime("12/20/2008"));

Friday, May 2, 2008

Duplicate Records Count

SELECT empname,COUNT(empname) FROM test2 GROUP BY empname
HAVING COUNT(empname) > 1
SELECT COUNT(*),empname FROM test2 GROUP BY empname HAVING COUNT(*)>1

Deleting Duplicate Records in the Table

Table Name : Test2
Fields : empid,empname

Query to Delete the Duplicate values and keeping one value in the table.

set rowcount 1
select 1
while @@rowcount > 0
delete test2
where 1 < (select count(*) from test2 a2 where test2.empid = a2.empid)
set rowcount 0

Friday, February 29, 2008

.NET Web Application Setup & Deployemnt

Step 1: Create an ASP.NET Web application
1. Start Visual Studio .NET or Visual Studio 2005.
2. Use Visual C# .NET or Visual C# 2005 or use Visual Basic .NET or Visual Basic 2005 to create an ASP.NET Web Application project. Name the project Project1.

Note In Visual Studio 2005, create an ASP.NET Web Site project.
3. On the Build menu, click Build Solution.

Step 2: Add a Web Setup project to your solution
1. In Solution Explorer, right-click the Project1 solution, point to Add, and then click Add New Project. The New Project dialog box appears.
2. Under Project Types, click Setup and Deployment Projects.
3. Under Templates, click Web Setup Project.
4. In the Name text box, type WebSetupProject1.
5. In the Location text box, type C:\DeployFolder, and then click OK.

Step 3: Add the Web application files to Your Web Setup project
1. In the File System (WebSetupProject1) window, right-click Web Application Folder, point to Add, and then click File. The Add Files dialog box appears.
2. Locate the C:\Inetpub\wwwroot\Project1 folder.
3. Select all the files that are in the Project1 folder, and then click Open.
4. In the File System (WebSetupProject1) window, expand Web Application Folder.
5. Under Web Application Folder, right-click bin, point to Add, and then click File. The Add Files dialog box appears.
6. Locate the C:\Inetpub\wwwroot\Project1\bin folder.
7. Click the Project1.dll file, and then click Open.

Step 4: Configure the Bootstrapper URL for your Web Setup project
1. In Solution Explorer, right-click WebSetupProject1, and then click Properties. The WebSetupProject1 Property Pages dialog box appears.
2. In the Bootstrapper list box, click Web Bootstrapper. The Web Bootstrapper Settings dialog box appears.
3. In the Setup folder URL text box, type http://devserver/Bootstrap1, and then click OK.

Note devserver is a placeholder for the name of your Web server.
4. In the WebSetupProject1 Property Pages dialog box, click OK.
5. In Solution Explorer, right-click WebSetupProject1, and then click Build.

Step 5: Copy files to the bootstrapping application folder
1. In the C:\Inetpub\Wwwroot folder, create a folder that is named Bootstrap1.
2. Create a virtual directory that is named Bootstrap1, and then map this virtual directory to the C:\Inetpub\wwwroot\Bootstrap1 folder.
3. Copy the following files from the C:\DeployFolder\WebSetupProject1\debug folder to the C:\Inetpub\wwwroot\Bootstrap1 folder: • Setup.Exe
• WebSetupProject1.msi


Step 6: Run your Web Setup project on a remote (deployment) computer
1. Start Microsoft Internet Explorer.
2. Type the following URL in the address bar, and then press ENTER:
http://devserver/Bootstrap1/Setup.Exe
Note devserver is a placeholder for the name of your Web server.
3. In the File Download dialog box, click Open.
4. In the Security Warning dialog box, click Yes.
5. In the WebSetupProject1 dialog box, click Next.
6. Keep WebSetupProject1 in the Virtual directory text box. Click Next.
7. On the Confirm Installation page of the WebSetupProject1 dialog box, click Next.
8. On the Installation Complete page of the WebSetupProject1 dialog box, click Close.
9. Locate the C:\Inetpub\wwwroot\WebSetupProject1 folder.
10. Open the following file in a text editor such as Notepad:• If you are using Visual C# .NET or Visual C# 2005, open the Project1.csproj.webinfo file.
• If you are using Visual Basic .NET or Visual Basic 2005, open the Project1.vbproj.webinfo file.

11. Modify the URLPath element as follows:

Visual C# .NET or Visual C# 2005 code


Visual Basic .NET or Visual Basic 2005 code



12. Save the file as one of the following, depending on your project:• If you are using Visual C# .NET or Visual C# 2005, save the file as WebSetupProject1.csproj.webinfo.
• If you are using Visual Basic .NET or Visual Basic 2005, save the file as WebSetupProject1.vbproj.webinfo.

13. Open the following file, depending on your project:• If you are using Visual C# .NET or Visual C# 2005, open the Project1.csproj file.
• If you are using Visual Basic .NET or Visual Basic 2005, open the Project1.vbproj file.
You may receive the error message that appears in the "Symptoms" section of this article.

Saturday, February 23, 2008

.NET: Generating a Random Number in C#

private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}

Copy the above code in your class where you want to use it and call like this:

int returnValue = RandomNumber(5, 20);

.NET: How to create a scrollable DataGrid?

Place the Data Grid with the Div Tag:

.NET: Redirect .NET tracing to a file?

The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.


How to use the TextWriterTraceListener class to redirect Trace output to a file:

Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );
Trace.WriteLine( @"This will be writen to c:\log.txt!" );
Trace.Flush();

SQL-Server: Finding the Nth Highest & Nth Lowest in the SQL:

In the below way we can display any record, it can be fifth or 12th record from top. If we change the order by command to start in ascending order by changing the DESC to ASC ( or removing it , by default it is ASC ) we can get the lowest to highest and get the records from lowest ( last ) mark.

SELECT * FROM `student` where class='Six' ORDER BY mark desc LIMIT 0,1

SQL- Server: Case Statement

Sample for Case Statment:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

.NET : Framework & ASP.NET Questions

1.)Various Providers available in .NET:

1. Odbc Data Provider:System.Data.Odbc
2. OleDb Data Provider:System.Data.OleDb
3. SqlClient Data Provider:System.Data.SqlClient
4. OracleClient Data Provider:System.Data.OracleClient

2.)What is MSIL code?
This is an acronym for Microsft Intermediate Language. In .net code that a developers develops will be complied in to MSIL code by the respective compilers and this code will be targeted towards the CLR which inturn contains JIT Compilers .This MSIL code will be converted in to the machine understandable code by JIT compiler

3.What are various types of assemblies ?
1) shared assembly
2) private assembly
3) satellite assembly

4. What is an assembly and what does manifest consists?
An Assembly is the building block of .net having metadata,mainfest,culture info,ver no. Mainfest cantain the information about the Metadata

5. What is boxing and unboxing?
Box is used to convert Value type to reference type(ie. Object)
Unboxing is to convert Reference typr to Value Type

6. Types of caching?
There are 3 types of caching
1.Page caching
2.Fragment Caching
3.Output Caching

7. What are various authentication mechanisms in ASP.NET?
There are three type of authentication mechanism in asp.net:

1. Form Authentication
2. Window Authentication
3. Passport Authentication

8. What is CTS, CLS and CLR?
Common Type System CTS :A fundamental part of the .NET Framework's Common Language Runtime (CLR), the CTS specifies no particular syntax or keywords, but instead defines a common set of types that can be used with many different language syntaxes.

Common Language Specification (CLS):The Common Language Specification (CLS) describes a set of features that different languages have in common. The CLS includes a subset of the Common Type System (CTS).

The CLR is a multi-language execution environment

9. What are the main advantage in .net?
It is a Language independent, It supports all most all 40 LAngauges including third party languages

10. Where does the dispose method lie and how can it be used to clean up resources?
The dispose method is available in System.IDisposable interface. If you want to provide cleanup mechanism then implement this interface and provide the definition for dispose () method.

11. What is value type and reference type?
In simple words value types are those data types that store there values on stack memory and values are settle down at compile time example are "ENUM" and reference type are those data type that store there values in heap memory and settle down while run time i.e dynamic types examples are strings, class type etc

12. How can u manage sessions?
Session Can be managed in 3 ways using
1.in-proc
2.out-proc and
3. sql server.

13. How can u manage state?
Managing state is done by two ways
1. client side techniques like viewstate, querystring, cookies.
2. Server Side techniques like Application state, Session state.

JavaScript: Check all option for CheckBox Control.

To check all the Checkboxes in the CheckBox Control:
-----------------------------------------------------
function Allcheck()
{
var ln=document.getElementsByTagName('input');
for(i=1;i {
var input_type=ln[i].type;
if(input_type=="checkbox")
{
var Chck_ID=ln[i].id.indexOf("Check_All");
if(Chck_ID!=-1)
{
ln[i].checked=true;
}
}
}
}

Javscript E-Mail Validation:

Function for Email Validation:-
--------------------------------
function EmailValidation(fld)
{
if(fld.value!='')
{
var id=fld.value;
var Reg=new RegExp("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$");
if(id.match(Reg)==null)
{
alert("Please enter Valid Email-Id !");
fld.value='';
fld.focus();
return false;
}
}
}

Javscript : Function to check Float.

Function to check Float:-
----------------------------
function ChkFloat(fld)
{
if(fld.value!='')
{
var id=fld.value;
var Reg=new RegExp("^[\-]{0,1}[0-9]{1,}(([\.\,]{0,1}[0-9]{1,})|([0-9]{0,}))$");
if(id.match(Reg)==null)
{
alert("Please Enter Numeric Values !");
fld.value='';
fld.focus();
return false;
}
if(id.indexOf("-")!=-1)
{
alert("Please Enter Positive Values !");
fld.value='';
fld.focus();
return false;
}
}
}

SQL-Server :Example of COALESCE

To bring the Multiple Column in to single column using comma separator:

declare @var varchar(800)
select @var=COALESCE(@var +',', '')+ CAST( AS varchar(250)) from
print @var

SQL-Server : How to Kill the Database Users?

To view the Users who are all using the Database:
--------------------------------------------------
sp_who2

To Kill the User:
------------------

kill 'SPID'
eg: kill 58

SQL-Server : To view the Column Name,type,size in the Table

To view the Columns in the table called "Activity"
-----------------------------------------------------
Type: 1
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Activity'

Type: 2
select fname=col.name, dtype=type.name, col.length, col.status from syscolumns col
inner join sysobjects obj
on col.id = obj.id
inner join systypes type
on col.xtype = type.xtype
where obj.name= 'Activity'
and type.xtype = type.xusertype order by colid



To Get the total number of Columns in the Table:
---------------------------------------------------
SELECT Count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Activity'

Javascript Validation the CheckBox List:

The below code Validate the CheckBox list whether any one of the items are checked or not.

Name of the CheckBox list is : chkFunctionType

function fnValidate()
{
var flag=false;
var chkListfunction = document.getElementById ("chkFunctionType");
var arrCheckbox= chkListfunction.getElementsByTagName("input");
for(var i=0;i {
if(arrCheckbox[i].checked==true)
{
flag=true;
}
}
if(flag==false)
{
alert('Please select the Function Level');
return false;
}
}

Call this Function in the Button Click.

Javascript: Confirmation Msg

function checkdelete()
{
if(confirm('Are you certain that you want to delete this')==false)
{
return false;
}
}

Call the Function in Button OnClick="return checkdelete();"

JavaScript:Allow only Numerics in TextBox

---------------Method 1



In .aspx Page:



--------------Method 2

function validNum(fld)
{
if(fld.value!='')
{
var id=fld.value;
var Reg=new RegExp("^[0-9]*\[0-9]$");
if(id.match(Reg)==null)
{
alert("Please Enter Numeric Values !");
fld.value='';
fld.focus();
return false;
}
if(id.indexOf("-")!=-1)
{
alert("Please Enter Positive Values !");
fld.value='';
fld.focus();
return false;
}
}
}

In .aspx.cs Page:

Text Box Name: txtCorpName
txtCorpName.Attributes.Add("OnKeyup", "Javascript:return(validNum(this));");

onbeforeunload Javascript

There are some cases where you might want to instruct the user before he/She is navigating to the next page. That might be a meaningful message like "Are you sure you want to navigate away from the current page?"
Probably end user pressed the X button by mistake and he/she might loose his/her current state

There is onbeforeunload event for the JavaScript that fires when you are navigating away from the current page.
Here is the Code for that.



script type="text/javascript"
function close()
{
event.returnValue = "This will navigate to next page.";
}
script




body onbeforeunload="close()"



Note:
The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

Maxlength checking in Textarea Using Javascript

function maxcheck()
{
var maxval=1000;
var maxtxtlength=window.document.myform.Description.value.length;
if(parseInt(maxtxtlength)>parseInt(maxval))
{
alert("This Description field accept only 1000 characters");
window.document.myform.Description.innerText=window.document.myform.Description.value.substring(0,1000);
return false;
}
}

Accesing Parent Window through Childwindow using Javascript

///////////////////////Accessing Id///////////////////////////
alert(window.opener.document.getElementById("HidString").value)

///////////////////////End Accessing Id///////////////////////////

///////////////////////Accessing Function///////////////////////////
child.aspx
window.opener.LoadEmp(obj)

parent.aspx
function LoadEmp(ob)
{
alert(ob);
}

///////////////////////End Accessing Function///////////////////////////


///////////////////////Refershing Parent Page from Child page////////////

Response.Write("");

Reading and removing Listbox using Javascript

/////////////Reading/////////////////////////////////
var listEmp=document.getElementById("PMEmpname");

for(j=0;j
{
listEmp.options[j].value //Value field
listEmp.options[j].text //Text Field
}

///////////Deleting///////////////////////////////////

for(j=0;j{
listEmp.remove(j);
}

Using Javascript creating control without postback




















Friend Name

Email Id

Delete






/////////////////////////////////Javascript///////////////////////////
///////////////////This is for adding row/////////////////////////////
var rowcount=1;
var checkcount=1;
function fnAddRow()
{
rowcount++;
// var check=validate(); //this is for my page validation
if(check!=false)
{
var objTbl = document.getElementById("Tellafriend1");
var objTbody = objTbl.getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
//txtfriendname///
var friendnameval=document.createElement("td");
var friendnameDel = document.createElement("INPUT")
friendnameDel.setAttribute("type","text");
friendnameDel.setAttribute("name","txtfriendname"+rowcount);
friendnameDel.setAttribute("id","txtfriendname"+rowcount);
friendnameval.appendChild(friendnameDel)
row.appendChild(friendnameval);
//txtfriendname///
//txtfriendemail///
var friendemailval=document.createElement("td");
var friendemailDel = document.createElement("INPUT")
friendemailDel.setAttribute("type","text");
friendemailDel.setAttribute("name","txtfriendemail"+rowcount);
friendemailDel.setAttribute("id","txtfriendemail"+rowcount);
friendemailval.appendChild(friendemailDel)
row.appendChild(friendemailval);
//txtfriendemail///

//checkbox///
var checkval=document.createElement("td");
var ChkDel = document.createElement("INPUT")
ChkDel.setAttribute("type","checkbox");
ChkDel.setAttribute("name","chkDelete"+rowcount);
ChkDel.setAttribute("id","chkDelete"+rowcount);
checkval.appendChild(ChkDel)
row.appendChild(checkval);
//End check box checkbox///
objTbody.appendChild(row);
}
else
{
return false;
}
}
///////////////////End adding row/////////////////////////////

Note:For deleting i am using checkbox...................
///////////////Deleting Row//////////////////////////////////

function fnDelRow()
{
var ChkOption = ""
for(var i=2;i<=rowcount;i++)
{
var ChkCtrl = document.getElementById("chkDelete"+i)

if(ChkCtrl == '[object]')
{
if(ChkCtrl.checked)
{
ChkOption = "1"
delRow(ChkCtrl)
checkcount++;
}
}
}
if(ChkOption == "" && rowcount!=1)
{
alert("Select any one option to delete")
return false;
}
}
function delRow(button)
{
var row = button.parentNode.parentNode;
var tbody = document.getElementById('Tellafriend1').getElementsByTagName('tbody')[0];
tbody.removeChild(row);
}

/////////////////////////////End Deleting row////////////////////////////////

Statemanagement Using C#.Net

State Management is a process of maintaining the state of the control or variable after page postback from server or between pages. In Asp.Net we are having many ways to maintain the state management. Basically it is dividied into server side and client side state management. Depends on the resource that we have to plan. They are as follows....
1. Session state
2. Hidden Variables
3. Query String
4. Cookies
5. ViewState
6. Caching
Out of which session state and caching are server side state management. others are client side state management.
1. Session State

Session State is responsible for maintaining the state of a variable between pages and page postback. There are two types of session state. They are
a. Application state
b. Session state
An object that is instant in application state will be available to the entire application. The lifetime of that instance will be available as long as application exists. Synatax for it is

Application.lock();
Application["Name"] = "Senthil";
Application.unlock();
string strName = Application["Name"].ToString();

and an instance created in session state will be available for that session (i.e browser).


Session["RoleID"] = "ADMIN";
string strRole = Session["RoleID"].ToString();

Session state can stored in three places
a. InProc - same system
b. StateServer - storing values in other server. Use " net start aspnet_state" for configuring the state server.
c. SQLServer - In database - use "aspnet_regsql" for configuring the sql server.


This can be set in web.config




To get more info about state management, set the trace to on





If pageoutput is set to false, then we find the contents in trace.axd file which is available in the root folder.

2. Hidden variables

Hidden controls are for storing few informations and retrieving it when page gets submits. We cannot get one hidden value in another page. The syntax for hidden variables are as follows.


<%=Request.Form("hid")%>

3. QueryString

Easiest way to transfer data between pages is the querystring. But we cannot transfer a bulk of data through it. Basically querystring has two keywords ? and &.


Example

document.frm.action="login.aspx?Name=" & strName & "?Role=ADMIN"
<%= Request.QueryString["Name"] %>

4. Cookies

Cookies are client side and it is used to store few values in the client machine. We cannot create cookies in server side. Many browsers restrict using cookies in the websites. The class that supports cookies in dotnet are HttpCookies.

5. ViewState

ViewState are used to maintain the state of the control. It can be set page wise or control wise. To set it by page wise


<% @ Page EnableviewState="True" %>


For setting viewstate control wise set the viewstate property to true.

The value of the control would be retained once the pages get postback.

6. Caching

Caching too places a part in state management. Its similar to session state but the only difference is we have to set the duration for it.
Caching can be done by page levels or application levels.

Syntax for page level caching[CODE]

<% outputcache duration="10" valuebyParam="none" />[CODE]

Javascript Debugger Enabling

Step 1. Disable Script Debugger - Make this option unchecked in the IE.
function someFunct()
{
Javascript:debugger;alert(window.name)
alert("Mahesh");
}

How to Set Screen width for any kind of resolution?



2) Call the function on load event of body.

Saturday, January 26, 2008

What are the different types of assemblies available and their purpose?

Private, Public/shared and Satellite Assemblies.

Private Assemblies : Assembly used within an application is known as private assemblies

Public/shared Assemblies : Assembly which can be shared across applicaiton is known as shared assemblies. Strong Name has to be created to create a shared assembly. This can be done using SN.EXE. The same has to be registered using GACUtil.exe (Global Assembly Cache).

Satellite Assemblies : These assemblies contain resource files pertaining to a locale (Culture+Language). These assemblies are used in deploying an Gloabl applicaiton for different languages.

OOPS Interview Questions:

1. What is Class?
A user-defined data structure that groups properties and methods. Class doesn’t occupy memory.

2. What is Object?
Instance of Class is called object. An object is created in memory using keyword “new”.

3. Difference between Struct and Class?
i) Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap
ii) Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface
iii) Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.

4. What is Encapsulation?
Wrapping up of data and function into a single unit is known as Encapsulation.

5. What is Properties?
Attribute of object is called properties. Eg1:- A car has color as property.
eg.: private string m_Color;
public string Color
{
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
Car Maruti = new Car();
Maruti.Color= “White”;
Console.Write(Maruti.Color);

6. Use of "this" Keyword?
Each object has a reference “this” which points to itself. Two uses of this keyword are 1)Can be used to refer to the current object, 2)It can also be used by one constructor to explicitly invoke another constructor of the same class.

7. What is Constructor?
- A constructor is a special method whose task is to initialize the object of its class
- It is special because its name is the same as the class name.
- They do not have return types, not even void and therefore they cannot return values.
- They cannot be inherited, though a derived class can call the base class constructor
- Constructor is invoked whenever an object of its associated class is created
Note: There is always atleast one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().

8. What is Static Members of the class?
-Static members belong to the whole class rather than to individual object
-Static members are accessed with the name of class rather than reference to objects.
Eg:
class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}
class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;
stud2.rollNo = 2;
stud2.mathsMarks = 43;
Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}

9. What is Static Method of the class?
Methods that you can call directly without first creating an instance of a class.
Eg: Main() Method, Console.WriteLine()

10. what is Destructor?
A destructor is just opposite to constructor. It has same as the class name, but with prefix ~ (tilde). They do not have return types, not even void and therefore they cannot return values.

11. What is Garbage Collection?
Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable.
.Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect()

12. Use of Enumeration?
Enumeration improves code readability. It also helps in avoiding typing mistake.

13. Concept of Heap and Stack:
The Program Instruction and Global and Static variables are stored in a region known as permanent storage area and the local variables are stored in another area called stack. The memory space located between these two regions is available for dynamic memory allocation during execution of program. This free memory region is called heap. The size of heap keeps on changing when program is executed due to creation and death of variables that are local to functions and blocks. Therefore, it is possible to encounter memory “overflow” during dynamic allocation process.

14. What is Value Type and Reference Type?
A variable is value type or reference type is solely determined by its data type.
Eg: int, float, char, decimal, bool, decimal, struct, etc are value types,
object type such as class, String, Array, etc are reference type.

15. what is Boxing and Un-Boxing?
Boxing: means converting value-type to reference-type.
Eg:
int I = 20;
string s = I.ToSting();
UnBoxing: means converting reference-type to value-type.
Eg:
int I = 20;
string s = I.ToString(); //Box the int
int J = Convert.ToInt32(s); //UnBox it back to an int.
Note: Performance Overheads due to boxing and unboxing as the boxing makes a copy of value type from stack and place it inside an object of type System.Object in the heap.

16. What is Inheritance?
The process of sub-classing a class to extend its functionality is called Inheritance.It provides idea of reusability.

17. What are Sealed Classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)

18. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

19. 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.

20. List of Facts in Inheritance?
- Multiple inheritance of classes is not allowed in C#.
- In C# you can implements more than one interface, thus multiple inheritance is achieved through interface.
- The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# (and the .NET framework)
- Structures (struct) in C# does not support inheritance, it can only implements interfaces.

21. What is Polymorphism?
Polymorphism means same operation may behave differently on different classes.
Eg:
Method Overloading is an example of Compile Time Polymorphism.
Method Overriding is an example of Run Time Polymorphism

22. How many types of Access Modifiers?
1) Public – Allows the members to be globally accessible
2) Private – Limits the member’s access to only the containing
3) Protected – Limits the member’s access to the containing type and all classes derived from the containing type
4) Internal – Limits the member’s access to within the current project

23. What is Method Overloading?
Method with same name but with different arguments is called method overloading. Method Overloading forms compile-time polymorphism.
Eg. class A1
{
void hello()
{
Console.WriteLine(“Hello”);
}
void hello(string s)
{
Console.WriteLine(“Hello {0}”,s);
}
}

24. What is Method Overriding?
Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass. Method overriding forms Run-time polymorphism.
Eg.
Class parent
{
virtual void hello()
{
Console.WriteLine(“Hello from Parent”);
}
}
Class child : parent
{

override void hello()
{
Console.WriteLine(“Hello from Child”);
}
}
static void main()

{
parent objParent = new child();
objParent.hello();
}
//Output

Hello from Child.

25. What is Virtual Method?
By declaring base class function as virtual, we allow the function to be overridden in any of derived class.
Eg:
Class parent
{
virtual void hello()
{
Console.WriteLine(“Hello from Parent”);
}
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”);
}
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

26. What is Interface?
- Interface states “what” to do, rather than “how” to do.
- An interface defines only the members that will be made available by an implementing object. The definition of the interface states nothing about the implementation of the members, only the parameters they take and the types of values they will return. Implementation of an interface is left entirely to the implementing class. It is possible, therefore, for different objects to provide dramatically different implementations of the same members.

Eg.
public interface IDrivable
{
void GoForward(int Speed);
}
public class Truck : IDrivable
{
public void GoForward(int Speed)
{
// Implementation omitted
}
}
public class Aircraft : IDrivable
{
public void GoForward(int Speed)
{
// Implementation omitted
}
}
public class Train : IDrivable
{
public void GoForward(int Speed)
{
// Implementation omitted
}
}

27. Difference between Interface and Abstract Class?
Multiple inheritance:
A class may implement several interfaces.
A class may extend only one abstract class.
Default implementation:
An interface cannot provide any code at all, much less default code.
An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Third party convenience:
An interface implementation may be added to any existing third party class.
A third party class must be rewritten to extend only from the abstract class.

Wednesday, January 23, 2008

Types of Multitasking

There are two types of multitasking:

1. Process Based:
- Process-based multitasking handles the concurrent execution of programs.
eg.:running word processor the same time you are browsing the net.
2. Thread Based
- Thread-based multitasking deals with the concurrent execution of pieces of the same program.
eg.: A text editor can be formatting text at the same time that it is printing.

Sunday, January 20, 2008

What is reflection?

Reflection is the mechanism of discovering class information solely at run time

What’s the use of SmartNavigation property?

Its a feature provided by ASP .NET to prevent the flickering and the redrawing when the page is posted back. Gets or sets a value indicating whether smart navigation is enabled.
VB: Public Property SmartNavigation As Boolean
C#: Public bool SmartNavigation {get; set;}

What is concept of Boxing and Unboxing?

Boxing and unboxing is a essential concept in. NET’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object.

Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation.

Various State Management in a Page:

There are Nine ways by which we can Maintain State of Page:

1. Application
2. Cookies
3. Hidden Fields
4. Query String
5. Session
6. Cache
7. Context
8. ViewState
9. Web.Config and Machine.Config

Keys Concept in DBMS.

1) PRIMARY KEY:-A primary key is a field that uniquely identifies each record in a table. As it uniquely identify each entity, it cannot contain null value and duplicate value.eg:-Consider the customer table, which has field :customer_number, customer_socialsecurity_number, and customer_address.here customer_number of each entity in customer table is distinct so customer-number can be a primary key of customer-table.
2) SUPER KEY :- If we add additional attributes to a primary key, the resulting combination would still uniquely identify an instance of the entity set. Such augmented keys are called superkey.A primary key is therefore a minimum superkey.
3) CANDIDATE KEY:-A nominee's for primary key field are know as candidate key.eg:-From above example of customer table, customer_socialsecurity_number is candidate key as it has all characteristics of primary key.
4) ALTERNATE KEY:-A candidate key that is not the primary key is called an Alternate key.eg:- In above example, customer_socialsecurity_number is a candidate key but not a primary key so it can be considered as alternate key.
5) COMPOSITE KEY:- Creating more than one primary key are jointly known as composite key.eg:-In above example, if customer_number and customer_socialsecurity_number are made primary key than they will be jointly known as composite key.
6) FOREIGN KEY:- Foreign key is a primary key of master table, which is reference in the current table, so it is known as foreign key in the current table. A foreign key is one or more columns whose value must exist in the primary key of another table.eg:-Consider two tables emp(contains employees description) and emp_edu(contains details of employee's education), so emp_id which is primary key in emp table will be referred as foreign key in emp_edu table.

Friday, January 18, 2008

What is viewstate?

View State is the built in structure for automatically retain the values amoung multiple requests for the same page. Viewstate is internally maintained in the HiddenField on the page.

Thursday, January 17, 2008

Define candidate key, alternate key, composite key?

A candidate key is one that can identify each row of a table uniquely.Generally a candidate key becomes the primary key of the table. If thetable has more than one candidate key, one of them will become theprimary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What is Canditate Key?

A table which is having more that one combination of column that could uniqly identify the rows in a table. Each combination is a canditate key.
Eg. In the supplier table SupplierID, Supplier name are the canditate key but we can pick up only the supplierID as a primary key.

Enabling an asynchronous web page

Step 1. Add the Async="true" attribute the page directive:


eg: Page Language="C#" Async="true" AutoEventWireup="true"

Step 2. Create events to start and end the asynchronous code that implements the System.Web.IHttpAsyncHandler.BeginProcessRequest and System.Web.IHttpAsyncHandler.EndProcessRequest


eg: IAsyncResult BeginGetAsyncData(Object src, EventArgs args, AsyncCallback cb,

Object state)
{ }

void EndGetAsyncData(IAsyncResult ar)
{ }



Step 3. call the AddOnPreRenderCompleteAsync method to declare the event handlers:


eg: BeginEventHandler bh=new BeginEventHandler(this.BeginGetAsyncData);
EndEventHandler eh= new EndEventHandler(this.EndGetAsyncData);
AddOnPreRenderCompleteAsync (bh,eh)