Sunday, January 9, 2011

What is Asynchronous One-Way Calls?


asynchronise one way calls means.
One-way calls are different from asynchronous calls from execution angle that the .NET Framework does not guarantee their execution. In addition, the methods used in this kind of call cannot have return values or out parameters. One-way calls are defined by using [OneWay()] attribute in class.

what is difference between manual reset event and auto reset event.


the difference between the manual reset event and auto reset event are as following.
The difference between them is if 10 threads are waiting for a ManualReset event then all of them will start executing unless some thread programmatically (manually) resets it.

In case of autoreset in the same scenario only 1 thread will start executing & the event will be automatically reset so other threads will have to wait.

what is an application domain?


the application domain means.
The logical and physical boundary created around every .NET application by the Common Language Runtime (CLR). The CLR can allow multiple .NET applications to be run in a single process by loading them into separate application domains. The CLR isolates each application domain from all other application domains and prevents the configuration, security, or stability of a running .NET applications from affecting other applications. Objects can only be moved between application domains by the use of remoting.

Display Gridview data in Upper case using RowDataBound event


You just need to add RowDataBound event. In which you have to set all text data  in upper case.
.aspx code:
    <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
    </asp:GridView>
.aspx.cs code :
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
         for (int i = 0; i < e.Row.Cells.Count; i++)
        {
             e.Row.Cells[i].Text = e.Row.Cells[i].Text.ToUpper();
        }
     }

Difference between Function Overloading and Overriding


Function overloading Function Overriding
In function Overloading :-
Same name but different type and/or number of argument.
Share same name for separate methods.
called Static polymorphisam,Compile Time Binding.
In function Overriding:-

Same name and same argument but found in base and derived class.
Disables the superclass method.
calledDynamic polymorphisam, runtime Binding.

Get table information of Sql server database.


Sql Query:
select * FROM sysobjects

it will show the details of all system table and users table

if you want information of specific table,then you can specify table name in where clause.

ex.
select *
FROM sysobjects
where name='table_name_here'

Use of Sealed class


Sealed class is used to restrict the user from inheriting in another class.
For defining sealed class, you have to define a class with prefix sealed keyword.
Once you define a class with sealed keyword, user can not inherit further.
How to create:
sealed class Sealedclassdeom
{
}

Get Method and Property Information of class Programmatically using Reflection in c#


using System.Reflection;
           MethodInfo[] mi = typeof(class1).GetMethods();
             foreach (MethodInfo in mi)
            {
                 MessageBox.Show(m.Name);
            }

           PropertyInfo[] pi = typeof(class1).GetProperties();
             foreach (PropertyInfo in pi)
            {
                 MessageBox.Show(p.Name);
            }

Download file from Internet in Windows Application


           System.Net.WebClient wc = new System.Net.WebClient();
            wc.DownloadFile("http://www.xyz.com/abc.mp3""hello.mp3");

            // first parameter is the path of file which is on the internet
            // second parameter is the filename which is used to save in local system.

call function using string Name

           MethodInfo mi = typeof(class1).GetMethod("functionnameHere");

             mi.Invoke(nullnull);

             //if function takes argument then

             mi.Invoke(nullnew object[] { "args1""args2" });

Get the value of another sheet in a current sheet


for example , you are on a worksheet  sheet1
and you want to access value of cell A2 of sheet2.
then you can use this formula,
=Sheet2!A2

Change Administrator password in windows7


start - > run - > lusrmgr.msc.
It will open one window.
You will see two folder.
1) user
2) Groups.
here select user. when you select user , it will show its users.
in that you find one user as "administrator". right click on it,
you find one option as "Set Password".
In that you can change password directly. and then press OK!
thats it..!!!

How to use Delta() in excel


Syntax:
=delta(number1,number2)
it will checks the number1 and number2 is same or not.
If number1 and number2 are the same,then  it will returns the 1 otherwise it returns 0.
Example:
=delta(10,10)     ==> 1
=delta(1,10)     ==> 0

Access CommandLine argument in Console application in c#


public static void Main(string[] args)
{

// First method
foreach (string s in args)
{
Console
.WriteLine(s);
}
  
//Second Method
foreach (string s in Environment.GetCommandLineArgs())
{
Console
.WriteLine(s);
}


}

Convert Binary Number into Decimal Number using Bin2Dec in Excel


there is one function called Bin2Dec Which converts the number in to decimal.
Syntax:
=Bin2Dec (number)
Example:
=Bin2dec(0110)
answer:
6

Record sound using SoundRecorder in Windows7


