Exemplo n.º 1
0
        /// <summary>
        /// Builds the url for the Handler.
        /// </summary>
        /// <returns>The encoded url.</returns>
        private string GetUrl()
        {
            string url = ResolveUrl(RenderUrl);

            url += "?" + KEY + "=" + WebManager.Encrypt(EncodeTicket(), DateTime.Now.AddSeconds(Expiration));
            return(url);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 获取博客标签列表
        /// </summary>
        /// <returns></returns>
        public Task <PageModel <BlogQueryModel> > QueryBlogList(BlogQueryParam param)
        {
            WebManager webManager = this.DbSession.GetRequiredService <WebManager>();
            var        query      = from b in Db.Set <T_Blog>().AsNoTracking()
                                    join u in Db.Set <T_UserInfo>().AsNoTracking() on b.UserId equals u.Id
                                    where b.Publish == ConstKey.Yes &&
                                    b.Delete == ConstKey.No &&
                                    u.Delete == ConstKey.No
                                    select new BlogQueryModel
            {
                Id          = b.Id.ToString(),
                NickName    = u.NickName,
                UserName    = u.UserName,
                Title       = b.Title,
                Content     = b.Content,
                ReadCount   = b.ReadCount,
                CmtCount    = b.CmtCount,
                PublishDate = b.PublishDate,
                AvatarUrl   = webManager.GetFullUrl(u.AvatarUrl)
            };

            if (string.IsNullOrEmpty(param.SortKey))
            {
                param.SortKey  = nameof(BlogQueryModel.PublishDate);
                param.SortType = SortTypeEnum.DESC;
            }
            return(query.ToOrderAndPageListAsync(param));
        }
Exemplo n.º 3
0
        public void BuildWithDependency(string functionFileName)
        {
            // Compile
            var environment = EnvironmentManager.CreateEnvironment(BASE_PATH, functionFileName);

            var functionFile = environment.FunctionFile;
            var projectFile  = environment.ProjectFile;
            var assemblyFile = environment.AssemblyFile;

            var restorer = new DependencyRestorer(environment);

            restorer.CopyAndRestore();

            var compiler = new DefaultCompiler(new DefaultParser(), new WithDependencyReferencesManager());
            var function = FunctionCreator.CreateFunction(functionFile, projectFile);

            compiler.Compile(function);

            // Invoke
            var invoker = new DefaultInvoker();

            var args = WebManager.GetHttpRequest();

            object result = invoker.Execute(function, args);
        }
Exemplo n.º 4
0
        public override SiteMapNode BuildSiteMap()
        {
            lock (this) {
                Clear();

                var dalc = WebManager.GetService <IDalc>(DalcName);
                var ds   = new DataSet();
                dalc.Load(ds, new Query(SourceName));
                rootNode = new SiteMapNode(this, "root", RootUrl, RootTitle);
                var idToNode = new Dictionary <string, SiteMapNode>();

                // build nodes
                foreach (DataRow r in ds.Tables[SourceName].Rows)
                {
                    var node = CreateNode(r);
                    idToNode[node.Key] = node;
                }
                // set hierarchy relations
                foreach (DataRow r in ds.Tables[SourceName].Rows)
                {
                    var node      = idToNode[Convert.ToString(r[IdField])];
                    var parentKey = Convert.ToString(r[FkField]);
                    if (r[FkField] != DBNull.Value && idToNode.ContainsKey(parentKey))
                    {
                        AddNode(node, idToNode[parentKey]);
                    }
                    else
                    {
                        AddNode(node, rootNode);
                    }
                }
            }
            return(rootNode);
        }
Exemplo n.º 5
0
 public void Initialize()
 {
     ThreadManager.Instance.GetThread(() =>
     {
         scores = WebManager.GetScores();
     }).Start();
 }
Exemplo n.º 6
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (HttpHandlerType != null)
                {
                    // If the configuration data is assosicated with
                    // this http handler
                    if (HttpHandlerType is Nequeo.Web.HttpHandler.Captcha)
                    {
                        // Get the query string from the captcha key
                        NameValueCollection queryString = context.Request.QueryString;
                        string text = queryString[Nequeo.Web.UI.Control.Captcha.KEY];

                        // Responed to the http request by writting to
                        // the stream the captcha image for the source request
                        HttpResponse response = context.Response;
                        Bitmap       bitmap   = WebManager.GenerateImage(text);

                        // Write the new captcha image to the request stream.
                        if (bitmap != null)
                        {
                            bitmap.Save(response.OutputStream, ImageFormat.Jpeg);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
                LogHandler.WriteTypeMessage(ex.Message, typeof(Captcha).GetMethod("ProcessRequest"));
            }
        }
Exemplo n.º 7
0
        public RepoCheck()
        {
            jm  = new JSONManager();
            tb  = new OrientTokenBuilder();
            tc  = new TypeConverter();
            ocb = new OrientCommandBuilder();
            wm  = new WebManager();
            wr  = new WebResponseReader();

            repo = new OrientRepo(jm, tb, tc, ocb, wm, wr);

            s = new SubUnit();

            p =
                new Person()
            {
                Name = "0", GUID = "0", Changed = new DateTime(2017, 01, 01, 00, 00, 00), Created = new DateTime(2017, 01, 01, 00, 00, 00)
            };

            u =
                new Unit()
            {
                Name = "0", GUID = "0", Changed = new DateTime(2017, 01, 01, 00, 00, 00), Created = new DateTime(2017, 01, 01, 00, 00, 00)
            };

            m =
                new MainAssignment()
            {
                Name = "0", GUID = "0", Changed = new DateTime(2017, 01, 01, 00, 00, 00), Created = new DateTime(2017, 01, 01, 00, 00, 00)
            };

            lp = new List <string>();
            lu = new List <string>();
        }
Exemplo n.º 8
0
        public ActionResult Back()
        {
            UserManager bll  = new UserManager();
            DateTime    now  = DateTime.Now;
            DateTime    dt   = Convert.ToDateTime(now.ToShortDateString());
            List <User> info = bll.GetAll();

            ViewBag.Use = info.Count();
            List <User> info1 = bll.Where(x => x.User_Condition == "在职");

            ViewBag.Use1 = info1.Count();
            List <User> info2 = bll.Where(x => x.User_Condition == "离职");

            ViewBag.Use2 = info2.Count();
            ClassManager  blll = new ClassManager();
            List <_class> cla  = blll.Where(x => x.DataTime == dt);

            ViewBag.Use3 = cla;
            ActionManager a      = new ActionManager();
            List <action> detail = a.GetAll();
            var           list   = detail.OrderByDescending(x => x.actiontime).Take(5).ToList();

            ViewBag.Use5 = list;
            WebManager web     = new WebManager();
            List <web> detail1 = web.GetAll();
            var        list1   = detail1.OrderByDescending(x => x.like).Take(5).ToList();

            ViewBag.Use4 = list1;
            return(View());
        }
Exemplo n.º 9
0
    protected string GetValueText()
    {
        var dalc         = WebManager.GetService <IDalc>(DalcServiceName);
        var relexParser  = new RelExQueryParser(false);
        var exprResolver = WebManager.GetService <NI.Common.Expressions.IExpressionResolver>("defaultExprResolver");

        var qContext = new Hashtable();

        if (DataContext is IDictionary)
        {
            qContext = new Hashtable((IDictionary)DataContext);
        }
        qContext["q"] = String.Empty;
        Query q = (Query)relexParser.Parse(Convert.ToString(exprResolver.Evaluate(qContext, GetRelex())));

        q.Root = new QueryConditionNode((QField)ValueFieldName, Conditions.Equal, (QConst)Value);           //& q.Root;
        var data = new Hashtable();

        if (dalc.LoadRecord(data, q))
        {
            var text = Convert.ToString(data[TextFieldName]);
            return(LocalizationEnabled?WebManager.GetLabel(text, this):text);
        }
        else
        {
            Value = null;
            return("");
        }
    }
Exemplo n.º 10
0
 public PPDServer(int port, WebManager webManager, RoomInfo roomInfo, ITimerManager timerManager, string logDir, string[] allowedModIds)
 {
     RoomInfo      = roomInfo;
     WebManager    = webManager;
     TimerManager  = timerManager;
     AllowedModIds = allowedModIds;
     if (!String.IsNullOrEmpty(logDir))
     {
         Logger = new Logger(logDir, String.Format("{0}.log", port));
     }
     contexts               = new List <ServerContextBase>();
     afterPushContexts      = new List <ServerContextBase>();
     afterPopContexts       = new List <ServerContextBase>();
     hostHandledData        = new Queue <NetworkData>();
     contextChains          = new Dictionary <ServerContextBase, ServerContextBase>();
     userLastUpdatedAt      = new Dictionary <int, DateTime>();
     delayedDisconnects     = new Dictionary <int, DateTime>();
     byteReader             = new TcpByteReader();
     byteReader.ByteReaded += byteReader_ByteReaded;
     host = new Host
     {
         Port = port
     };
     host.ReadClient += host_ReadClient;
     host.Closed     += host_Closed;
 }
Exemplo n.º 11
0
    public static object GetProviderObject(string prvName, object context, bool useCache)
    {
        var prv = WebManager.GetService <IProvider <object, object> >(prvName);

        return(GetProviderResult(prvName, context, useCache,
                                 x => prv.Provide(x)));
    }
Exemplo n.º 12
0
        public ActionResult Zan(int webId, int like)
        {
            WebManager dal  = new WebManager();
            WebManager dal1 = new WebManager();
            List <web> list = dal.Where(x => x.webId == webId);

            if (list != null)
            {
                web lis = new web()
                {
                    webId = webId,
                    like  = like + 1
                };
                bool list1 = dal1.Update(lis);
                if (list1)
                {
                    return(Redirect("/LiaoWeiYing/Home/Index"));
                }
                else
                {
                    return(Content("ss"));
                }
            }
            return(Content("ss"));
        }
Exemplo n.º 13
0
        // GET: LiaoWeiYing/Home
        public ActionResult Index(int pageIndex = 1, int userID = 0, int id = 1)
        {
            //var idd=Session["name"] as User;
            userID = ((User)(Session["User"])).UserId;
            WebManager dal1  = new WebManager();
            List <web> list1 = dal1.Where(x => x.web_typeID == id && x.web_Condition == "可见").OrderByDescending(x => x.webtime).ToList();

            web_typeManager dal2  = new web_typeManager();
            List <web_type> list2 = dal2.GetAll();

            ViewBag.list2 = list2;


            UserManager dal3  = new UserManager();
            List <User> list3 = dal3.Where(x => x.UserId == userID);

            ViewBag.list3 = list3;



            ReplayTypeManager dal5  = new ReplayTypeManager();
            List <ReplayType> list6 = dal5.GetAll();

            ViewBag.ReplayTypeID = new SelectList(list6, "ReplayTypeID", "ReplayTypeName");


            int pageSize = 3;
            var list4    = list1.Skip((pageIndex - 1) * pageSize)
                           .Take(pageSize).ToList();

            ViewBag.pageIndex = pageIndex;

            return(View(list4));
        }
Exemplo n.º 14
0
        public async Task <CountryViewModel> RequestCountryAsync(string countryName)
        {
            var uri          = ConfigurationManager.Config.GetSection("CountriesInfoAPI")["DefaultAPI"] + countryName;
            var responseText = await WebManager.Request(uri).ConfigureAwait(false);

            return(JsonConvert.DeserializeObject <CountryViewModel[]>(responseText).FirstOrDefault());
        }
Exemplo n.º 15
0
        public ActionResult Add(web info)
        {
            WebManager list1  = new WebManager();
            int        userID = ((User)(Session["User"])).UserId;
            DateTime   ss     = System.DateTime.Now;
            //webId, UserId, web_typeID, webHead, webResult, webtime, like, ReplayTypeID, web_Condition
            web ds = new web()
            {
                UserId        = userID,
                web_typeID    = info.web_typeID,
                webHead       = info.webHead,
                webResult     = info.webResult,
                webtime       = ss,
                like          = 0,
                ReplayTypeID  = info.ReplayTypeID,
                web_Condition = info.web_Condition
            };
            bool list = list1.Add(ds);

            if (list)
            {
                return(Redirect("/LiaoWeiYing/Home/Index"));
            }
            else
            {
                return(Content("发布失败"));
            }
        }
Exemplo n.º 16
0
 private void Start()
 {
     this.isPaused   = false;
     base.enabled    = false;
     this.WebManager = new WebManager(this);
     this.ForceGarbageCollection(new Action(this.OnGarbageCollectedStart));
 }
Exemplo n.º 17
0
    // Use this for initialization
    void Start () {
        material = cursor.GetComponent<Renderer>().material;
        material.color = MarchingCubes.Builder.colorMap[color];
        body = GetComponent<Rigidbody>();

        web = FindObjectOfType<WebManager>();
    }
Exemplo n.º 18
0
    public static void BindData(Chart chart, string prvName, object context, string[] seriesExpr, string labelExpr, string labelLookupName)
    {
        var prv         = WebManager.GetService <IProvider <object, object> >(prvName);
        var ognlContext = new Dictionary <string, object>();

        ognlContext["data"] = prv.Provide(context);

        var ognlExpr  = new NReco.OGNL.EvalOgnl();
        int seriesIdx = 0;

        foreach (var expr in seriesExpr)
        {
            var dataset = (IEnumerable)ognlExpr.Eval(expr, ognlContext);
            var series  = chart.Series[seriesIdx];
            foreach (var val in dataset)
            {
                var decVal = Convert.ToDecimal(val);
                series.Points.AddY(decVal);
            }
            seriesIdx++;
        }

        /*if (!String.IsNullOrEmpty(labelExpr)) {
         *      var labels = (IEnumerable)ognlExpr.Eval( labelExpr, ognlContext );
         *      var labelsList = new List<string>();
         *      var labelPrv = String.IsNullOrEmpty(labelLookupName) ? null : WebManager.GetService<IProvider<object,string>>(labelLookupName);
         *      foreach (var lbl in labels) {
         *              labelsList.Add( labelPrv!=null ? labelPrv.Provide(lbl) : Convert.ToString(lbl) );
         *      }
         *      res += "&"+labelParam+String.Join("|", labelsList.ToArray() );
         * }*/
    }
Exemplo n.º 19
0
        protected void ButtonPhoto_Click(object sender, EventArgs e)
        {
            if (FileUploadPicture.HasFile)
            {
                string filePath = "~/Files/Temp/" + FileUploadPicture.FileName;
                if (Path.GetExtension(filePath).ToLower() == ".jpg" || Path.GetExtension(filePath).ToLower() == ".jpeg")
                {
                    string fileName     = Session["UserId"] + Path.GetExtension(filePath).ToLower();
                    string relativePath = @"~\Files\Temp\" + fileName;
                    FileUploadPicture.SaveAs(Server.MapPath(relativePath));

                    //use WebManager to get the file, and save it
                    IImageInfo img = WebManager.GetImageInfo(FileUploadPicture);
                    img.Path     = Server.MapPath("~") + "\\Files\\Temp\\";
                    img.FileName = Session["UserId"] + ".jpg";

                    //now create resized versions, and save them
                    IImageInfo img160 = img.ResizeMe(160, 160);
                    img160.Save("~/Files/" + ConfigurationManager.AppSettings["folderName"].ToString() + "/ProfilesPhotos/");

                    LabelPhotoMessage.Visible = true;
                    LabelPhotoMessage.Text    = "You have successfully uploaded your picture.";

                    HiddenFieldPhotoUrl.Value = "Files/" + ConfigurationManager.AppSettings["folderName"].ToString() + "/ProfilesPhotos/" + Session["UserId"].ToString() + ".jpg";

                    File.Delete(Server.MapPath("~") + "\\Files\\Temp\\" + fileName);

                    SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
                    SqlCommand    sqlCmd  = new SqlCommand("sp_settingsPhotoEdit", sqlConn);
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.Add("@UserId", SqlDbType.Int).Value   = Convert.ToInt32(Session["UserId"]);
                    sqlCmd.Parameters.Add("@HasPhoto", SqlDbType.Bit).Value = true;

                    try
                    {
                        sqlConn.Open();
                        sqlCmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        sqlConn.Close();
                        sqlCmd.Dispose();
                        sqlConn.Dispose();
                    }
                }
                else
                {
                    LabelPhotoMessage.Visible = true;
                    LabelPhotoMessage.Text    = "Select a picture with JPG extenstion.";
                }
            }
            else
            {
                LabelPhotoMessage.Visible = true;
                LabelPhotoMessage.Text    = "Select a picture file.";
            }
        }
Exemplo n.º 20
0
        static async Task MainAsync(string[] args)
        {
            var authManager = new AuthManager(new WebManager());

            Console.WriteLine("If you have an auth token, enter it below. Else leave blank: ");
            var authToken = Console.ReadLine();

            if (string.IsNullOrEmpty(authToken))
            {
                authToken = await MakeNewUser(authManager);
            }
            if (string.IsNullOrEmpty(authToken))
            {
                Console.WriteLine("Error getting auth token!");
            }

            _webManager = new WebManager(authToken);
            await GetComputers();

            //await GetNames();
            //await GetUserInfo();
            //await MakePost();
            //await GetMessages();
            //await MakeComment();
            Console.ReadKey();
        }
Exemplo n.º 21
0
    public static IDictionary <string, object> ComposeTextFieldDescriptor(string name, string caption, IList <IDictionary <string, object> > conditions)
    {
        var fieldDescriptor = new Dictionary <string, object>();

        fieldDescriptor["name"]       = name;
        fieldDescriptor["caption"]    = WebManager.GetLabel(caption, "QueryConditionEditor");
        fieldDescriptor["dataType"]   = "string";
        fieldDescriptor["conditions"] = conditions != null
                        ? conditions
                        : new List <IDictionary <string, object> > {
            new Dictionary <string, object> {
                { "text", WebManager.GetLabel("like", "QueryConditionEditor") }, { "value", "like" }
            },
            new Dictionary <string, object> {
                { "text", WebManager.GetLabel("not like", "QueryConditionEditor") }, { "value", "!like" }
            },
            new Dictionary <string, object> {
                { "text", "=" }, { "value", "=" }
            },
            new Dictionary <string, object> {
                { "text", "<>" }, { "value", "!=" }
            }
        };
        var rendererData = new Dictionary <string, object>();

        rendererData["name"]        = "textbox";
        fieldDescriptor["renderer"] = rendererData;
        return(fieldDescriptor);
    }
Exemplo n.º 22
0
    public static IDictionary[] GetProviderDictionaries(string prvName, object context, bool useCache)
    {
        var prv = WebManager.GetService <IProvider <object, IDictionary[]> >(prvName);

        return(GetProviderResult(prvName, context, useCache,
                                 x => prv.Provide(x)) as IDictionary[]);
    }
Exemplo n.º 23
0
    protected void OdsOrderDetails_Selecting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        //since the select parameter contains a special type of parameter, rather than the primitive type
        //we can't use the built-in asp:paramter in object data-source, as it supports only primitive data types
        //for this purpose we have performed the required casting and assignment (if necessary) in this event handler method
        //however alternatively we can use 'control-parameter' in object-data-source for this type of special data type, which performs the casting automatically
        //e.InputParameters("employeeID") = CType(1,Int32)

        //saving page-mode and item id
        //int empId = (int)uint.MinValue;
        //if(e.InputParameters["employeeId"]!=null)
        //    empId =Int32.Parse(e.InputParameters["employeeId"].ToString());

        //empId = WebManager.StoreValue(this, ViewState, empId, formViewEmployee);

        // [ Added: Jalal On 03/17/2008 ]
        //e.InputParameters["employeeId"] = Int32.Parse(ViewState["Id"].ToString(), System.Globalization.CultureInfo.CurrentCulture);
        e.InputParameters["employeeId"] = WebManager.ParseItemId(this, formViewEmployee);
        //e.InputParameters["employeeId"] = Convert.ToInt32(WebManager.ParseItemId(this, formViewEmployee));
        //if the form view mode is in insert model, then we'll cancel the selection by object data source
        if (formViewEmployee.CurrentMode == FormViewMode.Insert)
        {
            e.Cancel = true;
        }
    }
Exemplo n.º 24
0
        /// <summary>
        ///     Loads resources file.
        /// </summary>
        private static void LoadResources()
        {
            ResourceManager.ContentUrlList        = new LogicArrayList <string>();
            ResourceManager.ChronosContentUrlList = new LogicArrayList <string>();
            ResourceManager.AppStoreUrlList       = new LogicArrayList <string>();

            string resourceFile = WebManager.DownloadConfigString("/res/resources.json");

            if (resourceFile != null)
            {
                LogicJSONObject jsonObject          = (LogicJSONObject)LogicJSONParser.Parse(resourceFile);
                LogicJSONArray  contentArray        = jsonObject.GetJSONArray("content");
                LogicJSONArray  chronosContentArray = jsonObject.GetJSONArray("chronosContent");
                LogicJSONArray  appStoreArray       = jsonObject.GetJSONArray("appstore");

                for (int i = 0; i < contentArray.Size(); i++)
                {
                    ResourceManager.ContentUrlList.Add(contentArray.GetJSONString(i).GetStringValue());
                }

                for (int i = 0; i < chronosContentArray.Size(); i++)
                {
                    ResourceManager.ChronosContentUrlList.Add(chronosContentArray.GetJSONString(i).GetStringValue());
                }

                for (int i = 0; i < appStoreArray.Size(); i++)
                {
                    ResourceManager.AppStoreUrlList.Add(appStoreArray.GetJSONString(i).GetStringValue());
                }
            }
            else
            {
                Debugger.Error("ResourceManager::loadResources resources.json not exist");
            }
        }
Exemplo n.º 25
0
        public ActionResult Delete(int webId, int UserId)
        {
            int userID = (((User)(Session["User"])).UserId);

            if (UserId != userID)
            {
                return(Content("<script>alert('对比起您没有权限删除别人的评论!!');window.location.href='/LiaoWeiYing/Home/Index';</script>"));
            }
            else
            {
                WebManager list1 = new WebManager();
                web        sdd   = new web()
                {
                    webId         = webId,
                    web_Condition = "不可见"
                };
                bool list2 = list1.Update1(sdd);
                if (list2)
                {
                    return(Redirect("/LiaoWeiYing/Home/Index"));
                }
                else
                {
                    return(Content("失败"));
                }
            }
        }
Exemplo n.º 26
0
        private async Task UpdateNextRowsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            pageId++;
            IsBusy = true;
            RefreshCommand.ChangeCanExecute();

            string url = Url + "&page=" + pageId;

            ObservableCollection <RowData> rows = await WebManager.LoadItemsAsync(url);

            Rows.RemoveAt(Rows.Count - 1);
            foreach (RowData rowData in rows)
            {
                Rows.Add(rowData);
            }
            Rows = RemoveDuplicateRows(Rows);
            Rows.Add(GetMoreRowData());
            IsBusy = false;
            RefreshCommand.ChangeCanExecute();
        }
