void getIDE() { this.enviMDFe.MDFe.infMDFe.ide = daoManifesto.GetIDE(objManifesto.sequencia).AsEnumerable().Select(c => new TMDFeInfMDFeIde { cUF = Acesso.cUF.ToString(), tpAmb = Acesso.TP_AMB == 1 ? TAmb.Item1 : TAmb.Item2, tpEmit = c["tpEmit"].ToString() == "1" ? TEmit.Item1 : TEmit.Item2, mod = TModMD.Item58, serie = Convert.ToInt32(c["serie"].ToString()).ToString(), nMDF = (Convert.ToInt32(objManifesto.numero)).ToString(), cMDF = objManifesto.sequencia.ToString().PadLeft(8, '0'), cDV = "", modal = TModalMD.Item1, dhEmi = daoUtil.GetDateServidor().ToString("yyyy-MM-ddTHH:mm:ss"), tpEmis = TMDFeInfMDFeIdeTpEmis.Item1, procEmi = TMDFeInfMDFeIdeProcEmi.Item0, verProc = Acesso.versaoMDFe, UFIni = c["UFIni"].ToString(), UFFim = c["UFFim"].ToString(), }).FirstOrDefault(); EnumerableRowCollection <DataRow> infMun = daoManifesto.GetInfMunCarrega(objManifesto.sequencia).AsEnumerable(); this.enviMDFe.MDFe.infMDFe.ide.infMunCarrega = infMun.Select(c => new TMDFeInfMDFeIdeInfMunCarrega { cMunCarrega = c["cMunCarrega"].ToString(), xMunCarrega = c["xMunCarrega"].ToString() } ).ToList(); List <string> lUFPer = infMun.Select(c => c["UFPer"].ToString()).Distinct().ToList(); foreach (string uf in lUFPer) { if (this.enviMDFe.MDFe.infMDFe.ide.UFFim.Equals(uf) || this.enviMDFe.MDFe.infMDFe.ide.UFIni.Equals(uf)) { this.enviMDFe.MDFe.infMDFe.ide.infPercurso = null; } else { if (this.enviMDFe.MDFe.infMDFe.ide.infPercurso == null) { this.enviMDFe.MDFe.infMDFe.ide.infPercurso = new List <TMDFeInfMDFeIdeInfPercurso>(); } this.enviMDFe.MDFe.infMDFe.ide.infPercurso.Add(new TMDFeInfMDFeIdeInfPercurso { UFPer = uf }); } } }
public static List <Conjugation> Read(string filename, string sheetname, WordAnalyzer analyzer) { ANALYZER = analyzer; string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; " + "Extended Properties=Excel 12.0;", filename); var adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetname + "$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "roots"); EnumerableRowCollection <DataRow> data = ds.Tables["roots"].AsEnumerable(); EnumerableRowCollection <ConjugationLine> entries = data.Select(x => new ConjugationLine { Verb = x.Field <string>("verb"), Solution = x.Field <string>("solution"), FirstTense = x.Field <string>("FirstTense"), SecondTense = x.Field <string>("SecondTense") ?? "", Person = x.Field <string>("Person"), }); var conjugations = new List <Conjugation>(); foreach (ConjugationLine entry in entries) { Conjugation conjugation = GetConjugation(entry); conjugations.Add(conjugation); } return(conjugations); }
private static HtmlBuilder CrosstabBody( this HtmlBuilder hb, SiteSettings ss, View view, Column groupByX, Column groupByY, string aggregateType, Column value, string timePeriod, DateTime month, EnumerableRowCollection <DataRow> dataRows) { var data = dataRows.Select(o => new CrosstabElement( o.String(groupByX.ColumnName), o.String(groupByY.ColumnName), o.Decimal("Value"))); var choicesX = groupByX?.TypeName == "datetime" ? CorrectedChoices(groupByX, timePeriod, month) : groupByX.ChoiceHash.ToDictionary( o => o.Key, o => new ControlData(o.Value.Text)); var choicesY = groupByY?.ChoiceHash.ToDictionary( o => o.Key, o => new ControlData(o.Value.Text)); return(hb.Table( ss: ss, choicesX: choicesX, choicesY: choicesY, aggregateType: aggregateType, value: value, daily: Daily(groupByX, timePeriod), columns: null, data: data)); }
public MorphemeContainer <Suffix> Read(DataSet ds, string tableName ) { EnumerableRowCollection <DataRow> data = ds.Tables[tableName].AsEnumerable(); EnumerableRowCollection <SuffixDictionaryLine> entries = data.Select(x => new SuffixDictionaryLine { Id = x.Field <string>("id")?.Trim(), Lex = x.Field <string>("lexicalForm")?.Trim(), Type = x.Field <string>("type")?.Trim(), Labels = x.Field <string>("flags")?.Trim() ?? "", Rules = x.Field <string>("rules")?.Trim() ?? "", Surfaces = x.Field <string>("surfaces")?.Trim(), }); var suffixesById = new Dictionary <string, Suffix>(); var suffixesBySurface = new MorphemeSurfaceDictionary <Suffix>(); foreach (SuffixDictionaryLine entry in entries) { AddSuffix(entry, suffixesById, suffixesBySurface); } return(new MorphemeContainer <Suffix>(suffixesById, suffixesBySurface)); }
public void Read(DataSet ds, string tableName, out Dictionary <string, Suffix> suffixesById, out MorphemeSurfaceDictionary <Suffix> suffixes) { EnumerableRowCollection <DataRow> data = ds.Tables[tableName].AsEnumerable(); EnumerableRowCollection <SuffixDictionaryLine> entries = data.Select(x => new SuffixDictionaryLine { Id = x.Field <string>("id"), Lex = x.Field <string>("lexicalForm"), Type = x.Field <string>("type"), Flags = x.Field <string>("flags") ?? "", Rules = x.Field <string>("rules") ?? "", Surfaces = x.Field <string>("surfaces"), }); suffixesById = new Dictionary <string, Suffix>(); suffixes = new MorphemeSurfaceDictionary <Suffix>(); foreach (SuffixDictionaryLine entry in entries) { AddSuffix(entry, suffixesById, suffixes); } }
private static HtmlBuilder CrosstabBody( this HtmlBuilder hb, SiteSettings ss, View view, string groupByX, string groupByY, string aggregateType, string value, string timePeriod, DateTime month, EnumerableRowCollection <DataRow> dataRows) { var data = dataRows.Select(o => new CrosstabElement( o["GroupByX"].ToString(), o["GroupByY"].ToString(), o["Value"].ToDecimal())); var xColumn = ss.GetColumn(groupByX); var yColumn = ss.GetColumn(groupByY); var choicesX = xColumn?.TypeName == "datetime" ? CorrectedChoices(xColumn, timePeriod, month) : CorrectedChoices( xColumn, xColumn?.Choices(data.Select(o => o.GroupByX))); var choicesY = CorrectedChoices( yColumn, yColumn?.Choices(data.Select(o => o.GroupByY))); return(hb.Table( ss: ss, choicesX: choicesX, choicesY: choicesY, aggregateType: aggregateType, value: ss.GetColumn(value), daily: Daily(xColumn, timePeriod), columns: null, data: data)); }
/// <summary> /// Given a collection of AttackGroup data, determine the earliest and /// latest time any action took place. Return those values in the out /// params for startTime and endTime. If no valid time can be determined, /// throw an exception. /// </summary> /// <param name="attackSet"></param> /// <param name="startTime">Earliest time of any action in the attackSet.</param> /// <param name="endTime">Latest time of any action in the attackSet.</param> private void GetTimeRange(EnumerableRowCollection <AttackGroup> attackSet, out DateTime startTime, out DateTime endTime) { startTime = default(DateTime); // Start time should be based on the first battle rather than // the first action, so that changing between players for display // yields the same scale in 'event time'. var minBattleTimes = from a in attackSet.Select(s => s.AnyAction) select a.MinEntry(c => c.Timestamp, v => v.BattlesRow.StartTime); var validMinTimes = minBattleTimes.Where(t => t != default(DateTime)); if (validMinTimes.Any()) { startTime = validMinTimes.Min(); } // Determine the time of the last action in the attack set. endTime = default(DateTime); var maxTimes = from a in attackSet.Select(s => s.AnyAction) select a.MaxEntry(c => c.Timestamp, v => v.Timestamp); var validMaxTimes = maxTimes.Where(t => t != default(DateTime)); if (validMaxTimes.Any()) { endTime = validMaxTimes.Max(); } // Verify we ended up with actual valid times. if ((startTime == default(DateTime)) && (endTime != default(DateTime))) { throw new ArgumentOutOfRangeException("startTime"); } if ((endTime == default(DateTime)) && (startTime != default(DateTime))) { throw new ArgumentOutOfRangeException("endTime"); } }
public static List <CrosstabElement> Elements( Column groupByX, Column groupByY, EnumerableRowCollection <DataRow> dataRows) { return(dataRows .Select(o => new CrosstabElement( o.String(groupByX.ColumnName), o.String(groupByY.ColumnName), o.Decimal("Value"))) .ToList()); }
public static Dictionary <string, CrosstabElement> Elements( Column groupByX, Column groupByY, EnumerableRowCollection <DataRow> dataRows) { var data = dataRows.Select(dataRow => new CrosstabElement( groupByX: dataRow.String(groupByX.ColumnName), groupByY: dataRow.String(groupByY.ColumnName), value: dataRow.Decimal("Value"))); return(ElementHash(data: data)); }
private void BtnSearch_Click(object sender, EventArgs e) { if (!(string.IsNullOrEmpty(txtYear.Text) || string.IsNullOrEmpty(txtWeek.Text))) { if (int.TryParse(txtYear.Text, out year) && int.TryParse(txtWeek.Text, out week)) { if (year > 2016 && week > 0 && week < 54) { try { bookingCollection = MainForm.DataSource.RetrieveBooking(year, week) .Tables[0] .AsEnumerable(); tripCollection = MainForm.DataSource.RetrieveTrip(year, week) .Tables[0] .AsEnumerable(); List <string> emailList = MainForm.DataSource.RetrieveCustomersEmail() .Tables[0] .AsEnumerable() .Select(r => r.Field <string>("email")) .ToList(); List <KeyValuePair <string, string> > departureList = tripCollection.Select(r => new KeyValuePair <string, string>( r.Field <string>("departurestop"), r.Field <string>("departurestop") + ", " + r.Field <string>("departurecountry") + ", " + r.Field <string>("departurestreet"))) .Distinct() .ToList(); cmbFrom.Enabled = true; cmbFrom.DataSource = new BindingSource(departureList, null); cmbFrom.DisplayMember = "Value"; cmbFrom.ValueMember = "Key"; cmbTo.Enabled = true; cmbTime.Enabled = true; cmbCustomer.Enabled = true; cmbCustomer.DataSource = emailList; txtNumberOfSeats.Enabled = true; return; } catch { } } } } ErrorMessage.Show("Ogiltig år eller vecka"); ClearControls(); }
private IList <Tuple <IToolParameter, double> > GlobalRange(ToolParameterContainer toolParameterContainer) { IList <Tuple <IToolParameter, double> > listOfRangeTuple = new List <Tuple <IToolParameter, double> >(); foreach (var currentToolParameter in toolParameterContainer.ToolParameter) { IList <double> data = _enumerableRowCollection.Select(x => x.Field <double>(currentToolParameter.ColumnName)).ToList(); listOfRangeTuple.Add(Tuple.Create(currentToolParameter, data.Max() - data.Min())); } return(listOfRangeTuple); }
}//end default constructor public JobModel(EnumerableRowCollection<DataRow> job) { Id = job.ElementAt(0).Field<int>("Job_Id"); Company = job.ElementAt(0).Field<string>("Name"); City = job.ElementAt(0).Field<string>("City"); State = job.ElementAt(0).Field<string>("State"); JobTitle = job.ElementAt(0).Field<string>("Title"); StartDate = job.ElementAt(0).Field<DateTime>("StartDate"); var endDate = job.ElementAt(0)["EndDate"]; EndDate = (endDate.GetType() != typeof(DBNull) ? job.ElementAt(0).Field<DateTime>("EndDate") : new DateTime()); JobDescription = job.Select(x => x.Field<string>("Description")).ToList<string>(); }//end One argument constructor
public static bool InRangeY(EnumerableRowCollection <DataRow> dataRows) { var inRange = dataRows.Select(o => o.String("GroupByY")).Distinct().Count() <= Parameters.General.CrosstabYLimit; if (!inRange) { Sessions.Set( "Message", Messages.TooManyCases(Parameters.General.CrosstabYLimit.ToString()).Html); } return(inRange); }
private static Dictionary <long, Types> Hash(EnumerableRowCollection <DataRow> dataRows) { var hash = dataRows .Select(o => o["ReferenceId"].ToLong()) .Distinct() .ToDictionary(o => o, o => Types.NotSet); dataRows.ForEach(dataRow => { var key = dataRow["ReferenceId"].ToLong(); hash[key] |= (Types)dataRow["PermissionType"].ToLong(); }); return(hash); }
public static bool InRangeY(Context context, EnumerableRowCollection <DataRow> dataRows) { var inRange = dataRows.Select(o => o.String("GroupByY")).Distinct().Count() <= Parameters.General.CrosstabYLimit; if (!inRange) { SessionUtilities.Set( context: context, message: Messages.TooManyCases( context: context, data: Parameters.General.CrosstabYLimit.ToString())); } return(inRange); }
public static bool InRangeY(Context context, EnumerableRowCollection <DataRow> dataRows, Column groupBy) { var inRange = groupBy == null || dataRows.Select(o => o.String(groupBy.ColumnName)).Distinct().Count() <= Parameters.General.CalendarYLimit; if (!inRange) { SessionUtilities.Set( context: context, message: Messages.TooManyRowCases( context: context, data: Parameters.General.CalendarYLimit.ToString())); } return(inRange); }
void GetTot() { try { this.enviMDFe.MDFe.infMDFe.tot = new TMDFeInfMDFeTot(); this.enviMDFe.MDFe.infMDFe.tot.qCT = this.enviMDFe.MDFe.infMDFe.infDoc.Select(c => c.infCT != null ? c.infCT.Count() : 0).ToList().Sum().ToString(); this.enviMDFe.MDFe.infMDFe.tot.qCTe = this.enviMDFe.MDFe.infMDFe.infDoc.Select(c => c.infCTe != null ? c.infCTe.Count() : 0).ToList().Sum().ToString(); this.enviMDFe.MDFe.infMDFe.tot.qNFe = this.enviMDFe.MDFe.infMDFe.infDoc.Select(c => c.infNFe != null ? c.infNFe.Count() : 0).ToList().Sum().ToString(); this.enviMDFe.MDFe.infMDFe.tot.qNF = this.enviMDFe.MDFe.infMDFe.infDoc.Select(c => c.infNF != null ? c.infNF.Count() : 0).ToList().Sum().ToString(); this.enviMDFe.MDFe.infMDFe.tot.cUnid = TMDFeInfMDFeTotCUnid.Item01; decimal vCarga = 0; decimal qCarga = 0; //foreach (string nr_lanc in infDoc.Select(c => c["nr_lanc"].ToString()).ToList()) //{ // foreach (DataRow row in daoManifesto.GetTot(nrLanc: nr_lanc).Rows) // { // vCarga += Convert.ToDecimal(row["vCarga"].ToString()); // qCarga += Convert.ToDecimal(row["qCarga"].ToString()); // } //} foreach (string nr_lanc in infDoc.Select(c => c["nr_lanc"].ToString()).ToList()) { foreach (DataRow row in daoManifesto.GetTotTemporario(nrLanc: nr_lanc).Rows) { vCarga += Convert.ToDecimal(row["vl_nf"].ToString()); qCarga += Convert.ToDecimal(row["vl_peso"].ToString()); } } this.enviMDFe.MDFe.infMDFe.tot.vCarga = vCarga.ToString("#0.00").Replace(",", "."); this.enviMDFe.MDFe.infMDFe.tot.qCarga = qCarga.ToString("#0.0000").Replace(",", "."); } catch (Exception) { throw; } }
private List <DropDownModel> FilterDatatableColoumn(EnumerableRowCollection <DataRow> uplodedFileDtRows, DataTable RecordDT_, string col) { try { var dtt = uplodedFileDtRows.Select(x => new DropDownModel { Name = x.Field <string>(col) }).ToList(); //DataTable TempTable = RecordDT_; //DataView view = new DataView(TempTable); //DataTable selected = view.ToTable("Selected", false, col); return(dtt); } catch (Exception ex) { throw ex; } }
/// <summary> /// Gets the report that lists the items sorted by from a specific word number only /// </summary> /// <param name="rows">The DataTable.AsEnumerable() object</param> /// <param name="fieldName">Name of field to get data for</param> /// <param name="wordNumber">From which word number to start sorting</param> private List <string> GetListSortedOnWordX(EnumerableRowCollection <DataRow> rows, string fieldName, int wordNumber) { IEnumerable <string> allDataForColumn = rows .Select(x => x.Field <string>(fieldName)); SortedDictionary <string, string> sortedDict = new SortedDictionary <string, string>(); foreach (string value in allDataForColumn) { List <string> words = value.Split(' ').ToList(); List <string> wordsToSort = words.Skip(wordNumber - 1).ToList(); string phraseToSort = wordsToSort.Aggregate("", (current, w) => current + " " + w); sortedDict.Add(phraseToSort, value); } return(sortedDict .Select(x => x.Value) .ToList()); //already sorted, no need to double work }
/// <summary> /// To look for differences between 2 DataTables. Determine which rows are present in one DataTable /// and not in the second /// </summary> /// <param name="r1">the first DataTable casted as AsEnumerable()</param> /// <param name="r2">the second DataTable casted as AsEnumerable()</param> /// <param name="dtRowsAdded">This DataTable contains the result</param> /// <returns>Bool. If true differences found.</returns> private static bool CompareRowsAdded(EnumerableRowCollection <DataRow> r1, EnumerableRowCollection <DataRow> r2, out DataTable dtRowsAdded) { bool hasRowsAdded = false; var added = r1.Select(r => r.Field <string>("pk")) .Except(r2.Select(r => r.Field <string>("pk"))); var va = (from row in r1.AsEnumerable() join pk in added on row.Field <string>("pk") equals pk select row); if (va.Count() > 0) { dtRowsAdded = va.CopyToDataTable(); hasRowsAdded = true; } else { dtRowsAdded = new DataTable(); } return(hasRowsAdded); }
public void AddEntries(DataSet ds, string tableName, MorphemeSurfaceDictionary <Root> roots) { EnumerableRowCollection <DataRow> data = ds.Tables[tableName].AsEnumerable(); EnumerableRowCollection <RootLine> entries = data.Select(x => new RootLine { Root = x.Field <string>("root"), Surfaces = x.Field <string>("surfaces") ?? "", Lex = x.Field <string>("lex"), Active = x.Field <string>("active") ?? "", Id = x.Field <string>("Id"), Flags = x.Field <string>("flags") ?? "", Rules = x.Field <string>("rules") ?? "", }); foreach (RootLine entry in entries) { if (entry.Active == "") { AddRoots(entry, roots); } } }
/// <summary> /// Gets the report that lists the frequency of the occurring fieldName, /// first ordered by frequency, then alphabetically on the same field /// </summary> /// <param name="rows">The DataTable.AsEnumerable() object</param> /// <param name="fieldName">Name of field to get frequency on its data</param> /// <returns>List of rows for the report</returns> private List <string> GetDataFrequency(EnumerableRowCollection <DataRow> rows, string fieldName) { IEnumerable <string> allDataForColumn = rows .Select(x => x.Field <string>(fieldName)); Dictionary <string, int> dataWithFrequency = new Dictionary <string, int>(); foreach (string value in allDataForColumn) { if (dataWithFrequency.ContainsKey(value)) { dataWithFrequency[value]++; } else { dataWithFrequency.Add(value, 1); } } return(dataWithFrequency .OrderByDescending(x => x.Value) .ThenBy(x => x.Key) .Select(x => $"{x.Key}, {x.Value}") .ToList()); }
public static Dictionary <string, decimal> GetStatisticDataSummary(EnumerableRowCollection <DataRow> scheduleData, int scheduleTimeSpentConstant, string scheduleStatisticUnknown) { var lstResult = new Dictionary <string, decimal>(); DataTable dt = new DataTable(); dt.Clear(); dt.Columns.Add(ScheduleDataModel.DataColumns.TotalHoursWorked); DataRow rowT = dt.NewRow(); decimal average = 0; var totalTimeSpent1 = scheduleData .Where(z => (string.IsNullOrEmpty(z[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString()) || z[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == scheduleStatisticUnknown)).Count() * scheduleTimeSpentConstant; // totalTimeSpent2 calculates the time of TimeSpent column <> 'UnKnown' var totalTimeSpent2 = scheduleData .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != scheduleStatisticUnknown) .Sum(x => Convert.ToDecimal(x[ScheduleDataModel.DataColumns.TotalHoursWorked])); lstResult.Add("TotalHoursWorked", totalTimeSpent1 + totalTimeSpent2); //finding total number o records var count = scheduleData .Select(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked]).Count(); lstResult.Add("Count", count); if (count != 0) { average = (totalTimeSpent1 + totalTimeSpent2) / count; } var list = scheduleData .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != scheduleStatisticUnknown); var list1 = scheduleData .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == scheduleStatisticUnknown); var rows = from row in list1.AsEnumerable() select row; foreach (DataRow row in rows) { if (row[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == scheduleStatisticUnknown) { rowT = dt.NewRow(); rowT[ScheduleDataModel.DataColumns.TotalHoursWorked] = scheduleTimeSpentConstant; dt.Rows.Add(rowT); } } var listMedian = list.Concat(dt.AsEnumerable()); var orderedList = listMedian.OrderBy(p => (Decimal)(p[ScheduleDataModel.DataColumns.TotalHoursWorked])); decimal median = 0; if (count != 0) { // calculating median for even number list if ((count % 2) == 0) { median = (Decimal)(orderedList.ElementAt(count / 2)[ScheduleDataModel.DataColumns.TotalHoursWorked]) + (Decimal)(orderedList.ElementAt((count - 1) / 2)[ScheduleDataModel.DataColumns.TotalHoursWorked]); median /= 2; } else { // calculating median for odd number list if (count == 1) { median = (Decimal)(orderedList.ElementAt(count - 1)[ScheduleDataModel.DataColumns.TotalHoursWorked]); } else { median = (Decimal)(orderedList.ElementAt(count / 2)[ScheduleDataModel.DataColumns.TotalHoursWorked]); } } } lstResult.Add("Average", average); lstResult.Add("Median", median); return(lstResult); }
public static List <decimal> GetStatisticDataSummary(EnumerableRowCollection <DataRow> scheduleData, int scheduleTimeSpentConstant) { DataTable dt = new DataTable(); dt.Clear(); dt.Columns.Add("TotalHoursWorked"); DataRow rowT = dt.NewRow(); decimal average = 0; var totalTimeSpent1 = scheduleData .Where(z => (string.IsNullOrEmpty(z["TotalHoursWorked"].ToString()) || z[ModuleOwnerDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == StatisticUnknown)).Count() * scheduleTimeSpentConstant; // totalTimeSpent2 calculates the time of TimeSpent column <> 'UnKnown' var totalTimeSpent2 = scheduleData .Where(x => x[ModuleOwnerDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != StatisticUnknown) .Sum(x => Convert.ToDecimal(x[ModuleOwnerDataModel.DataColumns.TotalHoursWorked])); //finding total number o records var count = scheduleData .Select(x => x[ModuleOwnerDataModel.DataColumns.TotalHoursWorked]).Count(); if (count != 0) { average = (totalTimeSpent1 + totalTimeSpent2) / count; } var list = scheduleData .Where(x => x[ModuleOwnerDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != StatisticUnknown); var list1 = scheduleData .Where(x => x[ModuleOwnerDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == StatisticUnknown); IEnumerable <DataRow> rows = from row in list1.AsEnumerable() select row; foreach (DataRow row in rows) { if (row[ModuleOwnerDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == "unknown") { rowT = dt.NewRow(); rowT["TotalHoursWorked"] = scheduleTimeSpentConstant; dt.Rows.Add(rowT); } } var listMedian = list.Concat(dt.AsEnumerable()); var orderedList = listMedian.OrderBy(p => Convert.ToDecimal(p[ModuleOwnerDataModel.DataColumns.TotalHoursWorked])); decimal median = 0; if (count != 0) { // calculating median for even number list if ((count % 2) == 0) { median = Convert.ToDecimal(orderedList.ElementAt(count / 2)[ModuleOwnerDataModel.DataColumns.TotalHoursWorked]) + Convert.ToDecimal(orderedList.ElementAt((count - 1) / 2)[ModuleOwnerDataModel.DataColumns.TotalHoursWorked]); median /= 2; } else { // calculating median for odd number list if (count == 1) { median = Convert.ToDecimal(orderedList.ElementAt(count - 1)[ModuleOwnerDataModel.DataColumns.TotalHoursWorked]); } else { median = Convert.ToDecimal(orderedList.ElementAt(count / 2)[ModuleOwnerDataModel.DataColumns.TotalHoursWorked]); } } } List <decimal> lstValues = new List <decimal>(); lstValues.Add(average); lstValues.Add(median); return(lstValues); }
public static Statistic GetStatisticData(EnumerableRowCollection <DataRow> scheduleData, int scheduleTimeSpentConstant, string scheduleStatisticUnknown) { var dataItem = new Statistic(); // totalTimeSpent1 calculates the time of 'UnKnown' value based on the ReleaseNotesTimeSpentConstant decimal totalTimeSpent1 = scheduleData .Where(z => (string.IsNullOrEmpty(z[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString()) || z[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == scheduleStatisticUnknown)) .Count() * scheduleTimeSpentConstant; // totalTimeSpent2 calculates the time of TimeSpent column <> 'UnKnown' decimal totalTimeSpent2 = scheduleData .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != scheduleStatisticUnknown) .Sum(x => Convert.ToDecimal(x[ScheduleDataModel.DataColumns.TotalHoursWorked])); // calculates the count of records whose TimeSpent <> 'UnKnown' var count = scheduleData .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != scheduleStatisticUnknown) .Select(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked]).Count(); // calculates the total count of records var totalCount = scheduleData .Select(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked]).Count(); dataItem.Total = totalTimeSpent1 + totalTimeSpent2; dataItem.Count = totalCount; var dt = new DataTable(); dt.Columns.Add(ScheduleDataModel.DataColumns.TotalHoursWorked); dt.AcceptChanges(); var rowT = dt.NewRow(); var list = scheduleData .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != scheduleStatisticUnknown); var list1 = scheduleData .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == scheduleStatisticUnknown); var rows = from row in list1.AsEnumerable() select row; // takes care of the logic of TimeSpent column with UnKnown value to calculate average and median foreach (var row in rows) { if (row[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() == scheduleStatisticUnknown) { rowT = dt.NewRow(); rowT[ScheduleDataModel.DataColumns.TotalHoursWorked] = scheduleTimeSpentConstant; dt.Rows.Add(rowT); } } var list2 = list.Concat(dt.AsEnumerable()); var dataRows = list2 as DataRow[] ?? list2.ToArray(); var rowItem = from row in dataRows.AsEnumerable() select row; if (rowItem.Any()) { //calculates the average value dataItem.Average = dataRows .Where(x => x[ScheduleDataModel.DataColumns.TotalHoursWorked].ToString().ToLower() != scheduleStatisticUnknown) .Select(x => Convert.ToDecimal(x[ScheduleDataModel.DataColumns.TotalHoursWorked])).Average(); //calculates the max and min values dataItem.Max = dataRows.Max(x => Convert.ToDecimal(x[ScheduleDataModel.DataColumns.TotalHoursWorked])); dataItem.Min = dataRows.Min(x => Convert.ToDecimal(x[ScheduleDataModel.DataColumns.TotalHoursWorked])); // gets the ordered list to find the median var orderedList = dataRows.OrderBy(p => Convert.ToDecimal(p[ScheduleDataModel.DataColumns.TotalHoursWorked])); // calculates median for even number list if ((totalCount % 2) == 0) { dataItem.Median = Convert.ToDecimal(orderedList.ElementAt(totalCount / 2)[ScheduleDataModel.DataColumns.TotalHoursWorked]) + Convert.ToDecimal(orderedList.ElementAt((totalCount - 1) / 2)[ScheduleDataModel.DataColumns.TotalHoursWorked]); dataItem.Median /= 2; } else { // calculating median for odd number list if (totalCount == 1) { dataItem.Median = Convert.ToDecimal(orderedList.ElementAt(totalCount - 1)[ScheduleDataModel.DataColumns.TotalHoursWorked]); } else { dataItem.Median = Convert.ToDecimal(orderedList.ElementAt(totalCount / 2)[ScheduleDataModel.DataColumns.TotalHoursWorked]); } } } return(dataItem); }
public static string CreateUpdateSql(this Dictionary <string, string> dic, string connName, string tableName, string ID, EnumerableRowCollection <DataRow> dt = null) { if (Config.Constant.IsOracleDb) { if (dt == null) { dt = GetFieldTable(connName, tableName).AsEnumerable(); } var fields = dt.Select(c => c[0].ToString()).ToArray(); StringBuilder sb = new StringBuilder(); foreach (string key in dic.Keys) { if (key == "ID") { continue; } if (!fields.Contains(key) && !fields.Contains(key.ToUpper())) { continue; } if (key == "SERIALNUMBER")//流水号不能修改 { continue; } string value = dic[key] != null ? dic[key].Replace("'", "''") : dic[key]; sb.AppendFormat(",{0}={1}", key, GetValue(dt, key, value)); } if (sb.ToString().Trim() == "") { return(""); } string sql = string.Format(@"UPDATE {0} SET {2} WHERE ID='{1}';", tableName, ID, sb.ToString().Trim(',')); return(sql); } else { if (dt == null) { dt = GetFieldTable(connName, tableName).AsEnumerable(); } var fields = dt.Select(c => c[0].ToString()).ToArray(); StringBuilder sb = new StringBuilder(); foreach (string key in dic.Keys) { if (key == "ID") { continue; } if (!fields.Contains(key)) { continue; } if (key == "SerialNumber")//流水号不能修改 { continue; } string value = dic[key] != null ? dic[key].Replace("'", "''") : dic[key]; sb.AppendFormat(",{0}={1}", key, GetValue(dt, key, value)); } if (sb.ToString().Trim() == "") { return(""); } string sql = string.Format(@"UPDATE {0} SET {2} WHERE ID='{1}';", tableName, ID, sb.ToString().Trim(',')); return(sql); } }
private async Task DownloadMultipleFilesAsync(EnumerableRowCollection <DataRow> rows) { await Task.WhenAll(rows.Select(row => DownloadFileAsync(row))); }
public static string CreateUpdateSql(this Dictionary <string, string> dic, Dictionary <string, string> currentDic, string connName, string tableName, string ID, bool isFreeSerialNumber = false, EnumerableRowCollection <DataRow> dt = null) { if (Config.Constant.IsOracleDb) { if (dt == null) { dt = GetFieldTable(connName, tableName).AsEnumerable(); } var fields = dt.Select(c => c[0].ToString()).ToArray(); StringBuilder sb = new StringBuilder(); foreach (string key in dic.Keys) { if (key == "ID") { continue; } if (!fields.Contains(key) && !fields.Contains(key.ToUpper())) { continue; } if (!isFreeSerialNumber && key == "SERIALNUMBER")//流水号不能修改 { continue; } string value = dic[key] != null ? dic[key].Replace("'", "''") : dic[key]; sb.AppendFormat(",{0}={1}", key, GetValue(dt, key, value)); } if (sb.ToString().Trim() == "") { return(""); } var user = FormulaHelper.GetUserInfo(); if (fields.Contains("MODIFYTIME") && !dic.Keys.Contains("MODIFYTIME")) { sb.AppendFormat(",MODIFYTIME=to_date('{0}','yyyy-MM-dd hh24:mi:ss')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("MODIFYDATE") && !dic.Keys.Contains("MODIFYDATE")) { sb.AppendFormat(",MODIFYDATE=to_date('{0}','yyyy-MM-dd hh24:mi:ss')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("MODIFYUSERID") && !dic.Keys.Contains("MODIFYUSERID")) { sb.AppendFormat(",MODIFYUSERID='{0}'", user.UserID); } if (fields.Contains("MODIFYUSERNAME") && !dic.Keys.Contains("MODIFYUSERNAME")) { sb.AppendFormat(",MODIFYUSERNAME='******'", user.UserName); } if (fields.Contains("MODIFYUSER") && !dic.Keys.Contains("MODIFYUSER")) { sb.AppendFormat(",MODIFYUSER='******'", user.UserName); } string sql = string.Format(@"UPDATE {0} SET {2} WHERE ID='{1}';", tableName, ID, sb.ToString().Trim(',')); return(sql); } else { if (dt == null) { dt = GetFieldTable(connName, tableName).AsEnumerable(); } var fields = dt.Select(c => c[0].ToString()).ToArray(); StringBuilder sb = new StringBuilder(); foreach (string key in dic.Keys) { if (key == "ID") { continue; } if (!fields.Contains(key)) { continue; } if (!isFreeSerialNumber && key == "SerialNumber")//流水号不能修改 { continue; } string value = dic[key] != null ? dic[key].Replace("'", "''") : dic[key]; sb.AppendFormat(",{0}={1}", key, GetValue(dt, key, value)); } if (sb.ToString().Trim() == "") { return(""); } var user = FormulaHelper.GetUserInfo(); if (fields.Contains("ModifyTime") && !dic.Keys.Contains("ModifyTime")) { sb.AppendFormat(",ModifyTime='{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("ModifyDate") && !dic.Keys.Contains("ModifyDate")) { sb.AppendFormat(",ModifyDate='{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("ModifyUserID") && !dic.Keys.Contains("ModifyUserID")) { sb.AppendFormat(",ModifyUserID='{0}'", user.UserID); } if (fields.Contains("ModifyUserName") && !dic.Keys.Contains("ModifyUserName")) { sb.AppendFormat(",ModifyUserName='******'", user.UserName); } if (fields.Contains("ModifyUser") && !dic.Keys.Contains("ModifyUser")) { sb.AppendFormat(",ModifyUser='******'", user.UserName); } string sql = string.Format(@"UPDATE {0} SET {2} WHERE ID='{1}'", tableName, ID, sb.ToString().Trim(',')); return(sql); } }
public static string CreateInsertSql(this Dictionary <string, string> dic, string connName, string tableName, string ID, EnumerableRowCollection <DataRow> dt = null) { if (String.IsNullOrEmpty(ID)) { throw new Formula.Exceptions.BusinessValidationException("使用Dictionary 字典向数据库插入数据时不能插入主键为空字符串的数据"); } if (Config.Constant.IsOracleDb) { if (dt == null) { dt = GetFieldTable(connName, tableName).AsEnumerable(); } var fields = dt.Select(c => c[0].ToString()).ToArray(); StringBuilder sbField = new StringBuilder(); StringBuilder sbValue = new StringBuilder(); foreach (string key in dic.Keys) { if (key == "ID") { continue; } if (!fields.Contains(key)) { continue; } string value = dic[key] != null ? dic[key].Replace("'", "''") : dic[key]; value = GetValue(dt, key, value); sbField.AppendFormat(",{0}", key); sbValue.AppendFormat(",{0}", value); } var user = FormulaHelper.GetUserInfo(); if (fields.Contains("CREATETIME") && !dic.Keys.Contains("CREATETIME")) { sbField.AppendFormat(",{0}", "CREATETIME"); sbValue.AppendFormat(",to_date('{0}','yyyy-MM-dd hh24:mi:ss')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("CREATEDATE") && !dic.Keys.Contains("CREATEDATE")) { sbField.AppendFormat(",{0}", "CREATEDATE"); sbValue.AppendFormat(",to_date('{0}','yyyy-MM-dd hh24:mi:ss')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("CREATEUSERID") && !dic.Keys.Contains("CREATEUSERID")) { sbField.AppendFormat(",{0}", "CREATEUSERID"); sbValue.AppendFormat(",'{0}'", user.UserID); } if (fields.Contains("CREATEUSERNAME") && !dic.Keys.Contains("CREATEUSERNAME")) { sbField.AppendFormat(",{0}", "CREATEUSERNAME"); sbValue.AppendFormat(",'{0}'", user.UserName); } if (fields.Contains("CREATEUSER") && !dic.Keys.Contains("CREATEUSER")) { sbField.AppendFormat(",{0}", "CREATEUSER"); sbValue.AppendFormat(",'{0}'", user.UserName); } if (fields.Contains("ORGID") && !dic.Keys.Contains("ORGID")) { sbField.AppendFormat(",{0}", "ORGID"); sbValue.AppendFormat(",'{0}'", user.UserOrgID); } if (fields.Contains("COMPANYID") && !dic.Keys.Contains("COMPANYID")) { sbField.AppendFormat(",{0}", "COMPANYID"); sbValue.AppendFormat(",'{0}'", user.UserCompanyID); } if (fields.Contains("FLOWPHASE") && !dic.Keys.Contains("FLOWPHASE")) { sbField.AppendFormat(",{0}", "FLOWPHASE"); sbValue.AppendFormat(",'{0}'", "Start"); } if (fields.Contains("MODIFYTIME") && !dic.Keys.Contains("MODIFYTIME")) { sbField.AppendFormat(",{0}", "MODIFYTIME"); sbValue.AppendFormat(",to_date('{0}','yyyy-MM-dd hh24:mi:ss')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("MODIFYDATE") && !dic.Keys.Contains("MODIFYDATE")) { sbField.AppendFormat(",{0}", "MODIFYDATE"); sbValue.AppendFormat(",to_date('{0}','yyyy-MM-dd hh24:mi:ss')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("MODIFYUSERID") && !dic.Keys.Contains("MODIFYUSERID")) { sbField.AppendFormat(",{0}", "MODIFYUSERID"); sbValue.AppendFormat(",'{0}'", user.UserID); } if (fields.Contains("MODIFYUSERNAME") && !dic.Keys.Contains("MODIFYUSERNAME")) { sbField.AppendFormat(",{0}", "MODIFYUSERNAME"); sbValue.AppendFormat(",'{0}'", user.UserName); } if (fields.Contains("MODIFYUSER") && !dic.Keys.Contains("MODIFYUSER")) { sbField.AppendFormat(",{0}", "MODIFYUSER"); sbValue.AppendFormat(",'{0}'", user.UserName); } string sql = string.Format(@"INSERT INTO {0} (ID{2}) VALUES ('{1}'{3});", tableName, ID, sbField, sbValue); return(sql); } else { if (dt == null) { dt = GetFieldTable(connName, tableName).AsEnumerable(); } var fields = dt.Select(c => c[0].ToString()).ToArray(); StringBuilder sbField = new StringBuilder(); StringBuilder sbValue = new StringBuilder(); foreach (string key in dic.Keys) { if (key == "ID") { continue; } if (!fields.Contains(key)) { continue; } var keys = dic.Keys.ToList(); string value = dic[key] != null ? dic[key].Replace("'", "''") : dic[key]; value = GetValue(dt, key, value); sbField.AppendFormat(",{0}", key); sbValue.AppendFormat(",{0}", value); } //布局定义 foreach (string key in fields) { if (key.Contains("ID")) { var subKey = HttpContext.Current.Request["Sub_Key"]; var subID = HttpContext.Current.Request["Sub_ID"]; if (key == subKey) { if (key == subKey && !string.IsNullOrEmpty(subID)) { sbField.AppendFormat(",{0}", key); sbValue.AppendFormat(",'{0}'", subID); } } } } var user = FormulaHelper.GetUserInfo(); if (fields.Contains("CreateTime") && !dic.Keys.Contains("CreateTime")) { sbField.AppendFormat(",{0}", "CreateTime"); sbValue.AppendFormat(",'{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("CreateDate") && !dic.Keys.Contains("CreateDate")) { sbField.AppendFormat(",{0}", "CreateDate"); sbValue.AppendFormat(",'{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("CreateUserID") && !dic.Keys.Contains("CreateUserID")) { sbField.AppendFormat(",{0}", "CreateUserID"); sbValue.AppendFormat(",'{0}'", user.UserID); } if (fields.Contains("CreateUserName") && !dic.Keys.Contains("CreateUserName")) { sbField.AppendFormat(",{0}", "CreateUserName"); sbValue.AppendFormat(",'{0}'", user.UserName); } if (fields.Contains("CreateUser") && !dic.Keys.Contains("CreateUser")) { sbField.AppendFormat(",{0}", "CreateUser"); sbValue.AppendFormat(",'{0}'", user.UserName); } if (fields.Contains("OrgID") && !dic.Keys.Contains("OrgID")) { sbField.AppendFormat(",{0}", "OrgID"); sbValue.AppendFormat(",'{0}'", user.UserOrgID); } if (fields.Contains("CompanyID") && !dic.Keys.Contains("CompanyID")) { sbField.AppendFormat(",{0}", "CompanyID"); sbValue.AppendFormat(",'{0}'", user.UserCompanyID); } if (fields.Contains("FlowPhase") && !dic.Keys.Contains("FlowPhase")) { sbField.AppendFormat(",{0}", "FlowPhase"); sbValue.AppendFormat(",'{0}'", "Start"); } if (fields.Contains("ModifyTime") && !dic.Keys.Contains("ModifyTime")) { sbField.AppendFormat(",{0}", "ModifyTime"); sbValue.AppendFormat(",'{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("ModifyDate") && !dic.Keys.Contains("ModifyDate")) { sbField.AppendFormat(",{0}", "ModifyDate"); sbValue.AppendFormat(",'{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (fields.Contains("ModifyUserID") && !dic.Keys.Contains("ModifyUserID")) { sbField.AppendFormat(",{0}", "ModifyUserID"); sbValue.AppendFormat(",'{0}'", user.UserID); } if (fields.Contains("ModifyUserName") && !dic.Keys.Contains("ModifyUserName")) { sbField.AppendFormat(",{0}", "ModifyUserName"); sbValue.AppendFormat(",'{0}'", user.UserName); } if (fields.Contains("ModifyUser") && !dic.Keys.Contains("ModifyUser")) { sbField.AppendFormat(",{0}", "ModifyUser"); sbValue.AppendFormat(",'{0}'", user.UserName); } string sql = string.Format(@"INSERT INTO {0} (ID{2}) VALUES ('{1}'{3})", tableName, ID, sbField, sbValue); return(sql); } }
//�Public�Methods�(1)� public string Publish(string data) { try { var errors = new StringBuilder(); EnumerableRowCollection <DataRow> updatedItems = GetUpdatedItems(data).AsEnumerable(); foreach (Guid spSiteId in (updatedItems.Select(i => i["SiteId"])).Distinct()) { Guid siteId = spSiteId; using (var spSite = new SPSite(siteId)) { foreach ( Guid spWebId in (updatedItems.Where(i => (Guid)i["SiteId"] == siteId).Select(i => i["WebId"])).Distinct ()) { Guid webId = spWebId; using (SPWeb spWeb = spSite.OpenWeb(webId)) { spWeb.AllowUnsafeUpdates = true; foreach ( Guid spListId in (from i in updatedItems where (Guid)i["WebId"] == webId select i["ListId"]). Distinct()) { Guid listId = spListId; SPList spList = spWeb.Lists.GetList(listId, false); foreach (var listItem in updatedItems.Where(i => (Guid)i["ListId"] == listId).Select( i => new { Id = (int)i["ItemId"], StartDate = i["StartDate"], DueDate = i["DueDate"] })) { bool updated = false; SPListItem spListItem = null; if (listItem.StartDate != DBNull.Value) { spListItem = spList.GetItemById(listItem.Id); spListItem["StartDate"] = listItem.StartDate; updated = true; } if (listItem.DueDate != DBNull.Value) { if (spListItem == null) { spListItem = spList.GetItemById(listItem.Id); } spListItem["DueDate"] = listItem.DueDate; updated = true; } try { if (updated) { spListItem.Update(); } } catch (Exception exception) { errors.AppendLine( string.Format( @"Site ID: {0}. Web ID: {1}. List ID: {2}. Item ID: {3}. Error: {4}", siteId, webId, listId, listItem.Id, exception.GetBaseException().Message)); } } } spWeb.AllowUnsafeUpdates = false; } } } } string errorMessage = errors.ToString(); if (!string.IsNullOrEmpty(errorMessage)) { throw new Exception(errorMessage); } return(string.Empty); } catch (APIException) { throw; } catch (Exception e) { throw new APIException((int)Errors.Publish, e.Message); } }