Friday, August 14, 2009

DataTable Creation


    public class DataTableHelper
    {
        /// 
        /// To Create Table Skeleton.
        /// 
        /// Table Column Name as an Array/// Column DataType as an Array/// Name of the DataTable/// 
        public DataTable CreateDataTable(string[] ColumnName, string[] DataType, string TableName)
        {
            // Create DataTable.   
            DataTable table = new DataTable(TableName);
            try
            {
                for (int i = 0; i < ColumnName.Length; i++)
                {
                    // Create DataColumns and add them to DataTable.   
                    table.Columns.Add(CreateDataColumn(DataType[i].Trim(), ColumnName[i].Trim(), "Column", false, false, false));
                }
            }
            catch (Exception)
            {
            }
            return table;
        }

        /// 
        /// To create the table structure
        /// 
        /// Column DataType/// ColumnName/// Column Caption/// Is Auto Increament/// IsReadOnly/// /// 
        private DataColumn CreateDataColumn(string colType, string name, string caption, bool autoInc, bool readOnly, bool unique)
        {
            DataColumn column = new DataColumn();
            try
            {
                column.DataType = System.Type.GetType(colType);
                column.ColumnName = name;
                column.Caption = caption;
                column.AutoIncrement = autoInc;
                column.ReadOnly = readOnly;
                column.Unique = unique;
            }
            catch (Exception)
            {
            }

            return column;
        }

        /// 
        /// Add Row to a DataTable
        /// //How to Call?
        /// //tempDt = oblDataTableHelper.AddRowsToTable(strArrField, tempDt);
        /// 
        /// Column Data as String Array/// Name of DataTable to add the Row/// 
        public DataTable AddRowsToTable(string[] value, DataTable table)
        {
            // Generate row with values for each column.   
            DataRow row = table.NewRow();
            try
            {
                //Add values to the columns
                for (int i = 0; i < value.Length; i++)
                    row[i] = value[i];

                // Add row to table.   
                table.Rows.Add(row);
            }
            catch (Exception)
            {
            }

            return table;
        }

        /// 
        /// Check whether the table contains Duplicate value for a particular column
        /// 
        /// DataTable/// Name of Column to Check for Duplicate/// 
        public bool HasDuplicates(DataTable table, string columnName)
        {
            bool IsContainsDuplicates = false;
            try
            {
                Hashtable hTable = new Hashtable();

                foreach (DataRow row in table.Rows)
                    if (!hTable.Contains(row[columnName]))
                        hTable.Add(row[columnName], null);
                    else
                    {
                        IsContainsDuplicates = true;
                        break;
                    }
            }
            catch (Exception)
            {
            }

            return IsContainsDuplicates;
        }

        /// 
        /// Remove rows for certains columns contains duplicate value
        /// //How to Call?
        /// tempDt = oblDataTableHelper.RemoveDuplicateRows(tempDt, new System.Collections.Generic.List(ColumnName));
        /// 
        /// DataTable Instance/// ColumnName as List/// 
        public DataTable RemoveDuplicateRows(DataTable table, List keyColumns)
        {
            //DataTable results = myDataTable.AsEnumerable().Distinct().CopyToDataTable();

            DataTable duplicateTable = table.Clone();
            DataColumn[] primaryKey = new DataColumn[duplicateTable.Columns.Count];
            duplicateTable.Columns.CopyTo(primaryKey, 0);
            duplicateTable.PrimaryKey = primaryKey;

            DataRow[] dataRows = new DataRow[table.Rows.Count];
            table.Rows.CopyTo(dataRows, 0);
            foreach (DataRow dataRow in dataRows)
                if (duplicateTable.Rows.Contains(dataRow.ItemArray))
                    table.Rows.Remove(dataRow);
                else
                    duplicateTable.Rows.Add(dataRow.ItemArray);

            return table;
        }

        //tempDt = oblDataTableHelper.RemoveDuplicateRows(tempDt, ColumnName);
        /// 
        /// Remove rows for certains columns contains duplicate value
        /// 
        /// DataTable Instance/// ColumnName as Array/// 
        public DataTable RemoveDuplicateRows(DataTable dTable, string[] strColumns)
        {
            // create a dv from the source dt 
            DataView dv = new DataView(dTable);
            // set the output columns array of the destination dt 
            // true = yes, i need distinct values. 
            return dv.ToTable(true, strColumns);
        }
    }
Calling The Function
DataTableHelper oblDataTableHelper = new DataTableHelper();
string[] ColumnName = new string[] { "Column1", "Column2", "Column3", "Column4" };
string[] DataType = new string[] { "System.String", "System.String", "System.String", "System.String" };
System.Data.DataTable tempDt = null;
tempDt = oblDataTableHelper.CreateDataTable(ColumnName, DataType, "DataTableName");
Path that gives me the idea

