I want to Group questions and answers LINQ and have them display properly - linq

I'm trying to group properly to have my cell distribute eveningly. The printout is coming very odd and uneven.
is it the table i'm creating or group or both? I think the group is correct. My results are as shown in the image below.
Gold is the heading,
Green are the questions,
Red are the answers
Mt table is is below
var Sections = new OncologySection().SelectSections(projectID.ToString());
int iSection = 0;
int igroups = 0;
int ianswer = 0;
tb.CssClass = "";
tb.BorderWidth = 1;
tb.Width = new Unit("780px");
tb.Attributes.Add("runat", "server");
foreach (OncologySection section in Sections)
{
TableRow row1 = new TableRow();
iSection++;
// var getDistinctQuestion = getVoterAnswerstoList.Select(s => s.QuestionText ,s.Id).Distinct().ToList();
var getVoterAnswerstoList = new OncologyGeneratePDFDAL().DataforPDFCreation(Convert.ToInt32(projectID), Convert.ToInt32(voterid), Convert.ToInt32(caseId), Convert.ToInt32(voteSurveyId), Convert.ToInt32(section.SectionID)).OrderBy(os => os.SortOrder);
//var groupedCustomerList = getVoterAnswerstoList
// .GroupBy(u => u.QuestionText, u.QuestionText)
// .Select(grp => grp.ToList())
// .ToList();
var groupedCustomerList = getVoterAnswerstoList.GroupBy(x => new { x.QuestionText, x.DynamicValue }).ToList();
TableCell cell1 = new TableCell();
cell1.BorderWidth = 1;
cell1.Text = section.SectionName;
cell1.BorderColor = System.Drawing.Color.Goldenrod;
cell1.ColumnSpan = groupedCustomerList.Count();
row1.Cells.Add(cell1);
tb.Rows.Add(row1);
TableRow row2 = new TableRow();
foreach (var groups in groupedCustomerList)
{
igroups++;
TableCell cell2 = new TableCell();
var q = (from s in groups select s.QuestionText).FirstOrDefault();
cell2.BorderWidth = 1;
cell2.Text = q;
cell2.BorderColor = System.Drawing.Color.Green;
cell2.ColumnSpan = groupedCustomerList.Count();
row2.Cells.Add(cell2);
if (igroups == groupedCustomerList.Count())
{
tb.Rows.Add(row2);
}
else
{
row2.Cells.Add(cell2);
}
TableRow row3 = new TableRow();
foreach (var answers in groups)
{
ianswer++;
TableCell cell3 = new TableCell();
cell3.BorderWidth = 1;
cell3.BorderColor = System.Drawing.Color.DarkRed;
if (answers.DataTypeId == 7)
{
cell3.Text = answers.DynamicValue.ToString();
}
else if ((answers.DataTypeId == 5) || (answers.DataTypeId == 6) || (answers.DataTypeId == 8))
{
if (answers.VotingValue != 0)
{
cell3.Text = answers.VotingValue.ToString();
}
else
{
cell3.Text = " ";
}
}
else
{
cell3.Text = " ";
}
row3.Cells.Add(cell3);
tb.Rows.Add(row3);
}
}
}
}

Related

AmChart- After updating fieldMappings and dataSet,Graph is not plotting

Problem Statement:
after updating fieldMappings and dataSet during runtime(After clicking on a button) for a stockgraph, validateNow() / validteData() is not plotting the graph.
Note: MACD0 is added from 25th element onward and expoSignalLine0 is added from 33rd element onward in the dataprovider and fieldMapping is also getting updated and can be verified same in console.enter code here
Following is the Code snippet:
(addMACD function is called on click of a button)
function addMACD() {
var chart = AmCharts.charts[ 0 ];
AmCharts.MACDGraphs = 0;
AmCharts.expoSignalLineGraphs = 0;
var MACDField = "MACD"+ AmCharts.MACDGraphs;
var expoSignalLineField = "expoSignalLine"+ AmCharts.expoSignalLineGraphs;
chart.dataSets[0].fieldMappings.push( {
fromField : MACDField,
toField : MACDField
},
{
fromField : expoSignalLineField,
toField : expoSignalLineField
});
var currClose;
var prevClose;
var twelveDayEMA =[];
var twentySixDayEMA =[];
var MACDarray = [];
var signalLineArray = [];
var MACDperiod = 9 ;// 9 day exponential average
for ( var i = 1; i < (chart.dataSets[0].dataProvider.length); i++) {
var dp = chart.dataSets[0].dataProvider[i - 1];
prevClose = parseFloat(dp["close"]);
var dp = chart.dataSets[0].dataProvider[i];
currClose = parseFloat(dp["close"]);
if( i==1){
twelveDayEMA[i] = (0.15*currClose) + (0.85*prevClose);
twentySixDayEMA[i] = (0.075*currClose) + (0.925*prevClose);
}
else{
twelveDayEMA[i] = (0.15*currClose) + (0.85*twelveDayEMA[i - 1]);
twentySixDayEMA[i] = (0.075*currClose) + (0.925*twentySixDayEMA[i - 1]);
}
if(i >= 25){
MACDarray[i] = twelveDayEMA[i] - twentySixDayEMA[i] ;
dp[MACDField] = MACDarray[i];
if(i == 25){
signalLineArray[i] = MACDarray[i];
}
else{
signalLineArray[i] = ( MACDarray[i]*(2/( MACDperiod + 1)) ) + ( signalLineArray[i - 1]*(1-(2/( MACDperiod + 1))) )
}
}
if(i >=33){
dp[expoSignalLineField] = signalLineArray[i];
}
}
console.log(chart);
if ( chart.panels.length == 1 || chart.panels.length == 2 || chart.panels.length == 3 || chart.panels.length == 4 || chart.panels.length == 5) {
var newPanel = new AmCharts.StockPanel();
newPanel.allowTurningOff = true;
newPanel.title = "MACD";
newPanel.showCategoryAxis = false;
graph1 = new AmCharts.StockGraph();
graph1.valueField = MACDField;
graph1.useDataSetColors = false;
graph1.lineColor="#6699FF";
graph1.title = "MACD";
newPanel.stockGraphs.push( graph1 );
graph2 = new AmCharts.StockGraph();
graph2.valueField =expoSignalLineField;
graph2.useDataSetColors = false;
graph2.lineColor = "#990000";
graph2.title = "MACD2";
newPanel.stockGraphs.push( graph2 );
var legend = new AmCharts.StockLegend();
legend.markerType = "none";
legend.markerSize = 0;
newPanel.stockLegend = legend;
chart.addPanelAt( newPanel, 1 );
chart.validateData();
chart.validateNow();
//chart.write("chartdiv");
}
}
You have to call validateNow first, then call validateData.
Alternatively, you can call validateNow(true, false) which has the same effect as calling the two functions separately.
Updated fiddle