Exemplo n.º 27
0
    public static bool GetProviderBoolean(string prvName, object context, bool useCache)
    {
        var prv = WebManager.GetService <IProvider <object, object> >(prvName);
        var res = GetProviderResult(prvName, context, useCache,
                                    x => prv.Provide(x));

        return(AssertHelper.IsFuzzyTrue(res));
    }
Exemplo n.º 28
0
 public void AllPluginsStarted(TaskCompletionSource <bool> AllPluginsStartedSink)
 {
     // other plugins have had time to register their nancy modules
     // start the host now
     log.Info("Initializing WebManager...");
     WebAPIGlobal.ResultOfHostRunSink = AllPluginsStartedSink;
     WebManager.Initialize();
 }
Exemplo n.º 29
0
    // Use this for initialization
    void Start()
    {
        material       = cursor.GetComponent <Renderer>().material;
        material.color = MarchingCubes.Builder.colorMap[color];
        body           = GetComponent <Rigidbody>();

        web = FindObjectOfType <WebManager>();
    }
Exemplo n.º 30
0
    public static string PrepareDataUrl(string prvName, object context, string[] seriesExpr, string labelParam, string labelExpr, string labelLookupName)
    {
        var prv         = WebManager.GetService <IProvider <object, object> >(prvName);
        var ognlContext = new Dictionary <string, object>();

        ognlContext["data"] = prv.Provide(context);

        var     series   = new List <string>();
        decimal allMin   = 0;
        decimal allMax   = 0;
        var     ognlExpr = new NReco.OGNL.EvalOgnl();

        foreach (var expr in seriesExpr)
        {
            var     dataset     = (IEnumerable)ognlExpr.Eval(expr, ognlContext);
            var     datasetList = new List <string>();
            decimal min         = 0;
            decimal max         = 0;
            foreach (var val in dataset)
            {
                var decVal = Convert.ToDecimal(val);
                datasetList.Add(String.Format(CultureInfo.InvariantCulture, "{0:0.#}", decVal));
                if (decVal < min)
                {
                    min = decVal;
                }
                if (decVal > max)
                {
                    max = decVal;
                }
            }
            series.Add(String.Join(",", datasetList.ToArray()));

            if (allMin > min)
            {
                allMin = min;
            }
            if (allMax < max)
            {
                allMax = max;
            }
        }
        var res = String.Format(CultureInfo.InvariantCulture, "chd=t:{0}&chds={1:0.##},{2:0.##}&chxr=1,{1:0.##},{2:0.##},{3}", String.Join("|", series.ToArray()), allMin, allMax, (allMax - allMin) / 5);

        if (!String.IsNullOrEmpty(labelExpr))
        {
            var labels     = (IEnumerable)ognlExpr.Eval(labelExpr, ognlContext);
            var labelsList = new List <string>();
            var labelPrv   = String.IsNullOrEmpty(labelLookupName) ? null : WebManager.GetService <IProvider <object, string> >(labelLookupName);
            foreach (var lbl in labels)
            {
                labelsList.Add(labelPrv != null ? labelPrv.Provide(lbl) : Convert.ToString(lbl));
            }
            res += "&" + labelParam + String.Join("|", labelsList.ToArray());
        }
        return(res);
    }
