Pages

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

Friday, April 6, 2012

Data Structure: How to Create a One Way Linear Linked List in C# .Net

In the world of software engineering data structures like linked lists are often needed. Here is a way to create a one way linear linked list using C# .Net. But any other object oriented programming language can be used in the same way. Some common linked list functionality are given. Hope it will help you.


   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:   
   6:  namespace Datastructure
   7:  {
   8:      class Program
   9:      {
  10:          static void Main(string[] args)
  11:          {
  12:              OneWayLinearLinkedList linkedList = new OneWayLinearLinkedList();
  13:   
  14:              Console.WriteLine("Insert:");
  15:              for(int i = 0; i < 6; i++)
  16:              {
  17:                  linkedList.Insert(new Node(i));
  18:              }
  19:              linkedList.Print();
  20:   
  21:              Console.WriteLine("Insert At:");
  22:              linkedList.InsertAt(new Node(11), 3);
  23:              linkedList.Print();
  24:   
  25:              Console.WriteLine("Delete:");
  26:              linkedList.Delete(linkedList.NodeAt(2));
  27:              linkedList.Print();
  28:   
  29:              Console.WriteLine("Delete At:");
  30:              linkedList.DeleteAt(2);
  31:              linkedList.Print();
  32:   
  33:              Console.WriteLine("Clear:");
  34:              linkedList.Clear();
  35:              linkedList.Print();
  36:   
  37:              Console.ReadKey();
  38:          }
  39:      }
  40:   
  41:      /// <summary>
  42:      /// One way linear linked list
  43:      /// </summary>
  44:      public class OneWayLinearLinkedList
  45:      {
  46:          private Node head;
  47:   
  48:          public OneWayLinearLinkedList()
  49:          {
  50:              head = null;
  51:          }
  52:   
  53:          /// <summary>
  54:          /// Gets the node at a specific postion
  55:          /// </summary>        
  56:          public Node NodeAt(int index)
  57:          {
  58:              if (head == null)
  59:                  return null;
  60:              else if (index == 0)
  61:              {
  62:                  return head;
  63:              }
  64:              else
  65:              {
  66:                  Node currentNode = head.NextNode;
  67:                  Node currentNodeNext = currentNode.NextNode;
  68:   
  69:                  for (int i = 1; i < index; i++)
  70:                  {
  71:                      currentNode = currentNode.NextNode;
  72:                      currentNodeNext = currentNode.NextNode;
  73:                  }
  74:   
  75:                  return currentNode;
  76:              }
  77:          }
  78:          
  79:          /// <summary>
  80:          /// Inserts a node at the begining of the linked list
  81:          /// </summary>
  82:          public void Insert(Node newNode)
  83:          {            
  84:              if (head == null)
  85:              {                
  86:                  head = newNode;
  87:                  newNode.NextNode = null;
  88:              }
  89:              else
  90:              {
  91:                  newNode.NextNode = head;
  92:                  head = newNode;
  93:              }
  94:          }
  95:   
  96:          /// <summary>
  97:          /// Inserts a node at a specific position
  98:          /// </summary>
  99:          public void InsertAt(Node newNode, int index)
 100:          {
 101:              if (index == 0)
 102:              {
 103:                  newNode.NextNode = head;
 104:                  head = newNode;
 105:              }
 106:              else
 107:              {
 108:                  Node currentNode = head;
 109:                  Node currentNodeNext = head.NextNode;
 110:                  for (int i = 1; i < index; i++)
 111:                  {
 112:                      currentNode = currentNode.NextNode;
 113:                      currentNodeNext = currentNode.NextNode;
 114:                  }
 115:                  if (currentNode != null)
 116:                  {
 117:                      currentNode.NextNode = newNode;
 118:                      newNode.NextNode = currentNodeNext;
 119:                  }
 120:   
 121:              }
 122:          }
 123:          
 124:          /// <summary>
 125:          /// Deletes a node
 126:          /// </summary>
 127:          public void Delete(Node deleteNode)
 128:          {
 129:              bool isSuccess = false;
 130:   
 131:              if (head == null) return;
 132:   
 133:              else if (head.Equals(deleteNode))
 134:              {
 135:                  head = null;
 136:              }
 137:              else
 138:              {
 139:                  Node currentNode = head;
 140:                  Node currentNodeNext = head.NextNode;
 141:                  while (currentNodeNext != null)
 142:                  {
 143:                      if (currentNodeNext.Equals(deleteNode))
 144:                      {
 145:                          currentNode.NextNode = currentNodeNext.NextNode;
 146:                          currentNodeNext = null;
 147:                          break;
 148:                      }
 149:                      else
 150:                      {
 151:                          currentNode = currentNodeNext;
 152:                          currentNodeNext = currentNodeNext.NextNode;
 153:                      }
 154:                  }
 155:              }
 156:          }
 157:   
 158:          /// <summary>
 159:          /// Delets a node at a specific position
 160:          /// </summary>
 161:          public void DeleteAt(int index)
 162:          {
 163:              if (head == null) return;
 164:   
 165:              if (index == 0)
 166:              {
 167:                  head = null;
 168:              }
 169:              else
 170:              {
 171:                  Node currentNode = head;
 172:                  Node currentNodeNext = head.NextNode;
 173:                  for (int j = 1; j < index; j++)
 174:                  {
 175:                      currentNode = currentNode.NextNode;
 176:                      currentNodeNext = currentNode.NextNode;
 177:                  }
 178:                  if (currentNode != null)
 179:                  {
 180:                      currentNode.NextNode = currentNodeNext.NextNode;
 181:                  }
 182:              }
 183:          }
 184:   
 185:          /// <summary>
 186:          /// Prints the linear linked list
 187:          /// </summary>
 188:          public void Print()
 189:          {
 190:              Node firstNode = head;
 191:              while (firstNode != null)
 192:              {
 193:                  Console.Write(firstNode.Data + " ");
 194:                  firstNode = firstNode.NextNode;
 195:              }
 196:   
 197:              Console.Write("\n");
 198:          }
 199:   
 200:          /// <summary>
 201:          /// Clears the linked list
 202:          /// </summary>
 203:          public void Clear()
 204:          {
 205:              Node currentNode = head;
 206:              Node currentNodeNext;
 207:   
 208:              while (currentNode != null)
 209:              {
 210:                  currentNodeNext = currentNode.NextNode;
 211:                  currentNode = null;
 212:                  currentNode = currentNodeNext;
 213:              }
 214:   
 215:              head = null;
 216:          }
 217:   
 218:   
 219:   
 220:      }
 221:   
 222:      /// <summary>
 223:      /// Node for the one way linear linked list
 224:      /// </summary>
 225:      public class Node
 226:      {
 227:          public int Data { get; set; }
 228:          public Node NextNode { get; set; }
 229:   
 230:          public Node(int data)
 231:          {
 232:              this.Data = data;
 233:          }  
 234:      }
 235:  }

