public ActionResult Logout()
        {
            if (SessionContext != null && SessionContext.User != null)
            {
                using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction())
                {
                    try
                    {
                        SessionContext.UserSession.SessionPeriod.To = DateTime.Now;
                        SessionContext.UserSession.LogoutMessage    = MessageException.AuthenMessage.Logout;
                        SessionContext.UserSession.Save(SessionContext);

                        SessionContext.Log(0, PageID, 0, MessageException.AuthenMessage.Logout, MessageException.Success(SessionContext.User.ID.ToString()));

                        tx.Commit();
                    }
                    catch (Exception ex)
                    {
                        WebLogger.Error(ex.Message);
                        SessionContext.Log(0, PageID, 0, MessageException.AuthenMessage.Logout, MessageException.Fail(ex.Message));
                        tx.Rollback();
                    }
                }
            }

            Session.Clear();
            Session.Abandon();

            return(RedirectToAction("Index", "Login"));
        }
Example #2
0
        public static void StartServices(Action <StartOptions> opts)
        {
            // DI ready
            ServiceLocator.Start = (IServiceLocator locator) =>
            {
                var startOptions = new StartOptions();
                opts?.Invoke(startOptions);

                IProfiler        profiler   = startOptions.Profiler ?? new WebProfiler();
                IUserLocale      userLocale = new WebUserLocale();
                IApplicationHost host       = new WebApplicationHost(profiler, userLocale);
                ILocalizer       localizer  = new WebLocalizer(host, userLocale);

                ITokenProvider tokenProvider = startOptions.TokenProvider;
                IDbContext     dbContext     = new SqlDbContext(
                    profiler as IDataProfiler,
                    host as IDataConfiguration,
                    localizer as IDataLocalizer,
                    host as ITenantManager,
                    tokenProvider);
                IDataScripter    scripter        = new VueDataScripter(host, localizer);
                ILogger          logger          = new WebLogger(host, dbContext);
                IMessageService  emailService    = new IdentityEmailService(logger, host);
                IMessaging       messaging       = new MessageProcessor(host, dbContext, emailService, logger);
                ISmsService      smsService      = new SmsService(dbContext, logger);
                IWorkflowEngine  workflowEngine  = new WorkflowEngine(host, dbContext, messaging);
                IScriptProcessor scriptProcessor = new ScriptProcessor(scripter, host);
                IHttpService     httpService     = new HttpService();

                locator.RegisterService <IDbContext>(dbContext);
                locator.RegisterService <IProfiler>(profiler);
                locator.RegisterService <IApplicationHost>(host);
                locator.RegisterService <ILocalizer>(localizer);
                locator.RegisterService <IDataScripter>(scripter);
                locator.RegisterService <ILogger>(logger);
                locator.RegisterService <IMessageService>(emailService);
                locator.RegisterService <ISmsService>(smsService);
                locator.RegisterService <IMessaging>(messaging);
                locator.RegisterService <IWorkflowEngine>(workflowEngine);
                locator.RegisterService <IScriptProcessor>(scriptProcessor);
                locator.RegisterService <IHttpService>(httpService);
                if (tokenProvider != null)
                {
                    locator.RegisterService <ITokenProvider>(tokenProvider);
                }

                host.StartApplication(false);
                HttpContext.Current.Items.Add("ServiceLocator", locator);
            };

            ServiceLocator.GetCurrentLocator = () =>
            {
                var locator = HttpContext.Current.Items["ServiceLocator"];
                if (locator == null)
                {
                    new ServiceLocator();
                }
                return(HttpContext.Current.Items["ServiceLocator"] as IServiceLocator);
            };
        }
Example #3
0
        public ActionResult LogOut()
        {
            if (SessionContext != null)
            {
                using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction())
                {
                    try
                    {
                        SessionContext.UserSession.SessionPeriod.To = DateTime.Now;
                        SessionContext.UserSession.LogoutMessage    = "Logout";
                        SessionContext.UserSession.Save(SessionContext);

                        tx.Commit();
                    }
                    catch (Exception ex)
                    {
                        WebLogger.Error(ex.GetAllMessages());
                        tx.Rollback();
                    }
                }
            }

            Session.Clear();
            Session.Abandon();

            return(RedirectToAction("Index", "Login"));
        }