Exemplo n.º 31
0
        private bool CheckCourseAvailabilityFromMasterClassSchedule(Course course)
        {
            InsertLog("Checking availability of " + course.CourseCode + " " + course.Section + "...", Color.Black);

            WebManager schedulePage = new WebManager("https://banweb.cityu.edu.hk/pls/PROD/hwscrssh_cityu.P_DispOneSection");
            try
            {
                String[] courseSubjectAndCode = Regex.Split(course.CourseCode, @"(?<=\D)(?=\d)");
                schedulePage.SetReferer("https://banweb.cityu.edu.hk/pls/PROD/hwscrssh_cityu.P_GetCrse")
                        .AddParameter("term", AddDropTerm)
                        .AddParameter("subj", courseSubjectAndCode[0])
                        .AddParameter("crse", courseSubjectAndCode[1])
                        .AddParameter("camp", "")
                        .AddParameter("web_avail", "")
                        .Load();
                InsertLog(schedulePage.ToString());

                // Retrive the course details
                foreach (HtmlAgilityPack.HtmlNode row in schedulePage.GetHtmlNodeCollection("//div[@class='body']//tr[@bgcolor='#ffccff']"))
                {
                    HtmlAgilityPack.HtmlNodeCollection courseDetails = row.SelectNodes("td");

                    if (courseDetails[1].InnerText == course.Section)
                    {
                        courseDetails[6].SelectSingleNode("span[@style='display:none']")?.Remove();
                        int.TryParse(courseDetails[6].InnerText.Substring(2), out course.AvaliableQuota);

                        courseDetails[8].SelectSingleNode("span[@style='display:none']")?.Remove();
                        int.TryParse(courseDetails[8].InnerText, out course.WaitlistQuota);
                        break;
                    }
                }

                return (course.AvaliableQuota > 0 || course.WaitlistQuota > 0);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (ex is WebException)
                {
                    InsertLog("Server returned error: " + ex.Message, Color.Red);

                    if (ex.Message == "Break in attempt" || ex.Message == "Session timeout")
                    {
                        if (PrepareLogin() && Login()) return CheckCourseAvailabilityFromMasterClassSchedule(course);
                    }
                }
                else if (ex is NullReferenceException || ex is ArgumentOutOfRangeException)
                {
                    InsertLog("Cannot retrieve the course details.", Color.Red);
                }
                else InsertLog(ex.ToString(), Color.Red);
            }

            return false;
        }
