public async Task AddServer(string serverAddress)
 {
     if (_serverAddresses.Exists(x => x == serverAddress))
     {
         throw new Exception("Server already exists");
     }
     _serverAddresses.Add(serverAddress);
     var session = _sessionFactory.Create();
     await session.AddAsync(new Server(serverAddress));
 }
Example #2
0
        public async Task InitSettings()
        {
            var session             = _sessionFactory.Create();
            var areSettingsExisting = session.Get <Settings>().Any();

            if (!areSettingsExisting)
            {
                await session.AddAsync(new Settings(DEFAULT_PERIOD, isRunning : false));
            }
        }
        public IEnumerable <Category> Execute(IEnumerable <WcfHierarchicalTaxon> departments)
        {
            _session = SessionFactory.Create(ConnectionString);
            var sfCategories = departments.ToList();
            var categories   = new List <Category>();

            try
            {
                foreach (var sfCategory in sfCategories)
                {
                    var category = BuildCategory(sfCategory);
                    if (category == null)
                    {
                        continue;
                    }

                    categories.Add(BuildCategory(sfCategory));
                }

                BuildParentChildCategoryRelationships(categories, sfCategories);
            }
            finally
            {
                _session.Close();
            }

            return(categories);
        }
        public async Task <ActionResult <Session> > Create()
        {
            UserModel user = await userManager.GetUserAsync(HttpContext.User);

            if (user?.UserId == null)
            {
                return(StatusCode(StatusCodes.Status403Forbidden));
            }

            Session session = SessionFactory.Create(user);

            await sessionService.Create(session);

            Game game = new Game {
                Id = session.Id
            };

            Board board = BoardFactory.New(session.Id);

            GameOperations.AddPlayer(game, user.UserId);


            await gameService.Create(game);

            await boardService.Create(board);

            user.AddSession(session);
            await userManager.UpdateAsync(user);

            return(CreatedAtRoute("GetSession", new { id = session.Id }, session));
        }
Example #5
0
        /// <summary>
        /// Persist categories and parent/child category relationships to Ucommerce
        /// </summary>
        /// <param name="categories">transformed categories</param>
        public void Send(IEnumerable <Category> categories)
        {
            var newCategories = categories.ToList();

            _session = SessionFactory.Create(ConnectionString);

            try
            {
                WriteCategories(newCategories);
            }
            catch (Exception ex)
            {
                Log.Fatal($"A fatal exception occurred trying to write category data to Ucommerce: \n{ex}");
                throw new MigrationException("A fatal exception occurred trying to write category data to Ucommerce", ex);
            }

            try
            {
                WriteCategoryRelationships(newCategories);
            }
            catch (Exception ex)
            {
                Log.Fatal($"A fatal exception occurred trying to write product definition data to Ucommerce: \n{ex}");
                throw new MigrationException("A fatal exception occurred trying to write category data to Ucommerce", ex);
            }

            Log.Info("category migration done.");
        }
        public override string SetNewData(XtraReport report, string defaultUrl)
        {
            // Save a report to the storage under a new URL.
            // The defaultUrl parameter contains the report display name specified by a user.
            if (CanSetData(defaultUrl))
            {
                SetData(report, defaultUrl);
            }
            else
            {
                using (var session = SessionFactory.Create()) {
                    MemoryStream ms = new MemoryStream();
                    report.SaveLayout(ms);

                    var reportEntity = new ReportEntity(session)
                    {
                        Url    = defaultUrl,
                        Layout = ms.ToArray()
                    };

                    session.CommitChanges();
                }
            }
            return(defaultUrl);
        }
 public override Dictionary <string, string> GetUrls()
 {
     // Get URLs and display names for all reports available in the storage
     using (var session = SessionFactory.Create()) {
         return(session.Query <ReportEntity>().ToDictionary <ReportEntity, string, string>(report => report.Url, report => report.Url));
     }
 }
Example #8
0
        protected override void TestFilterByOneWithManyProducts_Impl()
        {
            using (var session = SessionFactory.Create())
            {
                foreach (var num in Enumerable.Range(1, 3000))
                {
                    var product = new Product
                    {
                        Code = num.ToString(),
                        Name = new MultiCulturalString(ru, "RU_" + num)
                               .SetLocalizedString(en, "EN_" + num)
                    };
                    session.Add(product);
                }
            }


            using (var session = SessionFactory.Create())
            {
                Func <Product> actualProduct = () => session.AsQueryable <Product>()
                                               .SingleOrDefault(p => p.Name.ToString() == "RU_2017");

                Assert.That(actualProduct, Is.Not.Null.After(100));
            }
        }
 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 override bool CanSetData(string url)
 {
     // Check if the URL is available in the report storage.
     using (var session = SessionFactory.Create()) {
         return(session.GetObjectByKey <ReportEntity>(url) != null);
     }
 }
        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();
            }
        }
