Rss Feed Like Us on facebook Google Plus
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

July 4, 2013

How to prevent page going back on backspace button click

Stop page going back on backspace button click in asp.net,C#,java,PHP.


1. To prevent page going back on backspace or browser back button. you can achieve this by short snippet by javascript below.

<script type="text/javascript">
function preventBack() 
{ 
    window.history.forward(); 
}
setTimeout(function () { preventBack() }, 0);
window.onunload = function () { null };
</script>
.

Follow my blog with Bloglovin
Read More

Disable Button after once Click by Javascript

Disable Button after clicking on it.If when you set disabled="disabled" immediately after
the user clicks the button, and the form doesn't submit because before form submission button is already diasabled..

Uses- It prevents double form submission/ prevent double postback


 you could try these things

1st Way...

//JAVASCRIPT
<script type="text/javascript">
function disable() {
            var v = confirm('Are you sure to save');
            if (v == true) {
                setTimeout(function () { document.getElementById('<%= btnSave.ClientID %>').disabled = true }, 1);
                return true;
            }
            return false;
        }
 
        function preventBack() { window.history.forward(); }
        setTimeout(function () { preventBack() }, 0);
        window.onunload = function () { null };
</script>
//HTML
<input type="button" id="btnsave" runat="server" value="Save" onclick="javascript:disable()" />
2nd Way

myInputButton.disabled = "disabled";
myForm.submit()
Whether it be due to a users lack of tech know-how or a twitch of the finger, a secondary click of a forms ‘Submit’ button could result in the form being submitted twice. Depending on the action of the form this could in turn send two enquiries, create two orders or insert a record into the database twice.

3rd Way

<input type="submit" name="Submit" value="Submit" onclick="this.disabled=true; this.value='Please Wait...';" /> 

4th Way
We can also use AJAX to disable postback element on Request Begin to prevent multiple clicks.

<form id="form1" runat="server">
<asp:scriptmanager id="sc" runat="server" enablepartialrendering="true">  
</asp:scriptmanager>
<script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginReq);
    function beginReq(sender, args) {
        document.getElementById('<%= lblMessage.ClientID %>').innerText = "Processing.....";
        args.get_postBackElement().disabled = true;
    }  
</script>
<asp:updatepanel id="updpnlSubmit" runat="server">  
    <ContentTemplate>  
        <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />  
        <asp:Label ID="lblMessage" runat="server"></asp:Label>  
    </ContentTemplate>  
</asp:updatepanel>
</form>

Read More

June 27, 2013

change internet explorer page setup programmatically with C#

Change printer setting of internet explorer with C#,basically you can change it bu updating
registry key.

Users can easily change Internet Explorer printer settings for the page margins, the header, and the footer through the Internet Explorer user interface. However, Internet Explorer and the Web Browser control do not include methods to change these settings programmatically.

The following steps outline how Microsoft Internet Explorer accesses the printer settings:

  1. Internet Explorer tries to obtain the values from the following registry key:
    HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\PageSetup
  2. If the key in step 1 does not exist, Internet Explorer tries to create this key by copying the values from the following key:
    HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\PageSetup
  3. If the key in step 2 does not exist, default values are provided.
Checkout the below program..

using Microsoft.Win32;
 
namespace iesttings
{
    Class ie
    {
        public void ChangeIEPageSetupSetting()
        {
            string strKey = "Software\\Microsoft\\Internet Explorer\\PageSetup";
            bool bolWritable = true;
            string strName = "header";
            object oValue = "";
            string strName1 = "footer";
            object oValue1 = "";
            string strName2 = "margin_top";
            object oValue2 = "0.75";
            string strName3 = "margin_right";
            object oValue3 = "0.75";
            string strName4 = "margin_bottom";
            object oValue4 = "0.75";
            string strName5 = "margin_left";
            object oValue5 = "0.75";
 
            RegistryKey oKey = Registry.CurrentUser.OpenSubKey(strKey, bolWritable);
 
            oKey.SetValue(strName, oValue);
            Console.WriteLine("0 updated");
            oKey.SetValue(strName1, oValue1);
            Console.WriteLine("1 updated");
            oKey.SetValue(strName2, oValue2);
            Console.WriteLine("2 updated");
            oKey.SetValue(strName3, oValue3);
            Console.WriteLine("3 updated");
            oKey.SetValue(strName4, oValue4);
            Console.WriteLine("4 updated");
            oKey.SetValue(strName5, oValue5);
            Console.WriteLine("5 updated");
 
            oKey.Close();
            Console.ReadLine();
 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           ie obj = new ie();
            obj.ChangeIEPageSetupSetting();
        }
    }
}

