/// <summary>
        /// 服务年限奖励金额修正
        /// </summary>
        private void DoEditMoney()
        {
            string prefix   = FileModule.FindFirstByProperties("Name", "Portal").RootPath + "\\Default\\";
            string FilePath = RequestData.Get("FileId") + "";

            FilePath = prefix + FilePath;
            DataTable      Dt = ExcelToDataTable(FilePath, 4);
            CommPowerSplit Ps = new CommPowerSplit();

            bool IsPower = false;

            if (Ps.IsHR(UserInfo.UserID, UserInfo.LoginName) || Ps.IsAdmin(UserInfo.LoginName) || Ps.IsInAdminsRole(UserInfo.LoginName))
            {
                IsPower = true;
            }

            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                try
                {
                    string   workno  = Dt.Rows[i]["工号"] + "";
                    SysUser  UserEnt = SysUser.FindFirstByProperties(SysUser.Prop_WorkNo, Dt.Rows[i]["工号"]);
                    SysGroup Group   = SysGroup.TryFind(UserEnt.Pk_corp);

                    TravelMoneyConfig TM    = new TravelMoneyConfig();
                    decimal           Money = 0.0m;

                    if (!string.IsNullOrEmpty(Dt.Rows[i]["服务年限奖励金"] + ""))
                    {
                        decimal M = 0.0m;
                        if (decimal.TryParse(Dt.Rows[i]["服务年限奖励金"] + "", out M))
                        {
                            Money = M;
                        }
                    }

                    string HasUsed = string.Empty;
                    if (!string.IsNullOrEmpty(Dt.Rows[i]["是否已用"] + ""))
                    {
                        HasUsed = ((Dt.Rows[i]["是否已用"] + "") == "是" || (Dt.Rows[i]["是否已用"] + "") == "Y") ? "Y" : "N";
                    }

                    string UpdateSQL = @"declare @id varchar(36)
                                        select top 1 @id=Id from FL_Culture..TravelMoneyConfig where WorkNo='{0}' and {3}
                                        order by CreateTime desc ;
                                        update FL_Culture..TravelMoneyConfig set Money={1}, HaveUsed='{2}'
                                        where Id=@id";
                    //权限
                    string Condition = string.Empty;
                    Condition = IsPower ? " 1=1 " : " Corp ='" + Group.GroupID + "'  ";
                    UpdateSQL = string.Format(UpdateSQL, workno, Money, HasUsed, Condition);
                    DataHelper.ExecSql(UpdateSQL);
                }
                catch (Exception e)
                {
                    //throw new Exception(e.Message);
                }
            }
            this.PageState.Add("State", "1");
        }
    private void loadStudent(long studentId)
    {
        UserModule userModule = new UserModule();
        FileModule fileModule = new FileModule();
        Student student = (Student) userModule.getUserByUserId(studentId);

        student_id.Text = student.USER_ID.ToString();
        first_name.Text = student.FIRSTNAME;
        last_name.Text = student.LASTNAME;
        email.Text = student.EMAIL;

        //get profile pic
        string profilePicLocation = fileModule.getProfilePicLocation(studentId);
        if(profilePicLocation.Length > 0)
            profile_pic.ImageUrl = "~/" + profilePicLocation;

        //get courses attended
        IList<Enrollment> courseEnrolled = student.COURSE_ENROLLED;
        foreach (Enrollment enrollment in courseEnrolled)
        {
            Course course = enrollment.COURSE;
            student_writeup.Text += course.COURSE_NAME + "<br />";

        }
    }
        static void Main(string[] args)
        {
            LogManager.Assign(new SimpleLogManager <ConsoleLogger>());

            // Module manager handles all modules in the server
            var moduleManager = new ModuleManager();

            // Let's serve our downloaded files (Windows 7 users)
            var fileService = new DiskFileService("/", string.Format(@"C:\Users\{0}\Downloads", Environment.UserName));

            // Create the file module and allow files to be listed.
            var module = new FileModule(fileService)
            {
                ListFiles = true
            };

            // Add the module
            moduleManager.Add(module);
            moduleManager.Add(new BodyDecodingModule(new UrlFormattedDecoder()));
            moduleManager.Add(new MyModule());

            // And start the server.
            var server = new HttpServer(moduleManager);

            server.Start(IPAddress.Any, 8080);

            Console.ReadLine();
        }
Exemple #4
0
        private void AddEmbeddedResources(Assembly assembly, FileModule fileModule)
        {
            string contentNamespace = null;

            foreach (var resourceName in assembly.GetManifestResourceNames())
            {
                if (!resourceName.Contains("Content"))
                {
                    continue;
                }

                contentNamespace = resourceName;
                break;
            }

            if (contentNamespace == null)
            {
                return;
            }

            int pos = contentNamespace.IndexOf("Content");

            contentNamespace = contentNamespace.Substring(0, pos);
            fileModule.Resources.Add(new Resources.EmbeddedResourceLoader("/content/", Assembly.GetCallingAssembly(),
                                                                          contentNamespace));
        }
Exemple #5
0
        public ActionResult Index()
        {
            var mdu = new ProductsModule <ListFilterBase, PRODUCT>();
            Dictionary <bool, string> productInfo = mdu.GetProductInfo();

            TempData["productInfo"] = productInfo;

            ListViewBase model = new ListViewBase();
            Dictionary <int, List <FileViewModel> > files = new Dictionary <int, List <FileViewModel> >();

            using (var module = ListFactoryService.Create(ListMethodType.PRODUCT))
            {
                model.Result = (module.DoGetList(model.Filter) as ListResultBase);

                foreach (var data in (model.Result.Data as List <PRODUCT>))
                {
                    //取檔案
                    using (FileModule fileModule = new FileModule())
                    {
                        var file = fileModule.GetFiles((int)data.ID, "Products");
                        if (!files.ContainsKey(data.ID))
                        {
                            files.Add(data.ID, new List <FileViewModel>());
                        }
                        files[data.ID] = file;
                    }
                }
            }
            TempData["Files"] = files;
            return(View(model));
        }