Example #12
0
        public void Setup()
        {
            this.sessionFactory     = SessionFactory.Create();
            this.employeeNHibernate = new EmployeeNH(this.sessionFactory);

            this.BeginTransaction();
        }
 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 IEnumerable <ProductDefinition> Execute(IEnumerable <ProductTypeViewModel> sfProductTypes)
        {
            _session = SessionFactory.Create(ConnectionString);
            var productDefinitionList = new List <ProductDefinition>();

            try
            {
                foreach (var sfProductType in sfProductTypes)
                {
                    var definition = _session.Query <ProductDefinition>()
                                     .FirstOrDefault(a => a.Name == sfProductType.Title);
                    if (definition != null)
                    {
                        continue;
                    }

                    var newDefinition = (new ProductDefinition()
                    {
                        Name = sfProductType.Title
                    });

                    AddInventoryDefinitionField(newDefinition);
                    AddCustomDefinitionFields(newDefinition, sfProductType);
                    productDefinitionList.Add(newDefinition);
                }
            }
            finally
            {
                _session.Close();
            }

            return(productDefinitionList);
        }
 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 override string SetNewData(DevExpress.XtraReports.UI.XtraReport report, string defaultUrl)
        {
            // Save a report to the storage under a new URL.
            // The defaultUrl parameter contains the report display name specified by a user.
            if (CanSetData(defaultUrl))
            {
                SetData(report, defaultUrl);
            }
            else
            {
                using (var session = SessionFactory.Create())
                {
                    MemoryStream ms = new MemoryStream();
                    report.SaveLayout(ms);

                    var reportEntity = new TSOUTERREPORT(session)
                    {
                        Url = defaultUrl
                    };
                    this.SaveToFile(reportEntity.Url, ms);
                    session.CommitChanges();
                }
            }
            return(defaultUrl);
        }
        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 ScannedServersService(SessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
            var session = sessionFactory.Create();

            _serverAddresses = session.Get <Server>().Select(x => x.Address).ToList();
        }
 public override byte[] GetData(string url)
 {
     // Get the report data from the storage.
     using (var session = SessionFactory.Create()) {
         var report = session.GetObjectByKey <ReportEntity>(url);
         return(report.Layout);
     }
 }
 public List <GeneralType> GetPackageType()
 {
     using (ISession session = SessionFactory.Create())
     {
         List <PackageTypeModel> packageTypeModel = RepositoriyFactory.GetRepo <IPackageTypeRepository>(session).GetPackageTypes().Where(x => x.IsHandlingUnitOnly == true).ToList();
         return(GeneralTypeMapper.MapPackageToGeneralTypes(packageTypeModel));
     }
 }
 public List <Accessorial> GetNonCommercialAccessorials()
 {
     using (ISession session = SessionFactory.Create())
     {
         List <AccessorialModel> accessorialModels = RepositoriyFactory.GetRepo <IAccessorialRepository>(session).GetNonSpecificAccessorials();
         return(AccessorialMapper.MapToAccessorials(accessorialModels));
     }
 }
 public List <DisabledDate> GetDisabledDates()
 {
     using (ISession session = SessionFactory.Create())
     {
         List <HolidayModel> holidays = RepositoriyFactory.GetRepo <IHolidayRepository>(session).GetHolidays();
         return(HolidayMapper.MapToDisabledDates(holidays));
     }
 }
 public List <Accessorial> GetDestinationSiteAccessorials()
 {
     using (ISession session = SessionFactory.Create())
     {
         List <AccessorialModel> accessorialModels = RepositoriyFactory.GetRepo <IAccessorialRepository>(session).GetDestinationSiteAccessorials();
         return(AccessorialMapper.MapToAccessorials(accessorialModels));
     }
 }
 public List <GeneralType> GetFreightClass()
 {
     using (ISession session = SessionFactory.Create())
     {
         List <FreightClassModel> freightClasses = RepositoriyFactory.GetRepo <IFreightClassRepository>(session).FreightClasses();
         return(GeneralTypeMapper.MapFreightClassesToGeneralTypes(freightClasses));
     }
 }
 public TSOUTERREPORT GetObjectByUrl(string url)
 {
     using (var session = SessionFactory.Create())
     {
         var reports = session.Query <TSOUTERREPORT>()
                       .Where(e => e.Url == url).FirstOrDefault();
         return(reports);
     }
 }