Finding path from cell x to cell y in a grid so that all cells are parsed once

I am trying to code an algorithm so that it can start from any "start" cell of a grid ( eg.cell no. 4 in the pic) and parse through each cell of a grid once. The grid can be of any size 3x3, 4x4, 8x8 etc.
The following codes generates such paths. And works fine for many cells in 8x8 grid. But for many cells, it takes forever to search a path.
I was wondering if there is some better solution that can be referenced, so that the solution can be optimized.
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
private var rand_Num;
public var node0_Mc:MovieClip ,node1_Mc:MovieClip,node2_Mc:MovieClip,node3_Mc:MovieClip,node4_Mc:MovieClip,node5_Mc:MovieClip,node6_Mc:MovieClip,node7_Mc:MovieClip,node8_Mc:MovieClip,node9_Mc:MovieClip,
node10_Mc:MovieClip,node11_Mc:MovieClip,node12_Mc:MovieClip,node13_Mc:MovieClip,node14_Mc:MovieClip,node15_Mc:MovieClip,node16_Mc:MovieClip,node17_Mc:MovieClip,node18_Mc:MovieClip,node19_Mc:MovieClip,
node20_Mc:MovieClip,node21_Mc:MovieClip,node22_Mc:MovieClip,node23_Mc:MovieClip,node24_Mc:MovieClip,node25_Mc:MovieClip,node26_Mc:MovieClip,node27_Mc:MovieClip,node28_Mc:MovieClip,node29_Mc:MovieClip,
node30_Mc:MovieClip,node31_Mc:MovieClip,node32_Mc:MovieClip,node33_Mc:MovieClip,node34_Mc:MovieClip,node35_Mc:MovieClip,node36_Mc:MovieClip,node37_Mc:MovieClip,node38_Mc:MovieClip,node39_Mc:MovieClip,
node40_Mc:MovieClip,node41_Mc:MovieClip,node42_Mc:MovieClip,node43_Mc:MovieClip,node44_Mc:MovieClip,node45_Mc:MovieClip,node46_Mc:MovieClip,node47_Mc:MovieClip,node48_Mc:MovieClip,node49_Mc:MovieClip,
node50_Mc:MovieClip,node51_Mc:MovieClip,node52_Mc:MovieClip,node53_Mc:MovieClip,node54_Mc:MovieClip,node55_Mc:MovieClip,node56_Mc:MovieClip,node57_Mc:MovieClip,node58_Mc:MovieClip,node59_Mc:MovieClip,
node60_Mc:MovieClip, node61_Mc:MovieClip, node62_Mc:MovieClip, node63_Mc:MovieClip;
public const NUM_COLS:Number = 8;
// 3 ;// 4 ;
public const NUM_ROWS:Number = 8;// 3 ;// 4 ;
var chain_Arr:Array = [];
var blockIndex_Arr:Array = [];
var nodearr:Array;
var adjacentNodeArray_Arr:Array = [];
var parsedNodeIndex_Arr:Array = [];
var validNextAdjacentNodeIndexArray_Arr:Array = [];
var validPreviousAdjacentNodeIndexArray_Arr:Array = [];
var savePair_Arr:Array = [];
var countChain_Num:Number = 0;
var saveParent_Arr:Array = [];
public function Main()
{
// constructor code
nodearr = [node0_Mc,node1_Mc,node2_Mc,node3_Mc,node4_Mc,node5_Mc,node6_Mc,node7_Mc,node8_Mc,node9_Mc,node10_Mc,node11_Mc,node12_Mc,node13_Mc,node14_Mc,node15_Mc,node16_Mc,node17_Mc,node18_Mc,node19_Mc,node20_Mc,node21_Mc,node22_Mc,node23_Mc,node24_Mc,node25_Mc,node26_Mc,node27_Mc,node28_Mc,node29_Mc,node30_Mc,node31_Mc,node32_Mc,node33_Mc,node34_Mc,node35_Mc,node36_Mc,node37_Mc,node38_Mc,node39_Mc,node40_Mc,node41_Mc,node42_Mc,node43_Mc,node44_Mc,node45_Mc,node46_Mc,node47_Mc,node48_Mc,node49_Mc,node50_Mc,node51_Mc,node52_Mc,node53_Mc,node54_Mc,node55_Mc,node56_Mc,node57_Mc,node58_Mc,node59_Mc,node60_Mc,node61_Mc,node62_Mc,node63_Mc];
var possibleAdjacentNodeIndex_Arr:Array = [];
initValidNextAdjacentNodeIndexArray();
initValidPreviousAdjacentNodeIndexArray();
savePair_Arr = [];
var startIndex_num:Number = 45;// 0 ;
rand_Num = 62;// randomRange(10, (NUM_COLS * NUM_ROWS) - 1);
getAllChainsFromParamNodeIndexParamParentChain(startIndex_num,[startIndex_num]);
}
function initValidNextAdjacentNodeIndexArray():void
{
for (var index_num = 0; index_num < NUM_COLS*NUM_ROWS; index_num++)
{
validNextAdjacentNodeIndexArray_Arr[index_num] = getValidNodeIndexArrayAdjacentToParamNodeIndex(index_num);
//trace(validNextAdjacentNodeIndexArray_Arr[index_num]);
}
}
function initValidPreviousAdjacentNodeIndexArray():void
{
for (var index_num = 0; index_num < NUM_COLS*NUM_ROWS; index_num++)
{
validPreviousAdjacentNodeIndexArray_Arr[index_num] = getValidNodeIndexArrayAdjacentToParamNodeIndex(index_num);
//trace(validNextAdjacentNodeIndexArray_Arr[index_num]);
}
}
//function getAllChainsFromParamNodeIndexParamParentChain( path_arr:Array,index_param_num:Number ):void
function getAllChainsFromParamNodeIndexParamParentChain( index_param_num:Number, parent_arr:Array ):void
{
var i;
if ( countChain_Num > 15 )
{
return;
}
reinitPath();
var adjacent_arr = getValidNodeIndexArrayAdjacentToParamNodeIndex(index_param_num);
for (i = 0; i < adjacent_arr.length; i++)
{
reinitPath();
if ( ( checkRepeat(chain_Arr)) )
{
continue;
}
chain_Arr.push(adjacent_arr[i]);
//trace("chain starts from", chain_Arr);
var nodeIndex_num:Number = adjacent_arr[i];
var nodeIndexExist_num = 0;
var parentNode_num:Number = parent_arr[parent_arr.length - 1];
var bool:Boolean;
while ( isNaN(nodeIndex_num) == false)
{
//var childNodeIndex_num = manageValidAdjacentIndexArray(parent_arr[parent_arr.length-1], parentNode_num , nodeIndex_num );
var childNodeIndex_num = manageValidAdjacentIndexArray(adjacent_arr[i],parentNode_num,nodeIndex_num);
//var childNodeIndex_num = manageValidAdjacentIndexArray(parentNode_num, parentNode_num , nodeIndex_num );
parentNode_num = nodeIndex_num;
nodeIndex_num = childNodeIndex_num;
if ( ( checkRepeat(chain_Arr)) )
{
break;
}
if ( isNaN(nodeIndex_num) == false)
{
chain_Arr.push(nodeIndex_num);
}
}
if (chain_Arr.length > NUM_COLS * NUM_ROWS - 1)
{
//if ( !( checkRepeat(chain_Arr)) )
{
trace(chain_Arr);
saveParent_Arr[saveParent_Arr.length ] = new Array();
for (var k = 0; k < rand_Num; k++)
{
saveParent_Arr[saveParent_Arr.length - 1].push( chain_Arr[k]);
}
countChain_Num++;
}
}
};
for (i = 0; i < adjacent_arr.length; i++)
{
var arr2:Array = parent_arr.slice();
arr2.push(adjacent_arr[i]);
getAllChainsFromParamNodeIndexParamParentChain( adjacent_arr[i], arr2 );
}
function reinitPath():void
{
chain_Arr = [];
chain_Arr = chain_Arr.concat(parent_arr);
}
}
private function checkRepeat(chain_arr:Array):Boolean
{
var bool:Boolean;
var num = rand_Num;
if (chain_arr.length >= num - 1)
{
for (var i = 0; i < saveParent_Arr.length; i++)
{
//trace( saveParent_Arr[i][0], saveParent_Arr[i][1]);
if (saveParent_Arr[i] != undefined)
{
var z = 0;
for (var j = 0; j < num; j++)
{
if (saveParent_Arr[i][j] == chain_arr[j])
{
z++;
if ( z >= num)
{
bool = true;
break;
}
}
else
{
break;
}
}
if (bool)
{
break;
}
}
}
}
return bool;
}
function randomRange( minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
function randomizeArray(arr:Array ):void
{
for (var i = 0; i < arr.length; i++)
{
var random = randomRange(0,arr.length - 1);
var temp = arr[i];
arr[i] = arr[random];
arr[random] = temp;
}
}
//will send NaN if no valid adjacent index array is possible
private function manageValidAdjacentIndexArray(chainStartIndex_num:Number, parentNodeIndex_param_num:Number, nodeIndex_num:Number):Number
{
var num_nan:Number;
var ret_num:Number;
var j;
//var tot:Number = validNextAdjacentNodeIndexArray_Arr[nodeIndex_num].length ;
j = 0;
var arr:Array = validNextAdjacentNodeIndexArray_Arr[nodeIndex_num];// getValidNodeIndexArrayAdjacentToParamNodeIndex(nodeIndex_num) ;
randomizeArray(arr);
while (arr.length > 0 )// && isNaN(ret_num))
{
ret_num = arr[j];//validNextAdjacentNodeIndexArray_Arr[nodeIndex_num][j] ;
//if this index is present in chain then remove it off
if (chain_Arr.indexOf(ret_num) >= 0)
{
//j++ ;
ret_num = num_nan;
}
j++;
if ( j >= arr.length )
{
ret_num = num_nan;
break;
}
}
return ret_num;
}
private function getValidAdjacentIndexToParamNodeIndex(nodeIndex_param_num:Number):Number
{
var adjacentNode_arr:Array = [];
var adjacentRow_arr:Array = [];
var adjacentCol_arr:Array = [];
var allIndex_arr:Array = [];
var r:Number;
var c:Number;
var row_num:Number = int(nodeIndex_param_num / NUM_COLS);
var col_num:Number = (nodeIndex_param_num % NUM_COLS);
allIndex_arr = getAllAdjacentNodeIndexArray(row_num,col_num);
validateIndices(allIndex_arr);
var ret_num:Number;
ret_num = allIndex_arr[0];
return ret_num;
}
function getValidNodeIndexArrayAdjacentToParamNodeIndex(nodeIndex_param_num:Number ):Array
{
var adjacentNode_arr = [];
for (var positionId_num = 0; positionId_num < 8; positionId_num++)
{
var num:Number = getNodeIndexAtParamPositionIdOfParamIndex(positionId_num,nodeIndex_param_num);
if (isNaN(num))
{
}
else
{
adjacentNode_arr.push(num);
}
}
return adjacentNode_arr;
}
private function getAllAdjacentNodeIndexArray(row_num:Number, col_num:Number,within_arr:Array=null):Array
{
var num:Number;
var index_arr:Array = [num,num,num,num,num,num,num,num];
var r:Number;
var c:Number;
if ( row_num > 0 )
{
r = row_num - 1;
c = col_num;
index_arr[0] = r * NUM_COLS + c;
}
if ( col_num < NUM_COLS-1)
{
r = row_num;
c = col_num + 1;
index_arr[1] = r * NUM_COLS + c;
}
if ( row_num < NUM_ROWS-1)
{
r = row_num + 1;
c = col_num;
index_arr[2] = r * NUM_COLS + c;
}
if ( col_num > 0 )
{
r = row_num;
c = col_num - 1;
index_arr[3] = r * NUM_COLS + c;
}
///////////////////////////////////////////
if ( row_num > 0 && col_num > 0)
{
r = row_num - 1;
c = col_num - 1;
index_arr[4] = r * NUM_COLS + c;
}
if ( row_num > 0 && col_num < NUM_COLS-1)
{
r = row_num - 1;
c = col_num + 1;
index_arr[5] = r * NUM_COLS + c;
}
if ( row_num < NUM_ROWS-1 && col_num < NUM_COLS-1)
{
r = row_num + 1;
c = col_num + 1;
index_arr[6] = r * NUM_COLS + c;
}
if ( row_num < NUM_ROWS-1 && col_num > 0 )
{
r = row_num + 1;
c = col_num - 1;
index_arr[7] = r * NUM_COLS + c;
}
return index_arr;
}
//the adjacent node must be present in within_arr, which we splice, one time for variation
function getNodeIndexAtParamPositionIdOfParamIndex( n:Number , nodeIndex_param_num:Number):Number
{
var adjacentNode_arr:Array = [];
var adjacentRow_arr:Array = [];
var adjacentCol_arr:Array = [];
var index_arr:Array = [];
var r:Number;
var c:Number;
var index_num:Number;
var row_num:Number = int(nodeIndex_param_num / NUM_COLS);
var col_num:Number = (nodeIndex_param_num % NUM_COLS);
index_arr = getAllAdjacentNodeIndexArray(row_num,col_num);
validateIndices(index_arr);
var ret_num:Number;
ret_num = index_arr[n];
return ret_num;
}
private function validateIndices(index_arr:Array):void
{
for (var i = 0; i < index_arr.length; i++)
{
if (chain_Arr.indexOf(index_arr[i]) == -1)
{
}
else
{
var num:Number;
index_arr[i] = num;//pushing NaN
}
}
}
}
}
It's a Hamiltonian path problem. It's NP complete and afaik there is still no efficient solution.
check this out: hamilton paths in grid graphs (pdf)
short randomized algorithm explanation: Princeton Hamiltonian path problem
or wikipedia: Hamiltonian path problem
edit:
I did some more research and for your special case of strongly connected square grids (nxn chessboards) a variation of the warndoffs rule for finding a knights tour might give you a solution in near linear time. See here: A method for finding hamiltonian paths and knight tours (pdf)

