public static IList<Row> GetRows (NHibernate.ISession session, DataFilter dataFilter) { lock (session) return session.CreateQuery("SELECT psm.Analysis " + dataFilter.GetFilteredQueryString(DataFilter.FromPeptideSpectrumMatch) + "GROUP BY psm.Analysis.id") .List<Analysis>() .Select(o => new AnalysisRow(o, dataFilter) as Row) .ToList(); }
public static IList<Row> GetRows (NHibernate.ISession session, DataFilter dataFilter) { lock (session) return dataFilter.Analysis.First().Parameters .Select(o => new AnalysisParameterRow(o, dataFilter) as Row) .ToList(); }
public Tests() { _objectType = "Function"; string baseDir = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(baseDir.Substring(0, baseDir.LastIndexOf("\\bin"))); AdapterSettings adapterSettings = new AdapterSettings(); adapterSettings.AppendSettings(new AppSettingsReader("App.config")); FileInfo log4netConfig = new FileInfo("Log4net.config"); log4net.Config.XmlConfigurator.Configure(log4netConfig); string twConfigFile = String.Format("{0}{1}.{2}.config", adapterSettings["AppDataPath"], adapterSettings["ProjectName"], adapterSettings["ApplicationName"] ); AppSettingsReader twSettings = new AppSettingsReader(twConfigFile); adapterSettings.AppendSettings(twSettings); _dataLayer = new Bechtel.DataLayer.RestDataLayer2(adapterSettings); _filter = Utility.Read<DataFilter>(adapterSettings["FilterPath"]); //_scenarios = Utility.Read<Scenarios>("Scenarios.xml"); _objectType = adapterSettings["ObjectType"]; _modifiedProperty = adapterSettings["ModifiedProperty"]; _modifiedValue = adapterSettings["ModifiedValue"]; _objectDefinition = GetObjectDefinition(_objectType); }
public void GetCount() { DataFilter dataFilter = new DataFilter { Expressions = new List<Expression> { new Expression { PropertyName = "Spool", RelationalOperator = RelationalOperator.EqualTo, Values = new Values { "01EKG11PS02001", } } } }; long count = _dataLayer.GetCount(_objectType, dataFilter); if (count == 0) { throw new AssertionException("No Rows returned."); } Assert.AreEqual(count, 1); }
internal void toExcel(bool selected, IDictionary<string, TableExporter.ITable> tables, DataFilter viewFilter, DataFilter basicFilter) { Text = "Generating Excel Report pages (1 of 6)"; var bg = new BackgroundWorker { WorkerReportsProgress = true }; bg.ProgressChanged += (x, y) => { switch (y.ProgressPercentage) { case 1: Text = "Generating Excel Report pages (2 of 6)"; break; case 2: Text = "Generating Excel Report pages (3 of 6)"; break; case 3: Text = "Generating Excel Report pages (4 of 6)"; break; case 4: Text = "Generating Excel Report pages (5 of 6)"; break; case 5: Text = "Generating Excel Report pages (6 of 6)"; break; default: break; } }; bg.RunWorkerCompleted += (x, y) => { if (y.Error != null) Program.HandleException(y.Error); Close(); }; bg.DoWork += (x, y) => { var reportDictionary = new Dictionary<string, object>(); int progress = 0; foreach(var nameTablePair in tables) { reportDictionary.Add(nameTablePair.Key, nameTablePair.Value); bg.ReportProgress(++progress); } reportDictionary.Add("Summary", getSummaryList(viewFilter, basicFilter)); TableExporter.ShowInExcel(tables, false); }; bg.RunWorkerAsync(); }
public AggregateRow(object[] queryRow, DataFilter dataFilter) { int column = -1; PeptideSpectrumMatches = Convert.ToInt32(queryRow[++column]); Sources = Convert.ToInt32(queryRow[++column]); Spectra = Convert.ToInt32(queryRow[++column]); DistinctMatches = Convert.ToInt32(queryRow[++column]); DistinctPeptides = Convert.ToInt32(queryRow[++column]); DistinctAnalyses = Convert.ToInt32(queryRow[++column]); DistinctCharges = Convert.ToInt32(queryRow[++column]); ProteinGroups = Convert.ToInt32(queryRow[++column]); DataFilter = dataFilter; }
public override Response Delete(string objectType, DataFilter filter) { try { IList<string> identifiers = GetIdentifiers(objectType, filter); Response response = Delete(objectType, identifiers); return response; } catch (Exception ex) { _logger.ErrorFormat("Error while deleting a list of data objects of type [{0}]: {1}", objectType, ex); throw new Exception("Error while deleting a list of data objects of type [" + objectType + "].", ex); } }
public void TestAggregation () { var lhs = new DataFilter() { MaximumQValue = 1 }; var rhs = new DataFilter() { Protein = new List<Protein>()}; rhs.Protein.Add(new Protein("foo", "bar")); var result = lhs + rhs; var rhs2 = new DataFilter() { Peptide = new List<Peptide>() }; rhs2.Peptide.Add(new TestPeptide("FOO")); var result2 = result + rhs2; Assert.AreEqual(1, result.Protein.Count); Assert.AreEqual(1, result2.Protein.Count); Assert.AreEqual(1, result2.Peptide.Count); Assert.AreEqual("foo", result.Protein.FirstOrDefault().Description); Assert.AreEqual("foo", result2.Protein.FirstOrDefault().Description); Assert.AreEqual("FOO", result2.Peptide.FirstOrDefault().Sequence); }
public void SetData(NHibernate.ISession session, DataFilter viewFilter) { this.session = session; this.viewFilter = viewFilter; ClearData(); dataGridView.Rows.Clear(); foreach (var filter in session.Query<PersistentDataFilter>().OrderByDescending(o => o.Id).ToList()) { dataGridView.Rows.Add(filter.Id, filter.MaximumQValue, filter.MinimumDistinctPeptides, filter.MinimumSpectra, filter.MinimumAdditionalPeptides, filter.GeneLevelFiltering, filter.DistinctMatchFormat, filter.MinimumSpectraPerDistinctMatch, filter.MinimumSpectraPerDistinctPeptide, filter.MaximumProteinGroupsPerPeptide, filter.TotalCounts.Clusters, filter.TotalCounts.ProteinGroups, filter.TotalCounts.Proteins, filter.TotalCounts.GeneGroups, filter.TotalCounts.Genes, filter.TotalCounts.DistinctPeptides, filter.TotalCounts.DistinctMatches, filter.TotalCounts.FilteredSpectra, filter.TotalCounts.ProteinFDR * 100, filter.TotalCounts.PeptideFDR * 100, filter.TotalCounts.SpectrumFDR * 100); dataGridView.Rows[dataGridView.RowCount - 1].Tag = filter; } dataGridView.Rows[0].Tag = viewFilter; dataGridView.Enabled = true; dataGridView.Refresh(); }
public InMemoryFilterMatcher(DataFilter dataFilter) { filters = new List<FilterMatcher>(); if (!string.IsNullOrEmpty(dataFilter.Location)) { if (dataFilter.Location.EndsWith(" with recurse")) { filters.Add(new LocationWithRecurseFilterMatcher(dataFilter.Location)); } else { filters.Add(new LocationFilterMatcher(dataFilter.Location)); } } if (!string.IsNullOrEmpty(dataFilter.Deleted)) { filters.Add(new FieldFilterMatcher<bool>("Deleted", dataFilter.Deleted)); } if (!string.IsNullOrEmpty(dataFilter.SamplePeriod)) { filters.Add(new SamplePeriodFilterMatcher("Sample Period", dataFilter.SamplePeriod)); } if (dataFilter.Criteria != null) { foreach (FilterEntry entry in dataFilter.Criteria) { if (entry.Name == "Id") { filters.Add(new IdFilterMatcher(entry.Value)); } else { filters.Add(new FieldFilterMatcher<string>(entry.Name, entry.Value)); } } } }
public SequenceCoverageForm (NHibernate.ISession session, DataModel.Protein protein, DataFilter viewFilter) { StartPosition = FormStartPosition.CenterParent; ShowIcon = false; WindowState = FormWindowState.Maximized; Text = protein.Accession; ResizeRedraw = true; DoubleBuffered = true; BackColor = SystemColors.Window; control = new SequenceCoverageControl(session, protein, viewFilter) { Dock = DockStyle.Fill, BackColor = this.BackColor }; control.SequenceCoverageFilter += (s, e) => OnSequenceCoverageFilter(e); Controls.Add(control); }
private List<Filter> FormFilterList(DataFilter dataFilter) { List<Filter> filterList = new List<Filter>(); try { foreach (org.iringtools.library.Expression expression in dataFilter.Expressions) { Filter filter = new Filter(); string propertyName = expression.PropertyName; DataProperty dataProperty = (from dp in _dataObjectDefinition.dataProperties where dp.propertyName.ToUpper() == propertyName.ToUpper() select dp).FirstOrDefault(); bool isString = (dataProperty.dataType == DataType.String || dataProperty.dataType == DataType.Char); filter.AttributeName = propertyName; if (expression.RelationalOperator == RelationalOperator.StartsWith) { if (!isString) throw new Exception("StartsWith operator used with non-string property"); filter.RelationalOperator = "like"; filter.Value = "\"" + expression.Values.FirstOrDefault() + "\""; } else if (expression.RelationalOperator == RelationalOperator.EndsWith) { if (!isString) throw new Exception("EndsWith operator used with non-string property"); filter.RelationalOperator = "like"; filter.Value = "\"" + expression.Values.FirstOrDefault() + "\""; } else if (expression.RelationalOperator == RelationalOperator.Contains) { if (!isString) throw new Exception("Contains operator used with non-string property"); filter.RelationalOperator = "like"; filter.Value = "\"" + expression.Values.FirstOrDefault() + "\""; } else if (expression.RelationalOperator == RelationalOperator.In) { filter.RelationalOperator = expression.RelationalOperator.ToString(); string values = String.Empty; int valueIndex = 1; int valueCount = expression.Values.Count(); foreach (string value in expression.Values) { if (isString) { if (valueIndex == valueCount) values += "\"" + value + "\""; else values += "\"" + value + "\", "; } else { if (valueIndex == valueCount) values += value; else values += value + ", "; } valueIndex++; } filter.Value = values; } else { filter.RelationalOperator = expression.RelationalOperator.ToString(); if (isString) filter.Value = "\"" + expression.Values.FirstOrDefault() + "\""; else filter.Value = expression.Values.FirstOrDefault(); } if (expression.LogicalOperator != LogicalOperator.None) filter.Logical = expression.LogicalOperator.ToString(); filterList.Add(filter); } } catch (Exception ex) { _logger.ErrorFormat("Error while marshalling a data filter into a filter list: {1}", ex); throw new Exception("Error while marshalling a data filter into a filter list.", ex); } return filterList; }
// GET: TaxPayments public ActionResult Index() { return(View(DataFilter.GetTaxPayments(TempData.Peek("Id") + ""))); }
// GET: MobilePhoneCalls public async Task <IActionResult> Index(int cpage, string phoneNumber, string day, string month, string year, string address, string min, string max, string roaming, string phoneNumberCheck, string dateTimeCheck, string addressCheck, string totalCostCheck, string roamingCheck, string page, string next, string previous) { var _min = Parse.FloatTryParse(min); var _max = Parse.FloatTryParse(max); var _day = Parse.IntTryParse(day); var _month = (month != null && SD.months.ContainsKey(month)) ? SD.months[month] : -1; if (_month == -1) { _month = Parse.IntTryParse(month); } var _year = Parse.IntTryParse(year); // Tuple <bool, string>[] show = SD.Show(new List <string>() { phoneNumberCheck, dateTimeCheck, dateTimeCheck, dateTimeCheck, addressCheck, totalCostCheck, totalCostCheck, roamingCheck }, new List <string>() { phoneNumber, day, month, year, address, min, max, roaming }); ViewData["columns"] = show; // var mobilePhoneCalls = await _context.MobilePhoneCalls.Include(m => m.PhoneLine).ToListAsync(); List <MobilePhoneCall> _mobilePhoneCalls = mobilePhoneCalls.ToList(); List <MobilePhoneCall> final_result = new List <MobilePhoneCall>(); var phoneNumberList = (phoneNumber != null) ? phoneNumber.Split(", ").ToList() : new List <string>(); _mobilePhoneCalls = DataFilter <MobilePhoneCall> .Filter(phoneNumberList, (m) => m.PhoneNumber, _mobilePhoneCalls).ToList(); _mobilePhoneCalls = DataFilter <MobilePhoneCall> .Filter(_year, (m) => m.DateTime.Year, _mobilePhoneCalls).ToList(); _mobilePhoneCalls = DataFilter <MobilePhoneCall> .Filter(_month, (m) => m.DateTime.Month, _mobilePhoneCalls).ToList(); _mobilePhoneCalls = DataFilter <MobilePhoneCall> .Filter(_day, (m) => m.DateTime.Day, _mobilePhoneCalls).ToList(); var addressList = (address != null) ? address.Split(", ").ToList() : new List <string>(); _mobilePhoneCalls = DataFilter <MobilePhoneCall> .Filter(addressList, (m) => m.Addressee, _mobilePhoneCalls, true).ToList(); _mobilePhoneCalls = DataFilter <MobilePhoneCall> .Filter(_min, _max, (m) => m.TotalCost, _mobilePhoneCalls).ToList(); _mobilePhoneCalls = DataFilter <MobilePhoneCall> .Filter(roaming, (m) => m.RoamingCall, _mobilePhoneCalls).ToList(); //Separar en paginas _mobilePhoneCalls = _mobilePhoneCalls.OrderBy(m => m.DateTime.Year).ThenBy(m => m.DateTime.Month).ToList(); var result = Paging <MobilePhoneCall> .Pages(_mobilePhoneCalls, page, cpage, (next != null), (previous != null)); ViewData["top"] = result.Item2; ViewData["mult"] = result.Item3; ViewData["page"] = result.Item4; bool[] mask = { phoneNumberCheck != null, dateTimeCheck != null, false, false, addressCheck != null, totalCostCheck != null, false, roamingCheck != null }; string csv = CSVStringConstructor(show, mask, result.Item1); string HttpSessionName = SD.HttpSessionString(new List <string> { "MobilePhoneCall", result.Item4.ToString(), phoneNumber, day, month, year, address, min, max, roaming, (phoneNumberCheck != null).ToString(), (dateTimeCheck != null).ToString(), (addressCheck != null).ToString(), (totalCostCheck != null).ToString(), (roamingCheck != null).ToString() }); HttpContext.Session.SetString(HttpSessionName, csv); return(View(result.Item1)); }
public override Response Delete(string objectType, DataFilter filter) { throw new Exception("Error while getting a count of type "); //// Not gonna do it. Wouldn't be prudent with a filter either. //Response response = new Response(); //Status status = new Status(); //status.Level = StatusLevel.Error; //status.Messages.Add("Delete not supported by the SP3D DataLayer."); //response.Append(status); //return response; }
public override IList<IDataObject> Get(string objectType, DataFilter filter, int pageSize, int startIndex) { ISession session = NHibernateSessionManager.Instance.GetSession(_settings["AppDataPath"], _settings["Scope"]); try { if (_databaseDictionary.IdentityConfiguration != null) { IdentityProperties identityProperties = _databaseDictionary.IdentityConfiguration[objectType]; if (identityProperties.UseIdentityFilter) { filter = FilterByIdentity(objectType, filter, identityProperties); } } DataObject objectDefinition = _databaseDictionary.dataObjects.Find(x => x.objectName.ToUpper() == objectType.ToUpper()); if (objectDefinition == null) { throw new Exception("Object type [" + objectType + "] not found."); } string ns = String.IsNullOrEmpty(objectDefinition.objectNamespace) ? String.Empty : (objectDefinition.objectNamespace + "."); Type type = Type.GetType(ns + objectType + ", " + _settings["ExecutingAssemblyName"]); // make an exception for tests if (type == null) { type = Type.GetType(ns + objectType + ", NUnit.Tests"); } ICriteria criteria = NHibernateUtility.CreateCriteria(session, type, objectDefinition, filter); if (pageSize == 0 && startIndex == 0) { List<IDataObject> dataObjects = new List<IDataObject>(); long totalCount = GetCount(objectType, filter); int internalPageSize = (_settings["InternalPageSize"] != null) ? int.Parse(_settings["InternalPageSize"]) : 1000; int numOfRows = 0; while (numOfRows < totalCount) { criteria.SetFirstResult(numOfRows).SetMaxResults(internalPageSize); dataObjects.AddRange(criteria.List<IDataObject>()); numOfRows += internalPageSize; } return dataObjects; } else { criteria.SetFirstResult(startIndex).SetMaxResults(pageSize); IList<IDataObject> dataObjects = criteria.List<IDataObject>(); return dataObjects; } } catch (Exception ex) { _logger.Error("Error in Get: " + ex); throw new Exception(string.Format("Error while getting a list of data objects of type [{0}]. {1}", objectType, ex)); } finally { CloseSession(session); } }
void setData(object sender, DoWorkEventArgs e) { Protein protein = e.Argument as Protein; if (viewFilter.HasSpectrumFilter || viewFilter.HasModificationFilter || !viewFilter.Analysis.IsNullOrEmpty()) { viewFilter = new DataFilter(viewFilter); lock (session) this.viewFilter.Peptide = session.CreateQuery("SELECT psm.Peptide " + viewFilter.GetFilteredQueryString(DataFilter.FromPeptideSpectrumMatch, DataFilter.PeptideSpectrumMatchToSpectrumSourceGroupLink)) .List<Peptide>(); } if (protein == Protein) return; var query = session.CreateQuery("SELECT pi.Offset+pm.Offset, pm " + "FROM PeptideInstance pi " + "JOIN pi.Peptide pep " + "JOIN pep.Matches psm " + "JOIN psm.Modifications pm " + "JOIN FETCH pm.Modification mod " + "WHERE pi.Protein=" + protein.Id.ToString()); IList<object[]> queryRows; lock (session) queryRows = query.List<object[]>(); var modifications = new Map<int, PeptideModification>(); foreach (var queryRow in queryRows) modifications[Convert.ToInt32(queryRow[0])] = queryRow[1] as PeptideModification; Protein = protein; Modifications = new ImmutableMap<int, PeptideModification>(modifications); }
public override IDictionary<string, string> GetHashValues(string objectType, DataFilter filter, int pageSize, int startIndex) { try { IList<IDataObject> dataObjects = Get(objectType, filter, pageSize, startIndex); IList<int> docIds = GetDocumentIds(dataObjects); return GetHashValues(docIds); } catch (Exception e) { _logger.Error("Error getting hash values: " + e.Message); throw e; } }
/// <summary> /// Returns true if all elements have been removed /// </summary> /// <param name="dataFilter"></param> /// <param name="itemNumber"></param> /// <returns></returns> private bool RemoveItemInContainer(DataFilter dataFilter, int itemNumber) { if (dataFilter.GeneGroup != null) { dataFilter.GeneGroup.RemoveAt(itemNumber); if (dataFilter.GeneGroup.Count > 0) { return(false); } } else if (dataFilter.Gene != null) { dataFilter.Gene.RemoveAt(itemNumber); if (dataFilter.Gene.Count > 0) { return(false); } } else if (dataFilter.Cluster != null) { dataFilter.Cluster.RemoveAt(itemNumber); if (dataFilter.Cluster.Count > 0) { return(false); } } else if (dataFilter.ProteinGroup != null) { dataFilter.ProteinGroup.RemoveAt(itemNumber); if (dataFilter.ProteinGroup.Count > 0) { return(false); } } else if (dataFilter.Protein != null) { dataFilter.Protein.RemoveAt(itemNumber); if (dataFilter.Protein.Count > 0) { return(false); } } else if (dataFilter.Peptide != null) { dataFilter.Peptide.RemoveAt(itemNumber); if (dataFilter.Peptide.Count > 0) { return(false); } } else if (dataFilter.DistinctMatchKey != null) { dataFilter.DistinctMatchKey.RemoveAt(itemNumber); if (dataFilter.DistinctMatchKey.Count > 0) { return(false); } } else if (dataFilter.SpectrumSourceGroup != null) { dataFilter.SpectrumSourceGroup.RemoveAt(itemNumber); if (dataFilter.SpectrumSourceGroup.Count > 0) { return(false); } } else if (dataFilter.SpectrumSource != null) { dataFilter.SpectrumSource.RemoveAt(itemNumber); if (dataFilter.SpectrumSource.Count > 0) { return(false); } } else if (dataFilter.Spectrum != null) { dataFilter.Spectrum.RemoveAt(itemNumber); if (dataFilter.Spectrum.Count > 0) { return(false); } } else if (dataFilter.Analysis != null) { dataFilter.Analysis.RemoveAt(itemNumber); if (dataFilter.Analysis.Count > 0) { return(false); } } else if (dataFilter.Charge != null) { dataFilter.Charge.RemoveAt(itemNumber); if (dataFilter.Charge.Count > 0) { return(false); } } else if (dataFilter.AminoAcidOffset != null) { dataFilter.AminoAcidOffset.RemoveAt(itemNumber); if (dataFilter.AminoAcidOffset.Count > 0) { return(false); } } else if (dataFilter.ModifiedSite != null || dataFilter.Modifications != null) { if (itemNumber < 0 && dataFilter.Modifications != null) { var targetedMods = (from mod in dataFilter.Modifications where Math.Round(mod.MonoMassDelta).ToString() == _modMassList[itemNumber] select mod).Distinct().ToList(); foreach (var mod in targetedMods) { dataFilter.Modifications.Remove(mod); } } else if (dataFilter.ModifiedSite != null) { dataFilter.ModifiedSite.RemoveAt(itemNumber); } if (dataFilter.Modifications != null && dataFilter.Modifications.Count > 0) { return(false); } } return(true); }
private void PopulateContainerBox(DataFilter dataFilter, List <List <KeyValuePair <string, int> > > containerBook, int pageIndex, TableLayoutPanel crumbTable, BreadCrumb crumb) { var firstColumnSize = 0; var lastColumnSize = 0; var largestDescription = 0; var dataSet = containerBook[pageIndex]; //clear current table and populate with the crumbs present in the current page crumbTable.Controls.Clear(); for (var x = 0; x < dataSet.Count; x++) { var kvp = dataSet[x]; var arrow = new Label { Text = ">", AutoSize = true, Margin = new Padding(0, 5, 0, 5) }; crumbTable.Controls.Add(arrow, 0, x); if (arrow.Width > 0) { firstColumnSize = arrow.Width; } var description = new Label { Text = kvp.Key, AutoSize = true, Margin = new Padding(5) }; crumbTable.Controls.Add(description, 1, x); if (description.Width > largestDescription) { largestDescription = description.Width; } var deleteLink = new LinkLabel { Text = "(x)", AutoSize = true, Margin = new Padding(0, 5, 0, 5) }; deleteLink.Click += delegate { var allGone = RemoveItemInContainer(dataFilter, kvp.Value); _subItemPopup.Close(); if (allGone) { BreadCrumbClicked(crumb, new BreadCrumbClickedEventArgs(crumb)); } else { BreadCrumbClicked(null, new BreadCrumbClickedEventArgs(null)); breadCrumbs_ListChanged(null, null); } }; crumbTable.Controls.Add(deleteLink, 2, x); if (deleteLink.Width > 0) { lastColumnSize = deleteLink.Width; } } //if there exists more than one page add navigation row if (containerBook.Count > 1) { //forward and back buttons if (pageIndex > 0) { var backButton = new Button { Text = "<-", Size = new Size(30, 20) }; backButton.Click += (x, y) => { PopulateContainerBox(dataFilter, containerBook, pageIndex - 1, crumbTable, crumb); if (_subItemPopup != null) { _subItemPopup.Size = _tableSize; } }; crumbTable.Controls.Add(backButton, 0, dataSet.Count); if (backButton.Width > firstColumnSize) { firstColumnSize = backButton.Width; } } if (pageIndex < containerBook.Count - 1) { var forwardButton = new Button { Text = "->", Size = new Size(30, 20) }; forwardButton.Click += (x, y) => { PopulateContainerBox(dataFilter, containerBook, pageIndex + 1, crumbTable, crumb); if (_subItemPopup != null) { _subItemPopup.Size = _tableSize; } }; crumbTable.Controls.Add(forwardButton, 2, dataSet.Count); if (forwardButton.Width > lastColumnSize) { lastColumnSize = forwardButton.Width; } } //middle page reporting / goto page control var cellPanel = new Panel { Size = new Size(largestDescription, 23) }; var pageLabel = new Label { Text = "Page ", AutoSize = true }; pageLabel.Font = new Font(pageLabel.Font.ToString(), 10.0f); var pageSelectBox = new TextBox { Text = (pageIndex + 1).ToString(), TextAlign = HorizontalAlignment.Center }; pageSelectBox.KeyPress += (x, y) => { //if enter is pressed go to selected page (or reset to current page if no valid page is selected) if (y.KeyChar == (char)13) { y.Handled = true; int tempInt; if (!int.TryParse(pageSelectBox.Text, out tempInt) || tempInt <= 0 || tempInt > containerBook.Count) { pageSelectBox.Text = (pageIndex + 1).ToString(); } else { PopulateContainerBox(dataFilter, containerBook, tempInt - 1, crumbTable, crumb); if (_subItemPopup != null) { _subItemPopup.Size = _tableSize; } } } }; pageSelectBox.Leave += (x, y) => { pageSelectBox.Text = (pageIndex + 1).ToString(); }; var totalLabel = new Label { Text = " of " + containerBook.Count, AutoSize = true }; totalLabel.Font = new Font(totalLabel.Font.ToString(), 10.0f); //add all three controls to the cell panel cellPanel.Controls.Add(pageLabel); cellPanel.Controls.Add(pageSelectBox); cellPanel.Controls.Add(totalLabel); //make sure boxes are wide enough pageSelectBox.Width = totalLabel.Width - 10; var totalCellWidth = pageLabel.Width + pageSelectBox.Width + totalLabel.Width; if (totalCellWidth > largestDescription) { largestDescription = totalCellWidth; cellPanel.Width = totalCellWidth; } //reposition controls to final locations var startlocation = (largestDescription - totalCellWidth) / 2; pageLabel.Location = new Point(startlocation, 0); pageSelectBox.Location = new Point(startlocation + pageLabel.Width, 0); totalLabel.Location = new Point(startlocation + pageLabel.Width + pageSelectBox.Width, 0); crumbTable.Controls.Add(cellPanel, 1, dataSet.Count); } //Hack: sadly the obvious .GetRowHeights() and .getColumnWidths //dont give consistantly valid results, as such proper dimentions have //to be calculated as the table is formed. var rowHeights = (crumbTable.GetRowHeights().Length) * 24; var columnWidths = firstColumnSize + lastColumnSize + 25 + largestDescription; _tableSize = new Size(columnWidths + 5, rowHeights + 5); }
private List <KeyValuePair <string, int> > CreateContainerContents(DataFilter dataFilter) { var contents = new List <KeyValuePair <string, int> >(); //go through the arduous process of figuring out what the data type is //and creating a list of all values present if (dataFilter.GeneGroup != null) { for (var x = 0; x < dataFilter.GeneGroup.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.GeneGroup[x].ToString(), x)); } } else if (dataFilter.Gene != null) { for (var x = 0; x < dataFilter.Gene.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.Gene[x].ToString(), x)); } } else if (dataFilter.Cluster != null) { for (var x = 0; x < dataFilter.Cluster.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.Cluster[x].ToString(), x)); } } else if (dataFilter.ProteinGroup != null) { for (var x = 0; x < dataFilter.ProteinGroup.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.ProteinGroup[x].ToString(), x)); } } else if (dataFilter.Protein != null) { for (var x = 0; x < dataFilter.Protein.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.Protein[x].Accession, x)); } } else if (dataFilter.Peptide != null) { for (var x = 0; x < dataFilter.Peptide.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.Peptide[x].Sequence, x)); } } else if (dataFilter.DistinctMatchKey != null) { for (var x = 0; x < dataFilter.DistinctMatchKey.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.DistinctMatchKey[x].ToString(), x)); } } else if (dataFilter.SpectrumSourceGroup != null) { for (var x = 0; x < dataFilter.SpectrumSourceGroup.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.SpectrumSourceGroup[x].Name, x)); } } else if (dataFilter.SpectrumSource != null) { for (var x = 0; x < dataFilter.SpectrumSource.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.SpectrumSource[x].Name, x)); } } else if (dataFilter.Spectrum != null) { for (var x = 0; x < dataFilter.Spectrum.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.Spectrum[x].NativeID, x)); } } else if (dataFilter.Analysis != null) { for (var x = 0; x < dataFilter.Analysis.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.Analysis[x].Name, x)); } } else if (dataFilter.Charge != null) { for (var x = 0; x < dataFilter.Charge.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.Charge[x].ToString(), x)); } } else if (dataFilter.AminoAcidOffset != null) { for (var x = 0; x < dataFilter.AminoAcidOffset.Count; x++) { contents.Add(new KeyValuePair <string, int>(dataFilter.AminoAcidOffset[x].ToString(), x)); } } else if (dataFilter.ModifiedSite != null || dataFilter.Modifications != null) { //modifications is a special case, containing two differnt filter types if (dataFilter.Modifications != null) { //mod masses have to be stored in a separate list due to //the way they have are removed from the breadcrumb trail _modMassList = new Dictionary <int, string>(); var distinctModMasses = (from mod in dataFilter.Modifications select Math.Round(mod.MonoMassDelta).ToString()) .Distinct().ToList(); for (var x = 0; x < distinctModMasses.Count; x++) { //to distinguish mass indexes from site indexes, //mass indexes are stored as negative numbers var translatedIndex = (x + 1) * -1; _modMassList.Add(translatedIndex, distinctModMasses[x]); contents.Add(new KeyValuePair <string, int>("Mass: " + distinctModMasses[x], translatedIndex)); } } if (dataFilter.ModifiedSite != null) { //modified sites can be added as normal for (var x = 0; x < dataFilter.ModifiedSite.Count; x++) { contents.Add(new KeyValuePair <string, int>("Residue: " + dataFilter.ModifiedSite[x].ToString(), x)); } } } //sort everything into aplhebitical order to aid in finding specific filters contents.Sort((a, b) => string.Compare(a.Key, b.Key)); return(contents); }
public virtual void SetDataFilter(DataFilter dataFilter) { columnVisible = dataFilter.ShowColumns; combineLogic = dataFilter.CombineLogic; }
public override void SetDataFilter(DataFilter dataFilter) { base.SetDataFilter(dataFilter); cboValues.SetSelection(filter.Values, "Key", "Value", filter.Value); }
// GET: InsuranceRenewals public ActionResult Index() { return(View(DataFilter.GetInsuranceRenewals(TempData.Peek("Id") + ""))); }
// GET: Ranges public ActionResult Index() { return(View(DataFilter.GetRanges(TempData.Peek("Id") + ""))); }
public override Response Delete(string objectType, DataFilter filter) { try { IList<string> identifiers = GetIdentifiers(objectType, filter); return Delete(objectType, identifiers); } catch (Exception e) { string filterXML = Utility.SerializeDataContract<DataFilter>(filter); _logger.Error(string.Format("Error deleting object type [{0}] with filter [{1}].", objectType, filterXML)); throw e; } }
public override IList<IContentObject> GetContents(string objectType, DataFilter filter, int pageSize, int startIndex) { try { IList<IDataObject> dataObjects = Get(objectType, filter, pageSize, startIndex); IList<int> docIds = GetDocumentIds(dataObjects); return GetContents(objectType, docIds); } catch (Exception e) { _logger.Error("Error getting contents: " + e.Message); throw e; } }
/// <summary> /// Gets rid of breadcrumbs that are have been updated to avoid duplication /// </summary> private void RemoveStaleBread() { var overallData = new DataFilter(); for (int x = breadCrumbs.Count - 1; x >= 0; x--) { var item = (DataFilter)breadCrumbs[x].Tag; if (breadCrumbs[x].Text.Contains("Q-value")) { breadCrumbs.RemoveAt(x); //Sometimes bugs and gets extra-long breadcrumb } else if (item.GeneGroup != null || item.Gene != null || item.Cluster != null || item.ProteinGroup != null || item.Protein != null) { if (overallData.GeneGroup != null || overallData.Gene != null || overallData.Cluster != null || overallData.ProteinGroup != null || overallData.Protein != null) { breadCrumbs.RemoveAt(x); } else { overallData.GeneGroup = overallData.GeneGroup ?? item.GeneGroup; overallData.Gene = overallData.Gene ?? item.Gene; overallData.Cluster = overallData.Cluster ?? item.Cluster; overallData.ProteinGroup = overallData.ProteinGroup ?? item.ProteinGroup; overallData.Protein = overallData.Protein ?? item.Protein; } } else if (item.PeptideGroup != null || item.Peptide != null || item.DistinctMatchKey != null) { if (overallData.PeptideGroup != null || overallData.Peptide != null || overallData.DistinctMatchKey != null) { breadCrumbs.RemoveAt(x); } else { overallData.PeptideGroup = overallData.PeptideGroup ?? item.PeptideGroup; overallData.Peptide = overallData.Peptide ?? item.Peptide; overallData.DistinctMatchKey = overallData.DistinctMatchKey ?? item.DistinctMatchKey; } } else if (item.SpectrumSourceGroup != null || item.SpectrumSource != null || item.Spectrum != null) { if (overallData.SpectrumSourceGroup != null || overallData.SpectrumSource != null || overallData.Spectrum != null) { breadCrumbs.RemoveAt(x); } else { overallData.SpectrumSourceGroup = overallData.SpectrumSourceGroup ?? item.SpectrumSourceGroup; overallData.SpectrumSource = overallData.SpectrumSource ?? item.SpectrumSource; overallData.Spectrum = overallData.Spectrum ?? item.Spectrum; } } else if (item.Analysis != null) { if (overallData.Analysis == null) { overallData.Analysis = item.Analysis; } else { breadCrumbs.RemoveAt(x); } } else if (item.Charge != null) { if (overallData.Charge == null) { overallData.Charge = item.Charge; } else { breadCrumbs.RemoveAt(x); } } else if (item.ModifiedSite != null || item.Modifications != null) { if (overallData.Modifications != null || overallData.ModifiedSite != null) { breadCrumbs.RemoveAt(x); } else { overallData.ModifiedSite = overallData.ModifiedSite ?? item.ModifiedSite; overallData.Modifications = overallData.Modifications ?? item.Modifications; } } //else // breadCrumbs.RemoveAt(x); } }
public SequenceCoverageControl (NHibernate.ISession session, DataModel.Protein protein, DataFilter viewFilter) { ResizeRedraw = true; DoubleBuffered = true; AutoScroll = true; ResidueGroupSize = 10; lineSpacing = 3; HeaderColor = Color.FromKnownColor(KnownColor.WindowText); OffsetColor = Color.FromKnownColor(KnownColor.GrayText); CoveredSequenceColor = Color.FromKnownColor(KnownColor.WindowText); UncoveredSequenceColor = Color.FromKnownColor(KnownColor.GrayText); HoverSequenceColor = Color.FromKnownColor(KnownColor.HotTrack); ModifiedSequenceColor = Color.Red; HeaderFont = new Font(new FontFamily(GenericFontFamilies.Monospace), 12); OffsetFont = new Font(new FontFamily(GenericFontFamilies.Monospace), 12); SequenceFont = new Font(new FontFamily(GenericFontFamilies.Monospace), 12); FilteredInSequenceFont = new Font(SequenceFont, FontStyle.Bold); HoverFont = new Font(SequenceFont, FontStyle.Bold | FontStyle.Underline); SetData(session, protein, viewFilter); ContextMenuStrip = new ContextMenuStrip(); ContextMenuStrip.Items.Add("Save image", null, (s, e) => bitmapSave()); ContextMenuStrip.Items.Add("Copy image", null, (s, e) => bitmapCopyToClipboard()); ContextMenuStrip.Items.Add("Copy sequence", null, (s, e) => sequenceCopyToClipboard()); }
// GET: FireExtinguishingEquipments public ActionResult Index() { return(View(DataFilter.GetFireExtingushingEquipments(TempData.Peek("Id") + ""))); }
public void SetData (NHibernate.ISession session, DataFilter viewFilter) { control.SetData(session, control.Protein, viewFilter); }
// GET: FireExtinguishingEquipments/Create public ActionResult Create() { ViewBag.FireExtinguishingEquipmentTypeId = new SelectList(db.FireExtinguishingEquipmentTypes, "Id", "Name"); ViewBag.FireStationId = new SelectList(DataFilter.GetFireStations(TempData.Peek("Id") + ""), "Id", "Name"); return(View()); }
public override IList<string> GetIdentifiers(string objectType, DataFilter filter) { throw new Exception("Error while getting a count of type "); //try //{ // List<string> identifiers = new List<string>(); // //NOTE: pageSize of 0 indicates that all rows should be returned. // IList<IDataObject> dataObjects = Get(objectType, filter, 0, 0); // foreach (IDataObject dataObject in dataObjects) // { // identifiers.Add((string)dataObject.GetPropertyValue("Tag")); // } // return identifiers; //} //catch (Exception ex) //{ // _logger.Error("Error in GetIdentifiers: " + ex); // throw new Exception( // "Error while getting a list of identifiers of type [" + objectType + "].", // ex // ); //} }
//http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart(旧网址) //http://docs.mongodb.org/manual/reference/sql-comparison/ /// <summary> /// Convert Query Sql To DataFilter /// </summary> /// <param name="Sql"></param> /// <returns></returns> public static DataFilter ConvertQuerySql(String Sql) { var rtnQuery = new DataFilter(); Sql = Sql.Trim(); //引号中的空格用 代替,引号以外的东西小写 Sql = Regular(Sql); //先将字符串里面的空格统一成单个空格 //Select A,B From C -> //Select A,B From C while (Sql.Contains(" ")) { Sql = Sql.Replace(" ", " "); } //找出Select ,From , Group String[] SqlToken = Sql.Split(" ".ToCharArray()); int SelectStartIndex = -1; int FromStartIndex = -1; int WhereStartIndex = -1; int GroupByStartIndex = -1; int OrderByStartIndex = -1; for (int i = 0; i < SqlToken.Length; i++) { switch (SqlToken[i].ToLower()) { case "select": SelectStartIndex = i; break; case "from": FromStartIndex = i; break; case "where": WhereStartIndex = i; break; case "group": GroupByStartIndex = i; break; case "order": OrderByStartIndex = i; break; default: break; } } String[] KeyWords = { "select", "from", "where", "group", "order" }; //From - > CollectionName GetKeyContent(FromStartIndex, SqlToken, KeyWords); MongoCollection mongoCol; //if ((strFrom != String.Empty) & SystemManager.GetCurrentDataBase().CollectionExists(strFrom)) //{ // mongoCol = SystemManager.GetCurrentDataBase().GetCollection(strFrom); //} //else //{ // return null; //} //From:由于当前肯定是从固定表里面取数据 mongoCol = SystemManager.GetCurrentCollection(); //Select 设定 必须项 //Select - > FieldList String strSelect = GetKeyContent(SelectStartIndex, SqlToken, KeyWords); if (strSelect == String.Empty) { return(null); } List <String> ColumnNameLst = MongoDbHelper.GetCollectionSchame(mongoCol); if (strSelect == "*") { //Select * foreach (String item in ColumnNameLst) { var field = new DataFilter.QueryFieldItem(); field.ColName = item; field.IsShow = true; field.sortType = DataFilter.SortType.NoSort; rtnQuery.QueryFieldList.Add(field); } } else { //Select A,B,C foreach (String item in strSelect.Split(",".ToCharArray())) { var field = new DataFilter.QueryFieldItem(); field.ColName = item; field.IsShow = true; field.sortType = DataFilter.SortType.NoSort; rtnQuery.QueryFieldList.Add(field); } } //Where 设定,可选项 String strWhere = GetKeyContent(WhereStartIndex, SqlToken, KeyWords); if (strWhere != String.Empty) { rtnQuery.QueryConditionList = SetQueryCondition(strWhere, ColumnNameLst); } //Order 设定,可选项 String strOrder = GetKeyContent(OrderByStartIndex, SqlToken, KeyWords); if (strOrder != String.Empty) { SetQueryOrder(rtnQuery, strOrder); } //Group 设定,可选项 String strGroup = GetKeyContent(GroupByStartIndex, SqlToken, KeyWords); if (strGroup != String.Empty) { //TODO:Group } return(rtnQuery); }
public override IList <IDataObject> Get(string objectType, DataFilter filter, int pageSize, int startIndex) { DataFilter newFilter = Utility.CloneDataContractObject <DataFilter>(filter); AccessLevel accessLevel = Authorize(objectType, ref newFilter); if (accessLevel < AccessLevel.Read) { throw new UnauthorizedAccessException(String.Format(UNAUTHORIZED_ERROR, _settings["scope"])); } ISession session = NHibernateSessionManager.Instance.GetSession(_settings["AppDataPath"], _settings["Scope"]); try { if (_dbDictionary.IdentityConfiguration != null) { IdentityProperties identityProperties = _dbDictionary.IdentityConfiguration[objectType]; if (identityProperties.UseIdentityFilter) { newFilter = FilterByIdentity(objectType, newFilter, identityProperties); } } DataObject objectDefinition = _dbDictionary.dataObjects.Find(x => x.objectName.ToUpper() == objectType.ToUpper()); if (objectDefinition == null) { throw new Exception("Object type [" + objectType + "] not found."); } string ns = String.IsNullOrEmpty(objectDefinition.objectNamespace) ? String.Empty : (objectDefinition.objectNamespace + "."); Type type = Type.GetType(ns + objectType + ", " + _settings["ExecutingAssemblyName"]); // make an exception for tests if (type == null) { type = Type.GetType(ns + objectType + ", NUnit.Tests"); } ICriteria criteria = NHibernateUtility.CreateCriteria(session, type, objectDefinition, newFilter); if (pageSize == 0 && startIndex == 0) { List <IDataObject> dataObjects = new List <IDataObject>(); long totalCount = GetCount(objectType, filter); int internalPageSize = (_settings["InternalPageSize"] != null) ? int.Parse(_settings["InternalPageSize"]) : 1000; int numOfRows = 0; while (numOfRows < totalCount) { if (filter != null && filter.OrderExpressions != null && filter.OrderExpressions.Count > 0) { criteria.SetFirstResult(numOfRows).SetMaxResults(internalPageSize); } else { NHibernate.Criterion.Order order = new NHibernate.Criterion.Order(objectDefinition.keyProperties.First().keyPropertyName, true); criteria.AddOrder(order).SetFirstResult(numOfRows).SetMaxResults(internalPageSize); } dataObjects.AddRange(criteria.List <IDataObject>()); numOfRows += internalPageSize; } return(dataObjects); } else { if (filter != null && filter.OrderExpressions != null && filter.OrderExpressions.Count > 0) { criteria.SetFirstResult(startIndex).SetMaxResults(pageSize); } else { NHibernate.Criterion.Order order = new NHibernate.Criterion.Order(objectDefinition.keyProperties.First().keyPropertyName, true); criteria.AddOrder(order).SetFirstResult(startIndex).SetMaxResults(pageSize); } IList <IDataObject> dataObjects = criteria.List <IDataObject>(); return(dataObjects); } } catch (Exception ex) { _logger.Error("Error in Get: " + ex); throw new Exception(string.Format("Error while getting a list of data objects of type [{0}]. {1}", objectType, ex)); } finally { CloseSession(session); } }
private DataFilter GetFilter(string filter) { int currentUserRoleWeight = CurrentUser?.RoleWeight ?? 0; bool siteAdmin = CurrentUser?.SiteAdmin ?? false; DataFilter tmpFilter = Globals.DefaultDataFilter; tmpFilter.UserRoleWeight = currentUserRoleWeight; if (string.IsNullOrWhiteSpace(filter) || filter == "[]") { return(tmpFilter); } try { tmpFilter = JsonConvert.DeserializeObject <DataFilter>(filter); if (tmpFilter == null) { return(Globals.DefaultDataFilter); } if (tmpFilter.PageSize > Globals.MaxRecordsPerRequest && siteAdmin == false) { tmpFilter.PageSize = Globals.MaxRecordsPerRequest; } if (currentUserRoleWeight > 0 && siteAdmin == false) { //the higher thier role the more records they can get in one call tmpFilter.PageSize = currentUserRoleWeight * Globals.DefaultDataFilter.PageSize; } if (Validator.HasSqlCommand(tmpFilter.SortBy)) { tmpFilter.SortBy = "Name"; } if (Validator.HasSqlCommand(tmpFilter.SortDirection)) { tmpFilter.SortDirection = "ASC"; } if (Validator.HasSqlCommand(tmpFilter.TimeZone)) { tmpFilter.TimeZone = ""; } for (int i = 0; i < tmpFilter.Screens.Count; i++) { var tmp = tmpFilter.Screens[i].Value + " " + tmpFilter.Screens[i].Command + " " + tmpFilter.Screens[i].Field + " " + tmpFilter.Screens[i].Junction + " " + tmpFilter.Screens[i].Operator + " " + tmpFilter.Screens[i].Type; if (Validator.HasSqlCommand(tmp)) { Debug.Assert(false, "SQL INJECTION! " + tmp); tmpFilter.Screens[i].Value = ""; tmpFilter.Screens[i].Command = ""; tmpFilter.Screens[i].Field = ""; tmpFilter.Screens[i].Junction = ""; tmpFilter.Screens[i].Operator = ""; tmpFilter.Screens[i].Type = ""; } } } catch (Exception ex) { _logger.InsertError(ex.Message, "ApiBaseController", "GetFilter"); return(tmpFilter); } return(tmpFilter); }
public IActionResult Search(string searchString, string button, uint?page) { _creatableStorage.Value.Create(new Log { Date = DateTime.Now, Message = "Entrou em Student/Search" }); uint pageOffset = Convert.ToUInt32(page.HasValue ? page.Value - 1 : 0); var query = _readerStore.AsFluentQuery() .Paginate(page ?? 1, 5); PaginatedResult <Student> students = !string.IsNullOrWhiteSpace(searchString) ? query .Filter(f => f.FirstMidName.ToLower().Contains(searchString.ToLower()) || f.LastName.ToLower().Contains(searchString.ToLower())) .LimitedSearch() : query.LimitedGet(); ViewData["SearchString"] = searchString; // Caso o botão clicado seja "FiltrarAtualizar" nós // atualizamos o último nome de cada estudante encontrado // com o nome fake composto por um número aleatório, só // pra demonstrar o uso de Update() em massa if (!string.IsNullOrWhiteSpace(searchString) && button == "FiltrarAtualizar") { Expression <Func <Student, bool> > filterExpression = f => f.FirstMidName.ToLower().Contains(searchString.ToLower()) || f.LastName.ToLower().Contains(searchString.ToLower()); var filter = new DataFilter <Student>() .AddFilter(filterExpression); // Todos com mesmo segundo nome var random = new Random(); // Alterando só um var first = students.Result.FirstOrDefault(); if (first != null) { var updated1 = _writerStore.AsFluentWriter() .Identifier(first.ID) .Update(new { LastName = $"LastName ({random.Next()})" }); var updated2 = _writerStore.AsFluentWriter() .Identifier(first.ID) .Update(c => new { LastName = $"{c.LastName} ({random.Next()})" }); } // Alterando a coleção inteira var updatedResult1 = _bulkWriterStore.AsFluentBulkWriter() .Filter(filterExpression) .BulkUpdate(new { LastName = $"LastName {random.Next()}" }); // Cada um com seu próprio segundo nome var updatedResult2 = _bulkWriterStore.AsFluentBulkWriter() .Filter(filterExpression) .BulkUpdate(c => new { LastName = $"{c.LastName} ({random.Next()})" }); students = new PaginatedResult <Student>( result: updatedResult2, offset: students.Offset, limit: students.Limit, total: students.Total ); } return(View(nameof(Index), students)); }
/// <summary> /// Создать запрос с фильтрацией. /// </summary> public IQueryable <TEntity> BuildFilteredQuery <TEntity>(IQueryable <TEntity> query, DataFilter filter) where TEntity : class { return(query); }
public override IList<string> GetIdentifiers(string objectType, DataFilter filter) { List<string> identifiers = new List<string>(); try { //NOTE: pageSize of 0 indicates that all rows should be returned. IList<IDataObject> dataObjects = Get(objectType, filter, 0, 0); foreach (IDataObject dataObject in dataObjects) { identifiers.Add((string)dataObject.GetPropertyValue("Id")); } } catch (Exception ex) { _logger.ErrorFormat("Error while getting a filtered list of identifiers of type [{0}]: {1}", objectType, ex); throw new Exception("Error while getting a filtered list of identifiers of type [" + objectType + "].", ex); } return identifiers; }
public ActionResult AjaxDirectLineData(DataFilter filter, int directLine, int page = 1, int rows = 100) { int warehouseID = 0, total = 0; List <object> dataList = new List <object>(); if (int.TryParse(Session["warehouseId"].ToString(), out warehouseID)) { Warehouses warehouse = db.Warehouses.Find(warehouseID); if (warehouse != null && warehouse.WarehouseType.Value.Equals((int)WarehouseTypeType.DropShip)) { /** Order Filter **/ var OrderFilter = db.Orders.AsNoTracking().Where(o => !o.StatusCode.Value.Equals((int)OrderStatusCode.Completed) && o.PaymentStatus.Value.Equals((int)OrderPaymentStatus2.Charged)); /** Shipping Method Filter **/ var MethodFilter = db.ShippingMethod.AsNoTracking().Where(m => m.IsEnable && m.IsDirectLine && m.DirectLine.Equals(directLine)); List <OrderJoinData> results = DataFilter(filter, OrderFilter, MethodFilter, EnumData.ProcessStatus.待出貨, warehouseID); if (results.Any()) { TimeZoneConvert timeZoneConvert = new TimeZoneConvert(); EnumData.TimeZone TimeZone = MyHelp.GetTimeZone((int)Session["TimeZone"]); int length = rows; int start = (page - 1) * length; total = results.Count(); results = results.OrderByDescending(oData => oData.order.TimeOfOrder).Skip(start).Take(length).ToList(); string[] skus = results.SelectMany(oData => oData.items.Select(i => i.ProductID)).Distinct().ToArray(); Dictionary <string, string> skuNameList = db.Skus.AsNoTracking().Where(s => s.IsEnable.Value && skus.Contains(s.Sku)).ToDictionary(s => s.Sku, s => s.ProductName); int[] methodIDs = results.Select(oData => oData.package.ShippingMethod.Value).Distinct().ToArray(); Dictionary <int, string> methodNameList = db.ShippingMethod.AsNoTracking().Where(m => m.IsEnable && methodIDs.Contains(m.ID)).ToDictionary(m => m.ID, m => m.ID + "-" + m.Name); int[] itemIDs = results.SelectMany(oData => oData.items.Select(i => i.ID)).ToArray(); Dictionary <int, string[]> serialOfItem = db.SerialNumbers.AsNoTracking().Where(s => itemIDs.Contains(s.OrderItemID)).GroupBy(s => s.OrderItemID).ToDictionary(s => s.Key, s => s.Select(ss => ss.SerialNumber).ToArray()); dataList.AddRange(results.Select(oData => new { OrderID = oData.order.OrderID, POId = oData.package.POId, PackageID = oData.package.ID, ItemID = oData.item.ID, PaymentDate = oData.payment != null ? timeZoneConvert.InitDateTime(oData.payment.AuditDate.Value, EnumData.TimeZone.EST).ConvertDateTime(TimeZone).ToString("MM/dd/yyyy<br />hh:mm tt") : "", Sku = oData.itemCount == 1 ? oData.item.ProductID : "Multi", DisplayName = oData.itemCount == 1 ? skuNameList[oData.item.ProductID] : "Multi", ItemCount = oData.itemCount, OrderQtyTotal = oData.items.Sum(i => i.Qty), ShippingCountry = oData.address.CountryName, ShippingMethod = methodNameList[oData.package.ShippingMethod.Value], StatusCode = Enum.GetName(typeof(OrderStatusCode), oData.order.StatusCode.Value), Comment = string.IsNullOrEmpty(oData.package.Comment) ? "" : oData.package.Comment, SupplierComment = string.IsNullOrEmpty(oData.package.SupplierComment) ? "" : oData.package.SupplierComment, Serials = oData.items.Where(i => serialOfItem.ContainsKey(i.ID)).ToDictionary(i => i.ID.ToString(), i => serialOfItem[i.ID]), SerialNumber = oData.itemCount + oData.item.Qty == 2 ? (serialOfItem.ContainsKey(oData.item.ID) ? serialOfItem[oData.item.ID].First() : "") : "Multi", TagNo = oData.package.TagNo, POInvoice = string.IsNullOrEmpty(oData.package.POInvoice) ? "" : oData.package.POInvoice })); } } } return(Json(new { total, rows = dataList }, JsonRequestBehavior.AllowGet)); }
public void TestSchemaUpdater() { Assert.AreEqual(15, SchemaUpdater.CurrentSchemaRevision); var testModel = new TestModel() { TestContext = TestContext }; TestModel.ClassInitialize(TestContext); testModel.TestInitialize(); testModelFile(testModel, "testModel.idpDB"); string filename = null; // test all revisions without a data filter applied // we don't need to test upgrade from 12 to 13; the extra table (PeptideModificationProbability) is ignored and necessary for the current NHibernate bindings // we don't need to test upgrade from 11 to 12; the changed table (XICMetrics) is ignored // we don't need to test upgrade from 10 to 11; the extra columns (GeneGroups, Genes) are ignored // we don't need to test upgrade from 9 to 10; the extra tables (XICMetrics, XICMetricsSettings) are ignored // we don't need to test upgrade from 8 to 9; the extra columns (GeneLevelFiltering, DistinctMatchFormat) are ignored // we don't need to test upgrade from 7 to 8; the extra columns are ignored // we don't need to test upgrade from 5 to 6; it simply forces reapplication of the basic filters // we don't need to test upgrade from 4 to 5; it's a simple null value fix filename = "testModel-v4.idpDB"; File.Copy("testModel.idpDB", filename, true); downgradeToRevision(filename, 4); testModelFile(testModel, filename); filename = "testModel-v3.idpDB"; File.Copy("testModel.idpDB", filename, true); downgradeToRevision(filename, 3); testModelFile(testModel, filename); filename = "testModel-v2.idpDB"; File.Copy("testModel.idpDB", filename, true); downgradeToRevision(filename, 2); testModelFile(testModel, filename); filename = "testModel-v1.idpDB"; File.Copy("testModel.idpDB", filename, true); downgradeToRevision(filename, 1); testModelFile(testModel, filename); filename = "testModel-v0.idpDB"; File.Copy("testModel.idpDB", filename, true); downgradeToRevision(filename, 0); testModelFile(testModel, filename); // test all revisions with a data filter applied (only check that the update worked this time) File.Copy("testModel.idpDB", "testFilter.idpDB", true); var dataFilter = new DataFilter { MaximumQValue = 1 }; using (var sessionFactory = SessionFactoryFactory.CreateSessionFactory("testFilter.idpDB")) using (var session = testModel.session = sessionFactory.OpenSession()) { dataFilter.ApplyBasicFilters(session); } filename = "testFilter-v4.idpDB"; File.Copy("testFilter.idpDB", filename, true); downgradeToRevision(filename, 4); testFilterFile(filename); filename = "testFilter-v3.idpDB"; File.Copy("testFilter.idpDB", filename, true); downgradeToRevision(filename, 3); testFilterFile(filename); filename = "testFilter-v2.idpDB"; File.Copy("testFilter.idpDB", filename, true); downgradeToRevision(filename, 2); testFilterFile(filename); filename = "testFilter-v1.idpDB"; File.Copy("testFilter.idpDB", filename, true); downgradeToRevision(filename, 1); testFilterFile(filename); filename = "testFilter-v0.idpDB"; File.Copy("testFilter.idpDB", filename, true); downgradeToRevision(filename, 0); testFilterFile(filename); }
public ActionResult AjaxShippedData(DataFilter filter, int page = 1, int rows = 100) { Orders = new GenericRepository <Orders>(db); Packages = new GenericRepository <Packages>(db); Items = new GenericRepository <Items>(db); Payments = new GenericRepository <Payments>(db); Addresses = new GenericRepository <Addresses>(db); Warehouses = new GenericRepository <Warehouses>(db); int warehouseID = 0, total = 0; List <object> dataList = new List <object>(); if (int.TryParse(Session["warehouseId"].ToString(), out warehouseID)) { Warehouses warehouse = Warehouses.Get(warehouseID); if (warehouse != null && warehouse.WarehouseType.Equals((int)WarehouseTypeType.DropShip)) { /** Order Filter **/ var OrderFilter = db.Orders.AsNoTracking().Where(o => o.StatusCode.Value.Equals((int)OrderStatusCode.Completed) || o.ShippingStatus.Value.Equals((int)OrderShippingStatus.PartiallyShipped)); /** Shipping Method Filter **/ var MethodFilter = db.ShippingMethod.AsNoTracking().Where(m => m.IsEnable); List <OrderJoinData> results = DataFilter(filter, OrderFilter, MethodFilter, EnumData.ProcessStatus.已出貨, warehouseID); if (results.Any()) { SerialNumbers = new GenericRepository <SerialNumbers>(db); TimeZoneConvert timeZoneConvert = new TimeZoneConvert(); EnumData.TimeZone TimeZone = MyHelp.GetTimeZone((int)Session["TimeZone"]); int length = rows; int start = (page - 1) * length; total = results.Count(); results = results.OrderByDescending(oData => oData.order.TimeOfOrder).Skip(start).Take(length).ToList(); int[] itemIDs = results.SelectMany(oData => oData.items.Select(i => i.ID)).ToArray(); Dictionary <int, string[]> serialOfItem = SerialNumbers.GetAll(true).Where(s => itemIDs.Contains(s.OrderItemID)).GroupBy(s => s.OrderItemID).ToDictionary(s => s.Key, s => s.Select(ss => ss.SerialNumber).ToArray()); dataList.AddRange(results.Select(oData => new { OrderID = oData.order.OrderID, POId = oData.package.POId, PackageID = oData.package.ID, ItemID = oData.item.ID, PaymentDate = oData.payment != null ? timeZoneConvert.InitDateTime(oData.payment.AuditDate.Value, EnumData.TimeZone.EST).ConvertDateTime(TimeZone).ToString("MM/dd/yyyy<br />hh:mm tt") : "", Sku = oData.itemCount == 1 ? oData.item.ProductID : "Multi", DisplayName = oData.itemCount == 1 ? oData.item.DisplayName : "Multi", ItemCount = oData.itemCount, OrderQtyTotal = oData.items.Sum(i => i.Qty), ShippingCountry = oData.address.CountryName, ShippingMethod = oData.method.Name, Type = oData.method.IsDirectLine ? "Direct Line" : "Dropship", StatusCode = Enum.GetName(typeof(OrderStatusCode), oData.order.StatusCode.Value), Comment = oData.package.Comment, SupplierComment = oData.package.SupplierComment, SerialNumber = oData.itemCount + oData.item.Qty == 2 ? (serialOfItem.ContainsKey(oData.item.ID) ? serialOfItem[oData.item.ID].First() : "") : "Multi", LabelID = string.IsNullOrEmpty(oData.package.TagNo) ? "" : oData.package.TagNo, TrackingNumber = oData.package.TrackingNumber, POInvoice = oData.package.POInvoice })); } } } return(Content(JsonConvert.SerializeObject(new { total, rows = dataList }), "appllication/json")); }
public override IList<IDataObject> Get(string objectType, DataFilter filter, int pageSize, int startIndex) { IList<IDataObject> dataObjects = new List<IDataObject>(); Proxy proxy = null; Session session = null; try { Connect(ref proxy, ref session); DataObject objDef = GetObjectDefinition(objectType); if (objDef != null) { string classObject = objDef.objectNamespace; string classIds = objDef.tableName.Replace("_", ","); if (classObject.ToLower() == "document" || classObject.ToLower() == "tag") { string eql = "START WITH {0} SELECT {1} WHERE Class.Id IN ({2})"; StringBuilder builder = new StringBuilder(); foreach (DataProperty dataProp in objDef.dataProperties) { string item = Utilities.ToQueryItem(dataProp); if (!string.IsNullOrEmpty(item)) { if (builder.Length > 0) builder.Append(","); builder.Append(item); } } eql = string.Format(eql, classObject, builder.ToString(), classIds); if (filter != null) { string whereClause = Utilities.ToSqlWhereClause(filter, objDef); if (!string.IsNullOrEmpty(whereClause)) { eql += whereClause.Replace(" WHERE ", " AND "); } } EqlClient eqlClient = new EqlClient(session); DataTable result = eqlClient.Search(session, eql, new object[0], startIndex, pageSize); dataObjects = ToDataObjects(result, objDef); } else { throw new Exception("Class object [" + classObject + "] not supported."); } } else { throw new Exception("Object type " + objectType + " not found."); } } finally { Disconnect(ref proxy, ref session); } return dataObjects; }
private List <OrderJoinData> DataFilter(DataFilter filter, IQueryable <Orders> OrderFilter, IQueryable <ShippingMethod> MethodFilter, EnumData.ProcessStatus processStatus, int warehouseID) { /** Order Filter **/ if (!filter.StatusCode.Equals(null)) { OrderFilter = OrderFilter.Where(o => o.StatusCode.Value.Equals(filter.StatusCode.Value)); } if (!filter.ShippingStatus.Equals(null)) { OrderFilter = OrderFilter.Where(o => o.ShippingStatus.Equals(filter.ShippingStatus)); } if (!filter.Source.Equals(null)) { OrderFilter = OrderFilter.Where(o => o.OrderSource.Equals(filter.Source)); } if (!string.IsNullOrWhiteSpace(filter.OrderID)) { OrderFilter = OrderFilter.Where(o => o.OrderID.ToString().Equals(filter.OrderID)); } if (!string.IsNullOrWhiteSpace(filter.UserID)) { OrderFilter = OrderFilter.Where(o => !string.IsNullOrWhiteSpace(o.eBayUserID) && o.eBayUserID.Contains(filter.UserID)); } if (!string.IsNullOrWhiteSpace(filter.SourceID)) { OrderFilter = OrderFilter.Where(o => (o.OrderSource.Equals(1) && (o.eBaySalesRecordNumber.Equals(filter.SourceID) || o.OrderSourceOrderId.Contains(filter.SourceID))) || (o.OrderSource.Equals(4) && o.OrderSourceOrderId.Equals(filter.SourceID))); } /** Package Filter **/ var PackageFilter = db.Packages.AsNoTracking().Where(p => p.IsEnable.Value && p.ProcessStatus.Equals((byte)processStatus)); if (!filter.MethodID.Equals(null)) { PackageFilter = PackageFilter.Where(p => p.ShippingMethod.Value.Equals(filter.MethodID.Value)); } if (!string.IsNullOrWhiteSpace(filter.Tracking)) { PackageFilter = PackageFilter.Where(p => p.TrackingNumber.ToLower().Contains(filter.Tracking.ToLower())); } /** Item Filter **/ var ItemFilter = db.Items.AsNoTracking().Where(i => i.IsEnable.Value && i.ShipFromWarehouseID.Value.Equals(warehouseID)); if (!string.IsNullOrWhiteSpace(filter.ItemName)) { ItemFilter = ItemFilter.Where(i => i.DisplayName.ToLower().Contains(filter.ItemName.ToLower()) || i.ProductID.Equals(filter.ItemName)); } /** Address Filter **/ var AddressFilter = db.Addresses.AsNoTracking().Where(a => a.IsEnable.Value); if (!string.IsNullOrWhiteSpace(filter.Country)) { AddressFilter = AddressFilter.Where(a => a.CountryCode.Equals(filter.Country)); } /** Payment Filter **/ var PaymentFilter = db.Payments.AsNoTracking().Where(p => p.IsEnable.Value && p.PaymentType.Value.Equals((int)PaymentRecordType.Payment)); if (!filter.DateFrom.Equals(new DateTime())) { DateTime dateFrom = new DateTime(filter.DateFrom.Year, filter.DateFrom.Month, filter.DateFrom.Day, 0, 0, 0); dateFrom = new TimeZoneConvert(dateFrom, MyHelp.GetTimeZone((int)Session["TimeZone"])).ConvertDateTime(EnumData.TimeZone.EST); PaymentFilter = PaymentFilter.Where(p => DateTime.Compare(p.AuditDate.Value, dateFrom) >= 0); } if (!filter.DateTo.Equals(new DateTime())) { DateTime dateTo = new DateTime(filter.DateTo.Year, filter.DateTo.Month, filter.DateTo.Day + 1, 0, 0, 0); dateTo = new TimeZoneConvert(dateTo, MyHelp.GetTimeZone((int)Session["TimeZone"])).ConvertDateTime(EnumData.TimeZone.EST); PaymentFilter = PaymentFilter.Where(p => DateTime.Compare(p.AuditDate.Value, dateTo) < 0); } return(OrderFilter.ToList() .Join(PackageFilter, o => o.OrderID, p => p.OrderID, (o, p) => new OrderJoinData() { order = o, package = p }) .Join(ItemFilter.GroupBy(i => i.PackageID.Value), oData => oData.package.ID, i => i.Key, (oData, i) => new OrderJoinData(oData) { item = i.First(), items = i.ToList(), itemCount = i.Sum(ii => ii.Qty + ii.KitItemCount).Value }) .Join(AddressFilter, oData => oData.order.ShippingAddress, a => a.Id, (oData, a) => new OrderJoinData(oData) { address = a }) .Join(MethodFilter, oData => oData.package.ShippingMethod, m => m.ID, (oData, m) => new OrderJoinData(oData) { method = m }) .GroupJoin(PaymentFilter, oData => oData.order.OrderID, p => p.OrderID.Value, (oData, p) => new { orderJoinData = oData, payment = p.Take(1) }) .SelectMany(o => o.payment.DefaultIfEmpty(), (o, p) => new OrderJoinData(o.orderJoinData) { payment = p }).ToList()); }
public override long GetCount(string objectType, DataFilter filter) { Proxy proxy = null; Session session = null; try { DataObject objDef = GetObjectDefinition(objectType); if (objDef != null) { Connect(ref proxy, ref session); Configuration config = GetConfiguration(objDef); int objType = (int)config.Template.ObjectType; string classIds = objDef.tableName.Replace("_", ","); string eql = string.Empty; if (objType == (int)ObjectType.Tag) { eql = string.Format("START WITH Tag WHERE Class.Id IN ({0})", classIds); } else if (objType == (int)ObjectType.Document) { eql = string.Format("START WITH Document WHERE Class.Id IN ({0})", classIds); } else { throw new Exception(string.Format("Object type [{0}] not supported.", objectType)); } if (filter != null) { string whereClause = Utilities.ToSqlWhereClause(filter, objDef); if (!string.IsNullOrEmpty(whereClause)) { eql += whereClause.Replace(" WHERE ", " AND "); } } EqlClient eqlClient = new EqlClient(session); DataTable dt = eqlClient.RunQuery(eql); return Convert.ToInt64(dt.Rows.Count); } else { throw new Exception(string.Format("Object type [{0}] not found.", objectType)); } } catch (Exception e) { _logger.Error(string.Format("Error getting object count for [{0}]: {1}", objectType, e.Message)); throw e; } finally { Disconnect(ref proxy, ref session); } }
public void GetDataFilterPageSortFull() { DataFilter filter = new DataFilter(); Expression expression = new Expression { PropertyName = "Area", Values = new Values { "90" }, RelationalOperator = RelationalOperator.EqualTo }; filter.Expressions.Add(expression); OrderExpression orderExpression = new OrderExpression { PropertyName = "System", SortOrder = SortOrder.Desc }; filter.OrderExpressions.Add(orderExpression); XDocument benchmark = null; string format = "p7xml"; XDocument xDocument = _adapterProvider.GetWithFilter( _settings["ProjectName"], _settings["ApplicationName"], _settings["GraphName"], filter, ref format, 10, 5, true ); string path = String.Format( "{0}GetXmlDataFilterPageSortFull.xml", _settings["AppDataPath"] ); if (_settings["TestMode"].ToLower() != "usefiles") { xDocument.Save(path); Assert.AreNotEqual(null, xDocument); } else { benchmark = XDocument.Load(path); Assert.AreEqual(benchmark.ToString(), xDocument.ToString()); } int total = 0; if (xDocument.Root.Attribute("total") != null) { int.TryParse(xDocument.Root.Attribute("total").Value, out total); } for (int i = 5; i < total; i += 5) { //the Provider clears the orderExpressions for getCount //not a problem for webservice, but we need to handle it here. filter.OrderExpressions.Add(orderExpression); xDocument = _adapterProvider.GetWithFilter( _settings["ProjectName"], _settings["ApplicationName"], _settings["GraphName"], filter, ref format, i, 5, true ); path = String.Format( "{0}GetXmlDataFilterPageSortFull.{1}.xml", _settings["AppDataPath"], (i / 5) + 1 ); if (_settings["TestMode"].ToLower() != "usefiles") { xDocument.Save(path); Assert.AreNotEqual(null, xDocument); } else { benchmark = XDocument.Load(path); Assert.AreEqual(benchmark.ToString(), xDocument.ToString()); } } }
public override IList<string> GetIdentifiers(string objectType, DataFilter filter) { try { IList<IDataObject> dataObjects = Get(objectType, filter, 0, -1); DataObject objDef = GetObjectDefinition(objectType); IList<string> identifiers = new List<string>(); foreach (IDataObject dataObject in dataObjects) { identifiers.Add(Convert.ToString(dataObject.GetPropertyValue(objDef.keyProperties.First().keyPropertyName))); } return identifiers; } catch (Exception e) { _logger.Error(string.Format("Error getting identifiers of object type [{0}]", objectType)); throw e; } }
public void Api_RoleController_GetUnassignedPermissionsForRole() { TreeMonDbContext context = new TreeMonDbContext(connectionKey); Role role = new Role(); role.AccountUUID = SystemFlag.Default.Account; role.Name = Guid.NewGuid().ToString("N"); role.DateCreated = DateTime.Now; role.EndDate = DateTime.Now; role.StartDate = DateTime.Now; Assert.IsTrue(context.Insert <Role>(role)); Permission assingedPermission = new Permission() { Action = "get", Active = true, Type = "t", AccountUUID = role.AccountUUID, AppType = "appType", Persists = true, StartDate = DateTime.UtcNow, Weight = 0, Key = "get" + Guid.NewGuid().ToString("N"), Name = Guid.NewGuid().ToString("N"), Deleted = false, DateCreated = DateTime.Now, EndDate = DateTime.Now }; context.Insert <Permission>(assingedPermission); RolePermission rolePermission = new RolePermission(); rolePermission.RoleUUID = role.UUID; rolePermission.AccountUUID = role.AccountUUID; rolePermission.PermissionUUID = assingedPermission.UUID; rolePermission.UUID = Guid.NewGuid().ToString("N"); rolePermission.DateCreated = DateTime.Now; context.Insert <RolePermission>(rolePermission); //this is what we want to pull back. Permission unAssignedPermission = new Permission() { Action = "get", Active = true, Type = "t", AccountUUID = SystemFlag.Default.Account, AppType = "appType", Persists = true, StartDate = DateTime.UtcNow, Weight = 0, Key = "get" + Guid.NewGuid().ToString("N"), Name = Guid.NewGuid().ToString("N"), Deleted = false, DateCreated = DateTime.Now, EndDate = DateTime.Now }; context.Insert <Permission>(unAssignedPermission); RolePermission runAssignedRolePermission = new RolePermission(); runAssignedRolePermission.RoleUUID = Guid.NewGuid().ToString("N"); //make up a role id not associated with above role runAssignedRolePermission.AccountUUID = role.AccountUUID; runAssignedRolePermission.PermissionUUID = unAssignedPermission.UUID; runAssignedRolePermission.UUID = Guid.NewGuid().ToString("N"); runAssignedRolePermission.DateCreated = DateTime.Now; context.Insert <RolePermission>(runAssignedRolePermission); Task.Run(async() => { DataFilter filter = new DataFilter(); filter.PageResults = false; ServiceResult res = await TestHelper.SentHttpRequest("GET", "api/Roles/" + role.UUID + "/Permissions/Unassigned/?filter=" + JsonConvert.SerializeObject(filter), "", _ownerAuthToken); Assert.IsNotNull(res); Assert.AreEqual(res.Code, 200); List <Permission> permissions = JsonConvert.DeserializeObject <List <Permission> >(res.Result.ToString()); Assert.IsNotNull(permissions); Assert.IsTrue(permissions.Count >= 1); int foundPermission = 0; int foundUnAssignedPermission = 0; foreach (Permission perm in permissions) { if (perm.Name == assingedPermission.Name && perm.AccountUUID == role.AccountUUID) { foundPermission++; } if (perm.Name == unAssignedPermission.Name) { foundUnAssignedPermission++; } } Assert.AreEqual(foundPermission, 0); //should be zero. We don't want the assinged permission Assert.AreEqual(foundUnAssignedPermission, 1); //should be 1 for the one above, but could be more. }).GetAwaiter().GetResult(); }
public void SetData(NHibernate.ISession session, DataModel.Protein protein, DataFilter viewFilter) { if (session == null) return; this.session = session.SessionFactory.OpenSession(); this.viewFilter = viewFilter; var workerThread = new BackgroundWorker() { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; workerThread.DoWork += setData; if (protein == Protein) workerThread.RunWorkerCompleted += refreshFilter; else workerThread.RunWorkerCompleted += renderData; workerThread.RunWorkerAsync(protein); }
public override IList <IDataObject> Get(string objectType, DataFilter filter, int pageSize, int startIndex) { ISession session = NHibernateSessionManager.Instance.GetSession(_settings["AppDataPath"], _settings["Scope"]); try { if (_databaseDictionary.IdentityConfiguration != null) { IdentityProperties identityProperties = _databaseDictionary.IdentityConfiguration[objectType]; if (identityProperties.UseIdentityFilter) { filter = FilterByIdentity(objectType, filter, identityProperties); } } DataObject objectDefinition = _databaseDictionary.dataObjects.Find(x => x.objectName.ToUpper() == objectType.ToUpper()); if (objectDefinition == null) { throw new Exception("Object type [" + objectType + "] not found."); } string ns = String.IsNullOrEmpty(objectDefinition.objectNamespace) ? String.Empty : (objectDefinition.objectNamespace + "."); Type type = Type.GetType(ns + objectType + ", " + _settings["ExecutingAssemblyName"]); // make an exception for tests if (type == null) { type = Type.GetType(ns + objectType + ", NUnit.Tests"); } ICriteria criteria = NHibernateUtility.CreateCriteria(session, type, objectDefinition, filter); if (pageSize == 0 && startIndex == 0) { List <IDataObject> dataObjects = new List <IDataObject>(); long totalCount = GetCount(objectType, filter); int internalPageSize = (_settings["InternalPageSize"] != null) ? int.Parse(_settings["InternalPageSize"]) : 1000; int numOfRows = 0; while (numOfRows < totalCount) { criteria.SetFirstResult(numOfRows).SetMaxResults(internalPageSize); dataObjects.AddRange(criteria.List <IDataObject>()); numOfRows += internalPageSize; } return(dataObjects); } else { criteria.SetFirstResult(startIndex).SetMaxResults(pageSize); IList <IDataObject> dataObjects = criteria.List <IDataObject>(); return(dataObjects); } } catch (Exception ex) { _logger.Error("Error in Get: " + ex); throw new Exception(string.Format("Error while getting a list of data objects of type [{0}]. {1}", objectType, ex)); } finally { CloseSession(session); } }
/// <summary> /// Group /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void groupToolStripMenuItem_Click(object sender, EventArgs e) { var query = new DataFilter(); Utility.OpenForm(new FrmGroup(query, false), true, true); }
public override IEnumerable <T> Get <T>(DataFilter filter, Pagination pagin) { DataConfigureAttribute custAttribute = DataConfigureAttribute.GetAttribute <T>(); string alias = "T0"; if (custAttribute != null) { filter = custAttribute.MetaData.DataAccess(filter);//数据权限 alias = custAttribute.MetaData.Alias; } string tableName = GetTableName <T>(custAttribute); List <KeyValuePair <string, string> > comMatch; string selectCol = GetSelectColumn <T>(custAttribute, out comMatch); string condition = filter.ToString(); var primaryKey = GetPrimaryKeys(custAttribute); foreach (var item in primaryKey) { filter.OrderBy(string.Format("[{0}].[{1}]", alias, item.ColumnName), OrderType.Ascending); } string orderby = filter.GetOrderString(); string orderByContrary = filter.GetContraryOrderString(); var builderRela = new StringBuilder(); if (custAttribute != null) { foreach (var item in custAttribute.MetaData.DataRelations) { builderRela.Append(item); } } const string formatCount = "SELECT COUNT(*) FROM [{0}] {3} {2} {1}"; DataTable recordCound = this.GetData(string.Format(formatCount, tableName, string.IsNullOrEmpty(condition) ? "" : "WHERE " + condition, builderRela, alias), filter.GetParameterValues()); pagin.RecordCount = Convert.ToInt64(recordCound.Rows[0][0]); if (pagin.AllPage == pagin.PageIndex && pagin.RecordCount > 0) { pagin.PageIndex--; } int pageSize = pagin.PageSize; if ((pagin.PageIndex + 1) * pagin.PageSize > pagin.RecordCount && pagin.RecordCount != 0) { pageSize = (int)(pagin.RecordCount - pagin.PageIndex * pagin.PageSize); if (pageSize < 0) { pageSize = pagin.PageSize; } } var builder = new StringBuilder(); const string formatTable = "SELECT {0} FROM {3} {6} {5} {4} limit {2},{1}"; builder.AppendFormat(formatTable, selectCol, pageSize, pagin.PageSize * pagin.PageIndex, string.Format("[{0}] {1}", tableName, custAttribute == null ? "T0" : custAttribute.MetaData.Alias), orderby, string.IsNullOrEmpty(condition) ? "" : "WHERE " + condition, builderRela, orderByContrary.Replace("[{0}].".FormatWith(alias), ""), orderby.Replace("[{0}].".FormatWith(alias), "")); DataTable table = this.GetData(builder.ToString(), filter.GetParameterValues()); if (table == null) { return(new List <T>()); } ; var list = new List <T>(); Dictionary <string, PropertyInfo> properties = GetProperties <T>(custAttribute); for (int i = 0; i < table.Rows.Count; i++) { list.Add(Reflection.ClassAction.GetModel <T>(table, i, comMatch, properties)); } return(list); }
public void SetData (NHibernate.ISession session, DataModel.Protein protein, DataFilter viewFilter) { Text = protein.Accession; control.SetData(session, protein, viewFilter); }
/// <summary> /// Gets the events ordered by timestamp. /// </summary> public abstract List <Event> GetEvents(TimeRange timeRange, DataFilter filter);
public override long GetCount(string objectType, DataFilter filter) { try { Connect(); //NOTE: pageSize of 0 indicates that all rows should be returned. //IList<IDataObject> dataObjects = Get(objectType, filter, 0, 0); //return dataObjects.Count(); return 5; } catch (Exception ex) { _logger.Error("Error in GetIdentifiers: " + ex); throw new Exception( "Error while getting a count of type [" + objectType + "].", ex ); } }
public FilterVM(DataFilter filter) { // call (deep) copy constructor this.filter = new DataFilter(filter); }
private DataFilter FilterByIdentity(string objectType, DataFilter filter, IdentityProperties identityProperties) { DataObject dataObject = _databaseDictionary.dataObjects.Find(d => d.objectName == objectType); DataProperty dataProperty = dataObject.dataProperties.Find(p => p.columnName == identityProperties.IdentityProperty); if (dataProperty != null) { if (filter == null) { filter = new DataFilter(); } //bool hasExistingExpression = false; if (filter.Expressions == null) { filter.Expressions = new List<org.iringtools.library.Expression>(); } else if (filter.Expressions.Count > 0) { org.iringtools.library.Expression firstExpression = filter.Expressions.First(); org.iringtools.library.Expression lastExpression = filter.Expressions.Last(); firstExpression.OpenGroupCount++; lastExpression.CloseGroupCount++; //hasExistingExpression = true; } //string identityValue = _keyRing[identityProperties.KeyRingProperty].ToString(); //org.iringtools.library.Expression expression = new org.iringtools.library.Expression //{ // PropertyName = dataProperty.propertyName, // RelationalOperator = RelationalOperator.EqualTo, // Values = new Values // { // identityValue, // }, // IsCaseSensitive = identityProperties.IsCaseSensitive //}; //if (hasExistingExpression) // expression.LogicalOperator = LogicalOperator.And; //filter.Expressions.Add(expression); } return filter; }
private void BindChart() { ConnDB conn = new ConnDB(); string strsql, strsql2, month; int deptid; deptid = (int)comboBoxDept.SelectedValue; List <Series> myseries = new List <Series>(); month = dateTimePicker1.Text.ToString(); if (deptid == 0) { strsql = "select SALE_TYPE_NAME 营业类型,dept_name 部门,Cdate 日期,DIRECT_HOURS 直接人工小时数,cast(round(DIRECT_COST, 2) as decimal(18, 2)) 直接人工成本,TEMP_HOURS 临时工小时数,cast(round(TEMP_COST, 2) as decimal(18, 2)) 临时工成本,INDIRECT_HOURS 间接人工小时数,cast(round(INDIRECT_COST, 2) as decimal(18, 2)) 间接人工成本,cast(round(POINTCOUNT, 2) as decimal(18, 2)) 产出台数,cast(round(COST, 2) as decimal(18, 2)) 预估成本,COST_POINT 预估单台成本,STANDARD_POINT 标准单台成本,cast(round(isnull(STANDARD_COST,0), 2) as decimal(18, 2)) 标准成本,cast(round(PROFIT, 2) as decimal(18, 2)) 盈亏 from COST_DEPT_CALCULATE where cdate like '" + month + "%' and sale_type_id =14"; strsql2 = "select distinct dept_name 部门 from COST_DEPT_CALCULATE where cdate like '" + month + "%' and sale_type_id =14"; } else { strsql = "select SALE_TYPE_NAME 营业类型,dept_name 部门,Cdate 日期,DIRECT_HOURS 直接人工小时数,cast(round(DIRECT_COST, 2) as decimal(18, 2)) 直接人工成本,TEMP_HOURS 临时工小时数,cast(round(TEMP_COST, 2) as decimal(18, 2)) 临时工成本,INDIRECT_HOURS 间接人工小时数,cast(round(INDIRECT_COST, 2) as decimal(18, 2)) 间接人工成本,cast(round(POINTCOUNT, 2) as decimal(18, 2)) 产出台数,cast(round(COST, 2) as decimal(18, 2)) 预估成本,COST_POINT 预估单台成本,STANDARD_POINT 标准单台成本,cast(round(isnull(STANDARD_COST,0), 2) as decimal(18, 2)) 标准成本,cast(round(PROFIT, 2) as decimal(18, 2)) 盈亏 from COST_DEPT_CALCULATE where cdate like '" + month + "%' and sale_type_id =14 and dept_id =" + deptid; strsql2 = "select distinct dept_name 部门 from COST_DEPT_CALCULATE where cdate like '" + month + "%' and sale_type_id =14 and dept_id = " + deptid; } DataSet ds = conn.ReturnDataSet(strsql); DataTable dt = ds.Tables[0]; DataSet ds2 = conn.ReturnDataSet(strsql2); XYDiagram dg = (XYDiagram)chartControlDeptDay.Diagram; if (dg != null) { dg.Panes.Clear(); } chartControlDeptDay.Series.Clear(); chartControlDeptDay.Annotations.Clear(); chartControlDeptDay.DataSource = dt; for (int i = 0; i < ds2.Tables[0].Rows.Count; i++) { //预估成本 myseries.Add(new Series(ds2.Tables[0].Rows[i][0].ToString() + "预估单台成本", DevExpress.XtraCharts.ViewType.Spline)); myseries[i * 2].ArgumentDataMember = dt.Columns["日期"].ToString(); myseries[i * 2].ValueDataMembersSerializable = dt.Columns["预估单台成本"].ToString(); chartControlDeptDay.Series.Add(myseries[i * 2]); //标准成本 myseries.Add(new Series(ds2.Tables[0].Rows[i][0].ToString() + "标准单台成本", DevExpress.XtraCharts.ViewType.Spline)); myseries[i * 2 + 1].ArgumentDataMember = dt.Columns["日期"].ToString(); myseries[i * 2 + 1].ValueDataMembersSerializable = dt.Columns["标准单台成本"].ToString(); chartControlDeptDay.Series.Add(myseries[i * 2 + 1]); //设置过滤 DataFilter df = new DataFilter("部门", "System.String", DataFilterCondition.Equal, ds2.Tables[0].Rows[i][0].ToString()); //series1.DataFiltersConjunctionMode = ConjunctionTypes.Or; myseries[i * 2].DataFilters.Clear(); myseries[i * 2].DataFilters.AddRange(new DataFilter[] { df }); myseries[i * 2 + 1].DataFilters.Clear(); myseries[i * 2 + 1].DataFilters.AddRange(new DataFilter[] { df }); //设置pane XYDiagram diagram = (XYDiagram)chartControlDeptDay.Diagram; if (i > 0) { //// Add secondary axes to the diagram, and adjust their options. //diagram.SecondaryAxesX.Add(new SecondaryAxisX(Convert.ToString(i - 1))); //diagram.SecondaryAxesY.Add(new SecondaryAxisY(Convert.ToString(i - 1))); //diagram.SecondaryAxesX[i - 1].Alignment = AxisAlignment.Near; //diagram.SecondaryAxesY[i - 1].Alignment = AxisAlignment.Near; //diagram.Panes[ds2.Tables[0].Rows[i][0].ToString()] diagram.Panes.Add(new XYDiagramPane(ds2.Tables[0].Rows[i][0].ToString())); SplineSeriesView myView1 = (SplineSeriesView)myseries[i * 2].View; //myView1.AxisX = diagram.SecondaryAxesX[i - 1]; //myView1.AxisY = diagram.SecondaryAxesY[i - 1]; myView1.Pane = diagram.Panes[i - 1]; SplineSeriesView myView2 = (SplineSeriesView)myseries[i * 2 + 1].View; //myView2.AxisX = diagram.SecondaryAxesX[i - 1]; //myView2.AxisY = diagram.SecondaryAxesY[i - 1]; myView2.Pane = diagram.Panes[i - 1]; chartControlDeptDay.Annotations.AddTextAnnotation(Convert.ToString(i)); XYDiagramPaneBase myPane = diagram.Panes[i - 1]; ((FreePosition)chartControlDeptDay.Annotations[i].ShapePosition).DockTarget = diagram.Panes[i - 1]; ((FreePosition)chartControlDeptDay.Annotations[i].ShapePosition).DockCorner = DockCorner.LeftTop; TextAnnotation myTextAnnotation = (TextAnnotation)chartControlDeptDay.AnnotationRepository.GetElementByName(Convert.ToString(i)); //myTextAnnotation.Text = "<color=red>" + ds2.Tables[0].Rows[i][0].ToString() + " </color>"; myTextAnnotation.Text = ds2.Tables[0].Rows[i][0].ToString(); myTextAnnotation.ShapeKind = ShapeKind.Rectangle; myTextAnnotation.ConnectorStyle = AnnotationConnectorStyle.None; } else { chartControlDeptDay.Annotations.AddTextAnnotation("Annotation 0"); XYDiagramPaneBase myPane = diagram.DefaultPane; ((FreePosition)chartControlDeptDay.Annotations[i].ShapePosition).DockTarget = myPane; ((FreePosition)chartControlDeptDay.Annotations[i].ShapePosition).DockCorner = DockCorner.LeftTop; TextAnnotation myTextAnnotation = (TextAnnotation)chartControlDeptDay.AnnotationRepository.GetElementByName("Annotation 0"); //myTextAnnotation.Text = "<color=red>" + ds2.Tables[0].Rows[i][0].ToString() + " </color>"; myTextAnnotation.Text = ds2.Tables[0].Rows[i][0].ToString(); myTextAnnotation.ShapeKind = ShapeKind.Rectangle; myTextAnnotation.ConnectorStyle = AnnotationConnectorStyle.None; } ((SplineSeriesView)myseries[i * 2].View).MarkerVisibility = DefaultBoolean.True; ((SplineSeriesView)myseries[i * 2 + 1].View).MarkerVisibility = DefaultBoolean.True; ((SplineSeriesView)myseries[i * 2].View).Color = Color.Orange; ((SplineSeriesView)myseries[i * 2 + 1].View).Color = Color.OliveDrab; ((FreePosition)chartControlDeptDay.Annotations[i].ShapePosition).InnerIndents.All = 0; ((FreePosition)chartControlDeptDay.Annotations[i].ShapePosition).OuterIndents.Top = 10; diagram.PaneDistance = 10; diagram.PaneLayoutDirection = PaneLayoutDirection.Vertical; diagram.DefaultPane.SizeMode = PaneSizeMode.UseWeight; diagram.DefaultPane.Weight = 1.2; } //外观 chartControlDeptDay.Legend.Visibility = DefaultBoolean.True; chartControlDeptDay.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center; chartControlDeptDay.Legend.AlignmentVertical = LegendAlignmentVertical.TopOutside; chartControlDeptDay.Legend.Direction = LegendDirection.LeftToRight; conn.Close(); }
public void Api_RoleController_GetUnassignedUsersForRole() { TreeMonDbContext context = new TreeMonDbContext(connectionKey); //add user to a role (we don't want to get this back Role role = new Role(); role.AccountUUID = SystemFlag.Default.Account; role.Name = Guid.NewGuid().ToString("N"); role.DateCreated = DateTime.Now; role.EndDate = DateTime.Now; role.StartDate = DateTime.Now; Assert.IsTrue(context.Insert <Role>(role)); User user = TestHelper.GenerateTestUser(Guid.NewGuid().ToString("N")); Assert.IsTrue(context.Insert <User>(user)); UserRole userRole = new UserRole(); userRole.RoleUUID = role.UUID; userRole.UUID = Guid.NewGuid().ToString("N"); userRole.AccountUUID = role.AccountUUID; userRole.UserUUID = user.UUID; userRole.DateCreated = DateTime.Now; userRole.EndDate = DateTime.Now; userRole.StartDate = DateTime.Now; Assert.IsTrue(context.Insert <UserRole>(userRole)); AccountMember am = new AccountMember() { AccountUUID = role.AccountUUID, MemberUUID = user.UUID, UUID = Guid.NewGuid().ToString("N") }; Assert.IsTrue(context.Insert <AccountMember>(am)); //this is what we want to pull back. User unAssignedUser = TestHelper.GenerateTestUser(Guid.NewGuid().ToString("N")); Assert.IsTrue(context.Insert <User>(unAssignedUser)); AccountMember uam = new AccountMember() { AccountUUID = role.AccountUUID, MemberUUID = unAssignedUser.UUID, UUID = Guid.NewGuid().ToString("N") }; Assert.IsTrue(context.Insert <AccountMember>(uam)); UserRole unAssigneduserRole = new UserRole(); unAssigneduserRole.RoleUUID = Guid.NewGuid().ToString("N"); unAssigneduserRole.UUID = Guid.NewGuid().ToString("N"); unAssigneduserRole.AccountUUID = role.AccountUUID; unAssigneduserRole.UserUUID = unAssignedUser.UUID; unAssigneduserRole.Name = Guid.NewGuid().ToString("N");; unAssigneduserRole.DateCreated = DateTime.Now; unAssigneduserRole.EndDate = DateTime.Now; unAssigneduserRole.StartDate = DateTime.Now; Assert.IsTrue(context.Insert <UserRole>(unAssigneduserRole)); Task.Run(async() => { DataFilter filter = new DataFilter(); filter.PageResults = false; ServiceResult res = await TestHelper.SentHttpRequest("GET", "api/Roles/" + role.UUID + "/Users/Unassigned/?filter=" + JsonConvert.SerializeObject(filter), "", _ownerAuthToken); Assert.IsNotNull(res); Assert.AreEqual(res.Code, 200); List <User> users = JsonConvert.DeserializeObject <List <User> >(res.Result.ToString()); Assert.IsNotNull(users); Assert.IsTrue(users.Count >= 1); int foundUser = 0; int foundUnAssignedUser = 0; foreach (User tmpUser in users) { if (tmpUser.Name == userRole.Name && tmpUser.AccountUUID == role.AccountUUID) { foundUser++; } if (tmpUser.UUID == unAssigneduserRole.UserUUID) { foundUnAssignedUser++; } } Assert.AreEqual(foundUser, 0); //should be zero. We don't want the assinged permission Assert.AreEqual(foundUnAssignedUser, 1); //should be 1 for the one above, but could be more. }).GetAwaiter().GetResult(); }
private AccessLevel Authorize(string objectType) { DataFilter dataFilter = new DataFilter(); return(Authorize(objectType, ref dataFilter)); }