Exemplo n.º 32
0
        private async Task ProcessChat(AspNetWebSocketContext context)
        {
            WebSocket         socket            = context.WebSocket;
            CancellationToken cancellationToken = new CancellationToken();
            bool isExits = WebManager.AddUser(userKey, socket);

            if (isExits == false)
            {
                //表示该用户有在线
                await WebManager.SendToMySelf(cancellationToken, $"用户【{this.userKey}】 已在线", this.userKey);
            }
            else
            {
                //表示登录成功
                //某人登陆后,给群里其他人发送提示信息(本人除外)
                await WebManager.SendLoginSucesssNotice(cancellationToken, $"用户【{this.userKey}】 进入聊天室,当前时间:{DateTime.Now.ToYYYYMMDD()}");

                while (socket.State == WebSocketState.Open)
                {
                    ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[2048]);
                    //接受指令
                    WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, cancellationToken);

                    //表示是关闭指令
                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        //移除该用户对应的socket对象
                        WebManager.RemoveUser(userKey);
                        //发送离开提醒
                        await WebManager.SendOutNotice(cancellationToken, $"用户【{this.userKey}】 离开聊天室,当前时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");

                        await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationToken);
                    }
                    //获取是发送消息指令
                    else
                    {
                        string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                        //这里要区分是单发还是群发(通过与前端在内容开头做一个标记,来区分是单发还是群发)
                        if (userMsg.Length > 8 && userMsg.Substring(0, 8) == "$--$--**")
                        {
                            //表示是单发,截取内容和接受者的标记
                            var    array         = userMsg.Split(new string[] { "$--$--**" }, StringSplitOptions.None);
                            var    receiveNotice = array[1];
                            string content       = $"用户【{this.userKey}】 发来消息:{array[2]},当前时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
                            WebManager.SendSingleMessage(cancellationToken, content, receiveNotice);
                        }
                        else
                        {
                            //表示群发信息
                            string content = $"用户【{this.userKey}】 群发消息:{userMsg},当前时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
                            WebManager.SendAllMessage(cancellationToken, content, userKey);
                        }
                    }
                }
            }
        }