Example #4
0
        public void StartServices()
        {
            // DI ready
            ServiceLocator.Start = (IServiceLocator locator) =>
            {
                IProfiler        profiler  = new WebProfiler();
                IApplicationHost host      = new WebApplicationHost(profiler);
                ILocalizer       localizer = new WebLocalizer(host);
                IDbContext       dbContext = new SqlDbContext(
                    profiler as IDataProfiler,
                    host as IDataConfiguration,
                    localizer as IDataLocalizer,
                    host as ITenantManager);
                ILogger               logger               = new WebLogger(host, dbContext);
                IMessageService       emailService         = new IdentityEmailService(logger, host);
                IMessaging            messaging            = new MessageProcessor(host, dbContext, emailService, logger);
                IRenderer             renderer             = new XamlRenderer(profiler, host);
                IWorkflowEngine       workflowEngine       = new WorkflowEngine(host, dbContext, messaging);
                IDataScripter         scripter             = new VueDataScripter(host, localizer);
                ISmsService           smsService           = new SmsService(dbContext, logger);
                IExternalLoginManager externalLoginManager = new ExternalLoginManager(dbContext);
                IUserStateManager     userStateManager     = new WebUserStateManager(host, dbContext);
                IExternalDataProvider dataProvider         = new ExternalDataContext();
                IScriptProcessor      scriptProcessor      = new ScriptProcessor(scripter, host);

                locator.RegisterService <IDbContext>(dbContext);
                locator.RegisterService <IProfiler>(profiler);
                locator.RegisterService <IApplicationHost>(host);
                locator.RegisterService <IRenderer>(renderer);
                locator.RegisterService <IWorkflowEngine>(workflowEngine);
                locator.RegisterService <IMessaging>(messaging);
                locator.RegisterService <ILocalizer>(localizer);
                locator.RegisterService <IDataScripter>(scripter);
                locator.RegisterService <ILogger>(logger);
                locator.RegisterService <IMessageService>(emailService);
                locator.RegisterService <ISmsService>(smsService);
                locator.RegisterService <IExternalLoginManager>(externalLoginManager);
                locator.RegisterService <IUserStateManager>(userStateManager);
                locator.RegisterService <IExternalDataProvider>(dataProvider);
                locator.RegisterService <IScriptProcessor>(scriptProcessor);

                HttpContext.Current.Items.Add("ServiceLocator", locator);
            };

            ServiceLocator.GetCurrentLocator = () =>
            {
                if (HttpContext.Current == null)
                {
                    throw new InvalidProgramException("There is no http context");
                }
                var currentContext = HttpContext.Current;
                var locator        = currentContext.Items["ServiceLocator"];
                if (locator == null)
                {
                    new ServiceLocator();
                }
                return(HttpContext.Current.Items["ServiceLocator"] as IServiceLocator);
            };
        }
Example #5
0
        public ActionResult LogOut()
        {
            try
            {
                SessionContext.LogOut(pageID);
            }
            catch (Exception ex)
            {
                WebLogger.Error(ex.GetAllMessages());
            }

            Session.Clear();
            Session.Abandon();

            return(RedirectToAction("Index", "Login"));
        }
Example #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ServiceLocator.Start = (locator) =>
            {
                IProfiler        profiler  = new WebProfiler();
                IApplicationHost host      = new WebApplicationHost(profiler);
                ILocalizer       localizer = new WebLocalizer(host);
                IDbContext       dbContext = new SqlDbContext(
                    profiler as IDataProfiler,
                    host as IDataConfiguration,
                    localizer as IDataLocalizer,
                    host as ITenantManager);
                IDataScripter scripter = new VueDataScripter(host, localizer);
                ILogger       logger   = new WebLogger(host, dbContext);

                locator.RegisterService <IDbContext>(dbContext);
                locator.RegisterService <IProfiler>(profiler);
                locator.RegisterService <IApplicationHost>(host);
                locator.RegisterService <ILocalizer>(localizer);
                locator.RegisterService <IDataScripter>(scripter);
                locator.RegisterService <ILogger>(logger);

                HttpContext.Current.Items.Add("ServiceLocator", locator);
            };

            ServiceLocator.GetCurrentLocator = () =>
            {
                var locator = HttpContext.Current.Items["ServiceLocator"];
                if (locator == null)
                {
                    new ServiceLocator();
                }
                return(HttpContext.Current.Items["ServiceLocator"] as IServiceLocator);
            };
        }
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="description">功能说明</param>
 /// <param name="param">说明参数,可以为空</param>
 public ManagerActionLoggerAttribute(string description, params string[] param)
     : base((e) =>
 {
     int userid;
     int.TryParse(CurrentUser.UserID, out userid);
     var db         = new ManagerContext();
     var repository = new ManagerEfRepository <WebLogger>();
     repository.SetDataContext(db);
     var webLogger = new WebLogger
     {
         ActionName     = e.ActionName,
         ControllerName = e.ControllerName,
         Description    = e.Descrption,
         UserId         = userid,
         UserName       = CurrentUser.UserName,
         RequestParams  = e.RequestParams,
         Authority      = e.Authority,
     };
     repository.Insert(webLogger);
 }, description, param)
 {
     _description = description;
 }
