public void CreateUpdateReadDelete() { Document doc; DateTime?initVersion; using (IStatelessSession ss = sessions.OpenStatelessSession()) { ITransaction tx; using (tx = ss.BeginTransaction()) { doc = new Document("blah blah blah", "Blahs"); ss.Insert(doc); Assert.IsNotNull(doc.LastModified); initVersion = doc.LastModified; Assert.IsTrue(initVersion.HasValue); tx.Commit(); } Thread.Sleep(100); // Only to be secure that next modification have a different version using (tx = ss.BeginTransaction()) { doc.Text = "blah blah blah .... blah"; ss.Update(doc); Assert.IsTrue(doc.LastModified.HasValue); Assert.AreNotEqual(initVersion, doc.LastModified); tx.Commit(); } using (tx = ss.BeginTransaction()) { doc.Text = "blah blah blah .... blah blay"; ss.Update(doc); tx.Commit(); } var doc2 = ss.Get <Document>("Blahs"); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = (Document)ss.CreateQuery("from Document where text is not null").UniqueResult(); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = (Document)ss.CreateSQLQuery("select * from Document").AddEntity(typeof(Document)).UniqueResult(); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = ss.CreateCriteria <Document>().UniqueResult <Document>(); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = (Document)ss.CreateCriteria(typeof(Document)).UniqueResult(); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); using (tx = ss.BeginTransaction()) { ss.Delete(doc); tx.Commit(); } } }
public async Task CreateUpdateReadDeleteAsync() { Document doc; DateTime?initVersion; using (IStatelessSession ss = Sfi.OpenStatelessSession()) { ITransaction tx; using (tx = ss.BeginTransaction()) { doc = new Document("blah blah blah", "Blahs"); await(ss.InsertAsync(doc)); Assert.IsNotNull(doc.LastModified); initVersion = doc.LastModified; Assert.IsTrue(initVersion.HasValue); await(tx.CommitAsync()); } await(Task.Delay(1100)); // Ensure version increment (some dialects lack fractional seconds). using (tx = ss.BeginTransaction()) { doc.Text = "blah blah blah .... blah"; await(ss.UpdateAsync(doc)); Assert.IsTrue(doc.LastModified.HasValue); Assert.AreNotEqual(initVersion, doc.LastModified); await(tx.CommitAsync()); } using (tx = ss.BeginTransaction()) { doc.Text = "blah blah blah .... blah blay"; await(ss.UpdateAsync(doc)); await(tx.CommitAsync()); } var doc2 = await(ss.GetAsync <Document>("Blahs")); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = (Document)await(ss.CreateQuery("from Document where text is not null").UniqueResultAsync()); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = (Document)await(ss.CreateSQLQuery("select * from Document").AddEntity(typeof(Document)).UniqueResultAsync()); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = await(ss.CreateCriteria <Document>().UniqueResultAsync <Document>()); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); doc2 = (Document)await(ss.CreateCriteria(typeof(Document)).UniqueResultAsync()); Assert.AreEqual("Blahs", doc2.Name); Assert.AreEqual(doc.Text, doc2.Text); using (tx = ss.BeginTransaction()) { await(ss.DeleteAsync(doc)); await(tx.CommitAsync()); } } }
public ICriteria CreateCriteria(Type persistentClass, string alias) { if (_isStateless) { return(_wrapStateless.CreateCriteria(persistentClass, alias)); } else { return(_wrap.CreateCriteria(persistentClass, alias)); } }
public IAggregateRoot LoadById(Guid id) { DetachedCriteria boundaryCriteria = DetachedCriteria.For <Event>() .SetProjection(Projections.Id()) .Add(Expression.Eq("IsSnapshot", true)) .Add(Expression.Eq("EntityId", id)) .AddOrder(new Order("SequenceNumber", false)) .SetFirstResult(0) .SetMaxResults(1); ICriteria criteria = _readSession.CreateCriteria(typeof(Event)) .Add(Expression.Eq("EntityId", id)) .Add(Subqueries.PropertyGe("SequenceNumber", boundaryCriteria)) .AddOrder(new Order("SequenceNumber", true)); IList <Event> events = criteria.List <Event>(); if (events.Count < 1) { throw new ArgumentException(string.Format("Entity with id {0} not found.", id)); } IAggregateRoot lastSnapshot = (IAggregateRoot)events[0].Data; lastSnapshot.Id = id; lastSnapshot.LoadFromEventStream(events.Skip(1).Select(x => x.Data)); lastSnapshot.Version = events.Last().Version; _trackedObjects.Add(lastSnapshot); return(lastSnapshot); }
private async Task <IList <HourlyAccmofMeasurement> > DailyQuery(IStatelessSession session, DateTime date, IEnumerable <int> Siteids) { var result = await session.CreateCriteria <HourlyAccmofMeasurement>() .Add(Restrictions.Eq("Createdt", date.Date) && Restrictions.In("Siteid", Siteids.ToArray())).ListAsync <HourlyAccmofMeasurement>(); return(result); }
public TEntity GetSessionless(object primaryKey) { using (IStatelessSession statelessSesssion = Session.SessionFactory.OpenStatelessSession()) { Type type = typeof(TEntity); // Getting the id property string idName = GetIdName(type); var criteria = statelessSesssion.CreateCriteria <TEntity>(); string[] propertiesArray = type.GetProperties().Select(pi => pi.Name).ToArray(); bool needsDistinct = false; foreach (string property in propertiesArray) { if (IsPropertyMapped(type, property) && IsPropertyAssociation(type, property)) { criteria = criteria.SetFetchMode(property, FetchMode.Join); needsDistinct = true; } } criteria = criteria.Add(NHibernate.Criterion.Restrictions.Eq(idName, primaryKey)); if (needsDistinct) { criteria = criteria.SetResultTransformer(NHibernate.Transform.Transformers.DistinctRootEntity); //porque isso nao funciona? } var list = criteria.List <TEntity>(); return(list.Distinct().SingleOrDefault()); } }
/// <summary> /// Returns a portion of the query results (sliced) using IStatelessSession. /// </summary> /// <param name="type">The target type.</param> /// <param name="firstRow">The number of the first row to retrieve.</param> /// <param name="maxRows">The maximum number of results retrieved.</param> /// <returns>The <see cref="Array"/> of results</returns> public virtual Array FindAllStateless(Type type, int firstRow, int maxRows) { IStatelessSession session = GetStatelessSession(); { try { ICriteria criteria = session.CreateCriteria(type); if (firstRow != int.MinValue) { criteria.SetFirstResult(firstRow); } if (maxRows != int.MinValue) { criteria.SetMaxResults(maxRows); } IList result = criteria.List(); Array array = Array.CreateInstance(type, result.Count); result.CopyTo(array, 0); return(array); } catch (Exception ex) { throw new DataException("Could not perform FindAllStateless for " + type.Name, ex); } } }
public IEnumerable <Document> GetAllItems() { foreach (Type universalSearchItemType in GetUniversalSearchItemTypes.Keys.OrderByDescending(type => type.FullName)) { using (MiniProfiler.Current.Step("Getting " + universalSearchItemType.FullName)) { var objects = new HashSet <object>(); using (MiniProfiler.Current.Step("Loading objects " + universalSearchItemType.Name)) { Type type = universalSearchItemType; var criteria = _session.CreateCriteria(universalSearchItemType); if (typeof(SiteEntity).IsAssignableFrom(type)) { criteria = criteria.Add(Restrictions.Eq("Site.Id", _site.Id)); } objects.AddRange( criteria .Add(Restrictions.Eq("IsDeleted", false)) .SetCacheable(true) .List() .Cast <object>() .Where(o => o.GetType() == type)); } foreach ( var generateDocument in GenerateDocuments(objects.OfType <SystemEntity>().ToHashSet(), universalSearchItemType)) { yield return(generateDocument); } } } }
/// <summary> /// Get an object from single item table /// </summary> /// <typeparam name="T">Object type to get</typeparam> /// <param name="session">The NHibernate session.</param> /// <param name="lockMode">The lock mode.</param> /// <returns></returns> public static T GetSingleObject <T>(this IStatelessSession session, LockMode lockMode) where T : class { return(session.CreateCriteria <T>() .SetLockMode(lockMode) .UniqueResult <T>()); }
private async Task <IList <DailyActualRevenue> > MonthlyQuery(IStatelessSession session, DateTime date, IEnumerable <int> siteIds) { var result = await session.CreateCriteria <DailyActualRevenue>() .Add(Restrictions.Where <DailyActualRevenue>(x => x.Createdt.Year == date.Year && x.Createdt.Month == date.Month)) .Add(Restrictions.In("Siteid", siteIds.ToArray())).ListAsync <DailyActualRevenue>(); return(result); }
private async Task <IList <DailyAccmofMeasurement> > MonthlyQuery(IStatelessSession session, int year, int month, IEnumerable <int> Siteids) { var result = await session.CreateCriteria <DailyAccmofMeasurement>() .Add(Restrictions.Where <DailyAccmofMeasurement>(x => x.Createdt.Year == year && x.Createdt.Month == month)) .Add(Restrictions.In("Siteid", Siteids.ToArray())).ListAsync <DailyAccmofMeasurement>(); return(result); }
private async Task <IList <HourlyActualRevenue> > DailyQuery(IStatelessSession session, DateTime date, IEnumerable <int> siteIds) { var result = await session.CreateCriteria <HourlyActualRevenue>() .Add(Restrictions.Eq("Createdt", date.Date) && Restrictions.In("Siteid", siteIds.ToArray())) .AddOrder(new Order("Revenue", false)) .ListAsync <HourlyActualRevenue>(); return(result); }
public async Task <IActionResult> GetHubbubDeviceInformation() { using (IStatelessSession session = sessionFactory.OpenStatelessSession()) { var hubbub = await session.CreateCriteria <ModbusHubbub>().ListAsync <ModbusHubbub>(); return(Ok(hubbub)); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { using (IStatelessSession session = mysqlDataAccess.GetStatelessSession()) using (var transaction = session.BeginTransaction()) { var command = await session.CreateCriteria <TbCommand>() // .Add(Restrictions.Ge("date", "2019-10-01 15:18:00")) // .AddOrder(NHibernate.Criterion.Order.Desc("date")) .UniqueResultAsync <TbCommand>(); if (command == null || command.Date == LastReadingCommandDate) { /// 제어 명령이 없으면 SOC 프로텍션 기능 실행 await SOCProtectFunction(stoppingToken); continue; } LastReadingCommandDate = command.Date; _logger.LogInformation($"command pcs1: {command.Ess1} pcs2: {command.Ess2} pcs3: {command.Ess3} pcs4: {command.Ess4}"); /// 1단계 SOC 내의 명령인지 체크 bool[] ValidSocs = new bool[] { await ValidatingSOC(1, command.Ess1), await ValidatingSOC(2, command.Ess2), await ValidatingSOC(3, command.Ess3), await ValidatingSOC(4, command.Ess4) }; bool pcs1_ok = ValidSocs[0]; bool pcs2_ok = ValidSocs[1]; bool pcs3_ok = ValidSocs[2]; bool pcs4_ok = ValidSocs[3]; await SendCommandWhenOK(ValidSocs[0], 1, command.Ess1, stoppingToken); await SendCommandWhenOK(ValidSocs[1], 2, command.Ess2, stoppingToken); await SendCommandWhenOK(ValidSocs[2], 3, command.Ess3, stoppingToken); await SendCommandWhenOK(ValidSocs[3], 4, command.Ess4, stoppingToken); await Task.Delay(1000, stoppingToken); } } catch (Exception ex) { _logger.LogError(ex, ex.Message); } } }
public void Criteria() { var testData = new TestData(Sfi); testData.createData(); using (IStatelessSession s = Sfi.OpenStatelessSession()) { Assert.AreEqual(1, s.CreateCriteria<Contact>().List().Count); } testData.cleanData(); }
public void CriteriaWithSelectFetchMode() { var testData = new TestData(Sfi); testData.createData(); using (IStatelessSession s = Sfi.OpenStatelessSession()) { Assert.AreEqual(1, s.CreateCriteria<Contact>().Fetch(SelectMode.Skip, "Org").List().Count); } testData.cleanData(); }
public void CriteriaWithSelectFetchMode() { var testData = new TestData(sessions); testData.createData(); using (IStatelessSession s = sessions.OpenStatelessSession()) { Assert.AreEqual(1, s.CreateCriteria <Contact>().SetFetchMode("Org", FetchMode.Select).List().Count); } testData.cleanData(); }
public async Task CriteriaAsync() { var testData = new TestData(Sfi); await(testData.createDataAsync()); using (IStatelessSession s = Sfi.OpenStatelessSession()) { Assert.AreEqual(1, (await(s.CreateCriteria <Contact>().ListAsync())).Count); } await(testData.cleanDataAsync()); }
//protected override async Task ExecuteAsync(CancellationToken stoppingToken) //{ // while(true) // { // stoppingToken.ThrowIfCancellationRequested(); // if (stoppingToken.IsCancellationRequested) // break; // if(DateTime.Now > NextRetriveForecastDate) // { // await UploadingForecastWeather(stoppingToken); // NextRetriveForecastDate = DateTime.Now.Date.AddDays(1); // } // if (DateTime.Now > NextRetriveTime) // { // await UploadingCurrentWeather(stoppingToken); // NextRetriveTime = DateTime.Now.Add(RefreshRate); // } // await Task.Delay(10); // } //} //private async void SaveRedis(List<Currentweather> results) //{ // foreach(Currentweather weather in results) // { // string redisKey = "weather.sid" + weather.Siteid; // HashEntry[] hashEntries = ConvertHashEntry<Currentweather>(weather, "ID"); // await redisDb.HashSetAsync(redisKey, hashEntries); // } //} //private HashEntry[] ConvertHashEntry<T>(T src, params string[] MissingFields) //{ // List<HashEntry> hashEntries = new List<HashEntry>(); // foreach(var pi in typeof(T).GetProperties()) // { // if (MissingFields.Contains(pi.Name)) // continue; // object value = pi.GetValue(src, null); // if (value != null) // { // HashEntry hashEntry = new HashEntry(pi.Name, value.ToString()); // hashEntries.Add(hashEntry); // } // } // return hashEntries.ToArray(); //} private async Task Clear(IStatelessSession session, CancellationToken token) { var results = await session.CreateCriteria <ForecastWeather>().ListAsync <ForecastWeather>(); int cnt = 0; foreach (ForecastWeather responseWeather in results) { await session.Query <ForecastWeather>().DeleteAsync(token); cnt++; } Logging($"All removed exist forecast weather ({cnt})"); }
/// <summary> /// Adds the chunk if not exists. /// </summary> /// <param name="session">The session.</param> /// <param name="chunk">The chunk.</param> /// <returns>True if the chunk already exists and this chunk is not /// inserted.</returns> public static bool AddChunkIfNotExists(IStatelessSession session, DataChunk chunk) { ICriteria crit = session.CreateCriteria(typeof(DataChunk)); ICriterion hashEq = Expression.Eq("Hash", chunk.Hash); crit.Add(hashEq); if ((DataChunk)crit.UniqueResult() == null) { // Save if no duplicate is found. session.Insert(chunk); return false; } else { return true; } }
/// <summary> /// Returns all instances found for the specified type /// using criteria and IStatelessSession. /// </summary> /// <param name="type">The target type.</param> /// <param name="criterias">The criteria expression</param> /// <param name="sortItems">An <see cref="Array"/> of <see cref="Order"/> objects.</param> /// <param name="firstRow">The number of the first row to retrieve.</param> /// <param name="maxRows">The maximum number of results retrieved.</param> /// <returns>The <see cref="Array"/> of results.</returns> public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[] sortItems, int firstRow, int maxRows) { using (IStatelessSession session = GetStatelessSession()) { try { ICriteria criteria = session.CreateCriteria(type); if (criterias != null) { foreach (ICriterion cond in criterias) { criteria.Add(cond); } } if (sortItems != null) { foreach (Order order in sortItems) { criteria.AddOrder(order); } } if (firstRow != int.MinValue) { criteria.SetFirstResult(firstRow); } if (maxRows != int.MinValue) { criteria.SetMaxResults(maxRows); } IList result = criteria.List(); Array array = Array.CreateInstance(type, result.Count); result.CopyTo(array, 0); return(array); } catch (Exception ex) { throw new DataException("Could not perform FindAllStateless for " + type.Name, ex); } } }
/// <summary> /// Adds the chunk if not exists. /// </summary> /// <param name="session">The session.</param> /// <param name="chunk">The chunk.</param> /// <returns>True if the chunk already exists and this chunk is not /// inserted.</returns> public static bool AddChunkIfNotExists(IStatelessSession session, DataChunk chunk) { ICriteria crit = session.CreateCriteria(typeof(DataChunk)); ICriterion hashEq = Expression.Eq("Hash", chunk.Hash); crit.Add(hashEq); if ((DataChunk)crit.UniqueResult() == null) { // Save if no duplicate is found. session.Insert(chunk); return(false); } else { return(true); } }
public void AddFastaFile(StreamReader reader, IProgressMonitor progressMonitor, ref IProgressStatus status, bool delayAnalyzeDb, out int duplicateSequenceCount) { Dictionary <string, ProtIdNames> proteinIds = new Dictionary <string, ProtIdNames>(); using (IStatelessSession session = SessionFactory.OpenStatelessSession()) // This is a long session, but there's no harm since db is useless till its done { var proteinNames = session.CreateCriteria <DbProteinName>().List <DbProteinName>().ToLookup(name => name.Id.Value); foreach (DbProtein protein in session.CreateCriteria(typeof(DbProtein)).List()) { if (protein.Id.HasValue) { proteinIds.Add(protein.Sequence, new ProtIdNames(protein.Id.Value, proteinNames[protein.Id.Value].ToArray())); } } int proteinCount = 0; duplicateSequenceCount = 0; using (var transaction = session.BeginTransaction()) using (IDbCommand insertProtein = session.Connection.CreateCommand()) using (IDbCommand insertName = session.Connection.CreateCommand()) { WebEnabledFastaImporter fastaImporter = new WebEnabledFastaImporter(new WebEnabledFastaImporter.DelayedWebSearchProvider()); // just parse, no search for now insertProtein.CommandText = @"INSERT INTO ProteomeDbProtein (Version, Sequence) Values (1,?);select last_insert_rowid();"; insertProtein.Parameters.Add(new SQLiteParameter()); insertName.CommandText = @"INSERT INTO ProteomeDbProteinName (Version, Protein, IsPrimary, Name, Description, PreferredName, Accession, Gene, Species, WebSearchStatus) Values(1,?,?,?,?,?,?,?,?,?)"; insertName.Parameters.Add(new SQLiteParameter()); // Id insertName.Parameters.Add(new SQLiteParameter()); // IsPrimary insertName.Parameters.Add(new SQLiteParameter()); // Name insertName.Parameters.Add(new SQLiteParameter()); // Description insertName.Parameters.Add(new SQLiteParameter()); // PreferredName insertName.Parameters.Add(new SQLiteParameter()); // Accession insertName.Parameters.Add(new SQLiteParameter()); // Gene insertName.Parameters.Add(new SQLiteParameter()); // Species insertName.Parameters.Add(new SQLiteParameter()); // WebSearchInfo foreach (DbProtein protein in fastaImporter.Import(reader)) { int iProgress = (int)(reader.BaseStream.Position * 100 / (reader.BaseStream.Length + 1)); if (!UpdateProgressAndCheckForCancellation(progressMonitor, ref status, string.Format(Resources.ProteomeDb_AddFastaFile_Added__0__proteins, proteinCount), iProgress)) { return; } bool existingProtein = false; ProtIdNames proteinIdNames; if (proteinIds.TryGetValue(protein.Sequence, out proteinIdNames)) { existingProtein = true; duplicateSequenceCount++; } else { ((SQLiteParameter)insertProtein.Parameters[0]).Value = protein.Sequence; proteinIdNames = new ProtIdNames(Convert.ToInt64(insertProtein.ExecuteScalar()), new DbProteinName[0]); proteinIds.Add(protein.Sequence, proteinIdNames); proteinCount++; } foreach (var proteinName in protein.Names) { // Skip any names that already exist if (proteinIdNames.Names.Any(dbProteinName => Equals(dbProteinName.Name, proteinName.Name))) { continue; } try { ((SQLiteParameter)insertName.Parameters[0]).Value = proteinIdNames.Id; ((SQLiteParameter)insertName.Parameters[1]).Value = proteinName.IsPrimary && !existingProtein; ((SQLiteParameter)insertName.Parameters[2]).Value = proteinName.Name; ((SQLiteParameter)insertName.Parameters[3]).Value = proteinName.Description; ((SQLiteParameter)insertName.Parameters[4]).Value = proteinName.PreferredName; ((SQLiteParameter)insertName.Parameters[5]).Value = proteinName.Accession; ((SQLiteParameter)insertName.Parameters[6]).Value = proteinName.Gene; ((SQLiteParameter)insertName.Parameters[7]).Value = proteinName.Species; ((SQLiteParameter)insertName.Parameters[8]).Value = proteinName.WebSearchStatus; // represent as a string for ease of serialization insertName.ExecuteNonQuery(); } catch (Exception exception) { Console.Out.WriteLine(exception); } } } if (!UpdateProgressAndCheckForCancellation(progressMonitor, ref status, Resources.ProteomeDb_AddFastaFile_Saving_changes, 99)) { return; } if (HasSubsequencesTable(() => session.Connection)) { DigestProteins(session.Connection, proteinIds, progressMonitor, ref status); } if (progressMonitor.IsCanceled) { return; } transaction.Commit(); } if (!delayAnalyzeDb) { AnalyzeDb(session.Connection); // NB This runs asynchronously and may interfere with further writes } UpdateProgressAndCheckForCancellation(progressMonitor, ref status, string.Format(Resources.ProteomeDb_AddFastaFile_Finished_importing__0__proteins, proteinCount), 100); } }
private async Task <T> GetIdentifiedObjectAsync <T>(int id, IStatelessSession session) where T : class { var modbusHubbubs = await session.CreateCriteria <T>().Add(Restrictions.Eq("Id", id)).UniqueResultAsync <T>(); return(modbusHubbubs); }
//private async Task<List<HubbubAnalogMappingTemplate>> GetAnalogTemplateListAsync(int siteid, IStatelessSession session) //{ // ICriterion expression = Restrictions.Eq("Siteid", siteid); // List<HubbubAnalogMappingTemplate> results = new List<HubbubAnalogMappingTemplate>(); // var modbusHubbubs = await session.CreateCriteria<ModbusHubbub>(). // Add(expression) // .ListAsync<ModbusHubbub>(); // foreach (ModbusHubbub modbusHubbub in modbusHubbubs) // { // var template = await GetAnalogModbusHubbubAsync(modbusHubbub, session); // results.Add(template); // } // return results; //} //private async Task<HubbubAnalogMappingTemplate> GetAnalogTemplateAsync(int siteid, int deviceid, IStatelessSession session) //{ // ICriterion expression = Restrictions.Eq("Siteid", siteid) && Restrictions.Eq("Deviceindex", deviceid); // var modbusHubbubs = await session.CreateCriteria<ModbusHubbub>(). // Add(expression) // .UniqueResultAsync<ModbusHubbub>(); // if (modbusHubbubs != null) // { // var template = await GetAnalogModbusHubbubAsync(modbusHubbubs, session); // return template; // } // else return null; //} //private async Task<HubbubAnalogMappingTemplate> GetAnalogModbusHubbubAsync(ModbusHubbub hubbub, IStatelessSession session) //{ // HubbubAnalogMappingTemplate hubbubTemplate = new HubbubAnalogMappingTemplate(); // hubbubTemplate.Hubbub = hubbub; // hubbubTemplate.ConnectionInfo = await GetIdentifiedObjectAsync<ModbusConnectionInfo>(hubbub.Connectionid, session); // hubbubTemplate.AnalogInputGroup = await GetIdentifiedObjectAsync<AnalogInputGroup>(hubbub.Aigroupid, session); // hubbubTemplate.AnalogInputPoints = await session.CreateCriteria<VwAnalogPoint>().Add(Restrictions.Eq("Groupid", hubbub.Aigroupid)).ListAsync<VwAnalogPoint>(); // return hubbubTemplate; //} private async Task <IList <T> > GetDataByHubbubIdAsync <T>(int Hubbubid, IStatelessSession session) where T : class { return(await session.CreateCriteria <T>().Add(Restrictions.Eq("Hubbubid", Hubbubid)).ListAsync <T>()); }
private async Task <IActionResult> GetTemplateCompress(int hubbubid, bool compress, IStatelessSession session) { ICriterion expression = Restrictions.Eq("Id", hubbubid); var hubbub = await session.CreateCriteria <ModbusHubbub>(). Add(expression) .UniqueResultAsync <ModbusHubbub>(); if (hubbub == null) { return(BadRequest(ApiResult.BadRequest("존재하지 않는 전력수집장치 ID 입니다"))); } ModbusHubbubMappingTemplate row = new ModbusHubbubMappingTemplate(); row.Hubbub = hubbub; row.ConnectionInfo = await GetIdentifiedObjectAsync <ModbusConnectionInfo>(hubbub.Connectionid, session); row.ModbusInputPointList = await GetDataByHubbubIdAsync <VwModbusInputPoint>(hubbub.Id, session); row.ModbusDigitalOutputPoints = await GetDataByHubbubIdAsync <VwDigitalOutputPoint>(hubbub.Id, session); row.ModbusDigitalStatusPoints = await GetDataByHubbubIdAsync <ModbusDigitalStatusPoint>(hubbub.Id, session); row.StandardAnalogPoints = await session.CreateCriteria <VwStandardAnalogPoint>() .Add(Restrictions.Eq("Disable", (SByte)0)) .ListAsync <VwStandardAnalogPoint>(); row.StandardPcsStatuses = await session.CreateCriteria <VwStandardPcsStatusPoint>().ListAsync <VwStandardPcsStatusPoint>(); //row.AnalogInputPoints = await GetGroupPointsAsync<VwAnalogPoint>(hubbub.Aigroupid, session); //row.DigitalInputGroup = await GetIdentifiedObjectAsync<DigitalInputGroup>(hubbub.Digroupid, session); //row.DigitalOutputGroup = await GetIdentifiedObjectAsync<DigitalOutputGroup>(hubbub.Dogroupid, session); //row.DigitalStatusGroup = await GetIdentifiedObjectAsync<DigitalStatusGroup>(hubbub.Stgroupid, session); //row.DigitalInputPoints = await GetGroupPointsAsync<ModbusDigitalInputPoint>(hubbub.Digroupid, session); //row.DigitalOutputPoints = await GetGroupPointsAsync<ModbusDigitalOutputPoint>(hubbub.Dogroupid, session); //row.DigitalStatusPoints = await GetGroupPointsAsync<ModbusDigitalStatusPoint>(hubbub.Stgroupid, session); JObject obj = JObject.FromObject(row); if (compress) { string ori_str = obj.ToString(); byte[] ori_bytes = Encoding.UTF8.GetBytes(ori_str); string ori_str_base64 = Convert.ToBase64String(ori_bytes); using (var outputStream = new MemoryStream()) { using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress)) { gZipStream.Write(ori_bytes, 0, ori_bytes.Length); } byte[] com_bytes = outputStream.ToArray(); string com_str_base64 = Convert.ToBase64String(com_bytes); return(Ok(com_str_base64)); } } else { return(Ok(row)); } }
public ICriteria CreateCriteria <T>() where T : class { return(_Session.CreateCriteria <T>()); }
public ICriteria CreateCriteria(string entityName, string alias) { return(statelessSession.CreateCriteria(entityName, alias)); }
/// <summary> /// 得到全部列列表 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public IList <T> List <T>() where T : class, new() { return(_session.CreateCriteria <T>().List <T>()); }
public async Task <IActionResult> DownloadPvData(int year, int month) { try { using (IStatelessSession session = peiuGridDataContext.SessionFactory.OpenStatelessSession()) { DateTime startDt = new DateTime(year, month, 1); DateTime endDt = startDt.AddMonths(1).AddDays(-1); var pv_datas = await session.CreateCriteria <PvData>() .Add(Restrictions.Eq("siteId", (short)6)) .Add(Restrictions.Where <PvData>(x => x.timestamp.Year == year && x.timestamp.Month == month)) .AddOrder(Order.Asc("timestamp")).ListAsync <PvData>(); var groupsData = pv_datas.GroupBy(key => key.siteId, value => value); var weathers = await session.CreateCriteria <Currentweather>() .Add(Restrictions.Where <Currentweather>(x => x.Timestamp.Year == year && x.Timestamp.Month == month)) .AddOrder(Order.Asc("Timestamp")) .ListAsync <Currentweather>(); var weather_result = weathers.ToArray(); StringBuilder sb = new StringBuilder(); sb.AppendLine("siteid,pv_ts,w_ts,year,month,day,hour,gen,temp,humidity,cloud"); Currentweather currentweather = null; foreach (IGrouping <short?, PvData> pvData in groupsData) { var timegroupsData = pvData.GroupBy(x => new DateTime(x.timestamp.Year, x.timestamp.Month, x.timestamp.Day, x.timestamp.Hour, 0, 0), value => value); short siteid = pvData.Key.Value; foreach (IGrouping <DateTime, PvData> row in pvData) { DateTime pv_ts = row.Key; Currentweather target_weather = weathers.LastOrDefault(x => x.Timestamp <= pv_ts && x.Timestamp >= pv_ts.AddHours(-1)); if (target_weather != null) { currentweather = target_weather; } else if (target_weather == null && currentweather != null) { target_weather = currentweather; } sb.AppendLine($"{siteid},{pv_ts}{target_weather.Timestamp}{pv_ts.ToString("yyyy,MM,dd,HH")},{row.Sum(x => x.TotalActivePower) / 3600},{target_weather.Temp},{target_weather.Humidity},{target_weather.Clouds}"); } } string str = sb.ToString(); byte[] dataBytes = Encoding.UTF8.GetBytes(str); string file = $"PV발전량이력_{year}_{month}.csv"; // Response... System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition { FileName = file, Inline = false // false = prompt the user for downloading; true = browser to try to show the file inline }; Response.Headers.Add("Content-Disposition", cd.ToString()); Response.Headers.Add("X-Content-Type-Options", "nosniff"); return(File(dataBytes, "application/octet-stream")); } }catch (Exception ex) { logger.LogError(ex, ex.Message); return(BadRequest()); } }
public ICriteria CreateCriteria(Type type) { return(_session.CreateCriteria(type)); }