Example #26
0
        public FileProviderExtension()
        {
            ServerSettings serverSettings = AppGroupSettings.GetServerSettings();

            this.Session        = SessionFactory.Create(serverSettings);
            this.LocalStorage   = new LocalStorage();
            this.LocationMapper = new LocationMapper(serverSettings.ServerUri, this.LocalStorage.StorageRootPath);
            this.StorageManager = new StorageManager(this.LocationMapper, this.Session, this.LocalStorage);
        }
        private static void ConfigAuthSession(BaseUser user, WeatherClientType clientType)
        {
            // clean all existing Cache
            //Mobizone.TSIC.Cache.DataCache.RemoveAllCacheBySession();

            var session       = SessionFactory.Create <IBLSessionPersisiter>();
            var clientSession = SessionFactory.Create <IClientSessionPersisiter>();

            session.RemoveSession();
            clientSession.RemoveSession();

            IBaseUserBL bl = BLLFactory.Create <IBaseUserBL>();

            session.UserID       = user.ID;
            session.BaseEmployee = user.BASE_EMPLOYEE;
            session.ProdType     = 1; //登录成功默认PND

            //var division = BLLFactory.Create<IBaseDictBL>().GetItemNameByCached(BaseDictType.DictTypeDivision,user.BaseEmployee.DIVISION);
            //if(division == BaseDictType.DivisionTypeMND) {
            //  session.ProdType = 2;
            //}

            clientSession.ClientType = clientType;

            //session.UserType = user.UserType;

            session.Roles = ExpendRole(bl.GetUserRoles(user.ID)); // load all the role

            //// Data Auth
            //var orgBL = BLLFactory.Create<IBaseOrgBL>();
            ISet <decimal> authOrg = new HashSet <decimal>();

            //var splitDate = DateTime.Parse("2012-03-07 03:00:00");
            //if(user.Updated == null || user.Updated < splitDate) {
            //  // 老式的ETMS授权
            //  authOrg = orgBL.FilterAbtCityOrgByCached(user.OrgAuth);
            //} else {
            //  authOrg = orgBL.ExpendOrgToAbtCityByCached(user.OrgAuth);
            //}
            //var userOrg = user.BaseEmployee.OrgID;
            //if(null != userOrg) {
            //  authOrg.Add(userOrg.Value);

            //  //展开到城市一级
            //  session.DataCenterCityAuth = orgBL.ExpendOrgToCenterCityByCached(userOrg.Value);
            //}

            //// Data Auth: PGS 自动授权 所有PG所在雅培城市
            //if(session.Roles.Contains(WeatherRole.PGM_PGS)) {
            //  var empBL = BLLFactory.Create<IBaseEmployeeBL>();
            //  var orgs = empBL.GetChildAbtCityBind(session.BaseEmployee.ID);
            //  authOrg.AddAll(orgs);
            //}

            session.DataOrgAuth = authOrg;
        }
 public CustomerInfo GetCustomerInfo(String email)
 {
     using (ISession session = SessionFactory.Create())
     {
         UserPersonalInfoModel userPersonalInfoModel = RepositoriyFactory.GetRepo <IUserPersonalInfoRepositoriy>(session).GetUserPersonalInfo(email);
         CustomerUserModel     customerUser          = RepositoriyFactory.GetRepo <ICustomerUserRepository>(session).GetCustomerUser(userPersonalInfoModel.UserPersonalInfoId);
         CustomerModel         customer = RepositoriyFactory.GetRepo <ICustomerRepository>(session).GetCustomer(customerUser.CustomerId);
         return(CustomerMapper.MapToCustomerInfo(customer));
     }
 }
        public ActionResult Delete(string url)
        {
            using (var session = SessionFactory.Create()) {
                var report = session.GetObjectByKey <ReportEntity>(url);
                session.Delete(report);

                session.CommitChanges();
            }
            return(Index());
        }
Example #30
0
        protected void AndGivenAValidSessionFactory()
        {
            _sessionFactory = new SessionFactory(_conString, _config);

            using (var session = _sessionFactory.Create())
            {
                // test connection
                session.Dispose();
            }
        }
 public override byte[] GetData(string url)
 {
     // Get the report data from the storage.
     using (var session = SessionFactory.Create())
     {
         MemoryStream vs = this.ReadFromFile(url);
         return(vs.ToArray());
         //return report.Layout;
     }
 }
        public bool RemoveSession()
        {
            var session = SessionFactory.Create <IBLSessionPersisiter>();

            session.RemoveSession();
            var clientSession = SessionFactory.Create <IClientSessionPersisiter>();

            clientSession.RemoveSession();
            return(true);
        }
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception == null)
            {
                return;
            }
            HttpContext.Current.Response.TrySkipIisCustomErrors = true;
            var exception = actionExecutedContext.Exception;

            try {
                var    clientSession = SessionFactory.Create <IClientSessionPersisiter>();
                var    session       = SessionFactory.Create <IBLSessionPersisiter>();
                string info          = clientSession.ClientType.ToString() + ";" + clientSession.ClientVersion;
                if (session.BaseEmployee != null)
                {
                    info += ";" + session.BaseEmployee.ID;
                }
                log.Fatal(string.Format("ErrorInfo={{{2}}}\nurl={{{0}}}\n body={{{1}}}", actionExecutedContext.Request.RequestUri,
                                        actionExecutedContext.Request.Content.ReadAsStringAsync().Result,
                                        info));
            } catch {
            }
            log.Fatal(exception);
            if (exception.InnerException != null)
            {
                exception = exception.InnerException;
                log.Fatal(exception.InnerException);
            }
            var controller = actionExecutedContext.ActionContext.ControllerContext.Controller as TSICAppJsonAPIController;

            if (controller != null)
            {
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new AppJsonResponse()
                {
                    Meta = new JsonAsyncObjectMetaData()
                    {
                        Type = "ExceptionModel",
                        Uri  = "Exception",
                    },
                    Data = new ExceptionModel()
                    {
                        Message = exception.Message,
                        Type    = exception.GetType().FullName,
                    }
                });
            }
            else
            {
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
                    HttpStatusCode.InternalServerError, new ErrorList {
                    Status  = "Error",
                    Message = exception.Message
                });
            }
        }