Exemplo n.º 33
0
        private bool CheckRegistrationStatus()
        {
            InsertLog("Checking registration status...", Color.Black);

            WebManager registrationPage = new WebManager("https://banweb.cityu.edu.hk/pls/PROD/bwskfreg.P_AltPin", WebManager.POST);
            try
            {
                registrationPage.AddParameter("term_in", AddDropTerm).Load();
                InsertLog(registrationPage.ToString());

                HtmlAgilityPack.HtmlNode infoText = registrationPage.GetHtmlNode("//span[@class='infotext']");
                if (infoText != null && infoText.InnerText.Contains("You may register during the following times"))
                {
                    return false;
                }
                else if (infoText != null && infoText.InnerText.Contains("WEB REGISTRATION PERIOD"))
                {
                    return true;
                }

                throw new WebException("Server busy or Unknown error");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (ex is WebException)
                {
                    InsertLog("Server returned error: " + ex.Message, Color.Red);

                    if (ex.Message == "Break in attempt" || ex.Message == "Session timeout")
                    {
                        if (PrepareLogin() && Login()) return CheckRegistrationStatus();
                    }
                }
                else InsertLog(ex.ToString(), Color.Red);
            }

            return false;
        }
Exemplo n.º 34
0
        private List<Course> GetCourseListFromMasterClassSchedule(String courseCode, List<String> courseSectionList)
        {
            InsertLog("Retrieving course details of " + courseCode + "...", Color.Black);

            WebManager schedulePage = new WebManager("https://banweb.cityu.edu.hk/pls/PROD/hwscrssh_cityu.P_DispOneSection");
            try
            {
                String[] courseSubjectAndCode = Regex.Split(courseCode, @"(?<=\D)(?=\d)");
                schedulePage.SetReferer("https://banweb.cityu.edu.hk/pls/PROD/hwscrssh_cityu.P_GetCrse")
                        .AddParameter("term", AddDropTerm)
                        .AddParameter("subj", courseSubjectAndCode[0])
                        .AddParameter("crse", courseSubjectAndCode[1])
                        .AddParameter("camp", "")
                        .AddParameter("web_avail", "")
                        .Load();
                InsertLog(schedulePage.ToString());

                // Retrieve the course title
                String courseTitle = "";
                String htmlSource = schedulePage.GetHtmlNode("//div[@class='body']/b[1]").InnerText;
                if (htmlSource.IndexOf("Course : " + courseCode + " ") >= 0)
                {
                    courseTitle = htmlSource.Substring(htmlSource.IndexOf("Course : " + courseCode + " ") + courseCode.Length + 10);

                    InsertLog("title: " + courseTitle, Color.Green);
                }
                else throw new NullReferenceException();

                // Retrive the course details
                List<Course> toReturn = new List<Course>();
                HtmlAgilityPack.HtmlNodeCollection courseTable = schedulePage.GetHtmlNodeCollection("//div[@class='body']//tr[@bgcolor='#ffccff']");
                if (courseTable != null)
                {
                    foreach (HtmlAgilityPack.HtmlNode row in courseTable)
                    {
                        HtmlAgilityPack.HtmlNodeCollection courseDetails = row.SelectNodes("td");

                        // Ignore the duplicate rows
                        if (courseDetails[0].InnerText != "" && courseSectionList.Remove(courseDetails[1].InnerText))
                        {
                            Course course = new Course();

                            course.CRN = courseDetails[0].InnerText;
                            course.CourseCode = courseCode;
                            course.Section = courseDetails[1].InnerText;
                            course.Title = courseTitle;

                            course.Credit = Convert.ToSingle(courseDetails[2].InnerText);
                            course.Date = courseDetails[9].InnerText;
                            course.DayOfWeek = courseDetails[10].InnerText;
                            course.Time = courseDetails[11].InnerText;
                            course.Room = courseDetails[13].InnerText + ", " + courseDetails[12].InnerText;
                            course.Instructor = courseDetails[14].InnerText;

                            courseDetails[6].SelectSingleNode("span[@style='display:none']")?.Remove();
                            int.TryParse(courseDetails[6].InnerText, out course.AvaliableQuota);
                            course.MaxQuota = Convert.ToInt32(courseDetails[7].InnerText);

                            courseDetails[8].SelectSingleNode("span[@style='display:none']")?.Remove();
                            int.TryParse(courseDetails[8].InnerText, out course.WaitlistQuota);

                            toReturn.Add(course);
                        }
                    }
                }

                String notFoundSections = "";
                foreach (String courseSection in courseSectionList)
                {
                    notFoundSections += (notFoundSections == "" ? "" : ", ") + courseSection;
                }
                if (notFoundSections != "")
                {
                    InsertLog("Cannot find section(s) " + notFoundSections + ".", Color.Red);
                }

                return toReturn;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (ex is WebException)
                {
                    InsertLog("Server returned error: " + ex.Message, Color.Red);

                    if (ex.Message == "Break in attempt" || ex.Message == "Session timeout")
                    {
                        if (PrepareLogin() && Login()) return GetCourseListFromMasterClassSchedule(courseCode, courseSectionList);
                    }
                }
                else if (ex is NullReferenceException || ex is ArgumentOutOfRangeException)
                {
                    InsertLog("Cannot retrieve the course details.", Color.Red);
                }
                else InsertLog(ex.ToString(), Color.Red);
            }

            return null;
        }
