How to copy DataTable to Excel File using OLEDB? [duplicate] - c#

This question already has answers here:
Excel Interop - Efficiency and performance
(7 answers)
Closed 9 years ago.
I am writing a program send data to excel by using oledb.
I used Update statement like next:
OleDbConnection MyConnection = new OleDbConnection(#"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + GeneralData.excelPath + "';Extended Properties=Excel 8.0;")
MyConnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = MyConnection;
myCommand.CommandType = System.Data.CommandType.Text;
string sql = "Update [test$] set press = " + pointsProperties[i].Pressure + ", temp = " + pointsProperties[i].Temperature + " where id= " + id;
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
The problem is I will use the sql statement more than 100 times, which takes much time, so I thought that using Data Table will take less time, so I wrote a code saving my data in data table like next:
public static System.Data.DataTable ExcelDataTable = new System.Data.DataTable("Steam Properties");
static System.Data.DataColumn columnID = new System.Data.DataColumn("ID", System.Type.GetType("System.Int32"));
static System.Data.DataColumn columnPress = new System.Data.DataColumn("Press", System.Type.GetType("System.Int32"));
static System.Data.DataColumn columnTemp = new System.Data.DataColumn("Temp", System.Type.GetType("System.Int32"));
public static void IntializeDataTable() // Called one time in MDIParent1.Load()
{
columnID.DefaultValue = 0;
columnPress.DefaultValue = 0;
columnTemp.DefaultValue = 0;
ExcelDataTable.Columns.Add(columnID);
ExcelDataTable.Columns.Add(columnPress);
ExcelDataTable.Columns.Add(columnTemp);
}
public static void setPointInDataTable(StreamProperties Point)
{
System.Data.DataRow ExcelDataRow = ExcelDataTable.NewRow(); // Must be decleared inside the function
// It will raise exception if decleared outside the function
ExcelDataRow["ID"] = Point.ID;
ExcelDataRow["Press"] = Point.Pressure;
ExcelDataRow["Temp"] = Point.Temperature;
ExcelDataTable.Rows.Add(ExcelDataRow);
}
The problem is I don’t know :
1- Is the second way is faster?
2- How to copy the Data Table to the excel file?
Thanks.

//Dump the datatable onto the sheet in one operation
public void InsertDataTableIntoExcel(Application xlApp, DataTable dt, Reectangle QueryDataArea)
{
TurnOnOffApplicationSettings(false);
using (var rn = xlApp.Range[ColumnNumberToName(QueryDataArea.X) + QueryDataArea.Y + ":" + ColumnNumberToName(QueryDataArea.X + QueryDataArea.Width - 1) + (QueryDataArea.Y + QueryDataArea.Height)].WithComCleanup())
{
rn.Resource.Value2 = Populate2DArray(dt);
}
TurnOnOffApplicationSettings(true);
}
private object[,] Populate2DArray(DataTable dt)
{
object[,] values = (object[,])Array.CreateInstance(typeof(object), new int[2] { dt.Rows.Count + 1, dt.Columns.Count + 1}, new int[2] { 1, 1 });
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
values[i + 1, j + 1] = dt.Rows[i][j] == DBNull.Value ? "" : dt.Rows[i][j];
}
}
return values;
}
public static string ColumnNumberToName(Int32 columnNumber)
{
Int32 dividend = columnNumber;
String columnName = String.Empty;
Int32 modulo;
while (dividend > 0)
{
modulo = (dividend - 1)%26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (Int32) ((dividend - modulo)/26);
}
return columnName;
}
public static Int32 ColumnNameToNumber(String columnName)
{
if (String.IsNullOrEmpty(columnName)) throw new ArgumentNullException("columnName");
char[] characters = columnName.ToUpperInvariant().ToCharArray();
Int32 sum = 0;
for (Int32 i = 0; i < characters.Length; i++)
{
sum *= 26;
sum += (characters[i] - 'A' + 1);
}
return sum;
}
private static XlCalculation xlCalculation = XlCalculation.xlCalculationAutomatic;
public void TurnOnOffApplicationSettings(Excel.Application xlApp, bool on)
{
xlApp.ScreenUpdating = on;
xlApp.DisplayAlerts = on;
if (on)
{
xlApp.Calculation = xlCalculation;
}
else
{
xlCalculation = xlApp.Calculation;
xlApp.Calculation = XlCalculation.xlCalculationManual;
}
xlApp.UserControl = on;
xlApp.EnableEvents = on;
}
WithComCleanup() is the VSTO Conrtib Libraries.