Wednesday, March 28, 2012

Design Pattern Tutorial Part 2: The Decorator Pattern (Structural Pattern) : Example in C#.net

Part 1

Here is an example of the implementation of the Decorator Pattern with C#.net.


   1:      class Program
   2:      {
   3:          static void Main(string[] args)
   4:          {
   5:              IComponent component = new Component();
   6:              Output("Original component: ", component);
   7:              Output("Decorated by A : ", new DecoratorA(component));
   8:              Output("Decorated by B: ", new DecoratorB(component));
   9:              Output("Decorated by A then by B: ", new DecoratorB(new DecoratorA(component)));
  10:              
  11:              DecoratorB b = new DecoratorB(new Component());
  12:              Output("Decorated by B then by A: ", new DecoratorA(b));
  13:              
  14:              // Extended behavior
  15:              Console.WriteLine("\t\t\t\t\t\t" + b.ExtendedBehaviour());
  16:   
  17:              Console.ReadKey();
  18:          }
  19:   
  20:          static void Output(string s, IComponent component)
  21:          {
  22:              Console.WriteLine(s + component.Operation());
  23:          }
  24:      }
  25:   
  26:      public interface IComponent
  27:      {
  28:          string Operation();
  29:      }
  30:   
  31:      public class Component : IComponent
  32:      {
  33:          private string firstName = "Debashish";
  34:          private string lastName = "Shiman";
  35:   
  36:          public string Operation()
  37:          {
  38:              return firstName + " " + lastName;
  39:          }
  40:      }
  41:   
  42:      public class DecoratorA : IComponent
  43:      {
  44:          IComponent component;
  45:   
  46:          public DecoratorA(IComponent c)
  47:          {
  48:              component = c;
  49:          }
  50:   
  51:          public string Operation()
  52:          {
  53:              string s = component.Operation();
  54:              s = "Mr " + s;
  55:              return s;
  56:          }
  57:      }
  58:   
  59:      public class DecoratorB : IComponent
  60:      {
  61:          IComponent component;
  62:   
  63:          public DecoratorB(IComponent c)
  64:          {
  65:              component = c;
  66:          }
  67:   
  68:          public string Operation()
  69:          {
  70:              string s = component.Operation();
  71:              s = s + ", Software Engineer";
  72:              return s;
  73:          }
  74:   
  75:          public string ExtendedBehaviour()
  76:          {
  77:              return " and Web Developer";
  78:          }
  79:      }