Subsonic 3.0.0.4 leaking SQL connections?

I've been using Subsonic 3.0.0.4 (ActiveRecord approach) for a while, and I recently coded a small page that basically retrieves about 500 records for a given year, and then i just loop through each of them, creating new instances of the Active Record class, just modifying the Period field, and saving each instance in the loop.
The issue is that after executing that page, a LOT of SQL connections are left hanging/open in SQL server (by looking at the sp_who2). Before the page finishes executing, I get the "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached." error.
The code is the following:
if (string.IsNullOrEmpty(tbPeriodoAGenerar.Text)) return;
var idPeriodo = Convert.ToInt32(tbPeriodoAGenerar.Text);
var nuevaEncuesta = new Encuesta();
nuevaEncuesta.IdPeriodo = idPeriodo;
nuevaEncuesta.IdResponsable = 1;
nuevaEncuesta.fechaCierre1 = Convert.ToDateTime(dpFechaCierre1.Value);
nuevaEncuesta.fechaCierre2 = Convert.ToDateTime(dpFechaCierre2.Value);
nuevaEncuesta.IdTipoEncuesta = (int)ETipoEncuesta.PorAnio;
nuevaEncuesta.nombreEncuesta = NombresEncuestas.COVA;
nuevaEncuesta.nombrePublico = NombresEncuestas.COVA_PUBLICO;
nuevaEncuesta.Save();
var empresasActivas = Empresa.Find(x => x.activo == 1);
foreach (var empresa in empresasActivas)
{
EmpresaEncuesta ee = new EmpresaEncuesta();
ee.IdEmpresa = empresa.IdEmpresa;
ee.IdEncuesta = nuevaEncuesta.IdEncuesta;
ee.IdEstatusContestado = (int)EEstatusEmpresaEncuesta.SinContestar;
ee.fechaMod = DateTime.Now;
ee.IdUsuario = 1;
ee.ipMod = IpUsuarioActual;
ee.Save();
}
if (chkMigrarRespuestas.Checked)
{
var periodosAnteriores = new EncuestaBO().ObtenerPeriodosAnteriores(NombresEncuestas.COVA, idPeriodo);
int? periodoAnterior = null;
if (periodosAnteriores.Tables[0].Rows.Count > 0)
{
periodoAnterior = Convert.ToInt32(periodosAnteriores.Tables[0].Rows[0][Columnas.ID_PERIODO]);
}
if (!periodoAnterior.HasValue) return;
var respuestasCortoPlazo = COVACortoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVACortoPlazo ccp;
foreach (var ccpAnterior in respuestasCortoPlazo)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ccpAnterior.IdEmpresa).Any()) continue;
ccp = new COVACortoPlazo();
ccp.IdEmpresa = ccpAnterior.IdEmpresa;
ccp.CuentaCortoPlazo = ccpAnterior.CuentaCortoPlazo;
ccp.ComentariosAdicionales = ccpAnterior.ComentariosAdicionales;
ccp.RetiroVoluntarioOpcionId = ccpAnterior.RetiroVoluntarioOpcionId;
ccp.RetiroVoluntarioOtroDesc = ccpAnterior.RetiroVoluntarioOtroDesc;
ccp.RetiroEmpresaOpcionId = ccpAnterior.RetiroEmpresaOpcionId;
ccp.RetiroEmpresaOtroDesc = ccpAnterior.RetiroEmpresaOtroDesc;
ccp.Periodo = idPeriodo;
ccp.Save();
}
var tablaCortoPlazoAnterior = COVATablaCortoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVATablaCortoPlazo ctcp;
foreach (var ctcpAnterior in tablaCortoPlazoAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctcpAnterior.IdEmpresa).Any()) continue;
ctcp = new COVATablaCortoPlazo();
ctcp.IdEmpresa = ctcpAnterior.IdEmpresa;
ctcp.Periodo = idPeriodo;
ctcp.COVASegmentoOpcionId = ctcpAnterior.COVASegmentoOpcionId;
ctcp.NivelDinamicaMin = ctcpAnterior.NivelDinamicaMin;
ctcp.NivelDinamicaMax = ctcpAnterior.NivelDinamicaMax;
ctcp.NombreBono = ctcpAnterior.NombreBono;
ctcp.COVAPeriodicidadOpcionId = ctcpAnterior.COVAPeriodicidadOpcionId;
ctcp.MetodoCalculo = ctcpAnterior.MetodoCalculo;
ctcp.COVABaseCalculoOpcionId = ctcpAnterior.COVABaseCalculoOpcionId;
ctcp.RealAnualizado = ctcpAnterior.RealAnualizado;
ctcp.Save();
}
var respuestasAnual = COVAAnual.Find(x => x.Periodo == (periodoAnterior));
COVAAnual ca;
foreach (var caAnterior in respuestasAnual)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == caAnterior.IdEmpresa).Any()) continue;
ca = new COVAAnual();
ca.IdEmpresa = caAnterior.IdEmpresa;
ca.CuentaAnual = caAnterior.CuentaAnual;
ca.NombreBono = caAnterior.NombreBono;
ca.FechaPago = caAnterior.FechaPago;
ca.ComentariosAdicionales = caAnterior.ComentariosAdicionales;
ca.RetiroVoluntarioOpcionId = caAnterior.RetiroVoluntarioOpcionId;
ca.RetiroVoluntarioOtroDesc = caAnterior.RetiroVoluntarioOtroDesc;
ca.RetiroEmpresaOpcionId = caAnterior.RetiroEmpresaOpcionId;
ca.RetiroEmpresaOtroDesc = caAnterior.RetiroEmpresaOtroDesc;
ca.Periodo = idPeriodo;
ca.Save();
}
var tablaAnualAnterior = COVATablaAnual.Find(x => x.Periodo == (periodoAnterior));
COVATablaAnual cta;
foreach (var ctaAnterior in tablaAnualAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctaAnterior.IdEmpresa).Any()) continue;
cta = new COVATablaAnual();
cta.IdEmpresa = ctaAnterior.IdEmpresa;
cta.Periodo = idPeriodo;
cta.COVASegmentoOpcionId = ctaAnterior.COVASegmentoOpcionId;
cta.NivelDinamicaMin = ctaAnterior.NivelDinamicaMin;
cta.NivelDinamicaMax = ctaAnterior.NivelDinamicaMax;
cta.Minimo = ctaAnterior.Minimo;
cta.Target = ctaAnterior.Target;
cta.Maximo = ctaAnterior.Maximo;
cta.RealAnualPagado = ctaAnterior.RealAnualPagado;
cta.MetodoCalculo = ctaAnterior.MetodoCalculo;
cta.COVABaseCalculoOpcionId = ctaAnterior.COVABaseCalculoOpcionId;
cta.Save();
}
var respuestasLargoPlazo = COVALargoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVALargoPlazo clp;
foreach (var clpAnterior in respuestasLargoPlazo)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == clpAnterior.IdEmpresa).Any()) continue;
clp = new COVALargoPlazo();
clp.IdEmpresa = clpAnterior.IdEmpresa;
clp.CuentaLargoPlazo = clpAnterior.CuentaLargoPlazo;
clp.ComentariosAdicionales = clpAnterior.ComentariosAdicionales;
clp.RetiroVoluntarioOpcionId = clpAnterior.RetiroVoluntarioOpcionId;
clp.RetiroVoluntarioOtroDesc = clpAnterior.RetiroVoluntarioOtroDesc;
clp.RetiroEmpresaOpcionId = clpAnterior.RetiroEmpresaOpcionId;
clp.RetiroEmpresaOtroDesc = clpAnterior.RetiroEmpresaOtroDesc;
clp.PermiteCompraAcciones = clpAnterior.PermiteCompraAcciones;
clp.Periodo = idPeriodo;
clp.Save();
}
var tablaLargoPlazoAnterior = COVATablaLargoPlazo.Find(x => x.Periodo == (periodoAnterior));
COVATablaLargoPlazo ctlp;
foreach (var ctlpAnterior in tablaLargoPlazoAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctlpAnterior.IdEmpresa).Any()) continue;
ctlp = new COVATablaLargoPlazo();
ctlp.IdEmpresa = ctlpAnterior.IdEmpresa;
ctlp.Periodo = idPeriodo;
ctlp.NombrePlan = ctlpAnterior.NombrePlan;
ctlp.COVATipoPlanOpcionId = ctlpAnterior.COVATipoPlanOpcionId;
ctlp.COVASegmentoOpcionId = ctlpAnterior.COVASegmentoOpcionId;
ctlp.NivelDinamicaMin = ctlpAnterior.NivelDinamicaMin;
ctlp.NivelDinamicaMax = ctlpAnterior.NivelDinamicaMax;
ctlp.RealPagadoFinalPlan = ctlpAnterior.RealPagadoFinalPlan;
ctlp.AniosEjerce = ctlpAnterior.AniosEjerce;
ctlp.MetodoCalculo = ctlpAnterior.MetodoCalculo;
ctlp.BaseCalculo = ctlpAnterior.BaseCalculo;
ctlp.Save();
}
var respuestasVentas = COVAVentas.Find(x => x.Periodo == (periodoAnterior));
COVAVentas cv;
foreach (var cvAnterior in respuestasVentas)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == cvAnterior.IdEmpresa).Any()) continue;
cv = new COVAVentas();
cv.IdEmpresa = cvAnterior.IdEmpresa;
cv.CuentaVentas = cvAnterior.CuentaVentas;
cv.ComentariosAdicionales = cvAnterior.ComentariosAdicionales;
cv.RetiroVoluntarioOpcionId = cvAnterior.RetiroVoluntarioOpcionId;
cv.RetiroVoluntarioOtroDesc = cvAnterior.RetiroVoluntarioOtroDesc;
cv.RetiroEmpresaOpcionId = cvAnterior.RetiroEmpresaOpcionId;
cv.RetiroEmpresaOtroDesc = cvAnterior.RetiroEmpresaOtroDesc;
cv.Periodo = idPeriodo;
cv.Save();
}
var tablaVentasAnterior = COVATablaVentas.Find(x => x.Periodo == (periodoAnterior));
COVATablaVentas ctv;
foreach (var ctvAnterior in tablaVentasAnterior)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == ctvAnterior.IdEmpresa).Any()) continue;
ctv = new COVATablaVentas();
ctv.IdEmpresa = ctvAnterior.IdEmpresa;
ctv.Periodo = idPeriodo;
ctv.COVASegmentoOpcionId = ctvAnterior.COVASegmentoOpcionId;
ctv.COVAPeriodicidadOpcionId = ctvAnterior.COVAPeriodicidadOpcionId;
ctv.Minimo = ctvAnterior.Minimo;
ctv.Target = ctvAnterior.Target;
ctv.Maximo = ctvAnterior.Maximo;
ctv.RealAnualizado = ctvAnterior.RealAnualizado;
ctv.MetodoCalculo = ctvAnterior.MetodoCalculo;
ctv.BaseCalculo = ctvAnterior.BaseCalculo;
ctv.Save();
}
var respuestasGenerales = COVAGenerales.Find(x => x.Periodo == (periodoAnterior));
COVAGenerales cg;
foreach (var cgAnterior in respuestasGenerales)
{
if (!empresasActivas.Where(emp => emp.IdEmpresa == cgAnterior.IdEmpresa).Any()) continue;
cg = new COVAGenerales();
cg.IdEmpresa = cgAnterior.IdEmpresa;
cg.AccionesPorSituacionActual = cgAnterior.AccionesPorSituacionActual;
cg.ComentariosAccionesSituacionActual = cgAnterior.ComentariosAccionesSituacionActual;
cg.TomaCuentaSituacionDefinicionObjetivos = cgAnterior.TomaCuentaSituacionDefinicionObjetivos;
cg.Periodo = idPeriodo;
cg.Save();
}
}
Am I doing it the wrong way? At this point, I am not sure if this is a Subsonic bug or if I need to manually close the connection myself somehow.
I've googled for posts about similar problems when using subsonic, but none have come up. The usual cause for the error I get is not closing the SqlDataReader, but I honestly do not believe Subsonic is not closing it..and Im using the latest version.
Any ideas? Any help is greatly appreciated.
Any time you have a loop on an ORM-based object you have to consider there's probably an N+1 issue. I can't see your model, but I'll bet that in your loop you're executing a number of additional queries.
I know that Save() fires and closes an ExecuteScalar() - this should not leave a connection open. However, if you're fetching related records inside that loop - yeah that could have problems.
So - I would recommend using a profiler of some kind and the debugger to step through your loop - see what queries are made.
Alternatively - this is ripe for using the BatchInsert stuff which would keep everything in a nice, tidy single-connection transaction.
Read here for more:
http://subsonic.wekeroad.com/docs/Linq_Inserts