Related

Blocking Collection shows Duplicate entries

I first retrieve Total number of rows in my table (say 100) and then divide them into chunks (say 25). Then I create a task (taskFetch) which fetches rows from MyTable in chunks into DataTable (each containing 25 records) using Parallel.Foreach() method. There's another nested Parallel,Foreach() which uses Partitioner.Create() which retrieves data from each DataTable and Adds it into Blocking Collection (sourceCollection). For testing purpose I output the result on console and it was fine.
But, as I tried to retrieve data from sourceCollection I found duplicate entries. In real I have over 1500,000 records in table. I dont exactly think that duplicate entries are Add-ed but the way I'm Take-ing is something I'm a bit doubtful about.
Code
public async Task BulkMigrationAsync(string clearPVK, string EncZPK)
{
BlockingCollection<MigrationObject> sourceCollection = new BlockingCollection<MigrationObject>();
List<Task> tasksGeneratedPinBlock = new List<Task>();
int rangeFrom = 1;
int recordsInSet = 25;
int rangeTo = 25;
int setsCount = 0;
Dictionary<int, Tuple<int, int>> chunks = new Dictionary<int, Tuple<int, int>>();
SqlConnection conn = new SqlConnection(_Database.ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM MyTable); // Suppose If retrieves 100 rows
// getting total records from MyTable
using (conn)
{
conn.Open();
setsCount = Convert.ToInt32(cmd.ExecuteScalar()) / recordsInSet ; // then setsCount will be 4
conn.Close();
}
for (int i = 0; i < setsCount; i++)
{
chunks.Add(i, new Tuple<int, int>(rangeFrom, rangeTo));
rangeFrom = rangeTo + 1;
rangeTo = rangeTo + recordsInSet;
}
// Each chunk would contain 100000 records to be preocessed later
// chunks => {0, (1, 25)}
// {1, (26, 50)} // a chunk, chunk.Value.Item1 = 26 and chunk.Value.Item2 = 50
// {2, (51, 75)}
// {3, (76, 100)}
// fetching results in dataTable from DB in chunks and ADDING to sourceCollection
Task taskFetch = Task.Factory.StartNew(() =>
{
Parallel.ForEach(chunks, (chunk) =>
{
DataTable dt = new DataTable();
SqlConnection localConn = new SqlConnection(_Database.ConnectionString);
string command = #"SELECT * FROM ( SELECT RELATIONSHIP_NUM, CUST_ID, CODE, BLOCK_NEW, ROW_NUMBER() over (
order by RELATIONSHIP_NUM, CUST_ID) as RowNum FROM MyTable) SUB
WHERE SUB.RowNum BETWEEN chunk.Value.Item1 AND chunk.Value.Item2";
SqlDataAdapter da = new SqlDataAdapter(command, localConn);
try
{
using (da)
using (localConn)
{
da.Fill(dt);
}
}
finally
{
if (localConn.State != ConnectionState.Closed)
localConn.Close();
localConn.Dispose();
}
Parallel.ForEach(Partitioner.Create(0, dt.Rows.Count),
(range, state) =>
{
MigrationObject migSource = new MigrationObject();
for (int i = range.Item1; i < range.Item2; i++)
{
migSource.PAN = dt.Rows[i]["CUST_ID"].ToString();
migSource.PinOffset = dt.Rows[i]["CODE"].ToString();
migSource.PinBlockNew = dt.Rows[i]["BLOCK_NEW"].ToString();
migSource.RelationshipNum = dt.Rows[i]["RELATIONSHIP_NUM"].ToString();
Console.WriteLine(#"PAN " + migSource.PAN + " Rel " + migSource.RelationshipNum
+ " for ranges : " + range.Item1 + " TO " + range.Item2);
sourceCollection.TryAdd(migSource);
}
});
});
});
await taskFetch;
sourceCollection.CompleteAdding();
while (!sourceCollection.IsCompleted)
{
MigrationObject mig;
if (sourceCollection.TryTake(out mig)) // Seems to be the problem area because may be im not handling out
{
await Task.Delay(50);
Console.WriteLine(" Rel " + mig.RelationshipNum + " PAN " + mig.PAN);
}
}
}
My bad, Actually the problem area is :
Parallel.ForEach(Partitioner.Create(0, dt.Rows.Count),
(range, state) =>
{
MigrationObject migSource = new MigrationObject(); // creating the object outside For loop.
for (int i = range.Item1; i < range.Item2; i++)
{
migSource.PAN = dt.Rows[i]["CUST_ID"].ToString();
migSource.PinOffset = dt.Rows[i]["CODE"].ToString();
migSource.PinBlockNew = dt.Rows[i]["BLOCK_NEW"].ToString();
migSource.RelationshipNum = dt.Rows[i]["RELATIONSHIP_NUM"].ToString();
Console.WriteLine(#"PAN " + migSource.PAN + " Rel " + migSource.RelationshipNum
+ " for ranges : " + range.Item1 + " TO " + range.Item2);
sourceCollection.TryAdd(migSource);
}
});
instead I should have included ' MigrationObject migSource = new MigrationObject();' inside For loop :
Parallel.ForEach(Partitioner.Create(0, dt.Rows.Count),
(range, state) =>
{
for (int i = range.Item1; i < range.Item2; i++)
{
MigrationObject migSource = new MigrationObject();
migSource.PAN = dt.Rows[i]["CUST_ID"].ToString();
migSource.PinOffset = dt.Rows[i]["CODE"].ToString();
migSource.PinBlockNew = dt.Rows[i]["BLOCK_NEW"].ToString();
migSource.RelationshipNum = dt.Rows[i]["RELATIONSHIP_NUM"].ToString();
Console.WriteLine(#"PAN " + migSource.PAN + " Rel " + migSource.RelationshipNum
+ " for ranges : " + range.Item1 + " TO " + range.Item2);
sourceCollection.TryAdd(migSource);
}
});