Example #8
0
        public static void StartServices(IAppBuilder app)
        {
            // DI ready
            ServiceLocator.Start = (IServiceLocator locator) =>
            {
                IProfiler        profiler      = new WebProfiler();
                IUserLocale      userLocale    = new WebUserLocale();
                IApplicationHost host          = new WebApplicationHost(profiler, userLocale, locator);
                ILocalizer       localizer     = new WebLocalizer(host, userLocale);
                ITokenProvider   tokenProvider = new WebTokenProvider();
                IDbContext       dbContext     = new SqlDbContext(
                    profiler as IDataProfiler,
                    host as IDataConfiguration,
                    localizer as IDataLocalizer,
                    host as ITenantManager,
                    tokenProvider);
                ILogger               logger               = new WebLogger(host, dbContext);
                IMessageService       emailService         = new IdentityEmailService(logger, host);
                ISmsService           smsService           = new SmsService(dbContext, logger);
                IRenderer             renderer             = new XamlRenderer(profiler, host);
                IDataScripter         scripter             = new VueDataScripter(host, localizer);
                IExternalLoginManager externalLoginManager = new ExternalLoginManager(dbContext);
                IUserStateManager     userStateManager     = new WebUserStateManager(host, dbContext);
                IMessaging            messaging            = new MessageProcessor(host, dbContext, emailService, smsService, logger);
                IWorkflowEngine       workflowEngine       = new WorkflowEngine(host, dbContext, messaging);
                IExternalDataProvider dataProvider         = new ExternalDataContext();
                IScriptProcessor      scriptProcessor      = new ScriptProcessor(scripter, host);
                IHttpService          httpService          = new HttpService();
                IJavaScriptEngine     javaScriptEngine     = new JavaScriptEngine(dbContext, host, smsService);

                locator.RegisterService <IDbContext>(dbContext);
                locator.RegisterService <IProfiler>(profiler);
                locator.RegisterService <IApplicationHost>(host);
                locator.RegisterService <IRenderer>(renderer);
                locator.RegisterService <IWorkflowEngine>(workflowEngine);
                locator.RegisterService <IMessaging>(messaging);
                locator.RegisterService <IUserLocale>(userLocale);
                locator.RegisterService <ILocalizer>(localizer);
                locator.RegisterService <IDataScripter>(scripter);
                locator.RegisterService <ILogger>(logger);
                locator.RegisterService <IMessageService>(emailService);
                locator.RegisterService <ISmsService>(smsService);
                locator.RegisterService <IExternalLoginManager>(externalLoginManager);
                locator.RegisterService <IUserStateManager>(userStateManager);
                locator.RegisterService <IExternalDataProvider>(dataProvider);
                locator.RegisterService <IScriptProcessor>(scriptProcessor);
                locator.RegisterService <IHttpService>(httpService);
                locator.RegisterService <IJavaScriptEngine>(javaScriptEngine);
                locator.RegisterService <ITokenProvider>(tokenProvider);

                IDataProtectionProvider dataProtection = app.GetDataProtectionProvider();
                locator.RegisterService <IDataProtectionProvider>(dataProtection);

                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Items.Add("ServiceLocator", locator);
                }
            };

            IServiceLocator GetOrCreateStatic()
            {
                if (_currentLocator == null)
                {
                    _currentLocator = new ServiceLocator();
                }
                return(_currentLocator);
            }

            ServiceLocator.GetCurrentLocator = () =>
            {
                if (HttpContext.Current == null)
                {
                    return(GetOrCreateStatic());
                }
                var currentContext = HttpContext.Current;
                var locator        = currentContext.Items["ServiceLocator"];
                if (locator == null)
                {
                    var loc      = new ServiceLocator(); // side effects
                    var fromHttp = HttpContext.Current.Items["ServiceLocator"] as IServiceLocator;
                    if (loc != fromHttp)
                    {
                        throw new InvalidOperationException("Invalid service locator");
                    }
                }
                return(HttpContext.Current.Items["ServiceLocator"] as IServiceLocator);
            };
        }
Example #9
0
 static OAuth()
 {
     WebLogger = new WebLogger(typeof(OAuth));
 }
