public ActionResult Create(FormCollection collection) { var model = new Role(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { if (session.Load<Role>(m => m.Name.Equals(model.Name)) != null) { FlashFailure("角色名称[{0}]已经存在,创建失败!", model.Name); return View(model); } model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { FlashSuccess("角色[{0}]创建成功", model.Name); return Close(); } FlashFailure("创建角色[{0}]失败!", model.Name); return View(model); } }
public ActionResult Approve(FormCollection collection, long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要修改的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { var model = session.Load<TrainManagement>(m => m.Id.In(ids)); if (model == null) { FlashInfo("你没有选择任何可以审核的记录。"); return Close(); } if (!CanApprove(model)) { FlashWarn("无法审核,请检查所选记录状态!"); return Close(); } model.Status = TrainManStateConst.法规部门负责人已审核; model.UpdatedAt = DateTime.Now; model.UpdatedBy = CurrentAccountNo; if (session.Update(model)) FlashSuccess("记录审核成功"); else FlashError("记录审核失败,请联系管理员!"); return Close(); } }
public ActionResult Delete(FormCollection collection, long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要删除的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); var models = session.Find<TrainNotice>(m => m.Id.In(ids)); if (models.Count == 0) { FlashInfo("你没有选择任何可以删除的培训通知。"); return Close(); } var notices = string.Join(", ", models.Select(m => m.Title)); if (models.Any(model => !session.Delete(model))) { session.Rollback(); FlashError("删除培训通知{0}失败!", notices); return View(models); } session.Commit(); FlashSuccess("删除培训通知{0}成功!", notices); return Close(); } }
public ActionResult Submit(long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要操作的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { var model = session.Load<TrainNeed>(m => m.Id.In(ids)); if (model == null) { FlashWarn("没有可以操作的记录。"); return Close(); } if (!model.Type.Equals(TrainNeedType.公司)) { FlashInfo("只能提交类型为\"公司\"的记录!"); return Close(); } if (!CanSubmit(model)) { FlashWarn("该记录已经提交。"); return Close(); } return View(model); } }
public ActionResult Create(FormCollection collection) { var model = new SchoolSection(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); if (session.Load<SchoolSection>(m => m.Name.Equals(model.Name)) != null) { FlashWarn("校区{0}已经存在,创建失败。", model.Name); return View(model); } model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { session.Commit(); FlashSuccess("创建校区[{0}]成功!", model.Name); return Close(); } session.Rollback(); FlashFailure("创建校区[{0}]失败!", model.Name); return View(); } }
public ActionResult Edit(FormCollection collection, long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要修改的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { var model = session.Load<School>(m => m.Id.In(ids)); if (model == null) { FlashInfo("你没有选择任何可以修改的学校。"); return Close(); } TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } model.UpdatedAt = DateTime.Now; model.UpdatedBy = CurrentAccountNo; if (session.Update(model)) { FlashSuccess("学校更改成功"); return Close(); } return View(); } }
public ActionResult Active(FormCollection collection, long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要激活的用户。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); var models = session.Find<User>(m => m.Id.In(ids) && !m.IsActive); if (models.Count == 0) { FlashInfo("你没有选择任何需要激活的用户。"); return Close(); } foreach (User model in models) { if (!model.Active(session, CurrentAccountNo)) { session.Rollback(); FlashError("账户激活失败!"); return Close(); } } session.Commit(); FlashSuccess("账户激活成功"); return Close(); } }
public ActionResult GetFileContent(long id = 0) { if (id == 0) { return null; } using (var session = new SessionFactory().OpenSession()) { var model = session.Load<TrainStudyFiles>(id); if (model == null) { return null; } if (model.Suffix.Contains("doc")) { var src = model.HtmlFilePath; var path = Server.MapPath(src); if (!System.IO.File.Exists(path)) { FlashWarn("文件不存在!"); return Close(); } var content = string.Format(@"<iframe src=""{0}"" width=""100%"" height=""600px""></iframe>", src); Response.Write(content); } else { Response.Write(model.FlvHtml); } return null; } }
public ActionResult Install(string check) { SessionFactory CreateSession = new SessionFactory(); CreateSession.CreateSessionFactory<PostMapping>(); return RedirectToAction("Create"); }
//[Priviledge(Name = "首页", IsMenu = true, IsEntry = true, Position = 1)] public ActionResult Index() { using (var session = new SessionFactory().OpenSession()) { const string accountNavigationSql = "SELECT * FROM `navigations` WHERE `type` < 4 AND ((`auth_code` = 0) OR (`id` IN ( SELECT `navigation_id` FROM `navigation_priviledges` WHERE (`flag` = 1 AND `owner_id` IN (SELECT `role_id` FROM `account_role_refs` WHERE `account_id` IN ( SELECT `id` FROM `accounts` WHERE `name` = '{0}'))) OR (`flag` = 2 AND `owner_id` IN ( SELECT `id` FROM `accounts` WHERE `name` = '{0}'))))) ORDER BY `order_id` asc"; var accountNavs = session.FindBySql<Navigation>(string.Format(accountNavigationSql, CurrentAccountNo)); Session.Add(Const.AccountMenuItems, accountNavs); const string rolePinNavigationSql = "SELECT n.* FROM `account_navigation_refs` r LEFT JOIN `navigations` n ON r.`navigation_id` = n.`id` WHERE r.`type` = 1 AND r.`owner_id` IN (SELECT `role_id` FROM `account_role_refs` WHERE `account_id` IN ( SELECT `id` FROM `accounts` WHERE `name` = '{0}')) ORDER BY r.`order_id` ASC"; var pinRoleNavs = session.FindBySql<Navigation>(string.Format(rolePinNavigationSql, CurrentAccountNo)); Session.Add(Const.RolePinnedTask, pinRoleNavs); const string accountPinNavigationSql = "SELECT n.* FROM `account_navigation_refs` r LEFT JOIN `navigations` n ON r.`navigation_id` = n.`id` WHERE r.`type` = 2 AND r.`owner_id` IN ( SELECT `id` FROM `accounts` WHERE `name` = '{0}') ORDER BY r.`order_id` ASC"; var pinAccountNavs = session.FindBySql<Navigation>(string.Format(accountPinNavigationSql, CurrentAccountNo)); Session.Add(Const.AccountPinnedTask, pinAccountNavs); var model = session.Load<Account>(m => m.Name.Equals(CurrentAccountNo)); return View(model); } }
public ActionResult Create(FormCollection collection, long id = 0) { var model = new TrainManagementItem { TrainManId = id }; TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); var trainMan = session.Load<TrainManagement>(id); if (trainMan == null) { FlashError("培训不存在,请联系管理员!"); return Close(); } model.Year = trainMan.Year; model.TrainManName = trainMan.Name; model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { session.Commit(); FlashSuccess("创建记录成功!"); return Close(); } session.Rollback(); FlashFailure("创建记录失败!"); return View(); } }
public ActionResult Create(FormCollection collection) { var model = new SchoolDepartment(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { //model.ParentId //model.LeaderId model.LeaderName = model.LeaderId == 0 ? "" : session.Load<User>(model.LeaderId).Realname; if (session.Load<SchoolDepartment>(m => m.Name.Equals(model.Name)) != null) { FlashFailure("部门[{0}]已经存在", model.Name); return View(model); } model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { FlashSuccess("部门[{0}]创建成功", model.Name); return Close(); } FlashFailure("创建部门[{0}]失败!", model.Name); return View(); } }
public ActionResult Approve(FormCollection collection, long[] ids, long id = 0) { if (ids.Length == 0) { FlashWarn("请选择要批阅的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { var model = session.Load<TrainRecordFile>(m => m.Id.In(ids)); if (model == null) { FlashInfo("你没有选择任何可以批阅的记录。"); return Close(); } TryUpdateModel(model, collection.ToValueProvider()); model.UpdatedAt = DateTime.Now; model.UpdatedBy = CurrentAccountNo; if (session.Update(model)) { FlashSuccess("批阅记录成功"); return Close(); } FlashFailure("批阅记录失败,请联系管理员!"); return View(); } }
public ActionResult Delete(long[] ids, long id = 0) { if (ids.Length == 0) { FlashInfo("请选择要删除的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { var models = session.Find<PunishmentDossierFiles>(m => m.Id.In(ids)); if (models.Count == 0) { FlashInfo("你没有选择任何可以删除的记录。"); return Close(); } if (models.Any(m => !m.CreatedBy.Equals(CurrentAccountNo))) { FlashInfo("你不是创建人,不能删除{0}", string.Join(",", models.Where(m => !m.CreatedBy.Equals(CurrentAccountNo)).Select(m => m.FileName))); return Close(); } var contract = session.Load<PunishmentDossier>(id); if (contract == null) { FlashWarn("材料未找到,请联系管理员!"); return Close(); } if (!IsEditAble(contract)) { FlashInfo("材料已经提交,相关文件不能删除!"); return Close(); } return View(models); } }
public ActionResult Create(FormCollection collection) { var model = new TrainManagement(); TryUpdateModel(model, collection.ToValueProvider()); if (!ModelState.IsValid) { return View(model); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); model.CreatedAt = DateTime.Now; model.CreatedBy = CurrentAccountNo; ViewData.Model = model; if (session.Create(model)) { session.Commit(); FlashSuccess("创建记录成功!"); return Close(); } session.Rollback(); FlashFailure("创建记录失败!"); return View(); } }
public ActionResult Edit(long[] ids) { using (var session = new SessionFactory().OpenSession()) { var model = session.Load<TrainManagementItem>(ids[0]); if (model.ExamStatus != null && !model.ExamStatus.Equals(ExamStatusConst.未考试)) { FlashWarn("您已经完成该考试!"); return Close(); } var q = new Criteria<Exam>(session) .AndIn<TrainManagementItem>(m => m.TrainManId, n => n.TrainManId, n => n.Id == ids[0]); var exam = q.Load(); if (exam == null) { FlashWarn("考试不存在!请联系管理员!"); return Close(); } var models = session.Find<Question>(m => m.ExamId == exam.Id); if (models == null || !models.Any()) { FlashWarn("考试题目未设置!"); return Close(); } Response.Write(string.Format("<script>window.open('Exam?ids={0}','_blank')</script>", ids[0])); return Close(); } }
public ActionResult Delete(FormCollection collection, long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要删除的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); var models = session.Find<TrainManagement>(m => m.Id.In(ids)); if (models.Count == 0) { FlashInfo("你没有选择任何可以删除的记录。"); return Close(); } var displays = string.Join(", ", models.Select(m => string.Concat(m.Id))); if (session.Delete<TrainManagement>(m => m.Id.In(ids))) { session.Commit(); FlashSuccess("删除记录{0}成功!", displays); return Close(); } session.Rollback(); FlashError("删除记录{0}失败!", displays); return View(models); } }
public static SelectList BrandList() { Session ds = new SessionFactory().OpenSession(); IList<SupplierBrand> d = ds.Find<SupplierBrand>(); var item = new SupplierBrand {Id = 0, Brand = "无"}; d.Add(item); return new SelectList(d, "Id", "Brand"); }
static AreaCodeHelper() { if (_areaCodes != null) return; using (var session = new SessionFactory().OpenSession()) { _areaCodes = new Criteria<AreaCode>(session).Find(); } }
public static SelectList OrganizationList() { Session ds = new SessionFactory().OpenSession(); IList<Organization> d = ds.Find<Organization>(); var item = new Organization {Id = 0, Name = "无"}; d.Add(item); return new SelectList(d, "Id", "Name"); }
public static SelectList SupplierList() { Session ds = new SessionFactory().OpenSession(); IList<Supplier> d = ds.Find<Supplier>(); var item = new Supplier {Id = 0, Name = "无"}; d.Add(item); return new SelectList(d, "Id", "Name"); }
public static SelectList RoleList() { var ds = new SessionFactory().OpenSession(); var d = ds.Find<Role>(); var item = new Role() { Id = 0, Name = "无" }; d.Add(item); return new SelectList(d, "Id", "Name"); }
/// <summary> /// 读取滚动公告 /// </summary> /// <returns></returns> public static IList<Notice> GetScrollNotices() { using (var session = new SessionFactory().OpenSession()) { var today = DateTime.Today; var q = new Criteria<Notice>(session).Where(m => m.StopAt >= today); return q.Find(); } }
public ActionResult ClearActionLog(FormCollection collection) { using (var session = new SessionFactory().OpenSession()) { var dt = DateTime.Now.AddDays(-30); session.Delete<ActionLog>(m => m.CreatedAt < dt); FlashSuccess("清理日志成功!"); return RedirectToAction("Index"); } }
public ActionResult Exam(FormCollection collection, long[] ids) { if (ids.Length == 0) { FlashWarn("考试不存在!请联系管理员!"); return Close(); } using (var session = new SessionFactory().OpenSession()) { session.BeginTransaction(); var models = session.Find<ExamAnswer>(m => m.TrainManagementItemId == ids[0]); if (models == null || !models.Any()) { FlashWarn("用户答题记录不在在!请联系管理员!"); return Close(); } var trainManagementItem = session.Load<TrainManagementItem>(ids[0]); if (trainManagementItem == null) { FlashWarn("用户答题记录不在在!请联系管理员!"); return Close(); } trainManagementItem.ExamScore = 0; foreach (var question in models) { var score = GetDbQueryPara(question.Id + ""); try { question.Score = score==null||score.Equals("")?0:Decimal.Parse(score); trainManagementItem.ExamScore += question.Score; } catch (Exception) { FlashError("评分输入错误!"); return Close(); } } trainManagementItem.ExamStatus = ExamStatusConst.已评阅; trainManagementItem.UpdatedAt = DateTime.Now; trainManagementItem.UpdatedBy = "SYSTEM"; if (session.Update(trainManagementItem) && session.Update(models)) { session.Commit(); Response.Write("<script>window.close()</script>"); return Close(); } session.Rollback(); FlashError("提交试卷不成功,请联系管理员!"); return View(models); } }
public static string GetModelCodeFormDb(string tableName) { using (var session = new SessionFactory().OpenSession()) { var model = session.FindBySql<DbTable>("show full fields from " + tableName); if (model == null || model.Count == 0) { // table不存在 return null; } var tb = new StringBuffer(); foreach (var col in model) { tb += Environment.NewLine; if (col.Null.Equals("NO")) { tb += string.Format("[Required]{0}", Environment.NewLine); } if (col.Key.Equals("PRI")) { tb += "[PrimaryKey]" + Environment.NewLine; } if (!string.IsNullOrEmpty(col.Comment)) { tb += string.Format("[DisplayName(\"{0}\")]{1}", col.Comment, Environment.NewLine); } var type = col.Type; if (type.Contains("(")) { var temp = type.Split('('); type = temp[0]; var length = temp[1].Substring(0, temp[1].LastIndexOf(")", StringComparison.Ordinal)); if (type.Equals("text") || type.Equals("varchar")) tb += string.Format("[StringLength({0})]{1}", length, Environment.NewLine); } var name = col.Field.Pascalize(); var mappingDic = new Dictionary<string, string> { {"tinyint", "bool"}, {"int", "int"}, {"bigint", "long"}, {"varchar", "string"}, {"text", "string"}, {"datetime", "DateTime"}, {"decimal", "Decimal"} }; //未匹配的默认为string var typeStr = mappingDic[type] ?? "string"; tb += string.Format("public {0}{1}{2}{3}{4}", typeStr, (col.Null.Equals("YES") && !typeStr.Equals("string") ? "? " : " "), name, "{get; set;}", Environment.NewLine); } return tb.ToString(); } }
public GuidSequenceTester() { _factory = new SessionFactory(); using (var session = _factory.OpenSession()) { for (int i = 0; i <= 10000; i++) { session.Add(new DocumentWithGuid()); } } _session = _factory.OpenSession(); }
public ActionResult Delete(long[] ids) { if (ids.Length == 0) { FlashWarn("请选择要删除的记录。"); return Close(); } using (var session = new SessionFactory().OpenSession()) { ViewData.Model = session.Find<SchoolDepartment>(m => m.Id.In(ids)); return View(); } }
public static void WriteLog(ControllerContext controllerContext, ViewDataDictionary viewData) { var cc = controllerContext.Controller.ControllerContext; var category = GetCategory(controllerContext); var title = GetTitle(controllerContext); var log = new ActionLog { Controller = cc.RouteData.GetRequiredString("controller"), Action = cc.RouteData.GetRequiredString("action"), Url = controllerContext.HttpContext.Request.Path, CreatedAt = DateTime.Now, CreatedBy = "SYSTEM", Address = controllerContext.HttpContext.Request.UserHostAddress, Actor = TryGetUserName(controllerContext), Method = controllerContext.HttpContext.Request.HttpMethod, Category = GetCategory(controllerContext), Title = title.Equals(category) ? "查询" : title, Result = TryGetResult(controllerContext), ModelId = cc.RouteData.Values.ContainsKey("id") ? cc.RouteData.GetRequiredString("id") : null, Description = viewData.ContainsKey(Const.ToLogMessage) ? viewData[Const.ToLogMessage].ToString() : null }; if (log.Description == null && viewData.ContainsKey(Const.ToLogModel)) { // 取得描述 var model = viewData.ContainsKey(Const.ToLogModel) ? viewData[Const.ToLogModel] : viewData.Model; if (model != null) { if (!model.GetType().IsGenericType) { log.Description = model.Print(); } else { var objs = (IEnumerable<object>)model; log.Description = string.Join(";" + Environment.NewLine, objs.Select(m => m.Print())); } } } using (var ds = new SessionFactory().OpenSession()) { if (!ds.Create(log)) { Log.Error("记录日志失败:{0}", log.ToString()); } } }
public ActionResult ApproveLeader(long[] ids, long id = 0) { using (var session = new SessionFactory().OpenSession()) { var model = session.Load<TrainRecordFile>(m => m.Id.In(ids)); if (model == null) { FlashInfo("你没有选择任何可以修改的记录。"); return Close(); } return View(model); } }
public ISession OpenSession() { return(SessionFactory.OpenSession()); }
private static async void App(Options options) { IMetastore <JObject> metastore = null; KeyManagementService keyManagementService = null; if (options.Metastore == Metastore.ADO) { if (options.AdoConnectionString != null) { logger.LogInformation("using ADO-based metastore..."); metastore = AdoMetastoreImpl .NewBuilder(MySqlClientFactory.Instance, options.AdoConnectionString) .Build(); } else { logger.LogError("ADO connection string is a mandatory parameter with Metastore Type: ADO"); Console.WriteLine(HelpText.AutoBuild(cmdOptions, null, null)); return; } } else if (options.Metastore == Metastore.DYNAMODB) { logger.LogInformation("using DynamoDB-based metastore..."); AWSConfigs.AWSRegion = "us-west-2"; metastore = DynamoDbMetastoreImpl.NewBuilder().Build(); } else { logger.LogInformation("using in-memory metastore..."); metastore = new InMemoryMetastoreImpl <JObject>(); } if (options.Kms == Kms.AWS) { if (options.PreferredRegion != null && options.RegionToArnTuples != null) { Dictionary <string, string> regionToArnDictionary = new Dictionary <string, string>(); foreach (string regionArnPair in options.RegionToArnTuples) { string[] regionArnArray = regionArnPair.Split("="); regionToArnDictionary.Add(regionArnArray[0], regionArnArray[1]); } logger.LogInformation("using AWS KMS..."); keyManagementService = AwsKeyManagementServiceImpl .NewBuilder(regionToArnDictionary, options.PreferredRegion).Build(); } else { logger.LogError("Preferred region and <region>=<arn> tuples are mandatory with KMS Type: AWS"); Console.WriteLine(HelpText.AutoBuild(cmdOptions, null, null)); return; } } else { logger.LogInformation("using static KMS..."); keyManagementService = new StaticKeyManagementServiceImpl("mysupersecretstaticmasterkey!!!!"); } CryptoPolicy cryptoPolicy = BasicExpiringCryptoPolicy .NewBuilder() .WithKeyExpirationDays(KeyExpirationDays) .WithRevokeCheckMinutes(CacheCheckMinutes) .Build(); // Setup metrics reporters and always include console. IMetricsBuilder metricsBuilder = new MetricsBuilder() .Report.ToConsole(consoleOptions => consoleOptions.FlushInterval = TimeSpan.FromSeconds(60)); // CloudWatch metrics generation if (options.EnableCloudWatch) { // Fill in when we open source our App.Metrics cloudwatch reporter separately } IMetrics metrics = metricsBuilder.Build(); // Create a session factory for this app. Normally this would be done upon app startup and the // same factory would be used anytime a new session is needed for a partition (e.g., shopper). // We've split it out into multiple using blocks to underscore this point. using (SessionFactory sessionFactory = SessionFactory .NewBuilder("productId", "reference_app") .WithMetastore(metastore) .WithCryptoPolicy(cryptoPolicy) .WithKeyManagementService(keyManagementService) .WithMetrics(metrics) .Build()) { // Now create an actual session for a partition (which in our case is a pretend shopper id). This session is used // for a transaction and is disposed automatically after use due to the IDisposable implementation. using (Session <byte[], byte[]> sessionBytes = sessionFactory.GetSessionBytes("shopper123")) { const string originalPayloadString = "mysupersecretpayload"; foreach (int i in Enumerable.Range(0, options.Iterations)) { string dataRowString; // If we get a DRR as a command line argument, we want to directly decrypt it if (options.Drr != null) { dataRowString = options.Drr; } else { // Encrypt the payload byte[] dataRowRecordBytes = sessionBytes.Encrypt(Encoding.UTF8.GetBytes(originalPayloadString)); // Consider this us "persisting" the DRR dataRowString = Convert.ToBase64String(dataRowRecordBytes); } logger.LogInformation("dataRowRecord as string = {dataRow}", dataRowString); byte[] newDataRowRecordBytes = Convert.FromBase64String(dataRowString); // Decrypt the payload string decryptedPayloadString = Encoding.UTF8.GetString(sessionBytes.Decrypt(newDataRowRecordBytes)); logger.LogInformation("decryptedPayloadString = {payload}", decryptedPayloadString); logger.LogInformation("matches = {result}", originalPayloadString.Equals(decryptedPayloadString)); } } } // Force final publish of metrics await Task.WhenAll(((IMetricsRoot)metrics).ReportRunner.RunAllAsync()); }
public StatusSaverService(SessionFactory sessionFactory) { _sessionFactory = sessionFactory; }
public void Save(T entity) { SessionFactory.GetCurrentSession(_context).SaveOrUpdate(entity); }
public SlackController(PluginsCollection plugins, IConfigurationProvider config, SessionFactory sessionFactory) { _postMessageUrl = "https://slack.com/api/chat.postMessage"; _queue = new ProducerConsumerQueue <dynamic>(1, callback: Send); _sessionFactory = sessionFactory; _config = config; }
public Person QueryFirst() { using var session = SessionFactory.OpenStatelessSession(); return(session.Query <Person>().First(x => x.Id == CurrentId)); }
public ConsejeriaDtoMapper(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; }
public Session CreateActionSession(Session session, IXenConnection connection) { return(SessionFactory.CreateSession(session, connection, ConnectionTimeout)); }
public void OnInitialized(IContainerProvider containerProvider) { SessionFactory.Init(@"Server=.;Database=VendingMachine;Trusted_Connection=true"); }
public void Find() { var person = EntityHelper.CreateProxy <Person>(); person.Name = "test"; person.Age = 20; person.Money = 100; person.CreateTime = DateTime.Now; person.IsActive = true; using (ISession session = SessionFactory.CreateDefaultSession()) { session.Insert(person); int id = session.GetIndentifer <int>(); var queryable = session.Find <Person>().Where(s => s.Id == id); // 测试 Single 函数 person = queryable.Single(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); Assert.AreEqual("test", person.Name); Assert.AreEqual(20, person.Age.Value); Assert.AreEqual(100, person.Money.Value); Assert.AreEqual(true, person.IsActive); // 测试 SingleOrDefault 函数 person = queryable.SingleOrDefault(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); Assert.AreEqual("test", person.Name); Assert.AreEqual(20, person.Age.Value); Assert.AreEqual(100, person.Money.Value); Assert.AreEqual(true, person.IsActive); // 测试 First 函数 person = queryable.First(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); Assert.AreEqual("test", person.Name); Assert.AreEqual(20, person.Age.Value); Assert.AreEqual(100, person.Money.Value); Assert.AreEqual(true, person.IsActive); // 测试 FirstOrDefault 函数 person = queryable.FirstOrDefault(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); Assert.AreEqual("test", person.Name); Assert.AreEqual(20, person.Age.Value); Assert.AreEqual(100, person.Money.Value); Assert.AreEqual(true, person.IsActive); // 测试 Count 函数 Assert.AreEqual(1, queryable.Count()); Console.WriteLine(session.Provider.ExecutedCommandBuilder); // 测试 ToList 函数 var list = queryable.ToList(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); Assert.AreEqual(1, list.Count()); // 测试包含多个 Where 条件 queryable = session.Find <Person>() .Where(s => s.Id == id) .Where(s => s.Name.Contains("test")) .OrderBy(s => s.CreateTime) .OrderBy(s => s.Name) .Skip(0).Take(1); Assert.AreEqual(1, queryable.Count()); Console.WriteLine(session.Provider.ExecutedCommandBuilder); } }
/// <summary> /// 获取报价表报价成功的数据 /// </summary> /// <param name="page"></param> /// <param name="limit"></param> /// <param name="swhere"></param> /// <param name="sort"></param> /// <returns></returns> public object GetQuoteResultList(int page, int limit, string swhere, string sort) { string user = Tools.SessionHelper.GetSession <Base_UserInfo>(Tools.SessionHelper.SessinoName.CurUser).UserName; List <String> IDs = SessionFactory.GetCurrentSession().QueryOver <SupplierQuote>().Where(o => o.QuotationCompany == user).Select(t => t.InquiryTitle).List <string>().ToList(); //获取我参与过的项目的名称 StringBuilder where = new StringBuilder(); //拼接查询条件(项目名称格式化) foreach (var ID in IDs) { where.Append("'" + ID + "',"); } string ere = where.ToString().TrimEnd(',');//得到字符串并去掉最后的逗号 string temp = "1"; string temp1 = "1"; try { if (swhere != null) { int s = swhere.IndexOf("|"); int a = swhere.LastIndexOf("|"); temp = swhere.Substring(0, s); temp1 = swhere.Substring(a + 1, swhere.Length - a - 1); } } catch (Exception ee) { return("查询抛出异常" + ee); } try { List <SupplierQuote> upLoadList = Tools.ExecSqlHelp.ExecuteSql <SupplierQuote>("SELECT * FROM " + //"SupplierQuote WHERE quotestate=2 and InquiryTitle in (lists)", new List<SqlParameter>(){ // new SqlParameter(){ParameterName="lists",Value=ere} "SupplierQuote WHERE quotestate=2 and " + temp + " like '%" + temp1 + "%' and InquiryTitle in (" + ere + ")", null); //拼接SQL进行查询 return(Common.NewtonJsonHelper.Deserialize <object>("{\"curPage\":" + page + ",\"success\":true,\"total\":" + upLoadList.Count + ",\"QuoteResultList\":" + NewtonJsonHelper.Serialize(upLoadList, null) + "}", null)); //构造返回数据 } catch (Exception ee) { return("查询抛出异常" + ee); } #if debug //try //{ // string userName = Tools.SessionHelper.GetSession<Base_UserInfo>(Tools.SessionHelper.SessinoName.CurUser).UserName;//获取当前用户 // StringBuilder where = new StringBuilder(); // //swhere = swhere != null ? swhere.TrimStart(',') + ",STATE|int|0|=" : "STATE|int|0|="; // //where.Append(swhere); // where.Append(",InquiryTitle|string|"); // foreach (var ID in IDs) // { // where.Append("'" + ID + "',"); // } // string ere = where.ToString().TrimEnd(',') + "|in"; // swhere = string.IsNullOrEmpty(swhere) ? ere : ere + "," + swhere; // ////where.Append(",InquiryTitle in (@"); // //where.Append("InquiryTitle in (@"); // ////foreach (var ID in IDs) // ////{ // //// where.Append("'" + ID + "',"); // ////} // //for (int i = 0; i < IDs.Count; i++) // //{ // // where.Append("'" + IDs[i] + "',"); // //} // //string here = where.ToString().TrimEnd(',') + "@)"; // //swhere = string.IsNullOrEmpty(swhere) ? here : here + "," + swhere; // ////where.Append("@)"); // ////where.AppendFormat(",InquiryTitle in (@{0}@)" , IDs); // ////where.AppendFormat(",InquiryTitle|string|{0}|" + +"in" + ss); // PageParameter pagePara = new PageParameter() // { // PageIndex = page, // Limit = limit, // //Swhere = where.ToString(),a // Swhere = swhere, // Sort = sort, // ObjName = "QuoteResultList", // Igorelist = new List<string>() { "Inquiries" } // }; // QueryParameter query = new QueryParameter("SupplierQuote", pagePara.Swhere, pagePara, null); // return this.GetAllPageList(query); //} //catch (Exception ee) //{ // return null; //} /***/ #endif }
public void Update() { var person = EntityHelper.CreateProxy <Person>(); person.Name = "test"; person.Age = 20; person.Money = 100; person.CreateTime = DateTime.Now; person.IsActive = true; using (ISession session = SessionFactory.CreateDefaultSession()) { int i = session.Insert(person); int id = session.GetIndentifer <int>(); // Find 方法返回的对象都是原始对象而非代理对象 person = session.Find <Person>().Where(s => s.Id == id).Single(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); // 根据原始对象创建代理对象 person = person.ToEntityProxy(); person.Name = "test01"; person.Age = 31; person.Money = 200; i = session.Update(person); Console.WriteLine(session.Provider.ExecutedCommandBuilder); person = session.Find <Person>().Where(s => s.Id == id).Single(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); Assert.AreEqual(1, i); Assert.AreEqual("test01", person.Name); Assert.AreEqual(31, person.Age.Value); Assert.AreEqual(200, person.Money.Value); person = EntityHelper.CreateProxy <Person>(); person.Name = "test02"; person.Age = 22; person.Money = 101; person.CreateTime = DateTime.Now; person.IsActive = false; i = session.Update <Person>() .Set(person) .Where(s => s.Id == id) .Execute(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); person = session.Find <Person>().Where(s => s.Id == id).Single(); Assert.AreEqual(1, i); Assert.AreEqual("test02", person.Name); Assert.AreEqual(22, person.Age.Value); Assert.AreEqual(101, person.Money.Value); Assert.AreEqual(false, person.IsActive); i = session.Update <Person>().Set(s => s.Name, "test03") .Set(s => s.Age, 23) .Set(s => s.Money, 102) .Set(s => s.CreateTime, DateTime.Now) .Set(s => s.IsActive, true) .Where(s => s.Id == id) .Execute(); Console.WriteLine(session.Provider.ExecutedCommandBuilder); person = session.Find <Person>().Where(s => s.Id == id).Single(); Assert.AreEqual(1, i); Assert.AreEqual("test03", person.Name); Assert.AreEqual(23, person.Age.Value); Assert.AreEqual(102, person.Money.Value); Assert.AreEqual(true, person.IsActive); } }
public ISession OpenSession() { var session = new SessionWithLock(SessionFactory.OpenSession(), DatabaseLock, false); return(session); }
public static void Init(string connectionString) { SessionFactory.Init(connectionString); }
public RatingController(SessionFactory sessionFactory, SlackService slackService, RatingRepository ratingRepository) { this.sessionFactory = sessionFactory; this.slackService = slackService; this.ratingRepository = ratingRepository; }
public void Should_not_contain_a_missing_instance() { using (ISession session = SessionFactory.OpenSession()) Assert.Throws <ObjectNotFoundException>(() => session.Load <TestInstance>(47)); }
public EditPersonalInfoCommandHandler(SessionFactory sessionFactory) { _sessionFactory = sessionFactory; }
// TODO: This creates another session instance, should be executed inside the ThreadExecuter public static void PrintStartupInfo(SessionFactory factory, SettingsService settings, SqlDialect dialect) { if (settings.GetLocal().StashToLootFrom == 0) { Logger.Info("IA is configured to loot from the last stash page"); } else { Logger.Info($"IA is configured to loot from stash page #{settings.GetLocal().StashToLootFrom}"); } if (settings.GetLocal().StashToDepositTo == 0) { Logger.Info("IA is configured to deposit to the second-to-last stash page"); } else { Logger.Info($"IA is configured to deposit to stash page #{settings.GetLocal().StashToDepositTo}"); } using (var session = factory.OpenSession()) { var numItemsStored = session.CreateCriteria <PlayerItem>() .SetProjection(NHibernate.Criterion.Projections.RowCountInt64()) .UniqueResult <long>(); Logger.Info($"There are {numItemsStored} items stored in the database."); } if (settings.GetPersistent().ShowRecipesAsItems) { Logger.Info("Show recipes as items is enabled"); } else { Logger.Info("Show recipes as items is disabled"); } Logger.Info("Transfer to any mod is " + (settings.GetPersistent().TransferAnyMod ? "enabled" : "disabled")); Logger.Info("Experimental updates is " + (settings.GetPersistent().SubscribeExperimentalUpdates ? "enabled" : "disabled")); var mods = GlobalPaths.TransferFiles; if (mods.Count == 0) { Logger.Warn("No transfer files has been found"); } else { Logger.Info("The following transfer files has been found:"); foreach (var mod in mods) { Logger.Info($"\"{mod.Filename}\": Mod: \"{mod.Mod}\", HC: {mod.IsHardcore}"); } } Logger.Info("There are items stored for the following mods:"); foreach (var entry in new PlayerItemDaoImpl(factory, new DatabaseItemStatDaoImpl(factory, dialect), dialect).GetModSelection()) { Logger.Info($"Mod: \"{entry.Mod}\", HC: {entry.IsHardcore}"); } var gdPath = new DatabaseSettingDaoImpl(factory, dialect).GetCurrentDatabasePath(); if (string.IsNullOrEmpty(gdPath)) { Logger.Info("The path to Grim Dawn is unknown (not great)"); } else { Logger.Info($"The path to Grim Dawn is \"{gdPath}\""); } Logger.Info("Startup data dump complete"); }
public void Add(T entity) { SessionFactory.GetCurrentSession(_context).Save(entity); }
public void Should_load_the_matching_instance_and_send_it_the_message() { using (ISession session = SessionFactory.OpenSession()) session.Load <TestInstance>(27).ShouldNotBeNull(); }
public static void Init(string connectionString) { SessionFactory.Init(connectionString); DomainEvents.Init(); }
public T FindBy(TEntityKey id) { return(SessionFactory.GetCurrentSession(_context).Get <T>(id)); }
public override void TearDown() { SessionFactory.Dispose(); SessionFactory = null; SessionFactoryProvider = null; }
public void Remove(T entity) { SessionFactory.GetCurrentSession(_context).Delete(entity); }
public DisenrollCommandHandler(SessionFactory sessionFactory) { _sessionFactory = sessionFactory; }
public static ISession BeginSessionTransaction() { Session = SessionFactory.OpenSession(); return(Session); }
/// <summary> /// Get the list of repositories of a CMIS server /// Each item contains id + /// </summary> /// <returns>The list of repositories. Each item contains the identifier and the human-readable name of the repository.</returns> static public Dictionary <string, string> GetRepositories(ServerCredentials credentials) { Dictionary <string, string> result = new Dictionary <string, string>(); // If no URL was provided, return empty result. if (credentials.Address == null) { return(result); } // Create session factory. SessionFactory factory = SessionFactory.NewInstance(); Dictionary <string, string> cmisParameters = new Dictionary <string, string>(); cmisParameters[SessionParameter.BindingType] = BindingType.AtomPub; cmisParameters[SessionParameter.AtomPubUrl] = credentials.Address.ToString(); cmisParameters[SessionParameter.User] = credentials.UserName; cmisParameters[SessionParameter.Password] = credentials.Password.ToString(); IList <IRepository> repositories; try { repositories = factory.GetRepositories(cmisParameters); } catch (DotCMIS.Exceptions.CmisPermissionDeniedException e) { Logger.Debug("CMIS server found, but permission denied. Please check username/password. " + Utils.ToLogString(e)); throw; } catch (CmisRuntimeException e) { Logger.Debug("No CMIS server at this address, or no connection. " + Utils.ToLogString(e)); throw; } catch (CmisObjectNotFoundException e) { Logger.Debug("No CMIS server at this address, or no connection. " + Utils.ToLogString(e)); throw; } catch (CmisConnectionException e) { Logger.Debug("No CMIS server at this address, or no connection. " + Utils.ToLogString(e)); throw; } catch (CmisInvalidArgumentException e) { Logger.Debug("Invalid URL, maybe Alfresco Cloud? " + Utils.ToLogString(e)); throw; } // Populate the result list with identifier and name of each repository. foreach (IRepository repo in repositories) { if (!Utils.IsRepoNameHidden(repo.Name, ConfigManager.CurrentConfig.HiddenRepoNames)) { result.Add(repo.Id, repo.Name); } } return(result); }
public UnregisterCommandHandler(SessionFactory sessionFactory) { _sessionFactory = sessionFactory; }
public TransferCommandHandler(SessionFactory sessionFactory) { _sessionFactory = sessionFactory; }
private static void Run(string[] args, ThreadExecuter threadExecuter) { var factory = new SessionFactory(); // Settings should be upgraded early, it contains the language pack etc and some services depends on settings. var settingsService = StartupService.LoadSettingsService(); IPlayerItemDao playerItemDao = new PlayerItemRepo(threadExecuter, factory); IDatabaseItemDao databaseItemDao = new DatabaseItemRepo(threadExecuter, factory); RuntimeSettings.InitializeLanguage(settingsService.GetLocal().LocalizationFile, databaseItemDao.GetTagDictionary()); DumpTranslationTemplate(); threadExecuter.Execute(() => new MigrationHandler(factory).Migrate()); IDatabaseSettingDao databaseSettingDao = new DatabaseSettingRepo(threadExecuter, factory); LoadUuid(databaseSettingDao); var azurePartitionDao = new AzurePartitionRepo(threadExecuter, factory); IDatabaseItemStatDao databaseItemStatDao = new DatabaseItemStatRepo(threadExecuter, factory); IItemTagDao itemTagDao = new ItemTagRepo(threadExecuter, factory); IBuddyItemDao buddyItemDao = new BuddyItemRepo(threadExecuter, factory); IBuddySubscriptionDao buddySubscriptionDao = new BuddySubscriptionRepo(threadExecuter, factory); IRecipeItemDao recipeItemDao = new RecipeItemRepo(threadExecuter, factory); IItemSkillDao itemSkillDao = new ItemSkillRepo(threadExecuter, factory); AugmentationItemRepo augmentationItemRepo = new AugmentationItemRepo(threadExecuter, factory, new DatabaseItemStatDaoImpl(factory)); var grimDawnDetector = new GrimDawnDetector(settingsService); Logger.Debug("Updating augment state.."); augmentationItemRepo.UpdateState(); // TODO: GD Path has to be an input param, as does potentially mods. ParsingService parsingService = new ParsingService(itemTagDao, null, databaseItemDao, databaseItemStatDao, itemSkillDao, settingsService.GetLocal().LocalizationFile); StartupService.PrintStartupInfo(factory, settingsService); if (RuntimeSettings.Language is EnglishLanguage language) { foreach (var tag in itemTagDao.GetClassItemTags()) { language.SetTagIfMissing(tag.Tag, tag.Name); } } if (args != null && args.Any(m => m.Contains("-logout"))) { Logger.Info("Started with -logout specified, logging out of online backups."); settingsService.GetPersistent().AzureAuthToken = null; } using (CefBrowserHandler browser = new CefBrowserHandler()) { _mw = new MainWindow(browser, databaseItemDao, databaseItemStatDao, playerItemDao, azurePartitionDao, databaseSettingDao, buddyItemDao, buddySubscriptionDao, recipeItemDao, itemSkillDao, itemTagDao, parsingService, augmentationItemRepo, settingsService, grimDawnDetector ); Logger.Info("Checking for database updates.."); StartupService.PerformIconCheck(databaseSettingDao, grimDawnDetector); _mw.Visible = false; if (new DonateNagScreen(settingsService).CanNag) { Application.Run(new DonateNagScreen(settingsService)); } Logger.Info("Running the main application.."); StartupService.PerformGrimUpdateCheck(settingsService); Application.Run(_mw); } Logger.Info("Application ended."); }