Start -> run -> type "soundrecorder.exe" and hit enter
it will open one small application.
in that you find "start recording",then recording is starting.
when you press stop recording, it will ask for saving a sound file.
so you can make use of that file for further use

Calculate the Directory Size using c#


You can make use of this function:
        static long CalculateDirectorySize(DirectoryInfo directory,  bool includeSubdirectories)
        {
            long totalSize = 0;
             // Examine all contained files.
            foreach (FileInfo file in directory.EnumerateFiles())
            {
                totalSize += file.Length;
            }
            // Examine all contained directories.
            if (includeSubdirectories)
             {
                 foreach (DirectoryInfo dir in directory.EnumerateDirectories())
                {
                    totalSize += CalculateDirectorySize(dir, true);
                 }
             }
             return totalSize;

        }
How to call:
           DirectoryInfo dir = new DirectoryInfo("c:\\windows");
            long size = CalculateDirectorySize(dir, true);
            MessageBox.Show(size.ToString() + " Bytes");

Export datagridview to excel in vb.net

' creating Excel Application

Dim app As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application()





' creating new WorkBook within Excel application

Dim workbook As Microsoft.Office.Interop.Excel._Workbook = app.Workbooks.Add(Type.Missing)





' creating new Excelsheet in workbook

Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = Nothing



' see the excel sheet behind the program

app.Visible True



' get the reference of first sheet. By default its name is Sheet1.

' store its reference to worksheet

worksheet = workbook.Sheets("Sheet1")

worksheet = workbook.ActiveSheet



' changing the name of active sheet

worksheet.Name "Exported from gridview"





' storing header part in Excel

For i As Integer = 1 To dataGridView1.Columns.Count


  worksheet.Cells(1, i) = dataGridView1.Columns(i - 1).HeaderTextNext







' storing Each row and column value to excel sheet

For i As Integer = 0 To dataGridView1.Rows.Count - 2


  For j As Integer = 0 To dataGridView1.Columns.Count - 1



    worksheet.Cells(i + 2, j + 1) = dataGridView1.Rows(i).Cells(j).Value.ToString()

  Next
Next





' save the application

workbook.SaveAs("c:\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
  Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing)



' Exit from the application

app.Quit()

Advantage of c# over c,c++,java


Advantages over C and C++
It is compiled to an intermediate language (CIL) indepently of the language it was developed or the target architecture and operating system
Automatic garbage collection
Pointers no longer needed (but optional)
reflection capabilietis
Don't need to worry about header files ".h"
Definition of classes and functions can be done in any order
Declaration of functions and classes not needed
Unexisting circular dependencies
Classes can be defined within classes
There are no global functions or variables, everything belongs to a class
All the variables are initialized to their default values before being used (this is automatic by default but can be done manually using static constructors)
You can't use non-boolean variables (integers, floats...) as conditions. This is much more clean and less error prone
Apps can be executed within a restricted sandbox
Advantages over C++ and java
Formalized concept of get-set methods, so the code becomes more legible
More clean events management (using delegates)
  • Advantages over java
  • Usually it is much more efficient than java and runs faster
  • CIL (Common (.NET) Intermediate Language) is a standard language, while java bytecodes aren't
  • It has more primitive types (value types), including unsigned numeric types
  • Indexers let you access objects as if they were arrays
  • Conditional compilation
  • Simplified multithreading
  • Operator overloading. It can make development a bit trickier but they are optional and sometimes very useful
  • (limited) use of pointers if you really need them, as when calling unmanaged (native) libraries which doesn't run on top of the virtual machine (CLR)

Upload File/Image in asp.net

Take on fileupload control.

And one button to upload.



On button click event write this:



      string path = Server.MapPath("~/") + FileUpload1.PostedFile.FileName.ToString();
      FileUpload1.SaveAs(path);




It will save the images in root drive

Open URL in browser using Windows Application


//pass url here
string address = "http://www.google.com";
            if (!address.ToLower().StartsWith("http://"))
        {
          address = "http://" + address;
        }
         con.Close();

       System.Diagnostics.Process.Start(address);

Difference between primary key and unique key ?


Both provides uniqueness of records.
Primary key does not allow null values. but unique key allows one null value.
Primary key creates clustured index on the column, unique key creates nonclustured index on the column.

Defination : 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 the table has more than one candidate key, one of them will become the primary 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 lock escalation?

Lock escalation is the process of converting a lot of low level locks into higher level locks. Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks.

List Different Normalization Forms