Example #10
0
        public string Authentication(string idCard, string nameEng, string status)
        {
            try
            {
                WebLogger.Warn("Authenticating");

                Dictionary <string, object>   jsonResult = new Dictionary <string, object>();
                IList <SelfAuthenticatedUser> users      = SessionContext.PersistenceSession.QueryOver <SelfAuthenticatedUser>().List();
                IList <SelfAuthenticatedUser> user       = users.Where(s => s.LoginName.ToLowerInvariant() == nameEng.ToLowerInvariant() &&
                                                                       s.Person.OfficialIDNo == idCard &&
                                                                       s.UserRoles[0].Role.Id == int.Parse(status) &&
                                                                       !s.IsDisable &&
                                                                       s.IsEffective).ToList();



                if (0 < user.Count)
                {
                    if (user.Count != 1)
                    {
                        throw new Exception("User have more than one. System error.");
                    }

                    if (!user[0].IsBuiltin)
                    {
                        IList <iSabaya.UserSession> userSessions = SessionContext.PersistenceSession
                                                                   .QueryOver <iSabaya.UserSession>()
                                                                   .Where(us => us.User.ID == user[0].ID &&
                                                                          us.SessionPeriod.To == iSabaya.TimeInterval.MaxDate)
                                                                   .List();

                        if (userSessions.Any(u => u.User.ID == user[0].ID))
                        {
                            jsonResult.Add("result", 0);
                            jsonResult.Add("target", "");
                            jsonResult.Add("message", "Login Failed.");
                            SessionContext.StartFailedSession(null, idCard, Session.SessionID, "Login Attemp.");

                            return(new JavaScriptSerializer().Serialize(jsonResult));
                        }
                    }

                    BudgetConfiguration.CurrentConfiguration = GetConfiguration(SessionContext, SessionContext.MySystem.SystemID);
                    SessionContext.StartNewSession(user[0], Session.SessionID);

                    string targetPath = "";
                    switch (user[0].UserRoles[0].Role.Id)
                    {
                    case 1:
                        targetPath = FullUrl("Government");
                        break;

                    case 2:
                        targetPath = FullUrl("Budgetor");
                        break;

                    case 3:
                        targetPath = FullUrl("Evaluation");
                        break;

                    case 4:
                        targetPath = FullUrl("Admin");
                        break;

                    default:
                        throw new Exception("User Role Invalid.");
                    }


                    jsonResult.Add("result", 1);
                    jsonResult.Add("target", targetPath);
                    jsonResult.Add("message", "");
                }
                else
                {
                    jsonResult.Add("result", 0);
                    jsonResult.Add("target", "");
                    jsonResult.Add("message", "Login Failed.");
                    SessionContext.StartFailedSession(null, idCard, Session.SessionID, "Login Failed.");
                }

                WebLogger.Warn("End Authenticating");
                return(new JavaScriptSerializer().Serialize(jsonResult));
            }
            catch (Exception ex)
            {
                WebLogger.Error(ex.GetAllMessages());

                Dictionary <string, object> jsonResult = new Dictionary <string, object>();
                jsonResult.Add("result", 0);
                jsonResult.Add("target", "");
                jsonResult.Add("message", ex.ToString());

                SessionContext.StartFailedSession(null, idCard, Session.SessionID, ex.Message);

                SessionContext.Log(0, this.pageID, 0, "Login", "Fail : " + ex.Message);

                return(new JavaScriptSerializer().Serialize(jsonResult));
            }
        }
Example #11
0
        /// <summary>
        /// 附件文件分片全部上传好后保存
        /// </summary>
        /// <param name="addFileName"></param>
        /// <param name="flowId"></param>
        /// <returns></returns>
        public FileUploadInfo SaveAccessoryFileOrdinaryChunk(string addFileName)
        {
            if (!addFileName.HasRealValue())
            {
                throw new Exception("请选择文件");
            }

            string fileName = Request["filename"];

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Server.UrlDecode(fileName);
            }
            var locationid   = Request["locationid"];
            var location     = Request["location"];
            var LocationType = Request["LocationType"];

            if (!LocationType.HasRealValue())
            {
                LocationType = location;
            }
            var basePath = HMSUtil.GetDocPath(LocationType);
            var filePath = basePath + DateTime.Today.ToString("yyyyMMdd");

            DicCreate(filePath);

            int      sysMaxLength  = HMSUtil.GetConfig(EnuInitCode.MaxAttFileSize.ToString()).ToInt(30);
            int      MaxFileLength = 1024 * 1024 * sysMaxLength;
            FileInfo file          = new FileInfo(addFileName);

            var  userToken = AMSAuthentication.GetAuthToken();
            var  service   = new HMSServiceBase();
            var  db        = service.Init();
            long fileSize  = 0;

            try
            {
                if (file.Length > MaxFileLength)
                {
                    file.Delete();
                    throw new Exception($"上传的文件的大小超过限制{sysMaxLength}M");
                }

                fileSize = file.Length;
                var newFileName = fileName.Split('.').FirstOrDefault() + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(fileName);

                string destinationPath = Path.Combine(filePath, newFileName);
                if (System.IO.File.Exists(destinationPath))
                {
                    System.IO.File.Delete(destinationPath);
                }
                file.MoveTo(destinationPath);

                var accessoryService = new AccessoryService();
                var accessory        = accessoryService.GetBy(location, locationid, fileName);
                if (accessory == null || !accessory.AccessoryId.HasRealValue())
                {
                    accessory = new AccessoryEntity()
                    {
                        AccessoryLocation   = location,
                        AccessoryLocationId = locationid,
                        AccessoryName       = fileName,
                        CreateTime          = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        CreateUser          = AMSAuthentication.GetAuthToken().UserId,
                        CreateUserName      = AMSAuthentication.GetAuthToken().RealName,
                        CompanyId           = AMSAuthentication.GetAuthToken().CompanyId,
                        OwnerId             = "12345678"
                    };
                }
                else
                {
                    // 如果已经存在,是修改,则删除之前的文件
                    var deletePath = basePath + accessory.FileName;
                    if (System.IO.File.Exists(deletePath))
                    {
                        System.IO.File.Delete(deletePath);
                    }
                }

                // 修改和更新都需要的共用部分
                accessory.FileName = DateTime.Today.ToString("yyyyMMdd") + "/" + newFileName;
                accessory.FileSize = fileSize;
                accessory.LastestAccessDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                return(accessoryService.SaveAccessory(accessory));
            }
            catch (Exception ex)
            {
                file.Delete();
                WebLogger.Log($"FileExp:{ex.Message}");
                throw new Exception(ex.Message);
            }
        }
