Friday, August 21, 2009

CODE

Send E-Mail in Asp.Net application using Gmail Mail Server I will let you guys to create the above UI.
After you are done with this goto the click event of the Send button and paste the below code.


protected void btnSendMail_Click(object sender, EventArgs e)
{
try
{
/* Create a new blank MailMessage with the from and to adreesses*/
MailMessage mailMessage = new MailMessage(txtSender.Text,txtReceiver.Text);
/*Checking the condition that the cc is empty or not if not then * include them */
if (txtCc.Text != null && txtCc.Text != string.Empty)
{
mailMessage.CC.Add(txtCc.Text);
}
/*Checking the condition that the Bcc is empty or not if not then * include them*/
if (txtBcc.Text != null && txtBcc.Text != string.Empty)
{
mailMessage.Bcc.Add(txtBcc.Text);
}
//Ading Subject to the Mail
mailMessage.Subject = txtSubject.Text;
//Adding the Mail Body
mailMessage.Body = txtBody.Text;
/* Set the properties of the MailMessage to the values on the form as per the mail is HTML formatted or plain text */
if (rblMailFormat.SelectedItem.Text =="Text")
mailMessage.IsBodyHtml = false;
else
mailMessage.IsBodyHtml = true;
/* We use the following variables to keep track ofattachments and after we can delete them */
string attach1 = null;
string attach2 = null;
string attach3 = null;
/*strFileName has a attachment file name for attachment process. */
string strFileName = null;
/* Bigining of Attachment1 process & Check the first open file dialog for a attachment */
if (inpAttachment1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = inpAttachment1.PostedFile;
/* Get size of the file */
int attachFileLength = attFile.ContentLength;
/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
/* Get the file name */
strFileName = Path.GetFileName(inpAttachment1.PostedFile.FileName);
/* Save the file on the server */
inpAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName));
/* Create the email attachment with the uploaded file*/
Attachment attach = new
Attachment(Server.MapPath(strFileName));
/* Attach the newly created email attachment */
mailMessage.Attachments.Add(attach);
/* Store the attach filename so we can delete it later*/
attach1 = strFileName;
}
}
/* Attachment-2 Repeat previous step defiend above*/
if (inpAttachment2.PostedFile != null)
{
same for attachment 2
}
/* Attachment-3 Repeat previous steps step defiend above*/
if (inpAttachment3.PostedFile != null)
{
same for attachment 3
}
/* Set the SMTP server and send the email with attachment */
SmtpClient smtpClient = new SmtpClient();
// smtpClient.Host = emailServerInfo.MailServerIP;
//this will be the host in case of gamil and it varies from the service provider
smtpClient.Host = "smtp.gmail.com";
//smtpClient.Port = Convert.ToInt32 emailServerInfo.MailServerPortNumber);
//this will be the port in case of gamil for dotnet andit varies from the service provider
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
//smtpClient.Credentials = new System.Net.NetworkCredential(emailServerInfo.MailServerUserName,emailServerInfo.MailServerPassword);
smtpClient.Credentials = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text);
//this will be the true in case of gamil and it varies from the service provider
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
/* Delete the attachements if any */
try{
if (attach1 != null)
File.Delete(Server.MapPath(attach1));
if (attach2 != null)
File.Delete(Server.MapPath(attach2));
if (attach3 != null)
File.Delete(Server.MapPath(attach3));
}
catch{}
/* clear the controls */
txtSender.Text = string.Empty;
txtReceiver.Text = string.Empty;
txtCc.Text = string.Empty;
txtBcc.Text = string.Empty;
txtSubject.Text = string.Empty;
txtBody.Text = string.Empty;
txtUserName.Text = string.Empty;
/* Dispaly a confirmation message to the user. */
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Black;
lblMessage.Text = "Message sent.";
}
catch (Exception ex)
{
/* Print a message informing the user about the exception that was risen */
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Red;
lblMessage.Text = ex.ToString();
}
}
--------------------------------------------------------------
---------------------------------------------------------------
Write a code for Fibonacci Series

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

namespace Fibbonaci
{
class Program
{
static void Main(string[] args)
{
int oldnum, newnum, fibnum, maxnum;
Console.Write("Enter Any Value");
maxnum = int.Parse(Console.ReadLine());
oldnum = 0;
newnum = 1;
fibnum = oldnum + newnum;
Console.WriteLine(oldnum);
Console.WriteLine(newnum);
Console.WriteLine(fibnum);
for (; ; )
{
oldnum = newnum;
newnum = fibnum;
fibnum = oldnum + newnum;
if (fibnum > maxnum)
{
Console.WriteLine("");
break;
}
Console.WriteLine(fibnum);
}
Console.ReadLine();

}
}
}
==============================
FIND THE O/P OF THIS