Exemple #6
0
        public ActionResult Content(int?ID)
        {
            if (!ID.HasValue)
            {
                return(RedirectToAction("Index"));
            }

            ProductDetailsDataModel model;

            using (var module = ListFactoryService.Create(Enums.ListMethodType.PRODUCT))
            {
                model = (module.DoGetDetailsByID((int)ID) as ProductDetailsDataModel);
            }
            if (model.Data == null)
            {
                return(RedirectToAction("Index"));
            }

            //取檔案
            using (FileModule fileModule = new FileModule())
            {
                model.FilesData = fileModule.GetFiles((int)model.Data.ID, "Products");
            }
            return(View(model));
        }
Exemple #7
0
    /// <summary>
    /// 获取最终导出的完整文件路径
    /// </summary>
    /// <param name="ExcelName">excel名,如item-道具</param>
    /// <returns></returns>
    private string GetPath(string ExcelName)
    {
        // 获取表格相对于Excel文件夹的相对路径
        string excelFolderPath = ExcelFolder.ExcelPath.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);

        if (!excelFolderPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
        {
            excelFolderPath = excelFolderPath + Path.DirectorySeparatorChar;
        }

        Uri excelFolderUri = new Uri(excelFolderPath);
        Uri fileUri        = new Uri(ExcelFolder.ExportTables[ExcelName]);
        Uri relativeUri    = excelFolderUri.MakeRelativeUri(fileUri);
        // 注意:Uri转为的字符串中会将中文转义为%xx,需要恢复为非转义形式
        string relativePath = Uri.UnescapeDataString(relativeUri.ToString());

        if (ExcelNameSplitString != null)
        {
            string[] SplitRelativePath = relativePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string[] tempSplitRelativePath;
            relativePath = "";
            for (int i = 0; i < SplitRelativePath.Length - 1; i++)
            {
                tempSplitRelativePath = SplitRelativePath[i].Split(new string[] { ExcelNameSplitString }, StringSplitOptions.RemoveEmptyEntries);
                relativePath          = relativePath + tempSplitRelativePath[0] + "/";
            }
            relativePath = relativePath + SplitRelativePath[SplitRelativePath.Length - 1];
        }

        return(Path.GetDirectoryName(FileModule.CombinePath(ExportPath, relativePath)));
    }
        static void Main(string[] args)
        {
            //LogManager.Assign(new SimpleLogManager<ConsoleLogger>());

            // Module manager handles all modules in the server
            var moduleManager = new ModuleManager();

            // Let's serve our downloaded files (Windows 7 users)
            var fileService = new DiskFileService("/", $@"C:\Users\{Environment.UserName}\Downloads");

            // Create the file module and allow files to be listed.
            var module = new FileModule(fileService)
            {
                AllowFileListing = true,
            };



            // Add the module
            moduleManager.Add(module);
            moduleManager.Add(new MyModule());

            moduleManager.Add(new MyModule2());
            // And start the server.
            var server = new HttpServer(moduleManager);

            server.AllowedSslProtocols = SslProtocols.Ssl2;

            server.Start(IPAddress.Any, 0);
            Console.WriteLine("PORT " + server.LocalPort);

            //TrySendARequest(server);

            Console.ReadLine();
        }
        public ActionResult Content(int?id)
        {
            if (id == null)
            {
                throw new Exception("查無該活動賽事");
            }
            ApplyListContentModel model = new ApplyListContentModel();

            using (var applymodule = new ApplyFrontModule())
            {
                var listData = applymodule.GetList(0, true).ListData;
                if (listData.Count > 0)
                {
                    model.Data = listData.Where(o => o.ID == id).FirstOrDefault();
                    if (model.Data == null)
                    {
                        TempData["ErrorMsg"] = "查無該活動賽事";
                        return(RedirectToAction("List"));
                    }
                    //取檔案
                    using (var fileModule = new FileModule())
                    {
                        model.Files = fileModule.GetFiles((int)model.Data.ID, "Activity", "F");
                    }
                }
            }
            return(View(model));
        }
Exemple #10
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="ExcelName">excel名,如item-道具</param>
    /// <returns></returns>
    public bool SaveFile(string tableName)
    {
        try
        {
            if (IsExportKeepDirectoryStructure == true)
            {
                ExportPath = FileModule.GetExportDirectoryPath(tableName, ExportPath, IsExportKeepDirectoryStructure, true);
            }
            //如果文件夹不存在就创建
            if (Directory.Exists(ExportPath) == false)
            {
                Directory.CreateDirectory(ExportPath);
            }

            string       fileName2 = string.Concat(ExportNameBeforeAdd + ExportName + ExportNameAfterLanguageMark, ".", ExportExtension);
            string       savePath  = FileModule.CombinePath(ExportPath, fileName2);
            StreamWriter writer    = new StreamWriter(savePath, false, new UTF8Encoding(false));
            writer.Write(ExportContent);
            writer.Flush();
            writer.Close();
            return(true);
        }
        catch (Exception e)
        {
            AppLog.LogErrorAndExit(string.Format("导出失败:{0}", e.ToString()));
            return(false);
        }
    }