Note : - Your Web Application should have rights to change the registry settings.

Read More

June 4, 2013

Generate Excel to Export Data using Datatable

Generate Excel is a Major Feature which is used frequently in Web Applications as well as
in Console Applications. So i am going to present an article about generating excel with MS-Excel installed on and without MS-Excel installed on target computer.

Problem with Excel Automation
The technique that is most frequently used to transfer data to an Excel workbooks is Automation. With Automation, you can call methods and properties that are specific to Excel tasks, but this solution has many drawbacks. Some of them are described in the Microsoft Knowledge Base. Additionally, you have to manage the lifetime of the temporary Excel files(.xls) created on the server. Also, it is slow, because Excel runs in a separate process.


  • You can generate excel without MS-Office installed on target computer..
  • You Can Export Data Table data to created Excel

class GenerateExcel
 
{
//  This function will Genereate Excel without MS-Office installed on target computer
 public void CreateExcel(string fileName)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
                Console.WriteLine("** Excel Deleted ***");
            }
            if (!File.Exists(fileName))
            {
                FileStream stream = new FileStream(filename, FileMode.OpenOrCreate); 
                stream.Close();
                Console.WriteLine("** Excel Created ***");
            }
        }
  
        public void createExcelwithMSOffice(string fileName)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
                Console.WriteLine("** Excel Deleted ***");
                swlog.WriteLine("***  Excel Exists....Excel Deleted.....  ***");
            }
            if (!File.Exists(fileName))
            {
                Application xl = null;
                _Workbook wb = null;
                object misValue = System.Reflection.Missing.Value;
 
                xl = new Application();
                xl.SheetsInNewWorkbook = 1;
                wb = (_Workbook)(xl.Workbooks.Add(Missing.Value));
                wb.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                wb.Close(true, misValue, misValue);
                Console.WriteLine("** Excel Created ***");
                swlog.WriteLine("***    New Excel Created     ***");
            }
        }
 
 //  This function will export Datatable Data to Created Excel......

        public void ExportToSpreadsheet(System.Data.DataTable table, string name)
        {
            StreamWriter sw = null;
            sw = new StreamWriter(name);
            string ColValue;
            string ColName = "";
            if (table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    ColName = table.Columns[i].ColumnName.ToString() + "\t";
                    sw.Write(ColName);
                }
                sw.WriteLine("\t");
                foreach (DataRow row in table.Rows)
                {
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        ColName = table.Columns[i].ColumnName.ToString();
                        ColValue = row[i].ToString();
                        ColValue = ColValue.ToString().Replace(",", string.Empty) + "\t";
                        ColValue = ColValue.ToString().Replace(Environment.NewLine, " ");
                        ColValue = ColValue.ToString().Replace("\n", " ");
                        //ColValue = ColValue.ToString().Replace(" ", "");
                        ColValue = ColValue.ToString().Replace("-Select-;", "");
                        if (table.Columns[i].DataType.Name == "Boolean")
                        {
                            ColValue = ColValue.ToString().Replace("True", "Yes");
                            ColValue = ColValue.ToString().Replace("False", "No");
                        }
                        sw.Write(ColValue);
                    }
                    sw.WriteLine("\t");
                }
                sw.Close();
                Console.WriteLine("** Data Exported to Excel ***");
            }
            else
            {
                Console.WriteLine("** No Data to Export in Excel ***");
                Environment.Exit(0);
            }
        }
}

Calling the functions..


class Program
    {
        static void Main(string[] args)
        {
           System.Data.DataTable dt = new DataTable();
           GenerateExcel oexcel = new GenerateExcel ();
           string filename=@"C:\demo.xls";
           oexcel.CreateExcel(filename);
           oexcel.ExportToSpreadsheet(dt,filename);
         }
    } 
I hope this article gives you a head start in working with Excel files from .NET and C#.
Read More

April 23, 2013

Const, Read Only, Static in C#

Within a class, const, static and readonly members are special in comparison to the other
modifiers.

const vs. readonly

const and readonly perform a similar function on data members, but they have a few important differences.


const

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared. For example;
public class MyClass
{
  public const double PI = 3.14159;
}
PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.

Constants can be marked as public, private, protected, internal, or protected internal.
Constants are accessed as if they were static fields, although they cannot use the static keyword.