Example #12
0
        /// <summary>
        /// 工作流附件文件分片全部上传好后保存
        /// </summary>
        /// <param name="addFileName"></param>
        /// <param name="flowId"></param>
        /// <returns></returns>
        public FileUploadInfo SaveFlowFileOrdinaryChunk(string addFileName)
        {
            if (!addFileName.HasRealValue())
            {
                throw new Exception("请选择文件");
            }

            string fileName = Request["filename"];

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Server.UrlDecode(fileName);
            }

            string tempDirName = Request["tempDirName"];

            bool     isTemp        = false;
            int      sysMaxLength  = HMSUtil.GetConfig(EnuInitCode.MaxAttFileSize.ToString()).ToInt(30);
            int      MaxFileLength = 1024 * 1024 * sysMaxLength;
            FileInfo file          = new FileInfo(addFileName);
            string   dirName       = tempDirName.HasRealValue() ? tempDirName : HMSUtil.GetFlowDirName();

            var     userToken = AMSAuthentication.GetAuthToken();
            var     service   = new HMSServiceBase();
            var     db        = service.Init();
            decimal flowId    = Request["flowId"].ToDecimal(0);
            var     temp      = db.Queryable <FlowTemporaryEntity>()
                                .Where(x => x.CreateUser == userToken.UserId && x.FlowId == flowId)
                                .First();

            if (temp != null && temp.UploadFolder.HasRealValue())
            {
                dirName = temp.UploadFolder;
                isTemp  = true;
            }
            string direction = $@"{new FlowConfig().UploadRoot}\{dirName}\";

            long fileSize = 0;

            try
            {
                if (file.Length > MaxFileLength)
                {
                    file.Delete();
                    throw new Exception($"上传的文件的大小超过限制{sysMaxLength}M");
                }
                fileSize = file.Length;
                if (!Directory.Exists(direction))
                {
                    FileHelper.CreateDirectory(direction);
                }
                string destinationPath = Path.Combine(direction, fileName);
                if (System.IO.File.Exists(destinationPath))
                {
                    System.IO.File.Delete(destinationPath);
                }
                file.MoveTo(destinationPath);
            }
            catch (Exception ex)
            {
                file.Delete();
                WebLogger.Log($"FileExp:{ex.Message}");
                throw new Exception(ex.Message);
            }
            var url    = new FlowCommonService().GetAttrUrl(fileName, dirName);
            var result = new FileUploadInfo
            {
                FileName     = fileName,
                DirectorName = dirName,
                FileSize     = fileSize,
                CreateUser   = userToken.RealName,
                CreateTime   = DateTime.Now,
                Url          = url,
                IsTemp       = isTemp,
            };

            return(result);
        }
Example #13
0
        static void Main(string[] args)
        {
#if UNIX
            Console.WriteLine("Hello unix");
#else
            Console.WriteLine("Hello WIN");
#endif
            Program p = new Program();
            parseArgs(p, args);
            if (p.config == null)
            {
                Console.WriteLine("Failed to read config file");
                return;
            }
            if (p.config.key == null || p.config.iv == null)
            {
                Console.WriteLine("Key or IV not supplied. Can't start");
                return;
            }
            //Read key and iv

            /*Console.WriteLine("Enter Encryption key (base64)");
             * key = Console.ReadLine();
             * Console.WriteLine("Enter Encryption IV (base64)");
             * iv = Console.ReadLine();*/
            Console.WriteLine();
            p.securityMan = new SecurityManager(p.config.keyFileLocation, p.config.key, p.config.iv, p.config.userFileLocation, p.config.emailUserFileLocation);

            Debug.WriteLine("Creating logger");
            WebLogger logger = new WebLogger();
            //TODO Properly initialize
            Debug.WriteLine("Initalizing ticketStorage");
            if (p.config.ticketDirectory != null)
            {
                p.ticketStorage = new Tickets.TicketStorage(p.config.ticketDirectory);
            }
            else
            {
                p.ticketStorage = new Tickets.TicketStorage();
            }
            //TODO Properly initalize
            Debug.WriteLine("Creating Scheduler");
            p.scheduler = new Scheduler(p.ticketStorage, p.securityMan);
            Debug.WriteLine("Creating Method Manager");
            p.methodMan = new MethodMan(p.ticketStorage, p.scheduler);
            Debug.WriteLine("Creating Service Factory");
            ServiceFactory service = new ServiceFactory(logger, p.methodMan);
            Debug.WriteLine("Creating Web Server");
            p.server = new WebServer(service, logger);
            p.server.Listen(p.config.port);
            Debug.WriteLine("Main() is listening");
            p.securityMan.sendStartup();
            p.serviceServer = new ServiceServer(p.securityMan);
#if UNIX
            // Catch SIGINT and SIGUSR1
            UnixSignal[] signals = new UnixSignal[] {
                new UnixSignal(Mono.Unix.Native.Signum.SIGINT),
                new UnixSignal(Mono.Unix.Native.Signum.SIGUSR1),
                new UnixSignal(Mono.Unix.Native.Signum.SIGQUIT),
                new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
            };
            while (true)
            {
                int index = UnixSignal.WaitAny(signals, -1);
                p.server.Dispose();
                Mono.Unix.Native.Signum signal = signals[index].Signum;
                //Stop listening and close threads
                p.securityMan.sendShutdown("Recieved kill signal");
                Environment.Exit(0);
            }
#else
            Console.ReadKey();
#endif
        }