Example #34
0
 /// <summary>
 ///     Initializes the message context.
 /// </summary>
 /// <param name="messageContext">The message context.</param>
 /// <param name="args">The args.</param>
 /// <param name="currentSession">The current session.</param>
 private static void InitializeContext(IMessageContext messageContext,
                                       OutputGatewayEventHandlerArgs <TMessage, MessageHeader> args,
                                       Session currentSession)
 {
     messageContext.MessageInfo.Body               = args.Message;
     messageContext.MessageInfo.Header             = (MessageHeader)args.Header.Clone();
     messageContext.MessageInfo.CurrentSession     = currentSession;
     messageContext.MessageInfo.CurrentCallContext = args.Header.CallContext != null
                                                         ? (Session)args.Header.CallContext.Clone()
                                                         : SessionFactory.Create();
 }
Example #35
0
        public void TestExtendedSettings()
        {
            IApplication         app          = new NullApplication();
            IMessageStoreFactory storeFactory = new MemoryStoreFactory();
            SessionFactory       factory      = new SessionFactory(app, storeFactory);

            SessionID  sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET");
            Dictionary settings  = new Dictionary();

            settings.SetString(SessionSettings.USE_DATA_DICTIONARY, "N");
            settings.SetString(SessionSettings.SEND_REDUNDANT_RESENDREQUESTS, "Y");
            settings.SetString(SessionSettings.RESEND_SESSION_LEVEL_REJECTS, "Y");
            settings.SetString(SessionSettings.MILLISECONDS_IN_TIMESTAMP, "Y");
            settings.SetString(SessionSettings.CONNECTION_TYPE, "initiator");
            settings.SetString(SessionSettings.HEARTBTINT, "30");
            settings.SetString(SessionSettings.START_TIME, "12:00:00");
            settings.SetString(SessionSettings.END_TIME, "12:00:00");
            settings.SetString(SessionSettings.ENABLE_LAST_MSG_SEQ_NUM_PROCESSED, "Y");
            settings.SetString(SessionSettings.MAX_MESSAGES_IN_RESEND_REQUEST, "2500");
            settings.SetString(SessionSettings.SEND_LOGOUT_BEFORE_TIMEOUT_DISCONNECT, "Y");
            settings.SetString(SessionSettings.IGNORE_POSSDUP_RESEND_REQUESTS, "Y");

            Session session = factory.Create(sessionID, settings);

            Assert.That(session.SendRedundantResendRequests);
            Assert.That(session.ResendSessionLevelRejects);
            Assert.That(session.MillisecondsInTimeStamp);

            settings.SetString(SessionSettings.SEND_REDUNDANT_RESENDREQUESTS, "N");
            settings.SetString(SessionSettings.RESEND_SESSION_LEVEL_REJECTS, "N");
            settings.SetString(SessionSettings.MILLISECONDS_IN_TIMESTAMP, "N");
            session = factory.Create(sessionID, settings);

            Assert.That(!session.SendRedundantResendRequests);
            Assert.That(!session.ResendSessionLevelRejects);
            Assert.That(!session.MillisecondsInTimeStamp);
            Assert.That(session.EnableLastMsgSeqNumProcessed);
            Assert.That(session.MaxMessagesInResendRequest, Is.EqualTo(2500));
            Assert.That(session.SendLogoutBeforeTimeoutDisconnect);
            Assert.That(session.IgnorePossDupResendRequests);
        }