Exemple #11
0
        private static void Main(string[] args)
        {
            var filter = new LogFilter();

            filter.AddStandardRules();
            //LogFactory.Assign(new ConsoleLogFactory(filter));

            // create a server.
            var server = new Server();

            // same as previous example.
            var module = new FileModule();

            module.Resources.Add(new FileResources("/", Environment.CurrentDirectory + "\\files\\"));
            server.Add(module);
            server.RequestReceived += OnRequest;
            server.Add(new MultiPartDecoder());

            // use one http listener.
            server.Add(HttpListener.Create(IPAddress.Any, 8085));
            server.Add(new SimpleRouter("/", "/index.html"));

            // start server, can have max 5 pending accepts.
            server.Start(5);

            Console.ReadLine();
        }
        public ActionResult List()
        {
            ListViewBase model = new ListViewBase();
            Dictionary <int, List <FileViewModel> > files = new Dictionary <int, List <FileViewModel> >();

            using (var module = ListFactoryService.Create(ListMethodType.NEWS))
            {
                model.Result = (module.DoGetList(model.Filter) as ListResultBase);
                List <NEWS> dataBind = (model.Result.Data as List <NEWS>).ToList();
                foreach (var data in dataBind)
                {
                    data.CONTENT = data.CONTENT = PublicMethodRepository.StripHTML(data.CONTENT).SplitLengthString(60);
                    //取檔案
                    using (FileModule fileModule = new FileModule())
                    {
                        var file = fileModule.GetFiles((int)data.ID, "News");
                        if (!files.ContainsKey(data.ID))
                        {
                            files.Add(data.ID, new List <FileViewModel>());
                        }
                        files[data.ID] = file;
                    }
                }
                model.Result.Data = dataBind;
            }
            TempData["Files"] = files;
            return(View(model));
        }
Exemple #13
0
        public void Start(int port)
        {
            // Module manager handles all modules in the server
            var moduleManager = new ModuleManager();

            // Let's serve our downloaded files (Windows 7 users)
            var fileService = new DiskFileService("/", Settings.WebServerFolder);

            // Create the file module and allow files to be listed.
            var module = new FileModule(fileService)
            {
                ListFiles = false
            };

            var routerModule = new RouterModule();

            // Add the module
            //moduleManager.Add(module);
            moduleManager.Add(new WebServerModule());

            //moduleManager.Add(new BodyDecodingModule(new UrlFormattedDecoder()));

            // And start the server.
            var server = new HttpServer(moduleManager);

            server.Start(IPAddress.Any, port);
        }
Exemple #14
0
    private static void CheckExcelPath()
    {
        //判断指定的Excel文件是否存在
        if (!Directory.Exists(ExcelPath))
        {
            AppLog.LogErrorAndExit(string.Format("错误!!! 输入的Excel表格所在目录不存在,路径为:{0}", ExcelPath));
        }

        ExcelPath = Path.GetFullPath(ExcelPath);
        AppLog.Log(string.Format("提示: 您选择的Excel所在路径:{0}", ExcelPath));


        Dictionary <string, List <string> > temp = new Dictionary <string, List <string> >();
        SearchOption searchOption;

        if (IsIncludeSubfolder == true)
        {
            searchOption = SearchOption.AllDirectories;
        }
        else
        {
            searchOption = SearchOption.TopDirectoryOnly;
        }
        //获取指定文件夹夹所有Excel文件
        AllExcelPaths = FileModule.GetFileInfo(ExcelPath, "xlsx", searchOption);
    }
