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
        }

Get am/pm from datetime in sql query


below query gives you the am/pm from table field "yourdate"
and it gives in ascending order

SELECT SUBSTRING(CONVERT(varchar(20), yourdate, 22), 18, 3)  AS Expr1
FROM      table
ORDER BY expr1 ;

SUBSTRING(CONVERT(varchar(20), yourdate, 22), 18, 3)-->it gives you a am/pm.
o/p:
----
am
pm
am
pm

how to disable right click on images


this is script for disable right click on images for html pages.


  
<script language="JavaScript">
var clickmessage="Right click disabled on images!"
function disableclick(e)
{
if (document.all)
{
if (event.button==2||event.button==3)
     
{

if (event.srcElement.tagName=="IMG")
{
alert(clickmessage);
                  return false;
}
}
}
else if (document.layers)
{
if (e.which == 3)
{
alert(clickmessage);
return false;
}
}
else if (document.getElementById)
{
if (e.which==3&&e.target.tagName=="IMG")
{
            alert(clickmessage)
return false
}
}
}

function associateimages()
{
for(i=0;i<document.images.length;i++)
document.images[i].onmousedown=disableclick;
}
if (document.all)
{
document.onmousedown=disableclick
}
else if (document.getElementById)
{
document.onmouseup=disableclick
}
else if (document.layers)
{
associateimages()
}
</script>

How to disable particular Day of a Week in ASP.Net Calendar control?

The below little code snippet will help you to do that by using DayRender event of Calendar control.



ASPX
<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender"> </asp:Calendar>

CodeBehind
  protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.Date.DayOfWeek == DayOfWeek.Monday)
        {
            e.Day.IsSelectable = false;
        }
     }

How to disable to select Weekends(Saturday and Sunday) in Calendar control in asp.net?

and here is a solution for that :)


.aspx

<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender">
</asp:Calendar>

Code-behind
    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.IsWeekend)
        {
            e.Day.IsSelectable = false;
        }

    }

How to convert String to Char[] and Char[] to String?

First, we see how to convert string to character Array

string str = "Hello World!";
char[] ch = str.ToCharArray();




now, we see how to convert character array to string:

string strtarget = new string(ch);

Get maximum date from two different columns in a new columnn


if you want to get maximum date from two different columns you can like this:

select date1,date2,( (date1<date2)*date2 + (date2<date1)*date1 ) as maxdate
from table1.


if you want maximum date from field date1 and date2 and store into field date3 then you can use this formula:

update table1
set date3= ( (date1<date2)*date2 + (date2<date1)*date1 )

give hyperlink of specific worksheet in another workbook

here i am showing how to give link of particular worksheet ( lets take sheet1) of workbook(workbook1)
in another workbook ( workbook2).

then in workbook follow the steps as below :)




• Select a cell where you want to place the hyperlink;
• Type a description of the workbook you want to link to;
• Right click on that cell and choose Hyperlink...;
• Click the File... button and browse to the file location;
• Select the file you want to link to and click OK;
• If you want to go to a specific sheet in the workbook, click on the Bookmark... button, select the sheet name and click OK.


• You can also click the Screen Tip... button to add a description to your hyperlink that will pop up when a user holds the mouse over the hyperlink.
• Click OK to close the Insert Hyperlink dialog box and save your workbook.
• Try out the hyperlink to see how it works.

Get Multiple selected Items from Listbox in asp.net


There is no selecteditems method which returns listiem array. So here we can get the selectedindices and through index we can access the listbox selected item.


        Dim index() As Integer = Listbox1.GetSelectedIndices()
        For Each i In index
            MsgBox(Listbox1.Items(i).Value)
        Next

Verify path is directory or file

string path=@"C:\Desktop";
           
            if (System.IO.Directory.Exists(path))

             {
                 MessageBox.Show("Directory");

             }
              if(System.IO.File.Exists(path))
            {
                 MessageBox.Show("File");
            }

Difference between the DataGridView and DataGrid

Differences between the DataGridView and DataGrid controls
The DataGridView control provides numerous basic and advanced features that are missing in the DataGrid control. Additionally, the architecture of the DataGridView control makes it much easier to extend and customize than the DataGrid control.

Multiple column types
The DataGridView control provides more built-in column types than the DataGrid control. These column types meet the needs of most common scenarios, but are also easier to extend or replace than the column types in the DataGrid control.