int i = 1;
int j = 1;
Console.WriteLine(i==j); TRUE
Console.WriteLine(i.ToString() == j.ToString()); TRUE
Console.WriteLine((object)i == (object)j); FALSE

==============================
Calculating an Age in C# From a Date of Birth
public static int CalculateAge(DateTime birthdate)
{
// get the difference in years
int years = DateTime.Now.Year - birthdate.Year;
// subtract another year if we're before the
// birth day in the current year

if (DateTime.Now.Month < birthdate.Month (DateTime.Now.Month == birthdate.Month && DateTime.Now.Day < birthdate.Day))
years--;
return years;
}
=====================================
WAP to Upload file in Asp.Net
protected void cmdUploadFile_Click(object sender, EventArgs e)
{
strfileDirectory=”C:\Saini”;
//determine file to be uploaded
string strFileName = System.IO.Path.GetFileName(FileToUpload.PostedFile.FileName);
if((FileToUpload.PostedFile != null) && (FileToUpload.PostedFile.ContentLength>0))
{
try
{
//save the file to server
FileToUpload.PostedFile.SaveAs(strfileDirectory+strFileName);
uploadLblMeg.Visible=true;
uploadLblMeg.Text="File"+strfileDirectory+strFileName+"Uploaded Successfully";


}
catch(Exception ex)
{
uploadLblMeg.Visible=true;
uploadLblMeg.Text= ex.Message;
}
}
else
{
uploadLblMeg.Text="Select a file to Upload. Please try again !";
}


Syntax of Operator Overloading with Example?
Public struct HoursWorked
{
Float regularHours;
Float OvertimeHours;
}
//CREATING OVERLOADING OPERATOR
Public static HoursWorked operator +(HoursWorked a, HoursWorked b)
{
HoursWorked Result = new HoursWorked();
Result.RegularHours= a.RegularHours + b.RegularHours;
Result.OvertimeHours=a.OvertiemHours+b.OvertimeHours;
Return Result;
}

Testing

Unit Testing
Starting from the bottom the first test level is "Unit Testing". It involves checking that each feature specified in the "Component Design" has been implemented in the component. In theory an independent tester should do this, but in practice the developer usually does it, as they are the only people who understand how a component works. The problem with a component is that it performs only a small part of the functionality of a system, and it relies on co-operating with other parts of the system, which may not have been built yet. To overcome this, the developer either builds, or uses special software to trick the component into believe it is working in a fully functional system.

Integration Testing
As the components are constructed and tested they are then linked together to check if they work with each other. It is a fact that two components that have passed all their356 tests, when connected to each other produce one new component full of faults. These tests can be done by specialists, or by the developers. Integration Testing is not focused on what the components are doing but on how they communicate with each other, as specified in the "System Design". The "System Design" defines relationships between components. The tests are organized to check all the interfaces, until all the components have been built and interfaced to each other producing the whole system.

System Testing
Once the entire system has been built then it has to be tested against the "System Specification" to check if it delivers the features required. It is still developer focused, although specialist developers known as systems testers are normally employed to do it. In essence System Testing is not about checking the individual parts of the design, but about checking the system as a whole. In fact it is one giant component. System testing can involve a number of specialist types of test to see if all the functional and non-functional requirements have been met. In addition to functional requirements these may include the following types of testing for the non-functional requirements:
√ Performance - Are the performance criteria met?
√ Volume - Can large volumes of information be handled?
√ Stress - Can peak volumes of information be handled?
√ Documentation - Is the documentation usable for the system?
√ Robustness - Does the system remain stable under adverse circumstances?
There are many others, the need for which is dictated by how the system is supposed to perform.

Acceptance Testing
Acceptance Testing checks the system against the "Requirements". It is similar to systems testing in that the whole system is checked but the important difference is the change in focus:357 Systems testing checks that the system that was specified has been delivered. Acceptance Testing checks that the system will deliver what was requested. The customer should always do acceptance testing and not the developer . The customer knows what is required from the system to achieve value in the business and is the only person qualified to make that judgment. This testing is more of getting the answer for whether is the software delivered as defined by the customer. It’s like getting a green flag from the customer that the software is up to the expectation and ready to be used.

UML

What is UML?
The Unified Modeling Language (UML) is a graphical language for visualizing, specifying, constructing, and documenting the artifacts of a software-intensive system.UML provides blue prints for business process, System function, programming language statements, database schemas and reusable components.


What are advantages of using UML?
As the name suggest UNIFIED MODELING LANGUAGE. Modelling has been around for years, not only in software field but also in other trades like civil, mechanical etc.
Example in civil engineering drawing the main architecture built of diagram is a model by itself. Modelling makes complex and huge system to break up in to simple and discrete pieces that can be individually understood. Example simple flowchart drawing is modeling.

There are two main advantages of modeling:-
Readability: - Representing your whole architecture in flowchart, class diagrams, ER diagrams etc makes your project more readable. Especially when programmer’s change jobs handover becomes easier. More the project is not readable more the dependencies.

Reusability: - After the system is more readable and broken down to pieces, it becomes easier to identify redundant and similar modules. Thus increasing reusability.

So why UML? Well different languages have different ways of coding and syntaxes. In order to bring all languages in one roof UML is in to picture. As the term comes in UNIFIED, it unifies all disparate languages in one roof so that can be understood by people who are working on some other platforms.

ADO.Net

What’s difference between “Optimistic” and “Pessimistic” locking ?
In pessimistic locking when user wants to update data it locks the record and till then no
one can update data. Other user’s can only view the data when there is pessimistic locking.
In optimistic locking multiple users can open the same record for updating, thus increase
maximum concurrency. Record is only locked when updating the record. This is the most
preferred way of locking practically. Now a days browser based application is very common
and having pessimistic locking is not a practical solution.



How can we perform transactions in .NET?


A transaction symbolizes code or a set of components or procedures which must be executed as a unit. All the methods must execute successfully or the complete unit fails. A transaction can be described to cover the ACID properties for any applications
What are the ACID Properties?

Atomicity
Consistency
Isolation
Durability


The most common sequence of steps that would be performed while developing a transactional application is as follows:
√ Open a database connection using the Open method of the connection object.
√ Begin a transaction using the Begin Transaction method of the connection object. This method provides us with a transaction object that we will use later to commit or rollback the transaction. Note that changes caused by any queries executed before calling the Begin Transaction method will be committed to the database immediately after they execute. Set the Transaction property of the command object to the above mentioned transaction object.
√ Execute the SQL commands using the command object. We may use one or more command objects for this purpose, as long as the Transaction property of all the objects is set to a valid transaction object.
√ Commit or roll back the transaction using the Commit or Rollback method of the transaction object.
√ Close the database connection.

most common example for the transactions is Debit and Credit from the Accounts

PROGRAM

SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = null;

try
{
// BeginTransaction() Requires Open Connection
connection.Open();

transaction = connection.BeginTransaction();

// Assign Transaction to Command
command.Transaction = transaction;

// Execute 1st Command
command.CommandText = "Insert ...";
command.ExecuteNonQuery();

// Execute 2nd Command
command.CommandText = "Update...";
command.ExecuteNonQuery();

transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}

State


What is ViewState ?
Viewstate is a built-in structure for automatically retaining values amongst the multiple requests for the same page. The viewstate is internally maintained as a hidden field on the page but is hashed, providing greater security than developer-implemented hidden fields do.



What are the ways you can maintain state ?
Other than session variables you can use the following technique to store state :
√ Hidden fields
√ View state
√ Hidden frames
√ Cookies
√ Query strings

Caching

What is caching?
One of the most important factors in building high-performance, scalable Web applications is the ability to store items, whether data objects, pages, or parts of a page, in memory the initial time they are requested. You can store these items on the Web server or other software in the request stream, such as the proxy server or browser. This allows you to avoid recreating information that satisfied a previous request, particularly information that demands significant processor time or other resources. Known as caching, it allows you to use a number of techniques to store page output or application data across HTTP requests and reuse it. Thus, the server does not have to recreate information, saving time and resources.

What are different types of caching in ASP.NET?
ASP.NET provides two types of caching that you can use to create high-performance Web applications.
The first is called output caching, which allows you to store dynamic page and user control responses on any HTTP 1.1 cache-capable device in the output stream, from the originating server to the requesting browser. On subsequent requests, the page or user control code is not executed; the cached output is used to satisfy the request.
The second type of caching is traditional application data caching, which you can use to programmatically store arbitrary objects, such as data sets, to server memory so that your application can save the time and resources it takes to recreate them.

Assembly

What is an assembly?

  1. An Assembly is a logical unit of code
  2. Assembly is unit of deployment like EXE or a DLL
  3. One assembly can contain one or more files
  4. The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs
  5. An assembly is completely self-describing.An assembly contains metadata information, which is used by the CLR for everything from type checking and security to actually invoking the components methods. As all information is in the assembly itself, it is independent of registry. This is the basic advantage as compared to COM where the version was stored in registry.
  6. When you compile your source code by default the exe/dll generated is actually an assembly Unless your code is bundled as assembly it can not be used in any other application
  7. Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other. Assemblies can be private or shared. For private assembly deployment, the assembly is copied to the same directory as the client program that references it. No registration is needed, and no fancy installation program is required.70 When the component is removed, no registry cleanup is needed, and no uninstall program is required. Just delete it from the hard drive
  8. When you talk about version of a component you are actually talking about version of the assembly to which the component belongs.
  9. Every assembly file contains information about itself. This information is called as Assembly Manifest.
  10. In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.

Thursday, August 20, 2009

.Net Framework





.NET is a Framework that consists of two main components: the common language runtime and the .NET Framework class library. That's difficult to sum up in a sentence. A more practical definition would be that .NET is a new environment for developing and running software applications, featuring easy development of web-based services, run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability.

Features:
· Interoperability with other environments
· Support for developing language-independent applications
· Support for OOPs
· Support for Web applications.
· Support for Web service


.NET base class library
The .NET base class library is a collection of object-oriented types and interfaces that provide object models and services for many of the complex programming tasks you will face. Most of the types presented by the .NET base class library are fully extensible, allowing you to build types that incorporate your own functionality into your managed code.
The .NET Framework base class library contains the base classes that provide many of the services and objects you need when writing your applications. The class library is organized into namespaces. A namespace is a logical grouping of types that perform related functions


What is CLR?
The common language runtime can be thought of as the environment that manages code execution. It provides core services, such as

1. Class loader, which loads classes into the runtime.
2. MSIL to native code compiler, which converts MSIL code into native code.
3. Code manager, which manages the code during execution.
4. Garbage collector, which performs automatic memory management.
5. Security engine, which enforces security restrictions.
6. Type checker, which enforces strict type checking.
7. Thread support, which provides multithreading support to applications.
8. Exception manager, which provides a mechanism to handl the run-time exceptions.
9. Debug engine, which allows you to debug different types of applications.
10. COM marshaler, which allows .NET applications to exchange data with COM applications.
11. Base class library support, which provides the types that the applications need at run time.

For a program to run within the common language runtime and benefit from the managed execution environment, you need to write the source code of the program in a CLS-compliant language. The compilers of CLS-compliant languages compile the source code and generate an intermediate code, called MSIL code, and metadata. The MSIL code contains a CPU-independent set of instructions, which describes how to load, store, initialize, and call methods on objects. MSIL code also contains instructions that enable you to perform arithmetic and logical operations, access memory directly, control the flow of execution, handle exceptions, and perform other operations. Before you execute the MSIL code, you need to compile it into CPU-specific instructions. To execute the code, the runtime requires information about the code that is in the metadata. The metadata describes the code and defines the types that the code contains as well as references to other types that the code uses at run time. The MSIL code and the metadata are located in a portable executable file.

When you execute a portable executable file, the class loader loads the MSIL code and the metadata from the portable executable file into the run-time memory. Before the code is executed, it is passed to the native code compiler for compilation. The IL to native code compiler contains just-in-time (JIT) compilers for different CPU architectures and compiles the IL code into a native instruction set. The IL to native code compilation occurs when a method is called for the first time. For subsequent calls to the method, the existing JIT-compiled code is executed. Figure 1.4 shows the JIT compilation process.

What is CTS?
Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.
As discussed earlier, .NET aims at providing interoperability between applications. To create interoperable applications, you need a set of standard data types that would be used across applications. In addition, you require a set of guidelines to create user-defined classes and objects for the .NET Framework. These standards data types and the set of guidelines are contained in CTS. To ensure interoperability across applications, CTS includes only those data types and features that are compatible across languages. Consider an example of an application of which a part is created using C++. Subsequently, to provide a visual interface, you need to re create the entire application in Visual Basic. This means that you need to re create all the classes that you have used in the C++ application. This is because C++ and Visual Basic are not interoperable. The CTS feature for the .NET Framework simplifies such tedious tasks. If you create a class in any of the languages in the .NET Framework, you can use the same class in another language that is supported by the .NET Framework.
What is CLS?
The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA proposed standard document;
CLS is defined as a set of rules that a .NET language should follow to allow you to create applications that are interoperable with other languages. However, to achieve interoperability across languages, you can only use
objects with features listed in the CLS. These features are called CLS-compliant features.
For example C# supports uint32, which is a 32-bit unsigned integer data type that is not CLS-compliant. The uint32 data type is not supported by Visual Basic


. NET. If you use the u i n t 3 2 data type in a C# class , the class might not be interoperable with Visual Basic .NET applications. Only a CLS-compliant code is fully interoperable across languages. Although you can use the non-CLS fe a t u re in a . N ET language cl a s s , the class might not be available to other .NET languages. CLS works closely with CTS and MSIL to ensure language interoperability. You can also call CLS as a subset of CTS and MSIL, because CLS does not include all the features of CTS and MSIL. A compiler might not support some of the features of CTS and MSIL and still be CLS-compliant.


Following are some of the features of CLS:
· Global methods and variables are not allowed in a CLS-compliant language.
· Some data types, such as unsigned data types, are not allowed in a CLS compliant language.
· Unique names should be used in a CLS-compliant language. Even if the language is case- sensitive, you must use distinct names for different variables.
· Languages that are case-insensitive should be able to differentiate between the names.
· Any exception that you want to handle must be derived from the base class Exception.
· Pointers are not supported by a CLS-compliant language.