Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, July 5, 2011

How to create Excel file in C#

Note: You need to add the Microsoft Excel 12.0 Object Library to your project.


using Excel = Microsoft.Office.Interop.Excel; 

Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
private void releaseObject(object obj)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
GC.Collect();
}

Monday, July 4, 2011

Abstract vs Interface

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
This is a very clear article on the difference between an abstract class and an interface. The article also provides examples of implementations for both.

Comparisons at a glance:
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access ModfiersAn interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and ConstantsNo fields can be defined in interfacesAn abstract class can have fields and constrants defined

Sunday, July 3, 2011

Create JSON object in C#


JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);

Wednesday, June 29, 2011

Get Current User in Javascript (using Code behind)


Code behind:

protected string username;
protected void Page_Load(object sender, EventArgs e)
{
username = System.Web.HttpContext.Current.User.Identity.Name;
username = username.Replace("\\", "\\\\"); // not a very elegant hack
}
Points to note:
- variable "username" must be at least protected
- need to hack the username because javascript will strip the "\"

Javascript:

var userID = "<%=username %>";
Points to note:
- must put the <%= … %> in quotes

Monday, March 29, 2010

UrlEncode/UrlDecode in C#

Use HttpUtility.UrlEncode(string url) & HttpUtility.UrlDecode(string url) respectively.

You need the reference to System.Web.

Wednesday, March 24, 2010

Get class of a particular object

Suppose I have an object o.

I can retrieve its class by the function o.GetType().
Extend function further to o.GetType().Name to get the string value.

Tuesday, September 15, 2009

Thursday, September 3, 2009

Insert Group Headers within GridView

The idea is to group the data in the Grid View, then insert a group header for each group of items.
References:
http://blog.zygonia.net/PermaLink,guid,c093836d-8d97-4e5b-8a1c-8218742cb686.aspx
http://www.agrinei.com/gridviewhelper/gridviewhelper_en.htm
http://www.asp.net/learn/data-access/tutorial-27-cs.aspx

In a nutshell, we can do the following:
1) Add a RowDataBound event to add additional table row when we encounter new group.
2) Override the Render method to add additional table row when we encounter new group.

Issue at hand:
1) Add "Expand/Collapse" button in the group header, such that upon click, will set the respective rows to visible = true or false.

Wednesday, August 19, 2009

C#: Read a file into a byte array

public byte[] readByteArrayFromFile(string fileName){
byte[] buff = null;
try{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(fileName).Length;
buff = br.ReadBytes((int)numBytes);
}
catch (Exception ex) {Console.WriteLine(ex.Message); }
return buff;
}

Another option:
byte[] rawData = File.ReadAllBytes("filename");

(This method sacrifices the ability to have more explicit control on the file like FileAccess.Read etc.)

Source: http://kseesharp.blogspot.com/2007/12/read-file-into-byte-array.html

Monday, July 27, 2009

Setting Focus in ASP.NET

From NET 2.0 onwards, you can use
Page.SetFocus("SubmitButton")
or
SubmitButton.Focus()
to set the page focus to the Control with ID SubmitButton.

The first alternative may cause some problems if you are using MasterPages. Not sure why, but the 2nd method has no problems with MasterPages.

Tuesday, July 14, 2009

How to insert new record into database - the hassle-free way

The code is written in C# and it does not make use of DataAdapter, DataSet and all unnecessary objects..
using System.Data.SqlClient;
using System.Data;

// open the database connection
String connectionString = "..."; // get from the web. config file, and use connectionstrings.com as reference
SqlConnection cn = new SqlConnection(connectionString);
try
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("INSERT INTO CodeMaintenance (question, answer) VALUES ('hello', 'world')", cn);
    cmd.ExecuteNonQuery();
    cn.Close();
}
catch (Exception ex){ // print error message }