Example #14
0
        public string Authentication(string idCard, string nameEng, string status)
        {
            try
            {
                WebLogger.Warn("Authenticating");

                Dictionary <string, object> jsonResult = new Dictionary <string, object>();

                User user = null;

                switch (AuthenticateManager.Authenticate(SessionContext, SystemEnum.RiskAssessmentAnalysisSystem, idCard, nameEng, ref user))
                {
                case AuthenticateManager.AuthenState.AuthenticationSuccess:

                    BudgetConfiguration.CurrentConfiguration = GetConfiguration(SessionContext, SessionContext.MySystem.SystemID);
                    SessionContext.StartNewSession(user, Session.SessionID);

                    string targetPath = "";
                    switch (user.UserRoles[0].Role.Id)
                    {
                    case 1:
                        targetPath = FullUrl("Government");        //ส่วนราชการ
                        break;

                    case 2:
                        targetPath = FullUrl("Budgetor");        //ทำงบประมาณ
                        break;

                    case 3:
                        targetPath = FullUrl("Evaluation");        //เจ้าหน้าที่ประเมินงบ
                        break;

                    case 4:
                        targetPath = FullUrl("Admin");        //ผู้ดูแลระบบ
                        break;

                    default:
                        throw new Exception("User Role Invalid.");
                    }

                    jsonResult.Add("result", 1);
                    jsonResult.Add("target", targetPath);
                    jsonResult.Add("message", "");
                    SessionContext.Log(0, pageID, 0, MessageException.AuthenMessage.Login, MessageException.Success(SessionContext.User.ID.ToString()));
                    break;

                case AuthenticateManager.AuthenState.AuthenticationFail:
                    jsonResult.Add("result", 0);
                    jsonResult.Add("target", "");
                    jsonResult.Add("message", "Login Failed.");
                    SessionContext.Log(0, pageID, 0, MessageException.AuthenMessage.Login, MessageException.Fail(string.Format("{0} : {1}", idCard, nameEng)));
                    break;

                case AuthenticateManager.AuthenState.AlreadyLogin:
                    jsonResult.Add("result", 0);
                    jsonResult.Add("target", "");
                    jsonResult.Add("message", "Login Failed.");
                    SessionContext.Log(0, pageID, 0, MessageException.AuthenMessage.Login, MessageException.Fail(user.ID.ToString() + " : Login Attemp."));
                    break;

                default:
                    break;
                }

                WebLogger.Warn("End Authenticating");

                return(new JavaScriptSerializer().Serialize(jsonResult));

                #region old

                //Dictionary<string, object> jsonResult = new Dictionary<string, object>();
                //IList<SelfAuthenticatedUser> users = SessionContext.PersistenceSession.QueryOver<SelfAuthenticatedUser>().List();
                //IList<SelfAuthenticatedUser> user = users.Where(s => s.LoginName.ToLowerInvariant() == nameEng.ToLowerInvariant()
                //        && s.Person.OfficialIDNo == idCard
                //        && s.UserRoles[0].Role.Id == int.Parse(status)
                //        && !s.IsDisable
                //        && s.IsEffective).ToList();

                //if (0 < user.Count)
                //{
                //    if (user.Count != 1) { throw new Exception("User have more than one. System error."); }

                //    //if (!user[0].IsBuiltin)
                //    //{
                //    //    IList<iSabaya.UserSession> userSessions = SessionContext.PersistenceSession
                //    //        .QueryOver<iSabaya.UserSession>()
                //    //        .Where(us => us.User.ID == user[0].ID
                //    //            && us.SessionPeriod.To == iSabaya.TimeInterval.MaxDate)
                //    //        .List();

                //    //    if (userSessions.Any(u => u.User.ID == user[0].ID))
                //    //    {
                //    //        jsonResult.Add("result", 0);
                //    //        jsonResult.Add("target", "");
                //    //        jsonResult.Add("message", "Login Failed.");
                //    //        SessionContext.Log(0, pageID, 0, MessageException.AuthenMessage.Login, MessageException.Fail(userSessions[0].User.ID.ToString() + " : Login Attemp."));
                //    //        //SessionContext.StartFailedSession(null, idCard, Session.SessionID, "Login Attemp.");

                //    //        return new JavaScriptSerializer().Serialize(jsonResult);
                //    //    }
                //    //}

                //    BudgetConfiguration.CurrentConfiguration = GetConfiguration(SessionContext, SessionContext.MySystem.SystemID);
                //    SessionContext.StartNewSession(user[0], Session.SessionID);

                //    string targetPath = "";
                //    switch (user[0].UserRoles[0].Role.Id)
                //    {
                //        //case 1:
                //        //    targetPath = FullUrl("Government");//ส่วนราชการ
                //        //    break;
                //        case 2:
                //            targetPath = FullUrl("Budgetor");//ทำงบประมาณ
                //            break;
                //        case 3:
                //            targetPath = FullUrl("Evaluation");//เจ้าหน้าที่ประเมินงบ
                //            break;
                //        //case 4:
                //        //    targetPath = FullUrl("Admin");//ผู้ดูแลระบบ
                //        //    break;
                //        default:
                //            throw new Exception("User Role Invalid.");
                //    }

                //    jsonResult.Add("result", 1);
                //    jsonResult.Add("target", targetPath);
                //    jsonResult.Add("message", "");
                //    SessionContext.Log(0, pageID, 0, MessageException.AuthenMessage.Login, MessageException.Success(SessionContext.User.ID.ToString()));
                //}
                //else
                //{
                //    jsonResult.Add("result", 0);
                //    jsonResult.Add("target", "");
                //    jsonResult.Add("message", "Login Failed.");
                //    SessionContext.Log(0, pageID, 0, MessageException.AuthenMessage.Login, MessageException.Fail());
                //    //SessionContext.StartFailedSession(null, idCard, Session.SessionID, "Login Failed.");
                //}

                //WebLogger.Warn("End Authenticating");
                //return new JavaScriptSerializer().Serialize(jsonResult);

                #endregion old
            }
            catch (Exception ex)
            {
                WebLogger.Error(ex.GetAllMessages());

                Dictionary <string, object> jsonResult = new Dictionary <string, object>();
                jsonResult.Add("result", 0);
                jsonResult.Add("target", "");
                jsonResult.Add("message", ex.ToString());

                //SessionContext.StartFailedSession(null, idCard, Session.SessionID, ex.Message);

                SessionContext.Log(0, this.pageID, 0, MessageException.AuthenMessage.Login, MessageException.Fail(ex.Message));

                return(new JavaScriptSerializer().Serialize(jsonResult));
            }
        }