Add table to powerpoint slide using Open XML

I got the code for the Table in the powerpoint using the code generator, but I am not able to add the table to an existing powerpoint document.
I tried adding another table to the intended slide and doing the following:
Table table = slidePart.Slide.Descendants<Table>().First();
table.RemoveAllChildren();
Table createdTable = CreateTable();
foreach (OpenXmlElement childElement in createdTable.ChildElements)
{
table.AppendChild(childElement.CloneNode(true));
}
But that didn't work.
I am out of ideas on this issue.
My original target is to add a table with dynamic number of columns and fixed number of row to my presentation.
I know its been very long since this question is posted, but just in case if some one needs a working code to create table in pptx.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using A = DocumentFormat.OpenXml.Drawing;
using System.IO;
namespace ANF.Slides.TestEngine
{
class Program
{
static int index = 1;
static void Main(string[] args)
{
Console.WriteLine("Preparing Presentation");
PopulateData();
// GeneratedClass cls=new GeneratedClass();
//cls.CreatePackage(#"E:\output.pptx");
Console.WriteLine("Completed Presentation");
Console.ReadLine();
}
private static void PopulateData()
{
var overflow = false;
const int pageBorder = 3000000;
var db = new AdventureWorksEntities();
var products = db.Products;//.Take(5);
const string outputFile = #"E:\openxml\output.pptx";
File.Copy(#"E:\OpenXml\Template.pptx", outputFile, true);
using (var myPres = PresentationDocument.Open(outputFile, true))
{
var presPart = myPres.PresentationPart;
var slideIdList = presPart.Presentation.SlideIdList;
var list = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => presPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>();
var tableSlidePart = (SlidePart)list.Last();
var current = tableSlidePart;
long totalHeight = 0;
foreach (var product in products)
{
if (overflow)
{
var newTablePart = CloneSlidePart(presPart, tableSlidePart);
current = newTablePart;
overflow = false;
totalHeight = 0;
}
var tbl = current.Slide.Descendants<A.Table>().First();
var tr = new A.TableRow();
tr.Height = 200000;
tr.Append(CreateTextCell(product.Name));
tr.Append(CreateTextCell(product.ProductNumber));
tr.Append(CreateTextCell(product.Size));
tr.Append(CreateTextCell(String.Format("{0:00}", product.ListPrice)));
tr.Append(CreateTextCell(product.SellStartDate.ToShortDateString()));
tbl.Append(tr);
totalHeight += tr.Height;
if (totalHeight > pageBorder)
overflow = true;
}
}
}
static SlidePart CloneSlidePart(PresentationPart presentationPart, SlidePart slideTemplate)
{
//Create a new slide part in the presentation
SlidePart newSlidePart = presentationPart.AddNewPart<SlidePart>("newSlide" + index);
index++;
//Add the slide template content into the new slide
newSlidePart.FeedData(slideTemplate.GetStream(FileMode.Open));
//make sure the new slide references the proper slide layout
newSlidePart.AddPart(slideTemplate.SlideLayoutPart);
//Get the list of slide ids
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
//Figure out where to add the next slide (find max slide)
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
prevSlideId = slideId;
}
}
maxSlideId++;
//Add new slide at the end of the deck
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
//Make sure id and relid is set appropriately
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart);
return newSlidePart;
}
private static A.TableCell CreateTextCell(string text)
{
var textCol = new string[2];
if (!string.IsNullOrEmpty(text))
{
if (text.Length > 25)
{
textCol[0] = text.Substring(0, 25);
textCol[1] = text.Substring(26);
}
else
{
textCol[0] = text;
}
}
else
{
textCol[0] = string.Empty;
}
A.TableCell tableCell3 = new A.TableCell();
A.TextBody textBody3 = new A.TextBody();
A.BodyProperties bodyProperties3 = new A.BodyProperties();
A.ListStyle listStyle3 = new A.ListStyle();
textBody3.Append(bodyProperties3);
textBody3.Append(listStyle3);
var nonNull = textCol.Where(t => !string.IsNullOrEmpty(t)).ToList();
foreach (var textVal in nonNull)
{
//if (!string.IsNullOrEmpty(textVal))
//{
A.Paragraph paragraph3 = new A.Paragraph();
A.Run run2 = new A.Run();
A.RunProperties runProperties2 = new A.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
A.Text text2 = new A.Text();
text2.Text = textVal;
run2.Append(runProperties2);
run2.Append(text2);
paragraph3.Append(run2);
textBody3.Append(paragraph3);
//}
}
A.TableCellProperties tableCellProperties3 = new A.TableCellProperties();
tableCell3.Append(textBody3);
tableCell3.Append(tableCellProperties3);
//var tc = new A.TableCell(
// new A.TextBody(
// new A.BodyProperties(),
// new A.Paragraph(
// new A.Run(
// new A.Text(text)))),
// new A.TableCellProperties());
//return tc;
return tableCell3;
}
}
}