Excel Tool to compare two Excel Sheets

This is my current code. Open to receive any comments to improve the memory optimization.
When I am taking a sample of 1000000 * 8 with 1000000*8 data its resulting into out of memory exception. Would love to have advice on optimizing memory usage.
Compare The two tables in a data set named "Before" and "After" and fill all result tables.
private bool CompareAndFillResultTable(DataSet ds)
{
Stopwatch stopWatch = new Stopwatch(); stopWatch.Start();
System.Data.DataTable dt_copy;
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Copy();
dt_copy.TableName = "BeforeBackup";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["After"].Copy();
dt_copy.TableName = "AfterBackup";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "BeforeSingular";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "AfterSingular";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "Duplicates";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "Mismatch";
ds.Tables.Add(dt_copy);
foreach (System.Data.DataTable table in ds.Tables)
{
table.Columns.Add("Source_Label");
}
//Remove identical from before, then after
for (int i = 0; i < ds.Tables["Before"].Rows.Count; i++)
{
string BeforeCompareKeyVal = ds.Tables["Before"].Rows[i][Inputs.SortColumn].ToString();
if (ds.Tables["After"].Rows.Count > 0)
{
for (int j = 0; j < ds.Tables["After"].Rows.Count; j++)
{
string AfterCompareKeyVal = ds.Tables["After"].Rows[j][Inputs.SortColumn].ToString();
if (ds.Tables["Before"].Rows[i].ItemArray.SequenceEqual(ds.Tables["After"].Rows[j].ItemArray))
{
//copy Aftter row to duplicate Table and Remove row from After
DataRow rw = ds.Tables["After"].Rows[j];
rw[ds.Tables["After"].Columns.Count - 1] = "NA";
ds.Tables["Duplicates"].ImportRow(rw);
ds.Tables["After"].Rows.RemoveAt(j);
j--;
break;
}
if (Int64.Parse(BeforeCompareKeyVal) > Int64.Parse(AfterCompareKeyVal))// Review - 7
{
if (true)//all dup after + a before - set logic
{
//Copy After row to AfterSingular Table and Remove row from After
DataRow rw = ds.Tables["After"].Rows[j];
rw[ds.Tables["After"].Columns.Count - 1] = "After";
ds.Tables["AfterSingular"].ImportRow(rw);
ds.Tables["After"].Rows.RemoveAt(j);
j--;
if (ds.Tables["After"].Rows.Count == 0)
{
rw = ds.Tables["Before"].Rows[i];
rw[ds.Tables["Before"].Columns.Count - 1] = "Before";
ds.Tables["BeforeSingular"].ImportRow(rw);
}
continue;
}
}
if (Int64.Parse(BeforeCompareKeyVal) < Int64.Parse(AfterCompareKeyVal))// Review - 7
{
if (true)//all dup after and a before set logic
{
//Copy Before row to BeforeSingular Table
DataRow rw = ds.Tables["Before"].Rows[i];
rw[ds.Tables["Before"].Columns.Count - 1] = "Before";
ds.Tables["BeforeSingular"].ImportRow(rw);
break;
}
}
if (Int64.Parse(BeforeCompareKeyVal) == Int64.Parse(AfterCompareKeyVal))// Review - 7
{
//Copy Before, After row to Mismatch Table and Remove row from After
if (true)//all dup after and a before set logic
{
DataRow rwB = ds.Tables["Before"].Rows[i];
rwB[ds.Tables["Before"].Columns.Count - 1] = "Before";
DataRow rwA = ds.Tables["After"].Rows[j];
rwA[ds.Tables["After"].Columns.Count - 1] = "After";
ds.Tables["Mismatch"].ImportRow(rwB);
ds.Tables["Mismatch"].ImportRow(rwA);
ds.Tables["After"].Rows.RemoveAt(j);
j--;
break;
}
}
}
}
else
{
DataRow rw = ds.Tables["Before"].Rows[i];
rw[ds.Tables["Before"].Columns.Count - 1] = "Before";
ds.Tables["BeforeSingular"].ImportRow(rw);
continue;
}
}
//Add remaining after table rows to AfterSingular table
ds.Tables["AfterSingular"].Merge(ds.Tables["After"]);
//ds.Tables["AfterSingular"].Columns.Add("Source_Label", System.Type.GetType("System.String"), "After_Singular");
//ds.Tables["BeforeSingular"].Columns.Add("Source_Label", System.Type.GetType("System.String"), "Before_Singular");
//foreach (System.Data.DataTable table in ds.Tables)
//{
// DataRow colNames = table.NewRow();
// //foreach (var col in table.Columns)
// //{
// //}
// for (int i = 0; i < table.Columns.Count; i++)
// colNames[i] = table.Columns[i].ColumnName;
// table.Rows.InsertAt(colNames, 0);
//}
foreach (System.Data.DataTable table in ds.Tables)
{
table.Columns.Remove(Inputs.SortColumn);
table.AcceptChanges();
}
stopWatch.Stop(); lbAlert.Text = lbAlert.Text + "\n\n" + "Total Comparison time for B: " + Inputs.RowNoBeforeTable + " x " + Inputs.ColumnNoBeforeTable + " A: " + Inputs.RowNoAfterTable + " x " + Inputs.ColumnNoAfterTable + " is " + stopWatch.ElapsedMilliseconds + " ms, " + stopWatch.ElapsedMilliseconds / 1000 + " s";
return true;
}
Can you not just use a VBA script to do this kind of thing?
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
Cells(iRow, iCol).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 49407
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next iCol
Next iRow
End Sub