1NF
2NF
3NF
BCNF: Boyce-Codd Normal Form
4NF
5NF
ONF: Optimal Normal Form
DKNF: Domain-Key Normal Form

Difference between DELETE and TRUNCATE


Delete command removes rows based on the criteria which we define on Where clause.
Truncate removes all the rows from the table.
Syntax for Delete:
DELETE FROM tablename WHERE column_name <op> value
ex.
DELETE FROM employee where EMPID>10
it will removes all the employee havind EMPID is greater than 10.
Syntax for TRUNCATE:
TRUNCATE TABLE tablename
ex.
TRUNCATE TABLE employee
it will remove all the records from employee table:
Similarity:
delete from employee
is similar to
truncate table employee

How to create folder in c#


           System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("c:\\hello");
            if (!dir.Exists)
            {
                 dir.Create();
            }
it will check the directory exists or not if it is not exist then it will create the directory.

How to rename a database.


Syntax:
sp_renamdb 'olddatabasename' 'newdatabasename'

How to create folder in c#


           System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("c:\\hello");
            if (!dir.Exists)
            {
                 dir.Create();
            }
it will check the directory exists or not if it is not exist then it will create the directory.

How to delete duplicate rows

SELECT col1, col2, count(*)
FROM t1
GROUP BY col1, col2
HAVING count(*) > 1

check number is perfect number or not using c#


here  we can check the number is perfect number or not using the following code.
public bool IsPerfectNumber(int no)
{
            int i, j;
            int sum = 0;

             for (i = 1; i <= no; i++)
             {

                 if (no % i == 0)
                {
                    j = no / i;

                      if (j != no)
                         sum = sum + j;

                  }
             }
             if (sum == no)

                 return true;

             else
          
     return false;

}

Use of distinct in sql server


the word distinct is make the information of the field in the group.
we can understand it easily to se the example if the distinct.

syntex:-
select distinct <field name> from table name;

example:-

suppose there is data of database named "dept" as follow

     dept salary

salary 10,000
sales 11,000
salary 5,000
sales 7,000

select distinct dept,salary from dept;

output is:-

dept_name     salary

salary       15,000

sales       18,000

what is self join in sql server

the word self join means the table is join with it self it's called the self join.

the example of the self join is..

suppose we have to get the information from the table that is there any field that can contain the same value

then we can find the information wth the self join as below.

select * from employee e,employee f where e.emp_name=f.emp_name.

Difference between ORDER BY clause and GROUP BY clause in sql server.


here is the most comman difference of the order by clause or group by clause.
==>  the order by clause display the data in the sorted order of the given field

ex:- select * from employee order by emp_name desc,emp_no asc;

this query gives the output  in the ascending oredr of the emp_no and descending order of the emp_name.

==> while the group by clause is use to display the data in group of given field.

ex;- select * from employee group by emp_name.

this give the output data in the group of the emp_name.

what is integrity constraints in sql server.

the integity constraints are that changes made to the database by authorized users do not result in a loss of data consistency.

thus, the integrity constraints guards against the accidental damage to the database.

example of the integrity constraints are as follow.

(1) an account balance cannot be null.
(2) no two accounts can have the same account number
(3) every account number in the depositor relation must have the matching account number in the account relation.

what is PRIVILEGE in SQL Server

privilege means to give the some authotity to user such as

-authorisation to read data.
-authorisation to insert new data.
-authorisation to update data.
-authorisation to delete data.

each of this kind of authorisation is called privileges.

what is EMBEDDED sql in sql server


the means of the embedded sql is as follow.
==>the embedded means to coding the sql query in the general purpose programing language.and programmer must            access to a database

==> from general purpose programming language its called the embedded sql.

what is DYNAMIC sql in sql server


the means of the dynamic sql is as follow.
===>  the dynamic sql means component of sql allows program to construct and submit sql queries at run time it's called          the dynamic sql.

difference between EMBEDDED sql and DYNAMIC sql in sql server

the difference between the embedded and dynamic sql is as follows.

(1) the embedded means to coding the sql query in the general purpose programing language.and programmer must access to a database

from general purpose programming language its called the embedded sql.

-->the dynamic sql means component of sql allows program to construct and submit sql queries at run time it's called the dynamic sql.

(2)embedded sql statement must be completely present at the compile time.

-->while in the dynamic sql statement not present compile time only present at run time pehapes based on user input.

what is use of interlocked class


the use of the inter locked class is.
interlocked Class

Provides atomic operations for variables that are shared by multiple threads.

what is manualreset event and auto reset event.