Monday, August 10, 2009

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during

Failed to load viewstate.
match the control tree that was used to save viewstate
during the previous request. For example, when adding
controls dynamically, the controls added during a
post-back must match the type and position of the
controls added during the initial request.

This occurs in when press the command field(Edit button)
in the gridview.

To solve we have to bind the GridView once again.


 
protected void GridView1_RowEditing(object sender,
System.Web.UI.WebControls.GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}

Thursday, July 30, 2009

Image to Byte Array and Byte Array to Image

http://www.codeproject.com/KB/recipes/ImageConverter.aspx
 
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

HttpModule Execution Sequence

An application executes events that are handled by modules or user code that is defined in the Global.asax file in the following sequence:

1. BeginRequest
2. AuthenticateRequest
3. PostAuthenticateRequest
4. AuthorizeRequest
5. PostAuthorizeRequest
6. ResolveRequestCache
7. PostResolveRequestCache

After the PostResolveRequestCache event and before the PostMapRequestHandler event, an event handler (a page corresponding to the request URL) is created.

8. PostMapRequestHandler
9. AcquireRequestState
10. PostAcquireRequestState
11. PreRequestHandlerExecute

The event handler is executed.

12. PotRequestHandlerExecute
13. ReleaseRequestState
14. PostReleaseRequestState

After the PostReleaseRequestState event, response filters, if any, filter the output.

15. UpdateRequestCache
16. PostUpdateRequestCache
17. EndRequest

Wednesday, July 29, 2009

byte array to bitmap

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/e57f7731-c703-4c17-b1a2-32b155f9b745
 
public static Bitmap BytesToBitmap(byte[] byteArray)
{
using (MemoryStream ms = new MemoryStream(byteArray))
{
Bitmap img = (Bitmap)Image.FromStream(ms);
return img;
}
}


TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));

Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(byteArray);

Or,



ImageConverter ic = new ImageConverter();

Image img = (Image)ic.ConvertFrom(byteArray);

Bitmap bitmap1 = new Bitmap(img);

Friday, July 24, 2009

Tips

Tip #1 How to behold the power of incremental search

Command: Edit.IncrementalSearch

Shortcut: Ctrl+i

Tip #2 Ctrl+F3 to search for currently-selected word

Command: Edit.FindNextSelected

Tip #3 F3 to search for last thing you searched for

Command: Edit.FindNext

Tip #4 Customize what files to find in

Find In Files – Look in – Choose Search Folders

Tip #5 You can use a reg hack for customizing search results

HKCU\Software\Microsoft\VisualStudio\9.0\Find String Find=$f$e($l,$c):$t\r\n

Editing Tips

Tip #6 How not to accidentally copy a blank line

Tools – Options – Text Editor – All Languages – General, Uncheck Apply cut or copy to blank lines

Tip #7 How to cycle through the Clipboard ring

Command: Edit.CycleClipboardRing

Shortcut: Ctrl+Shift+v

Tip #8 How to use box/column selection in the editor

Command: Edit.LineUpColumnExtend, Edit.LineDownColumnExtend, Edit.CharRightColumnExtend, Edit.CharLeftColumnExtend

Shortcut: Shift+Alt+Arrow

Tip #9 You can copy a file’s full path / open windows explorer from the file tab channel

Command: File.CopyFullPath

Tip #10 Drag and drop code onto the toolbox’s general tab

Shortcut: Ctrl+Alt+x

Tip #11 You can use Ctrl+. to show a smart tag

Command: View.ShowSmartTag

Tip #12 You can insert a snippet by pressing Tab Tab

Type in snippet shortcut, then press Tab Tab

Customizing Tips

Tip #13 You can create temp or throw away projects

Tools - Options - Projects and Solutions - General, uncheck Save new projects when created

Tip #14 Change text editor font size via keyboard (Accessibility macros)

Command: Macros.Samples.Accessibility.DecreaseTextEditorFontSize

Command: Macros.Samples.Accessibility.IncreaseTextEditorFontSize

Tip #15 How to open a file without any UI

Ctrl+/ (or whatever Tools.GoToCommandLine is bound to)

alias fo file.openfile

fo

Tip #16 Guidelines in the editor registry key hack

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor String RBG(128,0,0) 5, 20

Tip #17 You can create a macro for your import/export settings

Tools – customize – commands – macros – drag and drop macro to toolbar

Tip #18 How to not show the start page (or have the last loaded solution open)

Tools - Options - Environment - Startup, At Startup

Tip #19 File tab channel registry hack

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0 key, you can create a DWORD UseMRUDocOrdering = 1

Tip #20 How to show Misc Files Project to keep your files around