Example #36
0
        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 Create(FormCollection collection)
        {
            var model = new TrainNeed();
            TryUpdateModel(model, collection.ToValueProvider());
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            using (var session = new SessionFactory().OpenSession())
            {

                session.BeginTransaction();
                var dept = new Criteria<Department>(session)
                  .AndIn<User>(m => m.Id, n => n.DepartmentId, m => m.Code.Equals(CurrentAccountNo)).Load();
                var models = session.Find<TrainNeed>(m => !m.IsCollected && m.Status.Equals(TrainNeedStatus.已提交部门负责人) && m.DeptId == dept.Id && m.Type.Equals(TrainNeedType.员工));
                if (models == null || !models.Any())
                {
                    FlashWarn("没有未汇总的需求!");
                    return Close();
                }
                foreach (var trainNeed in models)
                {
                    trainNeed.IsCollected = true;
                }
                model.DeptId = dept != null ? dept.Id : 0;
                model.Dept = dept != null ? dept.Name : null;
                model.IsCollected = false;
                model.CreatedAt = DateTime.Now;
                model.CreatedBy = CurrentAccountNo;
                model.Type = TrainNeedType.部门;
                ViewData.Model = model;
                ViewData["StaffNeeds"] = models;
                var exist = session.Load<TrainNeed>(m => m.Type.Equals(TrainNeedType.部门) && m.DeptId.Equals(model.DeptId) && m.Year.Equals(model.Year));
                if (exist != null)
                {
                    ModelState.AddModelError("Year", "本部门该年度部门培训需求已经存在!");
                    return View(model);
                }
                if (session.Create(model) && session.Update(models))
                {
                    session.Commit();
                    FlashSuccess("创建记录成功!");
                    return Close();
                }
                session.Rollback();
                FlashFailure("创建记录失败!");
                return View();
            }
        }
        public ActionResult Create(FormCollection collection)
        {
            var model = new TrainNeed();
            TryUpdateModel(model, collection.ToValueProvider());
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            using (var session = new SessionFactory().OpenSession())
            {

                session.BeginTransaction();
                var models = session.Find<TrainNeed>(m =>
                        !m.IsCollected && m.Status.Equals(TrainNeedStatus.已提交培训部门) && m.Type.Equals(TrainNeedType.部门));
                if (models == null || !models.Any())
                {
                    FlashWarn("没有未汇总的需求!");
                    return Close();
                }
                foreach (var trainNeed in models)
                {
                    trainNeed.IsCollected = true;
                }
                model.IsCollected = false;
                model.CreatedAt = DateTime.Now;
                model.CreatedBy = CurrentAccountNo;
                model.Type = TrainNeedType.公司;
                ViewData["StaffNeeds"] = models;
                ViewData.Model = model;
                var exist = session.Load<TrainNeed>(m => m.Type.Equals(TrainNeedType.公司) && m.Year.Equals(model.Year));
                if (exist != null)
                {
                    ModelState.AddModelError("Year", "该年度公司培训需求已经存在!");
                    return View(model);
                }
                if (session.Create(model) && session.Update(models))
                {
                    session.Commit();
                    FlashSuccess("创建记录成功!");
                    return Close();
                }
                session.Rollback();
                FlashFailure("创建记录失败!");
                return View();
            }
        }
        public ActionResult Create(FormCollection collection)
        {
            var model = new InstitutionManagement { UploadPerson = CurrentAccountNo.GetName() };
            TryUpdateModel(model, collection.ToValueProvider());
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            using (var session = new SessionFactory().OpenSession())
            {
                for (var i = 0; i < Request.Files.Count; i++)
                {
                    // 检查文件后缀名
                    var file = Request.Files[i];
                    if (file == null || file.ContentLength <= 0) continue;

                    var ext = Path.GetExtension(file.FileName);
                    if (string.IsNullOrEmpty(ext) || (!ext.Equals(".doc") && !ext.Equals(".docx")))
                    {
                        FlashFailure("文件 '{0}' 后缀名不符合要求 (doc,docx)", file.FileName);
                        return View();
                    }
                    var uppath = Server.MapPath("~/upload/");
                    var item = new UploadFile();
                    item.SaveFile(file, uppath, CurrentAccountNo);
                    item.CreateHtml();
                    model.FileId = item.Id;
                    model.FileName = file.FileName;

                }

                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 Create(FormCollection collection)
        {
            var model = new TrainNeed();
            TryUpdateModel(model, collection.ToValueProvider());
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            using (var session = new SessionFactory().OpenSession())
            {
                session.BeginTransaction();

                model.StaffCode = CurrentAccountNo;
                model.StaffName = CurrentAccountNo.GetName();
                var dept = new Criteria<Department>(session)
                   .AndIn<User>(m => m.Id, n => n.DepartmentId, m => m.Code.Equals(CurrentAccountNo)).Load();
                model.DeptId = dept != null ? dept.Id : 0;
                model.Dept = dept != null ? dept.Name : null;
                model.IsCollected = false;
                model.CreatedAt = DateTime.Now;
                model.CreatedBy = CurrentAccountNo;
                model.Type = TrainNeedType.员工;
                model.Status = "";
                var exist = session.Load<TrainNeed>(m => m.Type.Equals(TrainNeedType.员工) && m.DeptId.Equals(model.DeptId) && m.Year.Equals(model.Year) && m.StaffCode.Equals(CurrentAccountNo));
                if (exist != null)
                {
                    ModelState.AddModelError("Year", "您该年度需求已经存在!");
                    return View(model);
                }
                ViewData.Model = model;
                if (session.Create(model))
                {
                    session.Commit();
                    FlashSuccess("创建记录成功!");
                    return Close();
                }
                session.Rollback();
                FlashFailure("创建记录失败!");
                return View();
            }
        }
 public ActionResult Create(FormCollection collection)
 {
     var view = new TrainExperienceView();
     TryUpdateModel(view, collection.ToValueProvider());
     if (!ModelState.IsValid)
     {
         return View(view);
     }
     using (var session = new SessionFactory().OpenSession())
     {
         session.BeginTransaction();
         var model = new TrainExperience
         {
             CreatedAt = DateTime.Now,
             CreatedBy = CurrentAccountNo,
             TrainManItemId = view.TrainManItemId,
             Experience = view.Experience,
             Status = "",
             ApproveStatus = ""
         };
         if (null != session.Load<TrainExperience>(m => m.TrainManItemId.Equals(model.TrainManItemId)))
         {
             ModelState.AddModelError("TrainManName", "该培训心得已经存在!");
             return View(view);
         }
         ViewData.Model = view;
         if (session.Create(model))
         {
             session.Commit();
             FlashSuccess("创建记录成功!");
             return Close();
         }
         session.Rollback();
         FlashFailure("创建记录失败!");
         return View();
     }
 }
        public new ActionResult User(FormCollection collection, long[] ids)
        {
            if (ids.Length == 0)
            {
                FlashInfo("请选择要查看用户的角色。");
                return Close();
            }
            using (var session = new SessionFactory().OpenSession())
            {
                session.BeginTransaction();
                var roles = session.Find<Role>(m => m.Id.In(ids));
                if (roles == null || roles.Count == 0)
                {
                    FlashInfo("请选择要查看用户的角色。");
                    return Close();
                }
                ViewData["roleName"] = string.Join(",", roles.Select(m => m.Name));

                var roleIds = roles.Select(m => m.Id).ToList();
                var userIds = Request.Params["select_id"].ToLongArray();

                session.Delete<AccountRoleRef>(m => m.RoleId.In(ids));
                if (userIds.Length > 0)
                {
                    var q = new Criteria<Account>(session)
                        .AndIn<User>(m => m.Name, n => n.Code, n => n.Id.In(userIds))
                        .Select(m => m.Id);
                    var accountIds = q.To<long>();

                    if (accountIds.Count < userIds.Length)
                    {
                        FlashWarn("有{0}个用户没有激活,请全部激活后再操作。", userIds.Length - accountIds.Count);
                        return Close();
                    }

                    var toCreateItems = (from accountId in accountIds
                                         from roleId in roleIds
                                         select
                                             new AccountRoleRef
                                                 {
                                                     AccountId = accountId,
                                                     RoleId = roleId,
                                                     CreatedAt = DateTime.Now,
                                                     CreatedBy = CurrentAccountNo
                                                 }).ToArray();
                    if (toCreateItems.Length > 0)
                    {
                        if (session.Create(toCreateItems))
                        {
                            session.Commit();
                            FlashSuccess("给角色分配用户成功!");
                            return Close();
                        }
                    }
                    session.Rollback();
                    FlashFailure("给角色分配用户失败!");
                    return User(ids);
                }
                session.Commit();
                FlashSuccess("取消角色全部用户成功!");
                return Close();
            }
        }
        public ActionResult Pintask(FormCollection collection, long[] ids)
        {
            if (ids.Length == 0)
            {
                FlashInfo("请选择要查看用户的角色。");
                return Close();
            }
            using (var session = new SessionFactory().OpenSession())
            {
                var roles = session.Find<Role>(m => m.Id.In(ids));
                if (roles == null || roles.Count == 0)
                {
                    FlashInfo("请选择要查看用户的角色。");
                    return Close();
                }
                ViewData["roleName"] = string.Join(",", roles.Select(m => m.Name));

                var roleIds = roles.Select(m => m.Id).ToList();
                var navIds = Request.Params["select_id"].ToLongArray();

                session.Delete<AccountNavigationRef>(m => m.Type.Equals(NavigationPriviledge.RoleType) && m.OwnerId.In(ids));

                var toCreateItems = (from navId in navIds
                                     from roleId in roleIds
                                     select new AccountNavigationRef { OwnerId = roleId, NavigationId = navId, Type = AccountNavigationRef.RoleType, CreatedAt = DateTime.Now, CreatedBy = CurrentAccountNo }).ToArray();
                if (toCreateItems.Length > 0)
                {
                    if (session.Create(toCreateItems))
                    {
                        FlashSuccess("给角色设置常用功能成功!");
                        return Close();
                    }
                }
                FlashFailure("给角色设置常用功能失败!");
                return Pintask(ids);
            }
        }
Example #44
0
 //public bool AddOrganization(Organization organization)
 //{
 //    if (organization == null || organization.Id <= 0) return false;
 //    if (Id <= 0) return false;
 //    var q = new Criteria<AccountOrganizationRef>().Where(m => m.AccountId.Equals(Id) && m.OrganizationId.Equals(organization.Id));
 //    if (q.Count() > 0) return true;
 //    var r = new AccountOrganizationRef { AccountId = Id, OrganizationId = organization.Id };
 //    var db = new SessionFactory().OpenSession();
 //    return db.Create(r);
 //}
 public bool AddRole(Role role)
 {
     if (role == null || role.Id <= 0) return false;
     if (Id <= 0) return false;
     Criteria<AccountRoleRef> q =
         new Criteria<AccountRoleRef>().Where(m => m.AccountId.Equals(Id) && m.RoleId.Equals(role.Id));
     if (q.Count() > 0) return true;
     Session db = new SessionFactory().OpenSession();
     var r = new AccountRoleRef { AccountId = Id, RoleId = role.Id };
     return db.Create(r);
 }
        public ActionResult Exam(FormCollection collection, long[] ids)
        {
            if (ids.Length == 0)
            {
                FlashWarn("考试不存在!请联系管理员!");
                return Close();
            }
            using (var session = new SessionFactory().OpenSession())
            {
                session.BeginTransaction();
                var trainManagementItem = session.Load<TrainManagementItem>(ids[0]);
                if (trainManagementItem == null)
                {
                    session.Rollback();
                    FlashWarn("培训明细不存在!请联系管理员!");
                    return Close();
                }
                var exam = session.Load<Exam>(m => m.TrainManId == trainManagementItem.TrainManId);
                if (exam == null)
                {
                    session.Rollback();
                    FlashWarn("考试不存在!请联系管理员!");
                    return Close();
                }
                ViewData["ExamContent"] = exam.HtmlContent;
                var models = session.Find<Question>(m => m.ExamId == exam.Id);
                if (models == null || !models.Any())
                {
                    session.Rollback();
                    FlashWarn("考试题目未设置!");
                    return Close();
                }

                var answerList = new List<ExamAnswer>();
                foreach (var question in models)
                {
                    var answerStr = GetDbQueryPara(question.Id + "");
                    var answer = new ExamAnswer
                    {
                        CreatedAt = DateTime.Now,
                        CreatedBy = "SYSTEM",
                        Answer = answerStr,
                        QuestionId = question.Id,
                        StaffCode = CurrentAccountNo,
                        StaffName = CurrentAccountNo.GetName(),
                        TrainManagementItemId = trainManagementItem.Id
                    };
                    if(question.Type.Contains("选"))
                    {
                        answer.Score = answer.Answer.Replace(",", "").ToUpper().Equals(question.RightAnswer.ToUpper()) ? question.Value : 0;
                    }

                    answerList.Add(answer);
                }
                trainManagementItem.ExamStatus = ExamStatusConst.已考试;
                trainManagementItem.UpdatedAt = DateTime.Now;
                trainManagementItem.UpdatedBy = "SYSTEM";
                if (session.Update(trainManagementItem) && session.Create(answerList))
                {
                    session.Commit();
                    Response.Write("<script>window.close()</script>");
                    return Close();
                }
                session.Rollback();
                FlashError("提交试卷不成功,请联系管理员!");
                return View(models);
            }
        }
 //#region 通用控制器模块
 //public ActionResult CommonCreate<TModel>(FormCollection collection,
 //    Func<Session, bool> onTouch = null,
 //    Func<TModel, Session, bool> beforePersistance = null,
 //    Func<TModel, Session, bool> afterPersistance = null
 //    ) where TModel : class, new()
 //{
 //    using (var session = new SessionFactory().OpenSession())
 //    {
 //        try
 //        {
 //            session.BeginTransaction();
 //            if (onTouch != null && !onTouch(session))
 //            {
 //                return Close();
 //            }
 //            var model = new TModel();
 //            TryUpdateModel(model, collection);
 //            if (!ModelState.IsValid)
 //            {
 //                // ReSharper disable Mvc.ViewNotResolved
 //                return View(model);
 //                // ReSharper restore Mvc.ViewNotResolved
 //            }
 //            if (beforePersistance != null && !beforePersistance(model, session))
 //            {
 //                return Close();
 //            }
 //            if (typeof(TModel).GetInterface("IDboFollow") == typeof(IDboFollow))
 //            {
 //                model.SetPropertyValue("CreatedAt", DateTime.Now);
 //                model.SetPropertyValue("CreatedBy", CurrentAccountNo);
 //            }
 //            if (session.Create(model))
 //            {
 //                if (afterPersistance == null || afterPersistance(model, session))
 //                {
 //                    session.Commit();
 //                    FlashSuccess("{0}创建成功", SchemaHelper.GetObjectName<TModel>());
 //                    return Close();
 //                }
 //            }
 //            session.Rollback();
 //            FlashFailure("创建{0}失败!", SchemaHelper.GetObjectName<TModel>());
 //            return View(model);
 //        }
 //        catch (Exception ex)
 //        {
 //            session.Rollback();
 //            FlashError("发生错误:{0}", ex.Message);
 //            return View();
 //        }
 //    }
 //}
 //#endregion
 protected void CreateLog(string result = null, string description = null)
 {
     using (var session = new SessionFactory().OpenSession())
     {
         var log = new ActionLog
                       {
                           Controller = ControllerName,
                           Action = ActionName,
                           ModelId = ModelId,
                           UserId = CurrentAccountId,
                           Url = Url,
                           CreatedAt = DateTime.Now,
                           CreatedBy = "SYSTEM",
                           Address = Request.UserHostAddress,
                           Actor = CurrentAccountNo,
                           Category = GetCategory(),
                           Title = GetTitle(),
                           Result = result,
                           Description = description
                       };
         if (!session.Create(log))
         {
             Log.Error("记录日志失败:{0}", log.ToString());
         }
     }
 }
 public ActionResult Create(FormCollection collection)
 {
     var model = new Record();
     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;
         model.Time = DateTime.Now;
         model.Undertaker = CurrentAccountNo.GetName();
         var dept = new Criteria<Department>(session)
             .AndIn<User>(m => m.Id, n => n.DepartmentId, m => m.Code.Equals(CurrentAccountNo)).Load();
         model.DeptId = dept != null ? dept.Id : 0;
         model.Dept = dept != null ? dept.Name : null;
         model.State = "";
         model.ApproveState = "";
         ViewData.Model = model;
         if (session.Create(model))
         {
             session.Commit();
             FlashSuccess("创建记录成功!");
             return Close();
         }
         session.Rollback();
         FlashFailure("创建记录失败!");
         return Close();
     }
 }
        public ActionResult AddNavigation()
        {
            string url = Request.Params["nav"];
            string handleId = Request.Params["handleId"];

            try
            {
                CurrentAccountId = UserActivity.UserNameIdMapHolder.GetId(CurrentAccountNo);
            }
            catch (Exception e)
            {
                Log.Error("系统获取用户ID失败,错误信息:{0}", e.Message);
            }

            using (var session = new SessionFactory().OpenSession())
            {
                const string sql =
                    "SELECT id FROM `navigations` WHERE `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}'))) AND `url` = '{1}'";
                var exceptId = session.ExecuteScalar<string>(string.Format(sql, CurrentAccountNo, url.Replace("'", "''"))).TryToLong();
                if (!exceptId.HasValue)
                {
                    return new JsonResult
                               {
                                   Data = new { status = 100, message = "你未被授权,不能添加该项快捷操作!", handleId },
                                   ContentEncoding = Encoding.UTF8
                               };
                }
                var item =
                    session.Load<AccountNavigationRef>(
                        m => m.Type.Equals(2) && m.OwnerId.Equals(CurrentAccountId) && m.NavigationId.Equals(exceptId));
                if (item != null)
                {
                    return new JsonResult
                               {
                                   Data = new { status = 100, message = "你已添加该项快捷操作!", handleId },
                                   ContentEncoding = Encoding.UTF8
                               };
                }
                item = new AccountNavigationRef
                           {
                               Type = 2,
                               OwnerId = CurrentAccountId,
                               NavigationId = exceptId.GetValueOrDefault(0),
                               CreatedAt = DateTime.Now,
                               CreatedBy = CurrentAccountNo
                           };
                if (session.Create(item))
                {
                    return new JsonResult
                               {
                                   Data = new { status = 200, message = "增加成功!", handleId },
                                   ContentEncoding = Encoding.UTF8
                               };
                }
                return new JsonResult
                           {
                               Data = new { status = 100, message = "操作失败!", handleId },
                               ContentEncoding = Encoding.UTF8
                           };
            }
        }
        public ActionResult Create(FormCollection collection)
        {
            var model = new User();
            TryUpdateModel(model, collection.ToValueProvider());
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            if (model.Name.Equals("root", StringComparison.CurrentCultureIgnoreCase))
            {
                ModelState.AddModelError("Name", "该名称已被使用");
                return View(model);
            }
            using (var session = new SessionFactory().OpenSession())
            {
                session.BeginTransaction();
                if (session.Load<User>(m => m.Name.Equals(model.Name)) != null)
                {
                    FlashWarn("用户{0}已经存在,创建失败。", model.Name);
                    return View(model);
                }
                if (session.Load<User>(m => m.Code.Equals(model.Code)) != null)
                {
                    FlashWarn("工号{0}已经存在,创建失败。", model.Code);
                    return View(model);
                }
                model.IsActive = false;
                model.CreatedAt = DateTime.Now;
                model.CreatedBy = CurrentAccountNo;
                ViewData.Model = model;

                if (session.Create(model) && model.InitAccount(session, CurrentAccountNo))
                {
                    session.Commit();
                    UserActivity.UserNameIdMapHolder.Reset();
                    FlashSuccess("创建用户[{0}]成功!", model.Name);
                    return Close();
                }
                session.Rollback();
                FlashFailure("创建用户[{0}]失败!", model.Name);
                return View();
            }
        }