How to get the values of button templatefield in Gridview?

I want to display the row details of Gridview when user click the button of template field. I got the output to display the button in a Gridview using template field. But when user click the button it reload the page and display the empty template with rows.
Full Coding of c#
string selectedColumn;
string[] splitSelectedColumn;
string groupByColumn;
string[] splitGroupByColumn;
ArrayList listBtnOrLbl = new ArrayList();
int compareFlag = 0;
protected void btnRefresh_Click(object sender, EventArgs e)
{
selectedColumn = txtColumnNames.Text;
splitSelectedColumn = selectedColumn.Split(',');
groupByColumn = txtGroupBy.Text;
splitGroupByColumn = groupByColumn.Split(',');
string[] compareGroup = new string[splitGroupByColumn.Length];
//Grouping column names using selected column text
int flag = 1;
foreach (string columnName in splitSelectedColumn)
{
flag = 1;
foreach (string groupByName in splitGroupByColumn)
{
if (columnName.Equals(groupByName))
{
flag = 2;
break;
}
}
if (flag == 1)
{
groupByColumn = groupByColumn + "," + columnName;
}
}
// CREATE A TEMPLATE FIELD AND BOUND FIELD
BoundField bfield = new BoundField();
TemplateField[] ttfield = new TemplateField[splitGroupByColumn.Length];
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
if (i < splitGroupByColumn.Length)
{
ttfield[i] = new TemplateField();
ttfield[i].HeaderText = splitGroupByColumn[i];
GridView1.Columns.Add(ttfield[i]);
}
else
{
try
{
bfield.HeaderText = splitSelectedColumn[i];
bfield.DataField = splitSelectedColumn[i];
Response.Write("<br/>BOUND FIELD==" + splitGroupByColumn[i]);
GridView1.Columns.Add(bfield);
}
catch (Exception)
{
}
}
}
// CREATE DATA TABLE and COLUMN NAMES
DataTable dt = new DataTable();
//dt.Columns.Clear();
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
dt.Columns.Add(splitSelectedColumn[i]);
//Console.WriteLine(splitSelectedColumn[i]);
System.Diagnostics.Debug.WriteLine(splitSelectedColumn[i]);
Response.Write("<br/>DT COLUMN NAMES==" + splitSelectedColumn[i]);
}
//ADD ROWS FROM DATABASE
string cs = ConfigurationManager.ConnectionStrings["connectionStringDB"].ConnectionString;
//int compareFlag = 0;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
//cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] where ItemLookupCode='" + txtItemLookupCode.Text + "'and ChildItemLookupCode1='" + txtChildItemLookupCode.Text + "' group by " + groupByColumn + " ";
cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] group by " + groupByColumn + " ";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
string addData = string.Empty;
string[] stackss = new string[splitSelectedColumn.Length];
while (rd.Read())
{
//SET the FIRST VALUES in `stackss[]` for comparing next values of rd[]
if (compareFlag == 0)
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
compareGroup[i] = rd[splitGroupByColumn[i]].ToString();
Response.Write("<br/>COMPARE GROUP [i]==" + compareGroup[i]);
}
compareFlag = 1;
Response.Write("<br/>splitSelectedColumn.LENGTH==" + splitSelectedColumn.Length);
Response.Write("<br/>STACK.LENGTH==" + stackss.Length);
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
for (int i = 0; i < compareGroup.Length; i++)
{
stackss[i] = compareGroup[i];
}
//TESTING PURPOSE ONLY
for (int i = 0; i < stackss.Length; i++)
{
//stack[i] = "";
Response.Write("<br/>STACK.VALUES==" + stackss[i]);
}
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("Execute BUTTON");
listBtnOrLbl.Add("button");
}
//stackss = new string[] { "" };
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
int tempValue = 0;
for (int i = 0; i < compareGroup.Length; i++)
{
if (compareGroup[i] == rd[i].ToString())
{
tempValue = tempValue + 1;
if (tempValue == compareGroup.Length)
{
for (int k = 0; k < splitSelectedColumn.Length; k++)
{
stackss[k] = rd[k].ToString();
Response.Write("second rowsssss ==== " + stackss[k]);
if (k + 1 == splitSelectedColumn.Length)
{
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("compare flag checking");
Response.Write("Execute LABEL");
listBtnOrLbl.Add("label");
compareFlag = 0;
}
}
}
}
}
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
rd.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Gridview templatefield will generate when user click Refresh button. The above coding is that one to generate column and templatefield
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Response.Write("<br/>compare flag checking OVER button count=======================" + listBtnOrLbl.Count);
if (e.Row.RowType == DataControlRowType.DataRow)
{
int size = splitGroupByColumn.Length;
//Button[] lnkBtn = new Button[size];
Label[] lblData = new Label[size];
Response.Write("<br/>Inside button count=======================" + listBtnOrLbl.Count);
if ("button".Equals(listBtnOrLbl[j]))
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
Button lnkView = new Button();
lnkView.ID = "lnkView";
lnkView.Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
//lnkView.Text = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
e.Row.Cells[i].Controls.Add(lnkView);
}
j++;
}
else
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
lblData[i] = new Label();
lblData[i].ID = "lblView";
lblData[i].Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
Response.Write("<br/>PRINT label==" + lblData[i].Text);
e.Row.Cells[i].Controls.Add(lblData[i]);
//e.Row.Visible = false;
}
j++;
}
}
protected void ViewDetails(object sender, EventArgs e)
{
Response.Redirect("exit.aspx"); //for testing purpose I gave like this, But this method is not calling i think when user clicks button
Response.Write("testing....");
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('TESTING:')", true);
}
Output before user clicks the Button
output1
After clicks the button(first button)
output2
I already did like this before,but that was small one not more complex code like this. that was working fine. Now What i did wrong here?.
Thanks
I think ViewDetails() method is not calling when user clicks the button