Multiple ways to display data 
The DataGrid control is limited to displaying data from an external data source. The DataGridView control, however, can display unbound data stored in the control, data from a bound data source, or bound and unbound data together. You can also implement virtual mode in the DataGridView control to provide custom data management.

Multiple ways to customize the display of data
The DataGridView control provides many properties and events that enable you to specify how data is formatted and displayed. For example, you can change the appearance of cells, rows, and columns depending on the data they contain, or you can replace data of one data type with equivalent data of another type.

Multiple options for changing cell, row, column, and header appearance and behavior
The DataGridView control enables you to work with individual grid components in numerous ways. For example, you can freeze rows and columns to prevent them from scrolling; hide rows, columns, and headers; change the way row, column, and header sizes are adjusted; change the way users make selections; and provide ToolTips and shortcut menus for individual cells, rows, and columns.
The only feature that is available in the DataGrid control that is not available in the DataGridView control is the hierarchical display of information from two related tables in a single control. You must use two DataGridView controls to display information from two tables that are in a master/detail relationship.

Remove All Spaces From The Cell In Excel

Here we make use of substitute function to remove all spaces from the cell

For example,
Cell       A5       has value like “       12 34 56 78 st tin sd   ”

Then formula

=SUBSTITUTE(A5," ","")


It will give output as

12345678sttinsd

cropping image in c#


here i will create one bitmap from the image.
and using clone method i am getting(crop) the cropped image.

code snippet :


           Image img = Image.FromFile("c:\\hello.jpg");
           Bitmap bmpImage = new Bitmap(img);
           Bitmap bmpCrop = bmpImage.Clone(new Rectangle(100, 100, 300, 300), bmpImage.
           PixelFormat);

             bmpCrop.Save("c:\\hellocrop.jpg");

Access Browser Information Using JavaScript

<script type="text/javascript">


document.write("Browser CodeName: " + navigator.appCodeName);

document.write("<br /><br />");

document.write("Browser Name: " + navigator.appName);

document.write("<br /><br />");

document.write("Browser Version: " + navigator.appVersion);

document.write("<br /><br />");

document.write("Cookies Enabled: " + navigator.cookieEnabled);

document.write("<br /><br />");

document.write("Platform: " + navigator.platform);

document.write("<br /><br />");

document.write("User-agent header: " + navigator.userAgent);


</script>



it will give o/p as (for my computer) :


Browser CodeName: Mozilla

Browser Name: Opera

Browser Version: 9.80 (Windows NT 5.1; U; en)

Cookies Enabled: true

Platform: Win32

User-agent header: Opera/9.80 (Windows NT 5.1; U; en) Presto/2.5.22 Version/10.51

How To Find The Page Referrer in asp.net


Response.Write(Request.UrlReferrer.ToString());


by using Request.UrlReffer you can get the address of page which refers your page.

Function Which can accept n-number of argument.

    protected void add(params int[] arr)
    {
         int total = 0;
        foreach (int i in arr)
        {
            total += i;
        }
        
    }

above function can be called with n-number of argument.
   add(1, 2, 3, 4, 5, 6, 7, 9, 10);
   add(1, 2, 3, 4, 5, 6, 7, 9);
   add(1 );

Change Brightness of Image Realtime


public static Bitmap AdjustBrightness(Bitmap Imageint Value)
        {
           System.Drawing.Bitmap TempBitmap = Image;
            float FinalValue = (float)Value / 255.0f;
           System.Drawing.Bitmap NewBitmap = new System.Drawing.Bitmap(TempBitmap.Width, TempBitmap.Height);
           System.Drawing.Graphics NewGraphics = System.Drawing.Graphics.FromImage(NewBitmap);
             float[][] FloatColorMatrix ={
                     new float[] {1, 0, 0, 0, 0},
                     new float[] {0, 1, 0, 0, 0},
                     new float[] {0, 0, 1, 0, 0},
                     new float[] {0, 0, 0, 1, 0},
                     new float[] {FinalValue, FinalValue, FinalValue, 1, 1}
                };

           System.Drawing.Imaging.ColorMatrix NewColorMatrix = newSystem.Drawing.Imaging.ColorMatrix(FloatColorMatrix);
           System.Drawing.Imaging.ImageAttributes Attributes = newSystem.Drawing.Imaging.ImageAttributes();
           Attributes.SetColorMatrix(NewColorMatrix);
             NewGraphics.DrawImage(TempBitmap, new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0, TempBitmap.Width, TempBitmap.Height, System.Drawing.GraphicsUnit.Pixel, Attributes);
           Attributes.Dispose();
            NewGraphics.Dispose();
            return NewBitmap;
        }