Example #15
0
        public string Authentication(string idCard, string nameEng, string status)
        {
            try
            {
                SessionContext.PersistenceSession.Clear();
                WebLogger.Warn("Authenticating");
                var  jsonResult = new Dictionary <string, object>();
                User user       = null;
                BudgetConfiguration.CurrentConfiguration
                    = GetConfiguration(SessionContext, SessionContext.MySystem.SystemID);

                switch (AuthenticateManager
                        .Authenticate(SessionContext,
                                      SystemEnum.RiskAssessmentProjectOwnerSystem,
                                      idCard,
                                      nameEng,
                                      ref user))
                {
                case AuthenticateManager.AuthenState.AuthenticationSuccess:

                    SessionContext.StartNewSession(user, Session.SessionID);

                    var targetPath = "";
                    switch (user.UserRoles[0].Role.Id)
                    {
                    case 1:
                        targetPath = FullUrl("Government");        //ส่วนราชการ
                        break;

                    case 2:
                        targetPath = FullUrl("Budgetor");        //ทำงบประมาณ
                        break;

                    case 3:
                        targetPath = FullUrl("Evaluation");        //เจ้าหน้าที่ประเมินงบ
                        break;

                    case 4:
                        targetPath = FullUrl("Admin");        //ผู้ดูแลระบบ
                        break;

                    default:
                        throw new Exception("User Role Invalid.");
                    }

                    jsonResult.Add("result", 1);
                    jsonResult.Add("target", targetPath);
                    jsonResult.Add("message", "");
                    SessionContext.Log(0, PageID, 0, MessageException.AuthenMessage.Login, MessageException.Success(SessionContext.User.ID.ToString()));
                    break;

                case AuthenticateManager.AuthenState.AuthenticationFail:
                    jsonResult.Add("result", 0);
                    jsonResult.Add("target", "");
                    jsonResult.Add("message", "Login Failed.");
                    SessionContext.Log(0, PageID, 0, MessageException.AuthenMessage.Login, MessageException.Fail(string.Format("{0} : {1}", idCard, nameEng)));
                    break;

                case AuthenticateManager.AuthenState.AlreadyLogin:
                    jsonResult.Add("result", 0);
                    jsonResult.Add("target", "");
                    jsonResult.Add("message", "Login Failed.");
                    SessionContext.Log(0, PageID, 0, MessageException.AuthenMessage.Login, MessageException.Fail(user.ID.ToString() + " : Login Attemp."));
                    break;

                default:
                    break;
                }

                WebLogger.Warn("End Authenticating");

                return(new JavaScriptSerializer().Serialize(jsonResult));
            }
            catch (Exception ex)
            {
                WebLogger.Error(ex.GetAllMessages());

                var jsonResult = new Dictionary <string, object>();
                jsonResult.Add("result", 0);
                jsonResult.Add("target", "");
                jsonResult.Add("message", ex.ToString());

                SessionContext.StartFailedSession(null, idCard, Session.SessionID, ex.Message);
                SessionContext.Log(0, this.PageID, 0, "Login", "Fail : " + ex.Message);

                return(new JavaScriptSerializer().Serialize(jsonResult));
            }
        }