To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

readonly

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:
public class MyClass
{
  public readonly double PI = 3.14159;
}
or
public class MyClass
{
  public readonly double PI;
 
  public MyClass()
  {
    PI = 3.14159;
  }
}
Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used. Areadonly field can also be used for runtime constants as in the following example:
public static readonly uint l1 = (uint)DateTime.Now.Ticks;
Notes
  • readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
  • A readonly member can hold a complex object by using the new keyword at initialization.


static

Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields andstatic events. For example:
public class Car
{
  public static int NumberOfWheels = 4;
}
The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.

static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:
int i = Car.NumberOfWheels;


MSDN references

Read More

March 11, 2013

Difference Between Dispose vs Finalize

Introduction

We have been using the Dispose method for disposing objects in .NET. For the same purpose, we may also use the Finalize method. In this article I will try to explain what the Dispose and the Finalize methods are and where to use the Finalize and where to use the Dispose. I will also try to explain the difference between them.

Dispose
Garbage collector (GC) plays the main and important role in .NET for memory management so programmer can focus on the application functionality. Garbage collector is responsible for releasing the memory (objects) that is not being used by the application. But GC has limitation that, it can reclaim or release only memory which is used by managed resources. There are a couple of resources which GC is not able to release as it doesn't have information that, how to claim memory from those resources like File handlers, window handlers, network sockets, database connections etc. If your application these resources than it's programs responsibility to release unmanaged resources.

For example, if we open a file in our program and not closed it after processing than that file will not be available for other operation or it is being used by other application than they can not open or modify that file. For this purpose FileStream class provides Dispose method. We must call this method after file processing finished. Otherwise it will through exception Access Denied or file is being used by other program.

Close Vs Dispose

Some objects expose Close and Dispose two methods. For Stream classes both serve the same purpose. Dispose method calls Close method inside.

void Dispose() 
{ 
this.Close(); 
}

Here question comes, why do we need Dispose method in Stream. Having Dispose method will enable you to write below code and implicitly call dispose method and ultimately will call Close method.

using (FileStream file = new FileStream("path", FileMode.Open, FileAccess.Read)) 
{ 
//Do something with file 
} 
 
But for some classes both methods behave slightly different. For example Connection class. If Close method is called than it will disconnect with database and release all resources being used by the connection object and Open method will reconnect it again with database without reinitializing the connection object. However Dispose method completely release the connection object and cannot be reopen just calling Open method. We will have re-initialize the Connection object.

Creating Dispose
To implement Dispose method for your custom class, you need to implement IDisposableinterface. IDisposable interface expose Dispose method where code to release unmanaged resource will be written.

Finalize

Finalize method also called destructor to the class. Finalize method can not be called explicitly in the code. Only Garbage collector can call the the Finalize when object become inaccessible. Finalize method cannot be implemented directly it can only be implement via declaring destructor. Following class illustrate, how to declare destructor. It is recommend that implement Finalize and Dispose method together if you need to implement Finalize method. After compilation destructor becomes Finalize method.

public class MyClass:IDisposable 
{
//Construcotr 
public MyClass() 
{ 
//Initialization: 
}
//Destrucor also called Finalize 
~MyClass() 
{ 
this.Dispose(); 
}
public void Dispose() 
{ 
//write code to release unmanaged resource. 
} 
}

Using Finalize

Now question is, When to implement Finalize? There may be any unmanaged resource for example file stream declared at class level. We may not be knowing what stage or which step should be appropriate to close the file. This object is being use at many places in the application. So in this scenario Finalize can be appropriate location where unmanaged resource can be released. It means, clean the memory acquired by the unmanaged resource as soon as object is inaccessible to application.

Finalize is bit expensive to use. It doesn't clean the memory immediately. When application runs, Garbage collector maintains a separate queue/array when it adds all object which has finalized implemented. Other term GC knows which object has Finalize implemented. When the object is ready to claim memory, Garbage Collector call finalize method for that object and remove from the collection. In this process it just clean the memory that used by unmanaged resource. Memory used by managed resource still in heap as inaccessible reference. That memory release, whenever Garbage Collector run next time. Due to finalize method GC will not clear entire memory associated with object in fist attempt.

Conclusion

It is always recommended that, one should not implement the Finalize method until it is extremely necessary. First priority should always be to implement the Dispose method and clean unmanaged as soon as possible when processing finish with that.
Read More

© 2011-2016 Techimpulsion All Rights Reserved.


The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.