Exemple #15
0
    /// <summary>
    /// 将某张Excel表格转换为lua table内容保存到文件
    /// </summary>
    public static bool SaveTxtFile(Export export, string excelName, string sheetName)
    {
        try
        {
            string exportDirectoryPath = FileModule.GetExportDirectoryPath(excelName, export.ExportPath, export.IsExportKeepDirectoryStructure, false);
            //如果文件夹不存在就创建
            if (Directory.Exists(exportDirectoryPath) == false)
            {
                Directory.CreateDirectory(exportDirectoryPath);
            }

            //if (sheetName.StartsWith("'"))
            //    sheetName = sheetName.Substring(1);
            //if (sheetName.EndsWith("'"))
            //    sheetName = sheetName.Substring(0, sheetName.Length - 1);
            //if (sheetName.EndsWith("$"))
            //    sheetName = sheetName.Substring(0, sheetName.Length - 1);

            string       fileName2 = string.Concat(excelName + "-" + sheetName, ".", export.ExportExtension);
            string       savePath  = FileModule.CombinePath(exportDirectoryPath, fileName2);
            StreamWriter writer    = new StreamWriter(savePath, false, new UTF8Encoding(false));
            writer.Write(export.ExportContent);
            writer.Flush();
            writer.Close();
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Exemple #16
0
    public bool SaveFile(string tableName, string excelName, string sheetName)
    {
        try
        {
            if (IsExportKeepDirectoryStructure == true)
            {
                ExportPath = FileModule.GetExportDirectoryPath(tableName, ExportPath, IsExportKeepDirectoryStructure, false);
            }
            //如果文件夹不存在就创建
            if (Directory.Exists(ExportPath) == false)
            {
                Directory.CreateDirectory(ExportPath);
            }

            string s = "";
            if (excelName.Contains("-"))
            {
                s = excelName.Split('-')[1];
            }

            string       fileName2 = string.Concat(excelName + "-" + sheetName, ".", ExportExtension);
            string       savePath  = FileModule.CombinePath(ExportPath, fileName2);
            StreamWriter writer    = new StreamWriter(savePath, false, new UTF8Encoding(false));
            writer.Write(ExportContent);
            writer.Flush();
            writer.Close();
            return(true);
        }
        catch (Exception e)
        {
            AppLog.LogErrorAndExit(string.Format("导出失败:{0}", e.ToString()));
            return(false);
        }
    }
Exemple #17
0
    /// <summary>
    /// 将某张Excel表格转换为lua table内容保存到文件
    /// </summary>
    public static bool SaveErlangFile(string excelName, string tableName, string content)
    {
        try
        {
            //if (ErlangStruct.IsBeforeNameAddtb == true)
            //{
            //    if (!fileName.StartsWith("tb_"))
            //        fileName = string.Concat("tb_", fileName);
            //}
            string exportDirectoryPath = FileModule.GetExportDirectoryPath(excelName, ErlangStruct.SavePath, ErlangStruct.IsExportKeepDirectoryStructure);
            //如果文件夹不存在就创建
            if (Directory.Exists(exportDirectoryPath) == false)
            {
                Directory.CreateDirectory(exportDirectoryPath);
            }

            string       fileName2 = string.Concat(ErlangStruct.ExportNameBeforeAdd + tableName, ".", ErlangStruct.SaveExtension);
            string       savePath  = FileModule.CombinePath(exportDirectoryPath, fileName2);
            StreamWriter writer    = new StreamWriter(savePath, false, new UTF8Encoding(false));
            writer.Write(content);
            writer.Flush();
            writer.Close();
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Exemple #18
0
        private List <BannerDetailsModel> GetBannerList()
        {
            List <BannerDetailsModel> results = new List <BannerDetailsModel>();
            List <BANNER>             data    = new List <BANNER>();

            try
            {
                data = DB.BANNER
                       .Where(o => o.DISABLE == false)
                       .OrderByDescending(o => o.BUD_DT).ThenByDescending(g => g.SQ)
                       .ToList();
                FileModule fileModule = new FileModule();
                using (var bannerModule = new BannerModule())
                {
                    foreach (var d in data)
                    {
                        PublicMethodRepository.HtmlDecode(d);
                        BannerDetailsModel temp = bannerModule.DoGetDetailsByID(d.ID);
                        temp.Files = fileModule.GetFiles((int)d.ID, "Banner", "F");
                        results.Add(temp);
                    }
                }
                fileModule.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(results);
        }
        static void Main(string[] args)
        {
            // Template generators are used to render templates
            // (convert code + html to pure html).
            TemplateManager mgr = new TemplateManager();

            mgr.Add("haml", new HamlGenerator());

            // The httpserver is quite dumb and will only serve http, nothing else.
            HttpServer server = new HttpServer();

            // a controller mode implements a MVC pattern
            // You'll add all controllers to the same module.
            ControllerModule mod = new ControllerModule();

            mod.Add(new UserController(mgr));
            server.Add(mod);

            // file module will be handling files
            FileModule fh = new FileModule("/", Environment.CurrentDirectory);

            fh.AddDefaultMimeTypes();
            server.Add(fh);

            // Let's start pure HTTP, we can also start a HTTPS listener.
            server.Start(IPAddress.Any, 8081);

            Console.ReadLine();
        }
Exemple #20
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="authModule"></param>
 /// <param name="fileModule"></param>
 /// <param name="cacheModule"></param>
 /// <param name="thumbnailModule"></param>
 /// <param name="loggerFactory"></param>
 public UploadController(AuthModule authModule, FileModule fileModule, CacheModule cacheModule, ThumbnailModule thumbnailModule, ILoggerFactory loggerFactory)
 {
     this.authModule      = authModule;
     this.fileModule      = fileModule;
     this.cacheModule     = cacheModule;
     this.thumbnailModule = thumbnailModule;
     this.logger          = loggerFactory.CreateLogger("File");
 }
Exemple #21
0
        private static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Console.Title = "Web Server";


            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("  Rains Soft Web Server");
            Console.WriteLine("      Rains Soft");
            Console.WriteLine("  http://www.mobanhou.com");
            Console.WriteLine();
            Console.ResetColor();
            int i = 0;

            while (true)
            {
                if (i > 9)
                {
                    Console.WriteLine(".");
                    break;
                }
                else
                {
                    Console.Write(".");
                    i++;
                }
                System.Threading.Thread.Sleep(500);
            }

            var filter = new LogFilter();

            filter.AddStandardRules();
            var log = new ConsoleLogFactory(filter);

            LogFactory.Assign(log);
            Logger = LogFactory.CreateLogger(log.GetType()) as ConsoleAndTextLogger;
            Logger.Info("create server");
            // create a server.
            var server = new Server();

            // same as previous example.
            var module = new FileModule();

            module.Resources.Add(new FileResources("/", Environment.CurrentDirectory + "\\files\\"));
            server.Add(module);
            server.Add(new CustomHttpModule());
            server.RequestReceived += OnRequest;
            server.Add(new MultiPartDecoder());

            // use one http listener.
            server.Add(HttpListener.Create(IPAddress.Any, 8085));
            server.Add(new SimpleRouter("/", "/index.html"));
            Logger.Info("start server");
            // start server, can have max 5 pending accepts.
            server.Start(5);
            Console.Beep();
            Console.ReadLine();
        }
        public void ParseFileModuleOK(string source)
        {
            // Act
            FileModule module = source;

            // Assert
            Assert.NotNull(module);
            Assert.Equal(module.ToString().ToLower(), source.ToLower());
        }
        public void Watch()
        {
            ProjectWatcher = new ProjectFilesWatcher(this.BasePath);
            ProjectWatcher.Start();

            ProjectWatcher.ModuleStream.Subscribe("Logger", msm =>
            {
                //Console.WriteLine($"{msm}");
            });

            ProjectWatcher.ModuleStream.Subscribe("OnChange", MessageType.ModuleChanged, async msm =>
            {
                var module = this.Modules.FirstOrDefault(m => m.Name == msm.ModuleName);
                if (module is null)
                {
                    module = new FileModule(msm.FileFullPath, this.BasePath, this);
                    Modules.Add(module);
                }

                module.Parse();
                await module.SaveModuleOutput(false);
            });

            //ProjectWatcher.ModuleStream.Subscribe("OnCreate", MessageType.ModuleCreated, msm =>
            //{
            //    var module = Modules.FirstOrDefault(m => m.Name == msm.ModuleName);
            //    if (module is null)
            //    {
            //        module = new Module(msm.FileFullPath, this.BasePath, this);
            //        Modules.Add(module);
            //    }
            //});

            ProjectWatcher.ModuleStream.Subscribe("OnDelete", MessageType.ModuleDeleted, async msm =>
            {
                var module = Modules.FirstOrDefault(m => m.Name == msm.ModuleName);
                if (!(module is null))
                {
                    Modules.Remove(module);
                    await module.Clean();
                }
            });

            ProjectWatcher.ModuleStream.Subscribe("OnRename", MessageType.ModuleRenamed, async msm =>
            {
                var moduleOld = Modules.FirstOrDefault(m => m.Name == msm.ModuleName);
                if (!(moduleOld is null))
                {
                    await moduleOld.Clean();
                    Modules.Remove(moduleOld);
                }
                var module = new FileModule(msm.FileFullPath, this.BasePath, this);
                Modules.Add(module);
                module.Parse();
                await module.SaveModuleOutput();
            });
        }
Exemple #24
0
        static void Main(string[] args)
        {
            LogFactory.Assign(new ConsoleLogFactory());
            ServiceProvider.Bootstrap();

            ServiceHostInfo info = new ServiceHostInfo();

            info.Name     = ConfigurationMaster.Get(ServiceConfiguration.DefaultServiceConfigurationName);
            info.Address  = Dns.GetHostName();
            info.Port     = int.Parse(ConfigurationMaster.Get(ServiceConfiguration.DefaultServicePortConfigurationName));
            info.Binding  = new NetTcpBinding(ServiceConfiguration.DefaultNetTcpBindingName);
            info.Contract = typeof(IDeviceProfileService);
            info.Service  = typeof(DeviceProfileService);

            Console.WriteLine(string.Format(@"Service is starting on [{0}]", info.ToString()));

            ManagedServiceHostActivator <IDeviceProfileService> activator = new ManagedServiceHostActivator <IDeviceProfileService>(info);

            activator.Start();

            Console.WriteLine(string.Format(@"Service address [{0}]", activator.ServiceHost.Description.Endpoints.First().Address));

            string serverName      = ConfigurationMaster.Get(@"HttpServerName");
            string httpServerName  = serverName + " HTTP Server";
            int    httpBindingPort = int.Parse(ConfigurationMaster.Get(@"HttpServerPort"));

            Server server = null;

            server = new Server(httpServerName);
            server.Add(HttpListenerFactory.Create(IPAddress.Any, httpBindingPort));

            server.Add(new CameraListModule());
            server.Add(new CameraModule());
            server.Add(new CameraThumbnailModule());

            FileModule             fileModule = new FileModule();
            EmbeddedResourceLoader embedded   = new EmbeddedResourceLoader();

            embedded.Add("/", Assembly.GetExecutingAssembly(),
                         Assembly.GetExecutingAssembly().GetName().Name,
                         Assembly.GetExecutingAssembly().GetName().Name + @".Resources.favicon.ico");
            fileModule.Resources.Add(embedded);
            server.Add(fileModule);
            server.Add(new SimpleRouter("/favicon.ico", "/resources/favicon.ico"));

            server.Start(5);

            Console.WriteLine(string.Format("Start {0} on {1}.", httpServerName, httpBindingPort));

            Console.WriteLine();
            Console.WriteLine("Press any key to close service.");
            Console.ReadKey();

            server.Stop(true);
            activator.Stop();
        }
    protected void loadStudent(long studentId)
    {
        Student student = (Student)userModule.getUserByUserId(studentId);

        if (student != null)
        {
            Session["studentid"] = student.USER_ID;

            student_id_holder.Text = student.USER_ID.ToString();
            first_name.Text = student.FIRSTNAME;
            last_name.Text = student.LASTNAME;
            email.Text = student.EMAIL;
            phone.Text = student.PHONE;
            address1.Text = student.ADDRESS1;
            address2.Text = student.ADDRESS2;
            city_town.Text = student.CITY_TOWN;
            state.Text = student.STATE;
            zipcode.Text = student.ZIP_CODE;
            country.Text = student.COUNTRY;

            //populate projects applied for
            Session["applied_projects"] = student.PROJECTS_APPLIED;
            project_application_list.DataSource = Session["applied_projects"];
            project_application_list.DataBind();

            //populate assigned project
            if (student.TEAM_ASSIGNMENT.Count >= 1)
            {
                TeamAssignment tAssignment = student.TEAM_ASSIGNMENT.First(); //assume that there will only be 1 assignment per student
                Team assignedTeam = tAssignment.TEAM;
                ProjectAssignment pAssignment = assignedTeam.ASSIGNED_TO_PROJECT.First();
                Project assignedProject = pAssignment.PROJECT;

                project_title.Text = assignedProject.PROJECT_TITLE;
                project_company.Text = assignedProject.PROJECT_OWNER.USERNAME;
                contact_person.Text = assignedProject.CONTACT_NAME;
                contact_number.Text = assignedProject.CONTACT_NUMBER;
            }

            //load profile pic
            FileModule fileModule = new FileModule();
            string profile_pic_address = fileModule.getProfilePicLocation(student.USER_ID);
            if (profile_pic_address.Length > 0)
            {
                profile_pic.ImageUrl = "~/" + fileModule.getProfilePicLocation(student.USER_ID);
            }
            else
            {
                profile_pic.ImageUrl = "";
            }

            //load course enrolled
            course_list.DataSource = student.COURSE_ENROLLED;
            course_list.DataBind();
        }
    }
Exemple #26
0
        void init(int port)
        {
            if (mInitialed)
            {
                return;
            }

            Loom.Current.Initial();
            UtilsHelper.Init();

            UTNT.HttpServer.Utils.Instance.InternetCacheDir = UtilsHelper.TemporaryCachePath;
            //HttpServer.Utils.Instance.ApplicationDataDir = UtilsHelper.TemporaryCachePath;
            //HttpServer.Utils.Instance.LocalApplicationDataDir = UtilsHelper.TemporaryCachePath;

            AddEditableFileExtion(".txt");
            AddEditableFileExtion(".lua");
            AddEditableFileExtion(".xml");

            //HttpServer.Logging.LogFactory.Assign(new LogFactory());

            mServer.MaxContentSize     = 1024 * 1024 * 1024;
            mServer.ContentLengthLimit = 1024 * 1024 * 1024;

            var module = new FileModule();

            module.ContentTypes.Add("svg", new ContentTypeHeader("image/svg+xml"));
            //复杂的url必须先注册
            var loader = new UintyStreamAssetsLoader();

            loader.Add("/" + WWWCache.Instance.CustomPath, "/" + WWWCache.Instance.CustomPath, true);
            loader.Add("/", "/www/");

            module.Resources.Add(loader);

            mServer.Add(module);
            mServer.Add(new MultiPartDecoder());

            // use one http listener.
            mServer.Add(HttpListener.Create(System.Net.IPAddress.Any, port));
            mServer.Add(new SimpleRouter("/", "/index.html"));

            mServer.Add(new HandleRouter("/api/getrootdir", getRootDirHandler));
            mServer.Add(new HandleRouter("/api/getdir", getDirHandler));
            mServer.Add(new HandleRouter("/api/rename", renameHandler));
            mServer.Add(new HandleRouter("/api/addfold", addFoldHandler));
            mServer.Add(new HandleRouter("/api/addfile", addFileHandler));
            mServer.Add(new HandleRouter("/api/delete", deleteHandler));
            mServer.Add(new HandleRouter("/api/replacefile", repaceFileHandler));
            mServer.Add(new HandleRouter("/api/setcontent", setContentHandler));
            mServer.Add(new HandleRouter("/api/unzip", unzipHandler));
            mServer.Add(new HandleRouter("/api/getfile", getFileHandler));

            mServer.Add(new HandleRouter("/api/terminalinfo", getTerminalInfoHandler));

            mInitialed = true;
        }
Exemple #27
0
        private void AddFileResources(Assembly assembly, FileModule fileModule)
        {
            var assemblyPath = Path.GetDirectoryName(assembly.Location);
            var filePath     = Path.Combine(assemblyPath, "Public");

            if (Directory.Exists(filePath))
            {
                fileModule.Resources.Add(new Resources.FileResources("/content/", filePath));
            }
        }
Exemple #28
0
 public FileModuleTest()
 {
     _request = new HttpTestRequest {
         HttpVersion = "HTTP/1.1"
     };
     _context  = new HttpResponseContext();
     _response = _request.CreateResponse(_context);
     _module   = new FileModule("/files/", Environment.CurrentDirectory);
     _module.MimeTypes.Add("txt", "text/plain");
 }
Exemple #29
0
    /// <summary>
    /// 获取有效Excel文件,是否需要检查表格, 是否允许int、float型字段中存在空值
    /// </summary>
    public static void GetExportTables()
    {
        GetParamValue();
        CheckExcelPath();


        AllExcelPaths = RemoveTempFile(AllExcelPaths, ExcelTableSetting.ExcelTempFileFileNameStartString);
        FileModule.CheckSameName(AllExcelPaths, "xlsx");
        ExportTables = _getExportTables(AllExcelPaths, ExportPart, ExportExcept);
    }
Exemple #30
0
        static void Main(string[] args)
        {
            if (!Environment.UserInteractive)
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new ServerSVC()
                };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                dnsServer.Responded += DnsServer_Responded;
                dnsServer.Errored   += DnsServer_Error;

                bwThread.DoWork += DnsThread;
                bwThread.RunWorkerAsync();

                if (!Directory.Exists(ServerDirectory))
                {
                    Directory.CreateDirectory(ServerDirectory);
                    File.WriteAllText(ServerDirectory + @"\index.html", DefaultIndexHtml);
                }

                DiskFileService fileService = new DiskFileService("/", ServerDirectory);
                FileModule      module      = new FileModule(fileService)
                {
                    AllowFileListing = false,
                };


                Console.WriteLine("Server IP: " + ServerIP);

                ModuleManager httpManager = new ModuleManager();
                httpManager.Add(module);
                httpManager.Add(new HTTP_Module());
                HttpServer httpServer = new HttpServer(httpManager);
                httpServer.Start(IPAddress.Any, 80);
                Console.WriteLine("HTTP Server Started");



                ModuleManager httpsManager = new ModuleManager();
                httpsManager.Add(module);
                httpsManager.Add(new HTTPS_Module());
                HttpServer       httpsServer = new HttpServer(httpsManager);
                X509Certificate2 certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "\\cert.pfx", "server");
                httpsServer.Start(IPAddress.Any, 443, certificate);
                Console.WriteLine("HTTPS Server Started");


                Console.ReadLine();
            }
        }
Exemple #31
0
 /// <summary>
 /// 文件监听
 /// </summary>
 /// <param name="Module"></param>
 public static void FileMonitors(FileModule Module)
 {
     if (!Module.Module)
     {
         FileMonitor.MonitorInit(Module);
     }
     else
     {
         FileMonitor.MonitorRead(Module);
     }
 }
Exemple #32
0
 private static void AddMimeTypes(FileModule fm)
 {
     fm.AddDefaultMimeTypes();
     fm.MimeTypes["htc"]  = "text/x-component";
     fm.MimeTypes["json"] = "application/json";
     fm.MimeTypes["map"]  = "application/json";
     fm.MimeTypes["htm"]  = "text/html; charset=utf-8";
     fm.MimeTypes["html"] = "text/html; charset=utf-8";
     fm.MimeTypes["hbs"]  = "application/x-handlebars-template";
     fm.MimeTypes["woff"] = "application/font-woff";
 }
    protected void SaveZipFile(long userId, HttpPostedFile file)
    {
        FileModule fileModule = new FileModule();
        string filename = file.FileName;
        string extension = System.IO.Path.GetExtension(file.FileName.ToLower());

        if (extension != ".zip")
            throw new Exception("You can only upload zip files.");

        hidden_uploaded_file_ID.Value = fileModule.saveFileForUserId(userId, file.InputStream, FILE_TYPE.ZIP, file.FileName).UPLOADEDFILE_ID.ToString();
        hidden_uploaded_file_name.Value = filename;
    }
    private void loadStudent(long studentId)
    {
        UserModule userModule = new UserModule();
        FileModule fileModule = new FileModule();
        Student student = (Student) userModule.getUserByUserId(studentId);

        student_id.Text = student.USER_ID.ToString();
        first_name.Text = student.FIRSTNAME;
        last_name.Text = student.LASTNAME;
        email.Text = student.EMAIL;
        student_writeup.Text = student.WRITE_UP;

        //get profile pic
        string profilePicLocation = fileModule.getProfilePicLocation(studentId);
        if (profilePicLocation.Length > 0)
            profile_pic.ImageUrl = "~/" + profilePicLocation;
    }
    protected void loadUC(long UCId)
    {
        CourseModule courseModule = new CourseModule();

        UnitCoordinator uc = (UnitCoordinator)userModule.getUserByUserId(UCId);

        if (uc != null)
        {
            Session["ucid"] = uc.USER_ID;
            uc_id_holder.Text = uc.USER_ID.ToString();

            first_name.Text = uc.FIRSTNAME;
            last_name.Text = uc.LASTNAME;
            email.Text = uc.EMAIL;
            phone.Text = uc.PHONE;
            address1.Text = uc.ADDRESS1;
            address2.Text = uc.ADDRESS2;
            city_town.Text = uc.CITY_TOWN;
            state.Text = uc.STATE;
            zipcode.Text = uc.ZIP_CODE;
            country.Text = uc.COUNTRY;

            //populate course under UC
            Session["courses"] = courseModule.getCoursesUnderUC(uc.USER_ID);
            course_list.DataSource = Session["courses"];
            course_list.DataBind();

            //load profile pic
            FileModule fileModule = new FileModule();
            string profile_pic_address = fileModule.getProfilePicLocation(uc.USER_ID);
            if (profile_pic_address.Length > 0)
            {
                profile_pic.ImageUrl = "~/" + fileModule.getProfilePicLocation(uc.USER_ID);
            }
            else
            {
                profile_pic.ImageUrl = "";
            }
        }
    }
    protected void SubmitProjectButton_Click(object sender, EventArgs e)
    {
        ProjectModule projectModule = new ProjectModule();

        //Get user ID for project owner
        long ownerId;
        if(!Int64.TryParse(Session["userid"].ToString(), out ownerId))
        {
            Messenger.setMessage(error_message,"Error getting user ID, please log out and sign in again, or contact administrator.",LEVEL.DANGER);
            return;
        }

        try
        {
            //Get all chosen category IDs
            IList<Int64> categoryIds = new List<Int64>();
            string collectionCategoryIds = selected_categories.Value;// Request.Form["selected"];
            string[] categoryIdsStrings = new string[]{}; //an empty array
            if (collectionCategoryIds != null && collectionCategoryIds.Count() > 0)
            {
                categoryIdsStrings = collectionCategoryIds.Split(',');
            }
            foreach (string categoryIdsString in categoryIdsStrings)
            {
                long longValue = 0;
                Int64.TryParse(categoryIdsString, out longValue);
                categoryIds.Add(longValue);
            }

            //Load all inputs into a Project object
            Project project = new Project();
            if (Session["projectid"] != null)
            {
                project.PROJECT_ID = Convert.ToInt64(Session["projectid"].ToString());
            }
            project.PROJECT_TITLE = project_title.Text;
            project.CONTACT_NAME = contact_name.Text;
            project.CONTACT_NUMBER = contact_num.Text;
            project.CONTACT_EMAIL = contact_email.Text;
            project.PROJECT_REQUIREMENTS = project_requirements.Text;

            int convertedRecommendedSize;
            if (!Int32.TryParse(recommended_size.Text, out convertedRecommendedSize))
                throw new Exception("Invalid project size.");
            project.RECOMMENDED_SIZE = convertedRecommendedSize;
            project.ALLOCATED_SIZE = convertedRecommendedSize;
            Project newProject = projectModule.submitProject(project, ownerId);
            Session["projectid"] = newProject.PROJECT_ID;
            projectModule.registerProjectCategories(newProject, categoryIds);
            Session["projectid"] = null;

            //Set projectDocument with projectId
            FileModule fileModule = new FileModule();
            long convertedProjectDocumentId;
            if (hidden_uploaded_doc_ID.Value.Length > 0)
            {
                if (!Int64.TryParse(hidden_uploaded_doc_ID.Value.ToString(), out convertedProjectDocumentId))
                    throw new Exception("Cannot find projectDocumentId, please contact administrator.");
                fileModule.updateProjectDocumentOwner(convertedProjectDocumentId, project.PROJECT_ID);
            }

            Messenger.setMessage(error_message, "Project registered successfully. You will receive an email to update you of the status.", LEVEL.SUCCESS);
            clearAllFields();
        }
        catch (ProjectSubmissionException psex)
        {
            Messenger.setMessage(error_message, psex.Message, LEVEL.DANGER);
        }
        catch (InvalidEmailAddressException ieaex)
        {
            Messenger.setMessage(error_message, ieaex.Message, LEVEL.DANGER);
        }
        catch (ProjectCategoryRegistrationException pcrex)
        {
            Messenger.setMessage(error_message, "Project is submitted but categories are not registered: "+pcrex.Message
                +"<br />"
                +"You may still update the project by clicking Update.", LEVEL.DANGER);
        }
        catch (Exception ex)
        {
            Messenger.setMessage(error_message, ex.Message, LEVEL.DANGER);
        }
        finally
        {
            error_modal_control.Show();
            error_message_update_panel.Update();

            //SubmitProjectButton.Text = "Update";
            //NewProjectUpdatePanel.Update();
            //selected_categories.Value = "";
        }
    }
    protected void upload_document_Click(object sender, EventArgs e)
    {
        try
        {
            if (!DocumentUploader.HasFile)
                throw new Exception("Please provide a file.");

            long convertedStudentId;
            if (!Int64.TryParse(Session["userid"].ToString(), out convertedStudentId))
                throw new Exception("Cannot find user ID, please contact administrator.");

            string filename = DocumentUploader.FileName;
            FileModule fileModule = new FileModule();
            ProjectDocument projectDocument = fileModule.saveProjectFile(DocumentUploader.PostedFile.InputStream, FILE_TYPE.DOCUMENT,filename);
            uploaded_document_info.Text = filename;

            //store ID in hidden_uploaded_doc_ID
            hidden_uploaded_doc_ID.Value = projectDocument.PROJECTFILE_ID.ToString();

            Messenger.setMessage(error_message, "File uploaded successfully.", LEVEL.SUCCESS);
            //refreshCategoryList();
        }
        catch (SaveFileException sfex)
        {
            Messenger.setMessage(error_message, sfex.Message, LEVEL.DANGER);
        }
        catch (Exception ex)
        {
            Messenger.setMessage(error_message, ex.Message, LEVEL.DANGER);
        }
        finally
        {
            error_modal_control.Show();
            //NewProjectUpdatePanel.Update();
            selected_categories.Value = "";
        }
    }
    private void loadProject(long projectId)
    {
        ProjectModule projectModule = new ProjectModule();
        Project project = projectModule.getProjectById(projectId);

        project_id.Value = projectId.ToString();
        project_title.Text = project.PROJECT_TITLE;
        company_name.Text = project.PROJECT_OWNER.USERNAME;
        contact_name.Text = project.CONTACT_NAME;
        contact_number.Text = project.CONTACT_NUMBER;
        contact_email.Text = project.CONTACT_EMAIL;
        project_requirements.Text = project.PROJECT_REQUIREMENTS;
        uc_comments.Text = project.UC_REMARKS;
        allocated_slots.Text = project.RECOMMENDED_SIZE.ToString();

        //load categories
        IList<ProjectCategory> projectCategories = project.CATEGORIES;
        IList<Category> categories = new List<Category>();

        foreach (ProjectCategory projectCategory in projectCategories)
        {
            Category c = projectCategory.CATEGORY;
            categories.Add(c);
        }

        //load project applications
        IList<ProjectApplication> pendingApplications = new List<ProjectApplication>();
        foreach (ProjectApplication application in project.APPLICATIONS)
        {
            if (application.APPLICATION_STATUS == APPLICATION_STATUS.PENDING)
                pendingApplications.Add(application);
        }
        num_applications.Text = pendingApplications.Count.ToString();
        Session["applications"] = pendingApplications;
        project_application_list.DataSource = Session["applications"];
        project_application_list.DataBind();

        category_list.DataSource = categories;
        category_list.DataBind();

        //enable Apply button
        apply_button.Enabled = true;

        //If project has already been assigned, show a disabled overlay and the project members
        ProjectAssignment projectAssignment = null;

        if (project.ASSIGNED_TEAMS != null && project.ASSIGNED_TEAMS.Count > 0)
            projectAssignment = project.ASSIGNED_TEAMS.First(); //Because it is many-to-many, we use only the first result and assume that it will always have 1 team

        if (projectAssignment != null)
        {
            assigned_project_panel.Visible = true;
            IList<Student> projectMembers = new List<Student>();
            Team assignedTeam = projectAssignment.TEAM;

            foreach (TeamAssignment assignment in assignedTeam.TEAM_ASSIGNMENT)
            {
                Student member = assignment.STUDENT;
                projectMembers.Add(member);
            }
            assigned_project_members.DataSource = projectMembers;
            assigned_project_members.DataBind();

            apply_button.Enabled = false;
        }
        else
        {
            assigned_project_panel.Visible = false;
        }

        //get project documents
        FileModule fileModule = new FileModule();
        ProjectDocument projectDocument = fileModule.getProjectDocumentByProjectId(project.PROJECT_ID);
        if (projectDocument != null)
        {
            project_document_link.NavigateUrl = "#";
            string escapedPath = projectDocument.PROJECTFILE_PATH.Replace("\\","/");
            project_document_link.Attributes.Add("onclick", "window.open(\"../../" + escapedPath
                                               + "\",\"_blank\",\"menubar=no,height=600,width=800\");");
            project_document.Text = projectDocument.PROJECTFILE_NAME;
            project_document.Visible = true;
        }
        else
        {
            project_document_link.Attributes.Clear();
            project_document.Visible = false;
        }
    }
Exemple #39
0
    private void SaveProfilePicFile(long userId, HttpPostedFile file)
    {
        FileModule fileModule = new FileModule();
        string filename = file.FileName;
        string extension = System.IO.Path.GetExtension(file.FileName.ToLower());

        if (extension != ".jpeg" &&
            extension != ".jpg" &&
            extension != ".png")
            throw new Exception("You can only upload image files.");

        Session["profile_pic_file"] = fileModule.saveProfilePicForUserId(userId, file.InputStream, file.FileName);
    }
 public void File(Action<FileModule> configure)
 {
     var m = new FileModule();
     configure(m);
     Advanced.RegisterModule(m);
 }