Example #16
0
        /// <summary>
        /// 附件文件分片全部上传好后保存
        /// </summary>
        /// <param name="addFileName"></param>
        /// <param name="flowId"></param>
        /// <returns></returns>
        public FileUploadInfo SavePressDetailFileOrdinaryChunk(string addFileName)
        {
            if (!addFileName.HasRealValue())
            {
                throw new Exception("请选择文件");
            }

            string fileName = Request["filename"];

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Server.UrlDecode(fileName);
            }
            var locationid   = Request["locationid"];
            var location     = Request["location"];
            var LocationType = Request["LocationType"];

            if (!LocationType.HasRealValue())
            {
                LocationType = location;
            }
            var basePath = HMSUtil.GetDocPath(LocationType);
            var filePath = basePath + DateTime.Today.ToString("yyyyMMdd");

            DicCreate(filePath);

            int      sysMaxLength  = HMSUtil.GetConfig(EnuInitCode.MaxAttFileSize.ToString()).ToInt(30);
            int      MaxFileLength = 1024 * 1024 * sysMaxLength;
            FileInfo file          = new FileInfo(addFileName);

            var  userToken = AMSAuthentication.GetAuthToken();
            var  service   = new HMSServiceBase();
            var  db        = service.Init();
            long fileSize  = 0;

            try
            {
                if (!fileName.HasRealValue())
                {
                    throw new Exception("文件不能为空");
                }

                if (file.Length > MaxFileLength)
                {
                    file.Delete();
                    throw new Exception($"上传的文件的大小超过限制{sysMaxLength}M");
                }

                var fileNameSplits = fileName.Split('.');

                fileSize = file.Length;
                var newFileName = fileNameSplits.FirstOrDefault() + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(fileName);

                string destinationPath = Path.Combine(filePath, newFileName);
                file.MoveTo(destinationPath);

                //对指定格式才会对其进行缩略图的整合
                if (new Regex(@"\.(?:jpg|bmp|gif|png)$", RegexOptions.IgnoreCase).IsMatch(fileName.Trim()))
                {
                    var targetfilename = destinationPath.Insert(destinationPath.LastIndexOf("."), "-Thum");
                    if (System.IO.File.Exists(targetfilename))
                    {
                        System.IO.File.Delete(targetfilename);
                    }

                    ImageHelper.MakeThumbnail(destinationPath, targetfilename, 100, 100, "Cut", fileNameSplits.LastOrDefault());
                }

                var accessoryService = new AccessoryService();
                var accessory        = accessoryService.GetBy(location, locationid, "签收证明", fileNameSplits.FirstOrDefault(), fileNameSplits.LastOrDefault());
                if (accessory == null || !accessory.AccessoryId.HasRealValue())
                {
                    accessory = new AccessoryEntity()
                    {
                        AccessoryLocation   = location,
                        AccessoryLocationId = locationid,
                        AccessoryName       = "签收证明",
                        CreateTime          = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        CreateUser          = AMSAuthentication.GetAuthToken().UserId,
                        CreateUserName      = AMSAuthentication.GetAuthToken().RealName,
                        OwnerId             = "12345678"
                    };
                }
                else
                {
                    // 如果已经存在,是修改,则删除之前的文件
                    var deletePath = basePath + accessory.FileName;
                    if (System.IO.File.Exists(deletePath))
                    {
                        System.IO.File.Delete(deletePath);
                    }
                }

                // 修改和更新都需要的共用部分
                accessory.FileName = DateTime.Today.ToString("yyyyMMdd") + "/" + newFileName;
                accessory.FileSize = fileSize;
                accessory.LastestAccessDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                return(accessoryService.SavePresstbDetailAccessory(accessory));
            }
            catch (Exception ex)
            {
                file.Delete();
                WebLogger.Log($"FileExp:{ex.Message}");
                //  return JResult.Error("上传未成功,请联系网站管理员");
                throw new Exception(ex.Message);
            }
        }
Example #17
0
 public MvcApplication()
 {
     //HACK: Due to IIS Shutdown/Start event timings, Log4Net config file needs to be loaded during the applicatin's constructor, otherwise no log file may be generated.
     log4net.Config.XmlConfigurator.Configure(new FileInfo("Log4net.config"));
     _log = new WebLogger(GetType());
 }