split one big datatable to two separated datatables

I´m exporting datatables to Excel workbook. Problem is that the datatable holds 90000 rows and excel can only hold 67000 rows in every sheet.
So..
How can i divide one big datatable to two datatables, maybe with Linq ?
Then i can have datatable1 in sheet1 and datatable2 in sheet2
Sincerly
agh
Assuming that you're getting the 90,000 rows for this DataTable from a database somewhere, the most efficient approach would be to modify your SELECT statement into two new SELECT statements, each of which returns < 67,000 rows, and then do everything else the same.
Split your recordset. Perform one SELECT that extracts all 90,000 rows, and split it on Excel import step.
private List<DataTable> CloneTable(DataTable tableToClone, int countLimit)//Split function
{
List<DataTable> tables = new List<DataTable>();
int count = 0;
DataTable copyTable = null;
foreach (DataRow dr in tableToClone.Rows)
{
if ((count++ % countLimit) == 0)
{
copyTable = new DataTable();
copyTable = tableToClone.Clone();
copyTable.TableName = "Sample" + count;
tables.Add(copyTable);
}
copyTable.ImportRow(dr);
}
return tables;
}
protected void LinkReport_Click(object sender, EventArgs e)
{
DataTable dt2 = (DataTable)ViewState["dtab"];
List<DataTable> dt1 = CloneTable(dt2, 5);
DataSet ds = new DataSet("dst");
for (int i = 0; i < dt1.Count; i++)
{
ds.Tables.Add(dt1[i]);
}
string filePath = Server.MapPath("Reports/").ToString() + "master.xls";
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
file.Delete();
}
Export(ds, filePath);// Export into Excel
}
Clone - The fastest method to create tables with original columns structure is Clone method.
Export into Excel
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
public void Export(DataSet ds, string filePath)
{
string data = null;
string columnName = null;
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
//Excel.Worksheet xlWorkSheet;
Excel.Worksheet xlWorkSheet = null;
object misValue = System.Reflection.Missing.Value;
Excel.Range range;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int l = 0; l < ds.Tables.Count; l++)
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(l + 1);
xlWorkSheet.Cells[1, 1] = "Report";
xlWorkSheet.get_Range("A1:D1", Type.Missing).Merge(Type.Missing);
xlWorkSheet.get_Range("A1", "D1").Font.Bold = true;
xlWorkSheet.Cells.Font.Name = "Courier New";
if (l == 0)
{
xlWorkSheet.Name = "Sheet1";
}
else if (l == 1)
{
xlWorkSheet.Name = "Sheet2";
}
else if (l == 2)
{
xlWorkSheet.Name = "Sheet3";
}
else if (l == 3)
{
xlWorkSheet.Name = "Sheet4";
}
else if (l == 4)
{
xlWorkSheet.Name = "Sheet5";
}
for (i = 0; i <= ds.Tables[l].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[l].Columns.Count - 1; j++)
{
columnName = ds.Tables[l].Columns[j].ColumnName.ToString();
xlWorkSheet.Cells[3, j + 1] = columnName;
data = ds.Tables[l].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 5, j + 1] = data;
}
}
}
//for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
//{
// for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
// {
// data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
// xlWorkSheet1.Cells[i + 1, j + 1] = data;
// }
//}
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
// kill all excel processes
Process[] pros = Process.GetProcesses();
for (int p = 0; p < pros.Length; p++)
{
if (pros[p].ProcessName.ToLower().Contains("excel"))
{
pros[p].Kill();
break;
}
}
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
Try this One.. I have Worked out in Visual Studio 2005
DataTable[] splittedtables = dt.AsEnumerable()
.Select((row, index) => new { row, index })
.GroupBy(x => x.index / Input From User) // integer division, the fractional part is truncated
.Select(g => g.Select(x => x.row).CopyToDataTable())
.ToArray();
This should work.

Resources