close specific child form with specified name in windows application


            foreach (Form aForm in this.MdiChildren)
            {
                 if (aForm.Name == "Form1")
                 {
                     aForm.Close();
                     break;
                 }
             }

Find The Modem Which Is Attached to Computer

Here I will show you how you can get modem information using WMI and C#

Create new project - > now add reference  System.Management;

Code is:


using System.Management;


            ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_POTSModem");


            foreach (ManagementObject mo in mos.Get())
            {
                listBox1.Items.Add(mo["Caption"].ToString());

            }


If you use caption here, it will show the name of modem
If you want to get more information , you can refer this link:

http://msdn.microsoft.com/en-us/library/aa394360(VS.85).aspx

Get Last Cell value Used Within Specific Column


=INDIRECT("A"&COUNTA(A:A))
it will sho
w the cell value which is used by user.

Get Cumulative sum in specific column of table.

lets take sample data


ID       Amount1  Amount2
1         15
2         30
3         45
4         60


here amount2 is empty and we want cumulative sum in amount2 based on column amount1 , then you can use this query

update table_name as t1set amount2 = amount1 + ( select max(amount2) from table_name where id < t1.id )

Extracting numerator and denominator from a fraction

trick_1:


if you want ansere like 475/5, then the numerator becames 95, and denominator  becames 1.
for getting answer 95, you can use this formula

=RIGHT(TEXT(A1,"? ?/?"),LEN(TEXT(A1,"? ?/?"))-FIND("/",TEXT(A1,"? ?/?")))

or

=RIGHT(TEXT(A1,"? ?/????????"),LEN(TEXT(A1,"? ?/????????"))-FIND("/",TEXT(A1,"? ?/????????")))


trick_2:
numerator
=LEFT(TEXT(A1,"???/???"),FIND("/",TEXT(A1,"???/???"))-1)+0

denominator
=RIGHT(TEXT(A1,"???/???"),FIND("/",TEXT(A1,"???/???"))-1)+0

How to set Session Timeout in web.config

under system.web you can write session state.

<system.web>
       <sessionState     timeout="60"  />
</system.web>

The session time-out refers to the number of minutes before the user session is aborted. If a large file is being uploaded it is desirable to maintain the session state. The session time-out should always be longer than the amount of time you expect uploads to take. Note that this value is only relevant if you have session state enabled.
In the above web.config file above the sessionState is set to one hour.

C# .NET Change Brightness of Image - JPG, GIF, or BMP


public static Bitmap AdjustBrightness(Bitmap Imageint Value)
        {
            System.Drawing.Bitmap TempBitmap = Image;
            float FinalValue = (float)Value / 255.0f;
           System.Drawing.Bitmap NewBitmap = new System.Drawing.Bitmap(TempBitmap.Width, TempBitmap.Height);
           System.Drawing.Graphics NewGraphics = System.Drawing.Graphics.FromImage(NewBitmap);
             float[][] FloatColorMatrix ={
                     new float[] {1, 0, 0, 0, 0},
                     new float[] {0, 1, 0, 0, 0},
                     new float[] {0, 0, 1, 0, 0},
                     new float[] {0, 0, 0, 1, 0},
                     new float[] {FinalValue, FinalValue, FinalValue, 1, 1}
                 };

           System.Drawing.Imaging.ColorMatrix NewColorMatrix = newSystem.Drawing.Imaging.ColorMatrix(FloatColorMatrix);
            System.Drawing.Imaging.ImageAttributes Attributes = newSystem.Drawing.Imaging.ImageAttributes();
           Attributes.SetColorMatrix(NewColorMatrix);
             NewGraphics.DrawImage(TempBitmap, new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0, TempBitmap.Width, TempBitmap.Height, System.Drawing.GraphicsUnit.Pixel, Attributes);
           Attributes.Dispose();
            NewGraphics.Dispose();
            return NewBitmap;
        }

Blink the of form tab in Taskbar using FlashWindow from user32.dll

using System.Runtime.InteropServices;



        [DllImport("user32.dll")]

        public static extern int FlashWindow(IntPtr Hwnd, bool Revert); 



         // Add form's resize event to judge whether a form has been minimized or not.

        private void Form4_Resize(object sender, EventArgs e)

        {

             if (this.WindowState == FormWindowState.Minimized)

                 FlashWindow(this.Handlefalse);

        }