C# / VB .Net Performance tuning, Generate all possible Lottery combinations

Trying to generate all possible draws(combinations) for a lottery of unique 6 out of 42.
Actually looking for the most efficient way to do this (so that the actual generation does not take days).
Aside from the processing HOG (which is to be expected) .. i'm running into a memory limitation issue .. where my machine of 12GB ram cant hold 10% of the amount on number, let alone all combos.
So i decided to look into a Database alternative.
But with that i have the problem of duplicates (since i do not have the whole list in memory to check for existence).
I tried a lot of code versions but all are resource consuming.
Currently looking for alternatives that actually work :)
Here's my latest code sample that employs a database for later record processing and filtering and duplication removal:
public List<Draw> getDrawsContaining(List<int> initialBalls)
{
if (initialBalls == null)
initialBalls = new List<int>();
if (initialBalls.Count >= 6)
return new List<Draw> { new Draw(initialBalls) };
List<Draw> toReturn = new List<Draw>();
for (int i = 1; i <= 42; i++)
{
if (initialBalls.IndexOf(i) != -1)
continue;
initialBalls.Add(i);
toReturn.AddRange(getDrawsContaining(initialBalls));
initialBalls.Remove(i);
}
return toReturn;//.Distinct(dc).ToList();
}
AND say in the Page_Load i fire this :
try
{
using (SqlConnection connection = new SqlConnection(sqlConnectionString))
{
connection.Open();
String query = "TRUNCATE TABLE Draws";
SqlCommand command = new SqlCommand(query, connection);
//command.Parameters.Add("#id", "abc");
command.ExecuteNonQuery();
connection.Close();
}
DataTable dt = new DataTable("Draws");
dt.Columns.Add("Ball1");
dt.Columns.Add("Ball2");
dt.Columns.Add("Ball3");
dt.Columns.Add("Ball4");
dt.Columns.Add("Ball5");
dt.Columns.Add("Ball6");
for (int j = 1, k = 1; j <= 42 && k <= 42; )
{
List<Draw> drawsPart = getDrawsContaining(new List<int> { j, k });
if (drawsPart.Count > 0)
{
foreach (Draw d in drawsPart)
{
d.Balls.OrderBy(c => c);
DataRow dr = dt.NewRow();
dr["Ball1"] = d.Balls[0];
dr["Ball2"] = d.Balls[1];
dr["Ball3"] = d.Balls[2];
dr["Ball4"] = d.Balls[3];
dr["Ball5"] = d.Balls[4];
dr["Ball6"] = d.Balls[5];
dt.Rows.Add(dr);
}
DataTable tmp = dt.Copy();
dt.Rows.Clear();
AsyncDBSave AsyncDBSaveInstance = new AsyncDBSave(tmp, AsyncDBSaveDispose);
Thread t = new Thread(new ThreadStart(AsyncDBSaveInstance.commit));
t.Start();
}
k++;
if (k == 43) { j++; k = 1; }
}
}
catch (Exception ex)
{
var v = ex.Message;
throw;
}
Here we go... all very fast and efficient:
using System;
using System.Diagnostics;
static class Program
{
static void Main(string[] args)
{
byte[] results = new byte[6 * 5245786];
byte[] current = new byte[6];
int offset = 0;
var watch = Stopwatch.StartNew();
Populate(results, ref offset, current, 0);
watch.Stop();
Console.WriteLine("Time to generate: {0}ms", watch.ElapsedMilliseconds);
Console.WriteLine("Data size: {0}MiB",
(results.Length * sizeof(byte)) / (1024 * 1024));
Console.WriteLine("All generated; press any key to show them");
Console.ReadKey();
for (int i = 0; i < 5245786; i++)
{
Console.WriteLine(Format(results, i));
}
}
static string Format(byte[] results, int index)
{
int offset = 6 * index;
return results[offset++] + "," + results[offset++] + "," +
results[offset++] + "," + results[offset++] + "," +
results[offset++] + "," + results[offset++];
}
static void Populate(byte[] results, ref int offset, byte[] current, int level)
{
// pick a new candidate; note since we're doing C not P, assume ascending order
int last = level == 0 ? 0 : current[level - 1];
for (byte i = (byte)(last + 1); i <= 42; i++)
{
current[level] = i;
if (level == 5)
{
// write the results
results[offset++] = current[0];
results[offset++] = current[1];
results[offset++] = current[2];
results[offset++] = current[3];
results[offset++] = current[4];
results[offset++] = current[5];
}
else
{
// dive down
Populate(results, ref offset, current, level + 1);
}
}
}
}
Just for fun, non recursive version is about 2-3 times faster
static byte[] Populate2()
{
byte[] results = new byte[6 * 5245786];
int offset = 0;
for (byte a1 = 1; a1 <= 37; ++a1)
for (byte a2 = a1; ++a2 <= 38;)
for (byte a3 = a2; ++a3 <= 39;)
for (byte a4 = a3; ++a4 <= 40;)
for (byte a5 = a4; ++a5 <= 41;)
for (byte a6 = a5; ++a6 <= 42;)
{
results[offset] = a1;
results[offset+1] = a2;
results[offset+2] = a3;
results[offset+3] = a4;
results[offset+4] = a5;
results[offset+5] = a6;
offset += 6;
}
return results;
}