tools - options - environment – documents, show miscellaneous files in Solution Explorer

Tip #21 Edit project file from within IDE (unload project)

Unload project, edit project, reload project

Debugging Tips

Tip #22 You can use tracepoints to log stuff in your code

Right-click in indicator margin, select breakpoints, select Insert Tracepoint

Tip #23 How to get the find source dialog back

Solution Properties, under Common Properties - Debug Source Files, Delete Do no look for these source files edit box contents

Tip #24 You can disable the exception assistant

Tools – Options – Debugging – General, uncheck Enable the Exception Assistant

DatabindExpressions

Digging Into Data Binding Expressions

The case of the "Eval" should be maintained. ie. "E" should be CAPS and remaining should be small.
<%#Eval("ProductName")%>,<%#FormatPrice(Eval("UnitPrice"))%>

'<%#DataBinder.Eval(Container.DataItem,"ID")%>'

'<%# Eval("ID")%>'

'<%# Eval("HotelAmenities").ToString().Replace("±","") %>'

'<%# Eval("PropertyID", "Javascript:window.open(\"Map.aspx?PID={0}\")") %>'

Call a function from the aspx page when binding using "Eval"


ImageUrl ='<%# LoadImage(Convert.ToInt32(((System.Data.DataRowView)Container.DataItem)["StarRate"]),3) %>'

LoadImage => Function Name with two parameters starrate and imagenumber

Convert.ToInt32(((System.Data.DataRowView)Container.DataItem)["StarRate"]) => Convert "StarRate" to int


Concat String with "Eval"

Text='<%# "Customer Review: "+ ((System.Data.DataRowView)Container.DataItem)["CustomerRatings"].ToString()+"/5" %>'



PostBackUrl='<%# "~/HotelDetails.aspx?PropertyID=" + Eval("PropertyID") %> '

OR
PostBackUrl="'<%# "~/HotelDetails.aspx?PID=" + Eval("PropertyID") %> '"


PostBackUrl="~/SysAdmin/modifyAnnouncement.aspx?id=<%# Eval("intAnnouncementID")%>"
PostBackUrl="~/HotelDetails.aspx?PropertyID=<%# Eval("PropertyID")%>"

PostBackUrl="~/HotelDetails.aspx?PropertyID=" + '<%# Eval("ID")%>'

PostBackUrl='<%# Eval("PropertyID", "~/HotelDetails.aspx?PropertyID={0}") %>'


DataBinder.Eval versus Explicit Casting

http://unboxedsolutions.com/sean/archive/2005/03/06/455.aspx

http://weblogs.asp.net/rajbk/archive/2004/07/20/what-s-the-deal-with-databinder-eval-and-container-dataitem.aspx


As a regular DataBinder.Eval() user, now I feel a little
bit guilty after reading this KB article, and I'm curious
how many ASP.NET developers use explicit casting on a regular basis.
Drop me a line and let me know.

Let's say you are binding to a DataSet. This...

<%# ((System.Data.DataRowView)Container.DataItem)["au_id"] %>

...is significantly faster than this...

<%# DataBinder.Eval(Container.DataItem, "au_id") %>


Conditions with Eval


<%#(DataBinder.Eval(Container.DataItem, "checkedout" ) == "No"), ?"Check Out":""%>


'<%# !String.IsNullOrEmpty(Convert.ToString(((System.Data.DataRowView)Container.DataItem)["RackRate"] ).Trim()) ? "£ "+((System.Data.DataRowView)Container.DataItem)["RackRate"]:"" %>'


PopUpS
------

OnClientClick='<%# Eval("PropertyID", "Javascript:popupWin(\"Map.aspx?PID={0}\",500,400)") %>'


OnClientClick='<%# Eval("PropertyID", "Javascript:window.open(\"Map.aspx?PID={0}\")") %>'

OR

onClientClick='<%#String.Format("{0}\"{1}{2}{3}{4}\")", "javascript:window.open(","Map.aspx?PID=",Eval("PropertyID"), "&Guid=",Eval("GUID")) %>'

OnClientClick="popup(' <%# ((System.Data.DataRowView)Container.DataItem)["PropertyID"] %>');"

OnClientClick='<%# Eval("PropertyID", "Javascript:window.open(\"Map.aspx?PropertyID={0}\")") %>'


OnClientClick='<%# Eval('PropertyID', "Javascript:window.open('Map.aspx?PropertyID={0}','top=200,left=350,width=425,height=350, menubar=no,status=no,location=yes,toolbar=no,scrollbars=no')") %>'


"window.open(<%# DataBinder.Eval(Container.DataItem,"PropertyID","'Map.aspx?PID={0}'") %>,'question','scrollbars=yes,width=630,height=480,location=no,menubar=no,status=no,toolbar=no');"