Wednesday, July 28, 2010

How to Export DataTable to MS Excel 2007 (.xlsx) with C# .NET

These methods exports a datatable to Microsoft Excel 2007 format (.xlsx). All you have to do is to pass the following parameters:
sheetToCreate = File path,
dtToExport = The DataTable to be exported,
tableName = Sheet name in the Workbook

Cheers!!!

public void ExportToXLSX(string sheetToCreate, DataTable dtToExport, string tableName)
{
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in dtToExport.Rows) rows.Add(row);
ExportToXLSX(sheetToCreate, rows, dtToExport, tableName);
}

public void ExportToXLSX(string sheetToCreate, List<DataRow> selectedRows, DataTable origDataTable, string tableName)
{
char Space = ' ';
string dest = sheetToCreate;


if (File.Exists(dest))
{
File.Delete(dest);
}

sheetToCreate = dest;

if (tableName == null)
{
tableName = string.Empty;
}

tableName = tableName.Trim().Replace(Space, '_');
if (tableName.Length == 0)
{
tableName = origDataTable.TableName.Replace(Space, '_');
}

if (tableName.Length == 0)
{
tableName = "NoTableName";
}

if (tableName.Length > 30)
{
tableName = tableName.Substring(0, 30);
}

//Excel names are less than 31 chars
string queryCreateExcelTable = "CREATE TABLE [" + tableName + "] (";
Dictionary<string, string> colNames = new Dictionary<string, string>();

foreach (DataColumn dc in origDataTable.Columns)
{
//Cause the query to name each of the columns to be created.
string modifiedcolName = dc.ColumnName;//.Replace(Space, '_').Replace('.', '#');
string origColName = dc.ColumnName;
colNames.Add(modifiedcolName, origColName);

queryCreateExcelTable += "[" + modifiedcolName + "]" + " text,";

}

queryCreateExcelTable = queryCreateExcelTable.TrimEnd(new char[] { Convert.ToChar(",") }) + ")";

//adds the closing parentheses to the query string
if (selectedRows.Count > 65000 && sheetToCreate.ToLower().EndsWith(".xls"))
{
//use Excel 2007 for large sheets.
sheetToCreate = sheetToCreate.ToLower().Replace(".xls", string.Empty) + ".xlsx";
}

string strCn = string.Empty;
string ext = System.IO.Path.GetExtension(sheetToCreate).ToLower();
if (ext == ".xls") strCn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sheetToCreate + "; Extended Properties='Excel 8.0;HDR=YES'";
if (ext == ".xlsx") strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sheetToCreate + ";Extended Properties='Excel 12.0 Xml;HDR=YES' ";
if (ext == ".xlsb") strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sheetToCreate + ";Extended Properties='Excel 12.0;HDR=YES' ";
if (ext == ".xlsm") strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sheetToCreate + ";Extended Properties='Excel 12.0 Macro;HDR=YES' ";

System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection(strCn);
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(queryCreateExcelTable, cn);
cn.Open();
cmd.ExecuteNonQuery();
System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [" + tableName + "]", cn);
System.Data.OleDb.OleDbCommandBuilder cb = new System.Data.OleDb.OleDbCommandBuilder(da);

//creates the INSERT INTO command
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
cmd = cb.GetInsertCommand();

//gets a hold of the INSERT INTO command.
foreach (DataRow row in selectedRows)
{
foreach (System.Data.OleDb.OleDbParameter param in cmd.Parameters)
{
param.Value = row[colNames[param.SourceColumn.Replace('#', '.')]];
}

cmd.ExecuteNonQuery(); //INSERT INTO command.
}
cn.Close();
cn.Dispose();
da.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
}