How to you disable CheckBoxList value in the database of array a[]. in the code below

protected void Page_Load(object sender, EventArgs e)
{
SqlDataAdapter cmd = new SqlDataAdapter("select Theatre_size, Theatre_Cost from Theatre where Theatre_Name='" + Request.Cookies["tname"].Value + "'", con);
DataSet ds2 = new DataSet();
cmd.Fill(ds2);
CheckBoxList CbxList = new CheckBoxList();
if (ds2.Tables[0].Rows.Count > 0)
{
Label1.Text = "Ticket Cost RS " + ds2.Tables[0].Rows[0]["Theatre_Cost"].ToString() + "/";
x = Convert.ToInt32(ds2.Tables[0].Rows[0]["Theatre_size"].ToString());
for (int i = 1; i<=x; i++)
{
CbxList.DataSource = ds2;
CbxList.Items.Add(new ListItem(Convert.ToString(i)));
CbxList.ID = i.ToString();
CbxList.Text = i.ToString();
CbxList.RepeatDirection = RepeatDirection.Vertical;
CbxList.RepeatColumns = 10;
}
ph.Controls.Add(CbxList);
}
string u = "";
SqlDataAdapter da = new SqlDataAdapter("select SeatNo from Booking where Theatre_Name='" + Request.Cookies["tname"].Value + "' and ShowDate='" + Request.Cookies["bdate"].Value + "' and ShowTime='" + Request.Cookies["stime"].Value + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
x = Convert.ToInt32(ds2.Tables[0].Rows[0]["Theatre_size"].ToString());
int rcount = ds.Tables[0].Rows.Count;
if (rcount > 0)
{
rcount = rcount - 1;
while (rcount >= 0)
{
u = ds.Tables[0].Rows[rcount][0].ToString();
//string u = "32,55,1,4,8";
string[] a = u.Split(new char[] { ',' });
int y, z;
for (y = 0; y <= a.Length - 1; y++)
{
for (z = 1; z <= x; z++)
{
CheckBoxList lc = (CheckBoxList)ph.FindControl(z.ToString());
if (lc.Text == a[y])
{
lc.Enabled = false;
}
}
}
rcount = rcount - 1;
}
}
con.Close();
}
In this Code, after i have added CheckBoxList from i=1 to i=Theatre_size taken from SQL database. There is a Column in SQL with SeatNo(varhchar(60) takes values as 1,2,3 in table Booking
These values are stored in an array a[].
ph is the placeholder where checkBoxList is placed.
How will you disable the values of the CheckBoxList for array a[] of the SeatNo that are already saved in the database, while traversing through the values of the CheckBoxList placed in the PlaceHolder ph.
I tried the Below code but, it doesn't seem to work for disabling the CheckBoxList for a[].
string u = "";
SqlDataAdapter da = new SqlDataAdapter("select SeatNo from Booking where Theatre_Name='" + Request.Cookies["tname"].Value + "' and ShowDate='" + Request.Cookies["bdate"].Value + "' and ShowTime='" + Request.Cookies["stime"].Value + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
x = Convert.ToInt32(ds2.Tables[0].Rows[0]["Theatre_size"].ToString());
int rcount = ds.Tables[0].Rows.Count;
if (rcount > 0)
{
rcount = rcount - 1;
while (rcount >= 0)
{
u = ds.Tables[0].Rows[rcount][0].ToString();
//string u = "32,55,1,4,8";
string[] a = u.Split(new char[] { ',' });
Label2.Text = "hi";
int y, z;
for (y = 0; y <= a.Length - 1; y++)
{
for (z = 1; z <= x; z++)
{
CheckBoxList lc = (CheckBoxList)ph.FindControl(z.ToString());
if (lc.Text == a[y])
{
lc.Enabled = false;
}
}
//CheckBoxList1.Items[1].Enabled = false;
}
rcount = rcount - 1;
}
}
con.Close();
}

Categories