Exemplo n.º 35
0
        private List<Course> GetCourseListFromRegisteredRecords()
        {
            InsertLog("Retrieving your active registered course...", Color.Black);

            WebManager activeCoursePage = new WebManager("https://banweb.cityu.edu.hk/pls/PROD/hwskaddp_cityu.P_ChkReg");
            try
            {
                activeCoursePage.Load();
                InsertLog(activeCoursePage.ToString());

                String title = activeCoursePage.GetHtmlNode("//h2").InnerText;
                label_registeredCourse.Text = label_registeredCourse.Text.Replace(":", " for " + title.Replace("Active Registration (", "").Replace(")", "") + ":");

                List<Course> toReturn = new List<Course>();
                foreach (HtmlAgilityPack.HtmlNode row in activeCoursePage.GetHtmlNodeCollection("//table[2]//tr"))
                {
                    HtmlAgilityPack.HtmlNodeCollection courseDetails = row.SelectNodes("td");

                    // Ignore the first row
                    if (courseDetails != null && courseDetails[0].InnerText != "CRN")
                    {
                        Course course = new Course();

                        course.CRN = courseDetails[0].InnerText;
                        course.CourseCode = courseDetails[1].InnerText;
                        course.Section = courseDetails[2].InnerText;
                        course.Title = courseDetails[3].InnerText;

                        course.Credit = Convert.ToSingle(courseDetails[4].InnerText);

                        toReturn.Add(course);
                    }
                }

                InsertLog("Retrieved registered course.", Color.Blue);

                return toReturn;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (ex is WebException)
                {
                    InsertLog("Server returned error: " + ex.Message, Color.Red);

                    if (ex.Message == "Break in attempt" || ex.Message == "Session timeout")
                    {
                        if (PrepareLogin() && Login()) return GetCourseListFromRegisteredRecords();
                    }
                }
                else if (ex is NullReferenceException)
                {
                    InsertLog("Cannot retrieve registered course.", Color.Red);
                }
                else InsertLog(ex.ToString(), Color.Red);
            }

            return null;
        }