Change the font size and color of tooltip control text

string buttontooltip = "click here";
        public Form1()
        {
             InitializeComponent();
            toolTip1.SetToolTip(button1, buttontooltip);
            toolTip1.OwnerDraw = true;
            toolTip1.Draw += new DrawToolTipEventHandler(toolTip1_Draw);
             toolTip1.Popup += new PopupEventHandler(toolTip1_Popup);
         }

        void toolTip1_Popup(object sender, PopupEventArgs e)
        {
           e.ToolTipSize = TextRenderer.MeasureText(buttontooltip, new Font("Arial", 16.0f));
        }

        void toolTip1_Draw(object sender, DrawToolTipEventArgs e)
         {
             using (e.Graphics)
            {
               Font f = new Font("Arial", 16.0f);
                 e.DrawBackground();
                e.DrawBorder();
                buttontooltip = e.ToolTipText;
                 e.Graphics.DrawString(e.ToolTipText, f, Brushes.Rednew PointF(2, 2));
              
            }

        }

add gridview data to database

     foreach (DataRow dr in GridView1.Rows)
        {
// assumed that you have four columns in your gridview
            string t1 = dr[0].ToString();
             string t2 = dr[1].ToString();
             string dd1 =  dr[2].ToString();   
             string t3 = dr[3].ToString();

             string sql = "insert into table1 values('" + t1 + "','" + t2 + "','" + dd1 + "','" + t3 + "')";

           SqlConnection cn = new SqlConnection("conn");
           SqlCommand cmd = new SqlCommand(sql, cn);
             cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
        }

Here iterate through all the rows in gridview, get each cell value
from the cell values genearate sql string and then execute query.

make use foreach loop in java

int i[] = {1,2,3,4,5}

// now, if we want to iterate through each item of array i, then we can use foreach loop like this


for( int temp_var : i )
{


System.out.println ( temp_var)
}


o/p:

1
2
3
4
5

Learn OOPS Concepts: class,objects,inheritance,polymorphism,data encapulation and data abstraction


Classes & Objects :
Class is a collection of member data and member functions. objects contain data and code to manipulate that data. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In fact, objects are variables of type class. Once a class has -been defined, we can create any number of objects belonging to that class. Each object is associated with the data of type class with which they are created: A class is thus a collection of objects of similar type. For example, mango, apple and orange are members of the class fruit: Classes are user-defined data types and behave like the built-in types of a programming language. For example, the syntax used to create an object is no different than the syntax used to create an integer object in C. If fruit has been defined as a class, then the statement fruit mango; will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation
The wrapping. up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. These functions provide the interface between the object's data and the program. This insulation of the data from direct access by the program is called data hiding.
Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the essential properties of the objects that are to be created. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).
Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. For example, the bird robin is a part of the class flying bird which is again a part of the class bird. As illustrated in Fig.l.8, the principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived. In, OOP, the concept of inheritance provides the idea of reusability .This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. The real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what he wants; and to tailor the class in such a way that it does not introduce any undesirable side effects into the rest of the classes.
Note that each sub class defines only those features that are unique to it. Without the use of classification, each class would have to explicitly include all of its features.
Polymorphism
Polymorphism is another important OOP concept Polymorphism means the ability to take more than one form.. For example, an operation may exhibit different behavior m different instances.. The behavior depends upon the types. of data used in the operation For example, consider the operation of addition. For two numbers, the operation will generate a sum lf the operands are strings, then the operation would produce a third string by concatenation. Figure, l.9 illustrates that a single function name can be used to handle different number and different types of arguments. This is something similar to a particular word having several different meanings depending on the context.
Polymorphism plays an important in allowing objects having different internal structures to share the same external interface. This is means that a general class of operations may be accessed in ~ the same manner even though specific actions associated with each operation may differ: Polymorphism is extensively used in implementing inheritance.

call javascript function from the code behind page


learn how to call javascript function from the code-behind page programatically

string jv = "<script>openWin();</script>";

        Page.RegisterClientScriptBlock("JS", jv);

Last Day Of Month.

   int i = System.DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
      int j = System.DateTime.DaysInMonth(2010,3);


         
                   MessageBox.Show("Last Day is : " + i.ToString());
                   MessageBox.Show("Last Day is : " + j.ToString());