the meaning of th manual reset event an auto reset eventis.
both the events are the synchronise object such as monitor and semaphoresBoth of them can be used across processes as
these are kernel objects.

what is difference between %type and %rowtype

==>The %ROWTYPE attribute provides a record type that represents a row in a table.

    Create Type is used to create a type with multiple variables and is stored in the database.

==>%ROWTYPE is to be used whenever query returns a row of Database Table.

    RECORD TYPE is to be used whenever query returns a columns of different Tables.

    Eg :  TYPE <TYPE_NAME> IS RECORD (Name  Varchar2,No    Number);

What is Reader Writer Locks?


the use of the reader writer lock is as follow.
A reader/writer synchronization lock can and should be used to improve performance and scalability. A reader/writer lock ensures that only one thread can write to a resource at any one time and it allows multiple threads to read from a resource simultaneously as long as no thread is writing at the same time.

what is wi-fi and full form of wi-fi


-->Wi-Fi is a trademark of the Wi-Fi Alliance that may be used with certified products that belong to a class of wireless local area network (WLAN) devices based on the IEEE 802.11 standards.
-->A communication system that uses low-power microwave radio signals to connect laptop computers, PDAs, and web-enabled cell phones to the Internet.
-->full form of wi-fi is  Wireless fidelity.

What is AJAX


AJAX means.
AJAX = Asynchronous JavaScript and XML.

AJAX is not a new programming language, but a new way to use existing standards.

AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page

how to consume web service in atlas


There are two ways by which we can consume a web service one is using ‘Services’ tag and the other is by using
properties defined in Ajax components like ‘ServicePath’ , ‘ServiceMethod’ and ‘ServiceURL’. 
We can define the web service URL in the ‘Services’ tag using ‘atlas:ServiceReference’ tag. ‘Path’ property defines the web
service URL. If we also want to generate javascript proxy we need to set the ‘GenerateProxy’ to true. We have also set
one more property i.e. ‘InlineProxy’ property needs to be true so that the proxy code is available to the client javascript.
<atlas:ScriptManager IP="ScriptManager1" runat="server" EnablePartialRendering="True">
<Services>
     <atlas:ServicesReference InlineProxy="true" GenerateProxy="true" Path="webservice.asmx"/>
</Services>
</atlas:ScriptManager>

Hashtable in c#.net


A Hashtable is a collection of key-value pairs. In .NET, the class that implements a hash table is the Hashtable class.
Elements can be added to the hash table by calling the Add method passing in the key-value pairs that you want to add.
The objects used as keys must implement
Object.Equals and Object.GetHashCode methods.
The value can be any type.

The Appsettings section in WEB.CONFIG file.

Web.config file defines configuration for a web project. Using “AppSetting” section, we can define user-defined values. Example below defined is “Connection String” section, which will be used through out the project for database connection.

<Configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>

What Is The Windows Registry?

The Windows Registry is a directory which stores settings and options for Microsoft Windows operating systems. It contains information and settings for all the hardware, operating system software, most non-operating system software, and per-user settings.   If necessary, you can manually edit the registry by doing the following:

1.  Hit Start Button
2.  Select "Run"
3.  Type regedit and then hit the enter key

Any change you make in the registry is saved automatically.

What are the features are provided by LINQ to fine tuning concurrency at field level?


the features are as follows.

One of the best options provided by LINQ concurrency system is control of concurrency behavior at field level. There are three options we can specify using the ‘UpdateCheck’ attribute:-
• Never: - Do not use this field while checking concurrency conflicts.
• Always: - This option specifies that always use this field to check concurrency conflicts.
• WhenChanged :- Only when the member value has changed then use this field to detect concurrency conflicts.

Below is the code which show how we can use the ‘UpdateCheck’ attribute to control property / field level concurrency options as specified above.

[Column(DbType = "nvarchar(50)",UpdateCheck=UpdateCheck.Never)]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}

What kind of error reporting options are provided by LINQ when concurrency conflict occurs?


the option are as follows.

=> ContinueOnConflict :- This option says to the LINQ  engine that continue even if there are conflicts and finally return all conflicts at the end of the process.

=> FailOnFirstConflict :- This option says stop as soon as the first conflict occurs and return all the conflicts at that moment. In other words LINQ engine does not continue ahead executing the code.


Both these options can be provided as an input in ‘SubmitChanges’ method using the ‘ConflictMode’ enum. Below is the code of how to specify conflict modes.

=> objContext.SubmitChanges(ConflictMode.ContinueOnConflict);