Exemplo n.º 36
0
        private bool Login()
        {
            InsertLog("Logging in...", Color.Black);

            WebManager loginPage = new WebManager("https://banweb.cityu.edu.hk/pls/PROD/twgkpswd_cityu.P_WWWLogin", WebManager.POST);
            try
            {
                loginPage.AddParameter("p_username", Eid)
                        .AddParameter("p_password", Password)
                        .AddParameter("p_sess_id", SessionID)
                        .AddParameter("p_ip", IPAddress)
                        .AddParameter("to_url", "")
                        .Load();
                InsertLog(loginPage.ToString());

                // Check login status
                if (loginPage.GetHtmlNode("//meta[@http-equiv='refresh']") != null)
                {
                    InsertLog("Logged in as " + Eid, Color.Blue);

                    return true;
                }
                else
                {
                    InsertLog("Cannot verify your electronic ID and password.", Color.Red);

                    return false;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (ex is WebException)
                {
                    InsertLog("Server returned error: " + ex.Message, Color.Red);
                }
                else InsertLog(ex.ToString(), Color.Red);
            }

            return false;
        }
Exemplo n.º 37
0
        // Web interaction methods
        private bool PrepareLogin()
        {
            InsertLog("Waiting response from AIMS server...", Color.Black);

            WebManager loginPage = new WebManager("https://banweb.cityu.edu.hk/pls/PROD/twgkpswd_cityu.P_WWWLogin");
            try
            {
                loginPage.Load();
                InsertLog(loginPage.ToString());

                InsertLog("Server responsed.", Color.Blue);

                // Get required login parameters
                foreach (HtmlAgilityPack.HtmlAttribute attr in loginPage.GetHtmlNode("//input[@name='p_sess_id']").Attributes.AttributesWithName("value"))
                {
                    SessionID = attr.Value;
                }
                foreach (HtmlAgilityPack.HtmlAttribute attr in loginPage.GetHtmlNode("//input[@name='p_ip']").Attributes.AttributesWithName("value"))
                {
                    IPAddress = attr.Value;
                }

                InsertLog("p_ip: " + IPAddress + ", p_sess_id: " + SessionID, Color.Green);

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (ex is WebException)
                {
                    InsertLog("Server returned error: " + ex.Message, Color.Red);
                }
                else if (ex is NullReferenceException)
                {
                    InsertLog("Cannot retrieve the login parameters.", Color.Red);
                }
                else InsertLog(ex.ToString(), Color.Red);
            }

            return false;
        }
Exemplo n.º 38
0
        private bool SendRegistrationRequests(List<Course> requestList)
        {
            if (requestList.Count == 0) return true;

            InsertLog("Sending your registration request (priority: " + requestList[0].Priority + ")...", Color.Black);

            WebManager registrationPage = new WebManager("https://banweb.cityu.edu.hk/pls/PROD/bwckcoms.P_Regs", WebManager.POST);
            try
            {
                registrationPage.AddParameter("term_in", AddDropTerm)
                        .AddParameter("RSTS_IN", "DUMMY")
                        .AddParameter("assoc_term_in", "DUMMY")
                        .AddParameter("CRN_IN", "DUMMY")
                        .AddParameter("start_date_in", "DUMMY")
                        .AddParameter("end_date_in", "DUMMY")
                        .AddParameter("SUBJ", "DUMMY")
                        .AddParameter("CRSE", "DUMMY")
                        .AddParameter("SEC", "DUMMY")
                        .AddParameter("LEVL", "DUMMY")
                        .AddParameter("CRED", "DUMMY")
                        .AddParameter("GMOD", "DUMMY")
                        .AddParameter("TITLE", "DUMMY")
                        .AddParameter("MESG", "DUMMY")
                        .AddParameter("REG_BTN", "DUMMY")
                        .AddParameter("MESG", "DUMMY");

                // Drop requests
                int dropCount = 0;
                foreach (Course course in requestList.Where(course => course.Action == Course.ACTION_DROP))
                {
                    course.Status = Course.STATUS_SENT;

                    registrationPage.AddParameter("RSTS_IN", "DW")
                            .AddParameter("CRN_IN", course.CRN)
                            .AddParameter("assoc_term_in", "")
                            .AddParameter("start_date_in", "")
                            .AddParameter("end_date_in", "");
                    dropCount++;
                }

                // Wait requests
                int waitCount = 0;
                foreach (Course course in requestList.Where(course => course.Action == Course.ACTION_WAIT))
                {
                    course.Status = Course.STATUS_SENT;

                    registrationPage.AddParameter("RSTS_IN", "WL")
                            .AddParameter("CRN_IN", course.CRN)
                            .AddParameter("assoc_term_in", "")
                            .AddParameter("start_date_in", "")
                            .AddParameter("end_date_in", "");
                    waitCount++;
                }

                // Add requests
                int addCount = 0;
                foreach (Course course in requestList.Where(course => course.Action == Course.ACTION_ADD))
                {
                    course.Status = Course.STATUS_SENT;

                    registrationPage.AddParameter("RSTS_IN", "RW")
                            .AddParameter("CRN_IN", course.CRN)
                            .AddParameter("assoc_term_in", "")
                            .AddParameter("start_date_in", "")
                            .AddParameter("end_date_in", "");
                    addCount++;
                }

                // Update request list view
                this.Invoke((MethodInvoker)delegate
                {
                    // Run on UI thread
                    SetRequestListView();
                });

                registrationPage.AddParameter("regs_row", dropCount.ToString())
                        .AddParameter("wait_row", waitCount.ToString())
                        .AddParameter("add_row", addCount.ToString())
                        .AddParameter("REG_BTN", "Submit Changes")
                        .Load();
                InsertLog(registrationPage.ToString());

                // Check response content
                HtmlAgilityPack.HtmlNode infoText = registrationPage.GetHtmlNode("//span[@class='infotext']");
                if (infoText == null || !infoText.InnerText.Contains("WEB REGISTRATION PERIOD"))
                {
                    throw new WebException("Server busy or Unknown error");
                }

                // Update registered course list
                RegisteredCourseList.Clear();
                foreach (HtmlAgilityPack.HtmlNode row in registrationPage.GetHtmlNodeCollection("//table[@summary='Current Schedule']//tr"))
                {
                    HtmlAgilityPack.HtmlNodeCollection courseDetails = row.SelectNodes("td");

                    // Ignore the first row with <th>
                    if (courseDetails != null)
                    {
                        Course course = new Course();

                        course.CRN = courseDetails[2].InnerText;
                        course.CourseCode = courseDetails[3].InnerText + courseDetails[4].InnerText;
                        course.Section = courseDetails[5].InnerText;
                        course.Title = courseDetails[9].InnerText;

                        course.Credit = Convert.ToSingle(courseDetails[7].InnerText);

                        RegisteredCourseList.Add(course);
                    }
                }

                // Check registration errors
                bool registrationError = false;

                HtmlAgilityPack.HtmlNodeCollection errorTable = registrationPage.GetHtmlNodeCollection("//table[@summary='This layout table is used to present Drop or Withdrawal Errors.']//tr");
                if (errorTable != null)
                {
                    foreach (HtmlAgilityPack.HtmlNode row in errorTable)
                    {
                        HtmlAgilityPack.HtmlNodeCollection errorDetails = row.SelectNodes("td");

                        // Ignore the first row with <th>
                        if (errorDetails != null)
                        {
                            foreach (Course course in requestList.Where(course => errorDetails[4].InnerText.Contains(course.CRN)))
                            {
                                course.Status = "Error: " + errorDetails[4].InnerText;
                                registrationError = true;
                            }
                        }
                    }
                }

                errorTable = registrationPage.GetHtmlNodeCollection("//table[@summary='This layout table is used to present Registration Errors.']//tr");
                if (errorTable != null)
                {
                    foreach (HtmlAgilityPack.HtmlNode row in errorTable)
                    {
                        HtmlAgilityPack.HtmlNodeCollection errorDetails = row.SelectNodes("td");

                        // Ignore the first row with <th>
                        if (errorDetails != null)
                        {
                            foreach (Course course in requestList.Where(course => course.CRN == errorDetails[1].InnerText || course.CRN == errorDetails[2].InnerText))
                            {
                                // Check waitlist
                                if (errorDetails[0].InnerText.Contains(Course.STATUS_WAITLISTED))
                                {
                                    course.Action = Course.ACTION_WAIT;
                                    course.Status = Course.STATUS_PENDING;
                                }
                                else
                                {
                                    course.Status = "Error: " + errorDetails[0].InnerText;
                                    registrationError = true;
                                }
                            }
                        }
                    }
                }

                // Change the status to completed
                foreach (Course course in requestList.Where(course => course.Status == Course.STATUS_SENT))
                {
                    course.Status = Course.STATUS_COMPLETED;
                }

                // Update list views
                this.Invoke((MethodInvoker)delegate
                {
                    // Run on UI thread
                    SetRegisteredCourseListView();
                    SetRequestListView();
                });

                return (!registrationError);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                if (ex is WebException)
                {
                    InsertLog("Server returned error: " + ex.Message, Color.Red);

                    if (ex.Message == "Break in attempt" || ex.Message == "Session timeout")
                    {
                        if (PrepareLogin() && Login()) return SendRegistrationRequests(requestList);
                    }
                }
                else InsertLog(ex.ToString(), Color.Red);
            }

            return false;
        }
Exemplo n.º 39
0
        public void Initialize()
        {
            Essential.consoleWriter = new ConsoleWriter(Console.Out);
            Console.SetOut(Essential.consoleWriter);
            try
            {
                Console.WindowWidth = 130;
                Console.WindowHeight = 36;
            }
            catch { }
            Essential.ServerStarted = DateTime.Now;
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine();
            Console.WriteLine(@"                                          ______                    _   _       _ ");
            Console.WriteLine(@"                                         |  ____|                  | | (_)     | |");
            Console.WriteLine(@"                                         | |__   ___ ___  ___ _ __ | |_ _  __ _| |");
            Console.WriteLine(@"                                         |  __| / __/ __|/ _ \ '_ \| __| |/ _` | |");
            Console.WriteLine(@"                                         | |____\__ \__ \  __/ | | | |_| | (_| | |");
            Console.WriteLine(@"                                         |______|___/___/\___|_| |_|\__|_|\__,_|_|");
            Console.WriteLine();
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("                                         Essential Emulator Build " + Build + " by " + Creator);
            Console.WriteLine();
            Console.WriteLine("                         Credits to: Meth0d (Uber), Sojobo (Phoenix), Juniori (GTE) & Rootkit (Essential)");
            Console.WriteLine();
            Console.ResetColor();
            try
            {
                Essential.Configuration = new ConfigurationData("config.conf");
                DateTime now = DateTime.Now;
                try
                {
                    Essential.SWFDirectory = Essential.GetConfig().data["web.api.furni.hof_furni"];
                }
                catch { }
                if (!Directory.Exists("API"))
                    Directory.CreateDirectory("API");

                DatabaseServer dbServer = new DatabaseServer(Essential.GetConfig().data["db.hostname"], uint.Parse(Essential.GetConfig().data["db.port"]), Essential.GetConfig().data["db.username"], Essential.GetConfig().data["db.password"]);
                Database database = new Database(Essential.GetConfig().data["db.name"], uint.Parse(Essential.GetConfig().data["db.pool.minsize"]), uint.Parse(Essential.GetConfig().data["db.pool.maxsize"]));
                Essential.DatabaseManager = new DatabaseManager(dbServer, database);
                GroupsPartsData.InitGroups();
                try
                {
                    using (DatabaseClient dbClient = Essential.GetDatabase().GetClient())
                    {
                        dbClient.ExecuteQuery("SET @@global.sql_mode= '';");
                        dbClient.ExecuteQuery("UPDATE users SET online = '0'");
                        dbClient.ExecuteQuery("UPDATE rooms SET users_now = '0'");
                    }
                    Essential.Internal_Game.ContinueLoading();
                }
                catch { }

                Essential.Internal_Game = new Game(int.Parse(Essential.GetConfig().data["game.tcp.conlimit"]));

                Essential.PacketManager = new PacketManager();
                Essential.PacketManager.Load();
                Essential.mhandler = new MobileHandler();
                Essential.mhandler.Load();
                Console.WriteLine(Essential.PacketManager.Count + " Packets loaded!");
                Essential.antiAdSystem = new AntiAd();
                Essential.MusListener = new MusListener(Essential.GetConfig().data["mus.tcp.bindip"], int.Parse(Essential.GetConfig().data["mus.tcp.port"]), Essential.GetConfig().data["mus.tcp.allowedaddr"].Split(new char[] { ';' }), 20);
                Essential.SocketsManager = new SocketsManager(Essential.GetConfig().data["game.tcp.bindip"], int.Parse(Essential.GetConfig().data["game.tcp.port"]), int.Parse(Essential.GetConfig().data["game.tcp.conlimit"]));
                //ConnectionManage = new ConnectionHandeling(Essential.GetConfig().data["game.tcp.port"], int.Parse(Essential.GetConfig().data["game.tcp.conlimit"]), int.Parse(Essential.GetConfig().data["game.tcp.conlimit"]), true);
               Essential.HeadImagerURL = Essential.GetConfig().data["eventstream.imager.url"];
                using (DatabaseClient dbClient = Essential.GetDatabase().GetClient())
                {
                    dbClient.ExecuteQuery("UPDATE server_status SET bannerdata='" + EssentialEnvironment.globalCrypto.Prime + ":" + EssentialEnvironment.globalCrypto.Generator + "';");
                }
                Essential.SocketsManager.method_3().method_0();
                webSocketServerManager = new WebSocketServerManager(Essential.GetConfig().data["websocket.url"]);
                Console.WriteLine("Server started at " + Essential.GetConfig().data["websocket.url"]);
                webManager = new WebManager();
                TimeSpan timeSpan = DateTime.Now - now;
                Logging.WriteLine(string.Concat(new object[]
				    {
					    "Server -> READY! (",
					    timeSpan.Seconds,
					    " s, ",
					    timeSpan.Milliseconds,
					    " ms)"
				    }));
                using (DatabaseClient dbClient = Essential.GetDatabase().GetClient())
                {
                    dbClient.ExecuteQuery("UPDATE server_status SET server_started='" + Convert.ToInt32(GetUnixTimestamp()) + "'");
                }
                Console.Beep();
            }
            catch (KeyNotFoundException KeyNotFoundException)
            {
                Logging.WriteLine("Failed to boot, key not found: " + KeyNotFoundException);
                Logging.WriteLine("Press any key to shut down ...");
                Console.ReadKey(true);
                Essential.Destroy();
            }
            catch (InvalidOperationException ex)
            {
                Logging.WriteLine("Failed to initialize EssentialEmulator: " + ex.Message);
                Logging.WriteLine("Press any key to shut down ...");
                Console.ReadKey(true);
                Essential.Destroy();
            }
        }