=> objContext.SubmitChanges(ConflictMode.FailOnFirstConflict);

How can we use XML files to map stored procedures with .NET classes?

n case you have stored procedures in your project you can use ‘Function’ XML element to define your stored procedure name in the XML file. The client code does not change for binding the datacontext and XMLMappingsource object as below.

<?xml version="1.0" encoding="utf-8"?>

<Database Name="TstServer" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">

<Table Name="dbo.Customer" Member="WebAppMappingXML.clsCustomer">

<Type Name="WebAppMappingXML.clsCustomer">

<Column Name="CustomerId" Member="CustomerId" />

<Column Name="CustomerName" Member="CustomerName" />

<Column Name="CustomerCode" Member="CustomerCode" />

</Type>

</Table>

<Function Name="dbo.sp_getCustomerCode" Method="getCustomerByCode">

<Parameter Name="CustomerCode" Parameter="" />

<ElementType Name="clsCustomer" />

</Function>

</Database>

Explain One time binding in silverlight.

-->In one time binding data flows from object to the UI only once.

--> There is no tracking mechanism to update data on either side.

-->One time binding has marked performance improvement as compared to the previous two bindings discussed.

-->This binding is a good choice for reports where the data is loaded only once and viewed.

<TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=OneTime}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

What are the different ways provided to do layout in SilverLight?

==>There are three ways provided by Silverlight for layout.

(1)  management Canvas
(2) Grid
(3) Stack panel


Each of these methodologies fit in to different situations as per layout needs.
All these layout controls inherit from Panel class. 

Why can’t we consume ADO.NET directly in SilverLight?

==> Below are the different ingredients which constitute SilverLight plugin.

One of the important points to be noted is that it does not consist of ADO.NET. In other words you can not directly call ADO.NET code from SilverLight application. Now the other point to be noted is that it has the WCF component. In other words you can call a WCF service.

In other words you can create a WCF service which does database operations and silverlight application will make calls to the same. One more important point to be noted is do not return ADO.NET objects like dataset etc because  SilverLight will not be able to understand the same.

Saturday, January 8, 2011

Zip/compress one file using Gzipstream


using System.Security.Cryptography;

        private void button1_Click(object sender, EventArgs e)
        {

            // Path to file to compress and decompress.
            string fpath = @"e:\hello.exe";
           
            FileInfo f1 = new FileInfo(fpath);
                 Compress(fi);

         
            string fpath2 = @"e:\hello.gz";
            FileInfo f2 = new FileInfo(fpath2); 
                Decompress(f2);
           

        }
      
        public static void Compress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Prevent compressing hidden and
                // already compressed files.
                if ((File.GetAttributes(fi.FullName)
                  & FileAttributes.Hidden)
                  != FileAttributes.Hidden & fi.Extension != ".gz")
                {
                    // Create the compressed file.
                    using (FileStream outFile =
                                    File.Create(fi.FullName + ".gz"))
                    {
                        using (GZipStream Compress =
                              new GZipStream(outFile,
                              CompressionMode.Compress))
                        {
                            // Copy the source file into
                            // the compression stream.
                        inFile.CopyTo(Compress);

                            Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                                fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                        }
                    }
                }
            }
        }

        public static void Decompress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Get original file extension, for example
                // "doc" from report.doc.gz.
                string curFile = fi.FullName;
                string origName = curFile.Remove(curFile.Length -
                        fi.Extension.Length);

                //Create the decompressed file.
                using (FileStream outFile = File.Create(origName))
                {
                    using (GZipStream Decompress = new GZipStream(inFile,
                            CompressionMode.Decompress))
                    {
                        // Copy the decompression stream
                        // into the output file.
                            Decompress.CopyTo(outFile);
                            
                        Console.WriteLine("Decompressed: {0}", fi.Name);

                    }
                }
            }
        }

Send Email from asp.net


using System.Net.Mail;



        String userName = "your username";
        String passWord = "your password";
        String sendr = "your email id";
        String recer = "receiver of email";
        String subject = "subject of email";
        String body = "body part of email";

        MailMessage msgMail = new MailMessage(sendr, recer, subject, body);

        int PortNumber = 587; // port number
        SmtpClient smtp = new SmtpClient("smtpservername", PortNumber);
        msgMail.IsBodyHtml = true;
// if your body contains html tag

        
smtp.EnableSsl = true;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.Credentials = new System.Net.NetworkCredential(userName, passWord);
        try
        {

            smtp.Send(msgMail);
        }
        catch (Exception exp)

        {
            // error handling
        }