예제 #1
0
 public SQLWriter(Servers server, QueryType queryType, String tableName, int buffSize = 100)
 {
     m_queryType = queryType;
     m_buffSize = buffSize;
     m_server = server;
     m_tableName = tableName;
 }
예제 #2
0
        public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
        {
            if (request.path.StartsWith(PAGE_PREFIX))
            {
                dataRates.addUpLinkPoint(System.DateTime.Now, request.path.Length);

                try
                {
                    dataSources.vessel = FlightGlobals.ActiveVessel;
                    vesselChangeDetector.update(FlightGlobals.ActiveVessel);
                }
                catch (Exception e)
                {
                    PluginLogger.debug(e.Message + " "  + e.StackTrace);
                }

                dataRates.addDownLinkPoint(
                    System.DateTime.Now,
                    ((Servers.MinimalHTTPServer.ClientConnection)cc).Send(new OKResponsePage(
                        argumentsParse(request.path.Remove(0,
                            request.path.IndexOf(ARGUMENTS_START) + 1),
                            dataSources)
                   )));

                return true;
            }

            return false;
        }
        internal static ReadOnlyCollection<IRecord> GetRecords(Servers server, string recordName, DnsClient.RecordType type)
        {
            List<IRecord> records;

            return new ReadOnlyCollection<IRecord>(
                RecordRepository.TryGetValue(server, out records)
                    ? records.Where(r => r.Name == recordName && r.Type == type).ToList()
                    : new List<IRecord>());
        }
예제 #4
0
        public Main()
        {
            _fileActions = new FileActions();

            _ircParser = new Parser {FileActions = _fileActions};
            _ircParser.ParsingError += IrcParserParsingError;

            _servers = new Servers {FileActions = _fileActions, IrcParser = _ircParser};

            _workers = new Workers();
        }
예제 #5
0
 public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
 {
     if (!KSP.IO.FileInfo.CreateForType<TelemachusDataLink>(INDEX_PAGE).Exists)
     {
         throw new PageNotFoundResponsePage("Unable to find the Telemachus index page. Is it installed in the PluginData folder?");
     }
     else
     {
         throw new PageNotFoundResponsePage(
             "Did you mean to visit the <a href=\"/" + INDEX_PAGE + "\">index page</a>?");
     }
 }
예제 #6
0
        public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
        {
            DataSources dataSources = new DataSources();

            if (request.path.StartsWith(PAGE_PREFIX))
            {
                if (request.requestType == HTTPRequest.GET)
                {
                    dataRates.addUpLinkPoint(System.DateTime.Now, request.path.Length * UpLinkDownLinkRate.BITS_PER_BYTE);
                }
                else if (request.requestType == HTTPRequest.POST)
                {
                    dataRates.addUpLinkPoint(System.DateTime.Now, request.content.Length * UpLinkDownLinkRate.BITS_PER_BYTE);
                }

                try
                {
                    dataSources.vessel = kspAPI.getVessel();
                }
                catch (Exception e)
                {
                    PluginLogger.debug(e.Message + " " + e.StackTrace);
                }

                if (request.requestType == HTTPRequest.GET)
                {
                    dataRates.addDownLinkPoint(
                        System.DateTime.Now,
                        ((Servers.MinimalHTTPServer.ClientConnection)cc).Send(new OKResponsePage(
                            argumentsParse(request.path.Remove(0,
                                request.path.IndexOf(ARGUMENTS_START) + 1),
                                dataSources)
                        )) * UpLinkDownLinkRate.BITS_PER_BYTE);
                }
                else if (request.requestType == HTTPRequest.POST)
                {
                    dataRates.addDownLinkPoint(
                        System.DateTime.Now,
                        ((Servers.MinimalHTTPServer.ClientConnection)cc).Send(new OKResponsePage(
                            argumentsParse(request.content,
                                dataSources)
                        )) * UpLinkDownLinkRate.BITS_PER_BYTE);
                }

                return true;
            }

            return false;
        }
예제 #7
0
        public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
        {
            if (request.path.StartsWith("/server"))
            {
                try
                {
                    cc.Send(new OKResponsePage("Server Running.").ToString());
                }
                catch
                {
                    return false;
                }
            }

            return true;
        }
예제 #8
0
        public static DeviceGroup Create(RegistrationIdCollection registers, string groupName, Servers.GCMPushServer server)
        {
            string responsestr = createRequest(registers, groupName, server);

            if (responsestr == null)
            {
                return null;
            }
            else
            {
                DeviceGroup devgroup = new DeviceGroup(groupName, server);
                devgroup._notf_group_id = responsestr;
                devgroup.collection = registers;
            }

            return null;
        }
예제 #9
0
        private static string createRequest(RegistrationIdCollection registers, string groupName, Servers.GCMPushServer server)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(server._settings.DeviceGroup);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.Headers.Add(string.Format("Authorization:key={0}",server._apiKey));
            request.Headers.Add(string.Format("project_id:",server._settings.ProjectNumber));

            object reqContent = new
            {
                operation = "create",
                notification_key_name = groupName,
                registration_ids = registers.toList()
            };

            var requestStream = request.GetRequestStream();
            using(var swriter = new StreamWriter(requestStream))
            {
                swriter.Write(reqContent.ToJson());
                swriter.Flush();
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseStream = response.GetResponseStream();

            string responseStr = null;

            using(var sreader = new StreamReader(responseStream))
            {
                responseStr = sreader.ReadToEnd();
            }

            if(response.StatusCode == HttpStatusCode.OK)
            {
                return responseStr;
            }
            else
            {
                return null;
            }
        }
        public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
        {
            if (request.path.StartsWith(PAGE_PREFIX))
            {
                try
                {
                    OKResponsePage page = new OKResponsePage(
                            KSPByteReader, KSPTextReader,
                            request.path.Substring(PAGE_PREFIX.Length));
                    ((Servers.MinimalHTTPServer.ClientConnection)cc).Send(page);

                    return true;
                }
                catch
                {
                    return false;
                }
            }

            return false;
        }
예제 #11
0
        private void CreateToDir()
        {
            List <TreeNode> NodeList = Main.form_DataBase.GetTreeViewSelected();

            if (NodeList.Count == 0)
            {
                return;
            }
            TreeNode serverNode = Main.form_DataBase.GetRoot(NodeList.First());
            TreeNode dbNode     = NodeList.First().Parent.Parent;

            List <BuilderMethods> methods = new List <BuilderMethods>();

            if (configDir_cb_Add.Checked)
            {
                methods.Add(BuilderMethods.Add);
            }
            if (configDir_cb_GetAll.Checked)
            {
                methods.Add(BuilderMethods.SelectAll);
            }
            Servers server = (Servers)((TreeNodeTag)serverNode.Tag).Tag;

            Business.CreateCode CreateCode = new Business.CreateCode(server.Type);
            CodeCreate          param      = new CodeCreate();

            param.DbName      = ((TreeNodeTag)dbNode.Tag).Tag.ToString();
            param.NameSpace   = "";
            param.NameSpace1  = "";
            param.ServerID    = server.ID;
            param.BuilderType = BuilderType.Default;
            param.MethodList  = methods;
            param.CNSC        = new Config_NameSpaceClass().GetDefault();

            Business.CreateCode CreateCodeInstince = new Business.CreateCode(server.Type);
            StreamWriter        sw;
            string FileName = string.Empty;

            foreach (TreeNode node in NodeList)
            {
                param.TableName = ((TreeNodeTag)node.Tag).Tag.ToString();
                param.ClassName = param.TableName;

                //生成实体类
                FileName = Func.ExistsDirectory(string.Format("{0}\\{1}.{2}\\{3}{4}.cs", configDir_tb_OutputDir.Text, param.NameSpace, param.CNSC.Model, param.NameSpace1.IsNullOrEmpty() ? "" : param.NameSpace1 + "\\", param.ClassName));
                sw       = File.CreateText(FileName);
                sw.Write(CreateCodeInstince.GetModelClass(param));
                sw.Close();
                sw.Dispose();
                configDir_label_progress.Text = string.Format("生成文件:{0}", FileName);

                //生成数据类
                FileName = Func.ExistsDirectory(string.Format("{0}\\{1}.{2}\\{3}{4}.cs", configDir_tb_OutputDir.Text, param.NameSpace, param.CNSC.Data, param.NameSpace1.IsNullOrEmpty() ? "" : param.NameSpace1 + "\\", param.ClassName));
                sw       = File.CreateText(FileName);
                sw.Write(CreateCodeInstince.GetDataClass(param));
                sw.Close();
                sw.Dispose();
                configDir_label_progress.Text = string.Format("生成文件:{0}", FileName);

                //生成业务类
                FileName = Func.ExistsDirectory(string.Format("{0}\\{1}.{2}\\{3}{4}.cs", configDir_tb_OutputDir.Text, param.NameSpace, param.CNSC.Business, param.NameSpace1.IsNullOrEmpty() ? "" : param.NameSpace1 + "\\", param.ClassName));
                sw       = File.CreateText(FileName);
                sw.Write(CreateCodeInstince.GetBusinessClass(param));
                sw.Close();
                sw.Dispose();
                configDir_label_progress.Text = string.Format("生成文件:{0}", FileName);

                if (param.BuilderType == BuilderType.Factory)
                {
                    //生成接口类
                    FileName = Func.ExistsDirectory(string.Format("{0}\\{1}.{2}\\{3}{4}.cs", configDir_tb_OutputDir.Text, param.NameSpace, param.CNSC.Interface, param.NameSpace1.IsNullOrEmpty() ? "" : param.NameSpace1 + "\\", param.ClassName));
                    sw       = File.CreateText(FileName);
                    sw.Write(CreateCodeInstince.GetInterfaceClass(param));
                    sw.Close();
                    sw.Dispose();
                    configDir_label_progress.Text = string.Format("生成文件:{0}", FileName);

                    //生成工厂类
                    FileName = Func.ExistsDirectory(string.Format("{0}\\{1}.{2}\\{3}{4}.cs", configDir_tb_OutputDir.Text, param.NameSpace, param.CNSC.Factory, param.NameSpace1.IsNullOrEmpty() ? "" : param.NameSpace1 + "\\", param.ClassName));
                    sw       = File.CreateText(FileName);
                    sw.Write(CreateCodeInstince.GetFactoryClass(param));
                    sw.Close();
                    sw.Dispose();
                    configDir_label_progress.Text = string.Format("生成文件:{0}", FileName);
                }
            }
            MessageBox.Show("生成完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.configDir_label_progress.Text = "生成已完成";
            this.configDir_btn_Build.Enabled   = true;
        }
예제 #12
0
 public void RemoveServer(Server server)
 {
     Servers.Remove(server);
     SaveConfiguration();
 }
        public void GetSettings()
        {
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var filename = Path.Combine (documents, "proscanmobile_servers.xml");

            if (File.Exists (filename)) {

                stripIllegalXMLChars (filename);

                Servers s_tmp = new Servers ();

                XmlSerializer deserializer = new XmlSerializer (typeof(Servers));
                TextReader textReader = new StreamReader (filename, Encoding.UTF8);
                s_tmp = (Servers)deserializer.Deserialize (textReader);
                textReader.Close ();

                s = new Servers ();
                s.ServerList = new List<ServerDetails> ();

                foreach (ServerDetails sd_tmp in s_tmp.ServerList) {
                    s.ServerList.Add (new ServerDetails () {
                        host = XmlConvert.DecodeName(sd_tmp.host),
                        port = XmlConvert.DecodeName(sd_tmp.port),
                        desc = XmlConvert.DecodeName(sd_tmp.desc),
                        country = XmlConvert.DecodeName(sd_tmp.country),
                        state = XmlConvert.DecodeName(sd_tmp.state),
                        county = XmlConvert.DecodeName(sd_tmp.county),
                        open = XmlConvert.DecodeName(sd_tmp.open)
                    });
                }

                s_tmp = null;
            }

            filename = Path.Combine (documents, "proscanmobile_settings.xml");

            if (File.Exists (filename)) {

                stripIllegalXMLChars (filename);

                XmlSerializer deserializer = new XmlSerializer (typeof(Settings));
                TextReader textReader = new StreamReader (filename);
                si = (Settings)deserializer.Deserialize (textReader);
                textReader.Close ();
            }
        }
예제 #14
0
        public string GetBody(int _requestid, int _itemid, int _number, int _serviceid, int _rrid, int _rr_workflowid, string _se_dsn, int _environment, string _dsn_asset, string _dsn_ip)
        {
            string              strView              = "";
            Applications        oApplication         = new Applications(user, dsn);
            RequestItems        oRequestItem         = new RequestItems(user, dsn);
            ResourceRequest     oResourceRequest     = new ResourceRequest(user, dsn);
            Users               oUser                = new Users(user, dsn);
            Services            oService             = new Services(user, dsn);
            Variables           oVariable            = new Variables(_environment);
            Functions           oFunction            = new Functions(0, dsn, _environment);
            Requests            oRequest             = new Requests(user, dsn);
            Projects            oProject             = new Projects(user, dsn);
            ServiceRequests     oServiceRequest      = new ServiceRequests(user, dsn);
            ServiceEditor       oServiceEditor       = new ServiceEditor(user, _se_dsn);
            Servers             oServer              = new Servers(user, dsn);
            Workstations        oWorkstation         = new Workstations(user, dsn);
            AssetOrder          oAssetOrder          = new AssetOrder(user, dsn, _dsn_asset, _environment);
            AssetSharedEnvOrder oAssetSharedEnvOrder = new AssetSharedEnvOrder(user, dsn, _dsn_asset, _environment);
            PNCTasks            oPNCTask             = new PNCTasks(user, dsn);
            TSM          oTSM         = new TSM(user, dsn);
            StatusLevels oStatusLevel = new StatusLevels();

            DataSet dsRR = oResourceRequest.GetRequestService(_requestid, _serviceid, _number);

            if (dsRR.Tables[0].Rows.Count > 0)
            {
                if (_rrid == 0)
                {
                    Int32.TryParse(dsRR.Tables[0].Rows[0]["parent"].ToString(), out _rrid);
                }
                if (_rr_workflowid == 0)
                {
                    Int32.TryParse(dsRR.Tables[0].Rows[0]["id"].ToString(), out _rr_workflowid);
                }
            }

            // Workflow
            string strWorkflowName = "";
            int    intProject      = oRequest.GetProjectNumber(_requestid);

            if (intProject > 0)
            {
                strView += "<tr><td valign=\"top\"><b>Project Name:</b></td>";
                strView += "<td colspan=\"40\">" + oProject.Get(intProject, "name") + "</td></tr>";
                strView += "<tr><td valign=\"top\"><b>Project Number:</b></td>";
                strView += "<td>" + "<a href=\"" + oRequest.GetDataPointLink(_requestid, _environment) + "\" target=\"_blank\">" + oProject.Get(intProject, "number") + "</a></td></tr>";
            }
            else
            {
                string strTaskName = "N/A";
                if (_rr_workflowid > 0)
                {
                    strTaskName = oResourceRequest.GetWorkflow(_rr_workflowid, "name").Trim();
                }
                if ((strTaskName == "" || strTaskName == "N/A") && _rrid > 0)
                {
                    strTaskName = oResourceRequest.Get(_rrid, "name").Trim();
                }
                if ((strTaskName == "" || strTaskName == "N/A") && _requestid > 0)
                {
                    strTaskName = oServiceRequest.Get(_requestid, "name").Trim();
                }
                strView += "<tr><td valign=\"top\"><b>Task Name:</b></td>";
                strView += "<td colspan=\"40\">" + strTaskName + "</td></tr>";
            }
            strView += "<tr><td valign=\"top\"><b>Task Number:</b></td>";
            strView += "<td>" + "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"OpenNewWindowMenu('/datapoint/service/resource.aspx?id=" + oFunction.encryptQueryString(_rrid.ToString()) + "', '800', '600');\">CVT" + _requestid.ToString() + "-" + _serviceid.ToString() + "-" + _number.ToString() + "</a></td></tr>";
            //strWorkflowName += "<td>" + "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"OpenNewWindowMenu('" + oRequest.GetDataPointLink(_requestid, _environment) + "', '800', '600');\">CVT" + _requestid.ToString() + "</a></td>";

            string strWorkflowRequested  = "";
            string strWorkflowCreated    = "";
            string strWorkflowService    = "";
            string strWorkflowDepartment = "";
            string strWorkflowResources  = "";
            string strWorkflowStatus     = "";
            string strWorkflowComments   = "";
            int    intStatus             = 0;

            // Requested
            strWorkflowRequested += "<td valign=\"top\"><b>Requested By:</b></td>";
            int intRequestor        = oRequest.GetUser(_requestid);
            int intRequestorManager = 0;

            Int32.TryParse(oUser.Get(intRequestor, "manager"), out intRequestorManager);
            Int32.TryParse(oResourceRequest.Get(_rrid, "status"), out intStatus);
            strWorkflowRequested += "<td>" + oUser.GetFullName(intRequestor) + " (" + oUser.GetName(intRequestor) + ")" + "</td>";
            strWorkflowCreated   += "<td valign=\"top\"><b>Created On:</b></td>";
            if (_rrid > 0)
            {
                strWorkflowCreated += "<td>" + DateTime.Parse(oResourceRequest.Get(_rrid, "created")).ToLongDateString() + "</td>";
            }
            else
            {
                strWorkflowCreated += "<td>" + DateTime.Parse(oRequest.Get(_requestid, "created")).ToLongDateString() + "</td>";
            }
            // Service
            strWorkflowService += "<td valign=\"top\"><b>Service:</b></td>";
            if (_serviceid == 0)
            {
                strWorkflowService += "<td>" + oRequestItem.GetItem(_itemid, "service_title") + "</td>";
            }
            else
            {
                strWorkflowService += "<td>" + oService.GetName(_serviceid) + "</td>";
            }
            // Department
            strWorkflowDepartment += "<td valign=\"top\"><b>Department:</b></td>";
            strWorkflowDepartment += "<td>" + oApplication.Get(oRequestItem.GetItemApplication(_itemid), "service_title") + "</td>";
            // Resources
            string  strApprovers = "";
            DataSet dsApprovals  = oResourceRequest.GetApprovals(_requestid, _serviceid, _number);

            foreach (DataRow drApprover in dsApprovals.Tables[0].Rows)
            {
                int intApprover = Int32.Parse(drApprover["userid"].ToString());
                if (drApprover["approved"].ToString() == "" && drApprover["denied"].ToString() == "")
                {
                    if (strApprovers != "")
                    {
                        strApprovers += "\\n";
                    }
                    strApprovers += oUser.GetFullName(intApprover) + " (" + oUser.GetName(intApprover) + ")";
                }
            }
            bool boolAutomated = (oService.Get(_serviceid, "automate") == "1");

            if (boolAutomated == false)
            {
                DataSet dsReqForm = oRequestItem.GetForm(_requestid, _serviceid, _itemid, _number);
                if (dsReqForm.Tables[0].Rows.Count > 0)
                {
                    boolAutomated = (dsReqForm.Tables[0].Rows[0]["automated"].ToString() == "1" ? true : false);
                }
            }
            strWorkflowResources += "<td valign=\"top\"><b>Assigned:</b></td>";
            strWorkflowStatus    += "<td><b>Status:</b></td>";
            if (boolAutomated == true)
            {
                strWorkflowResources += "<td valign=\"top\">---</td>";
                intStatus             = (int)ResourceRequestStatus.NotAvailable; // Set to N/A since it is automated...
                strWorkflowStatus    += "<td>" + oStatusLevel.HTML(intStatus) + "</td>";
            }
            else
            {
                List <WorkflowStatus> RR = oResourceRequest.GetStatus(null, _rrid, null, null, null, null, false, _se_dsn);
                if (RR.Count > 0)
                {
                    StringBuilder strUsers = new StringBuilder();
                    foreach (string strUser in RR[0].users)
                    {
                        if (String.IsNullOrEmpty(strUser) == false)
                        {
                            strUsers.Append(strUser);
                            strUsers.AppendLine("<br/>");
                        }
                    }
                    strWorkflowResources += "<td valign=\"top\">" + strUsers.ToString() + "</td>";
                    strWorkflowStatus    += "<td>" + RR[0].status + "</td>";
                    if (String.IsNullOrEmpty(RR[0].comments) == false)
                    {
                        strWorkflowComments += "<td valign=\"top\"><b>Comments:</b></td>";
                        strWorkflowComments += "<td valign=\"top\">" + oFunction.FormatText(RR[0].comments) + "</td>";
                    }
                }
                else
                {
                    strWorkflowResources += "<td valign=\"top\"> N / A </td>";
                    strWorkflowStatus    += "<td> N / A </td>";
                }
            }
            strView += "<tr>" + strWorkflowRequested + "</tr><tr>" + strWorkflowCreated + "</tr><tr>" + strWorkflowService + "</tr><tr>" + strWorkflowDepartment + "</tr>" + "<tr>" + strWorkflowStatus + "</tr>" + (strWorkflowResources == "" ? "" : "<tr>" + strWorkflowResources + "</tr>") + (strWorkflowComments == "" ? "" : "<tr>" + strWorkflowComments + "</tr>");

            if (strView == "")
            {
                strView = "Information Unavailable";
            }
            else
            {
                strView = "<table cellpadding=\"3\" cellspacing=\"2\" border=\"0\" style=\"" + oVariable.DefaultFontStyle() + "\">" + strView + "</table>";
                StringBuilder      sbViewRequest       = new StringBuilder();
                Customized         oCustomized         = new Customized(user, dsn);
                DNS                oDNS                = new DNS(user, dsn);
                OnDemandTasks      oOnDemandTask       = new OnDemandTasks(user, dsn);
                Reports            oReport             = new Reports(user, dsn);
                Audit              oAudit              = new Audit(user, dsn);
                Enhancements       oEnhancement        = new Enhancements(user, dsn);
                ServerDecommission oServerDecommission = new ServerDecommission(0, dsn);
                Storage            oStorage            = new Storage(0, dsn);

                string strCatch = "1";
                try
                {
                    sbViewRequest.Append(oServiceEditor.GetRequestBody(_requestid, _serviceid, _number, dsn));
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "2";
                        sbViewRequest.Append(oCustomized.GetPNCDNSConflictBody(_requestid, _itemid, _number));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "3";
                        sbViewRequest.Append(oCustomized.GetStorage3rdBody(_requestid, _itemid, _number, _environment));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "4";
                        sbViewRequest.Append(oOnDemandTask.GetServerOther(_requestid, _serviceid, _number, _environment, _dsn_asset, _dsn_ip));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "5";
                        sbViewRequest.Append(GetBody(oReport.GetOrderReport(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "6";
                        sbViewRequest.Append(oServerDecommission.GetBody(_requestid, _number, _dsn_asset, _environment));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "7";
                        sbViewRequest.Append(oCustomized.GetDecommissionServerBody(_requestid, _itemid, _number, _dsn_asset));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "7.1";
                        sbViewRequest.Append(oWorkstation.GetApprovalSummary(_requestid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "8";
                        int intEnhancementID = oCustomized.GetEnhancementID(_requestid);
                        if (intEnhancementID > 0)
                        {
                            sbViewRequest.Append("<tr><td>");
                            sbViewRequest.Append(oCustomized.GetEnhancementBody(intEnhancementID, _environment, false));
                            sbViewRequest.Append("</td></tr>");
                        }
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "9";
                        int intIssueID = oCustomized.GetIssueID(_requestid);
                        if (intIssueID > 0)
                        {
                            sbViewRequest.Append("<tr><td>");
                            sbViewRequest.Append(oCustomized.GetIssueBody(intIssueID, _environment, false));
                            sbViewRequest.Append("</td></tr>");
                        }
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "10";
                        sbViewRequest.Append(GetBody(oCustomized.GetIIS(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "11";
                        sbViewRequest.Append(GetBody(oCustomized.GetRemediation(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "12";
                        sbViewRequest.Append(GetBody(oCustomized.GetServerArchive(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "13";
                        sbViewRequest.Append(GetBody(oCustomized.GetServerRetrieve(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "14";
                        sbViewRequest.Append(GetBody(oCustomized.GetTPM(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "15";
                        sbViewRequest.Append(GetBody(oCustomized.GetWorkstation(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "16";
                        sbViewRequest.Append(GetBody(oCustomized.GetThirdTierDistributed(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "17";
                        sbViewRequest.Append(GetBody(oCustomized.GetGeneric(_requestid, _itemid, _number), _serviceid));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "18";
                        sbViewRequest.Append(oDNS.GetDNSBody(_requestid, _itemid, _number, false, _environment));
                    }
                    if (sbViewRequest.ToString() == "")
                    {
                        strCatch = "19";
                        sbViewRequest.Append(oAudit.GetErrorBody(_requestid, _serviceid, _number));
                    }

                    if (sbViewRequest.ToString() == "")//Server Error Provisioning Support
                    {
                        strCatch = "20";
                        sbViewRequest.Append(oServer.GetErrorDetailsBody(_requestid, _itemid, _number, _environment));
                    }

                    if (sbViewRequest.ToString() == "") //Workstation Error Provisioning Support
                    {
                        strCatch = "21";
                        sbViewRequest.Append(oWorkstation.GetVirtualErrorDetailsBody(_requestid, _number, _environment));
                    }

                    if (sbViewRequest.ToString() == "") //Asset Procurement
                    {
                        strCatch = "22";
                        sbViewRequest.Append(oAssetOrder.GetOrderBody(_requestid, _itemid, _number));
                    }

                    if (sbViewRequest.ToString() == "") //Shared Environement - IM
                    {
                        strCatch = "23";
                        sbViewRequest.Append(oAssetSharedEnvOrder.GetOrderBody(_requestid, _itemid, _number));
                    }

                    if (sbViewRequest.ToString() == "") //Backup
                    {
                        strCatch = "24";
                        sbViewRequest.Append(oTSM.GetBody(_requestid, _itemid, _number, _dsn_asset, _dsn_ip));
                    }

                    if (sbViewRequest.ToString() == "") // New Enhancement
                    {
                        strCatch = "25";
                        sbViewRequest.Append(oEnhancement.GetBodyRequest(_requestid, _environment));
                    }

                    if (sbViewRequest.ToString() == "") // New Enhancement
                    {
                        strCatch = "26";
                        sbViewRequest.Append(oStorage.GetBody(_requestid, _itemid, _number, _dsn_asset, _dsn_ip, _environment, false));
                    }


                    if (sbViewRequest.ToString() == "")
                    {
                        //strViewRequest = "Information Unavailable";
                        sbViewRequest.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    }
                    else
                    {
                        if (sbViewRequest.ToString().Trim().StartsWith("<table") == false)
                        {
                            sbViewRequest.Insert(0, "<table cellpadding=\"3\" cellspacing=\"2\" border=\"0\" style=\"" + oVariable.DefaultFontStyle() + "\">");
                            sbViewRequest.Append("</table>");
                        }
                    }
                }
                catch
                {
                    sbViewRequest = new StringBuilder("&nbsp;&nbsp;** WARNING: Information Unavailable (# " + strCatch + ") **&nbsp;&nbsp;");
                }
                sbViewRequest.Insert(0, "<table cellpadding=\"3\" cellspacing=\"2\" border=\"0\" style=\"" + oVariable.DefaultFontStyle() + "\"><tr><td>");
                sbViewRequest.Append("</td></tr></table>");
                strView += "<br/>" + sbViewRequest.ToString();
            }
            return(strView);
        }
예제 #15
0
 public CommandHandler(IServiceProvider provider, DiscordSocketClient client, CommandService service, IConfiguration config, Servers servers, AutoRolesHelper autoRolesHelper, Images images)
 {
     _provider        = provider;
     _client          = client;
     _service         = service;
     _config          = config;
     _servers         = servers;
     _autoRolesHelper = autoRolesHelper;
     _images          = images;
 }
예제 #16
0
 public DataLinkResponsibility(Servers.AsynchronousServer.ServerConfiguration serverConfiguration, IKSPAPI kspAPI)
 {
     this.kspAPI = kspAPI;
 }
예제 #17
0
        public async Task SetLogChannel(string logType, IGuildChannel channel)
        {
            var   server       = Servers.GetServer(Context.Guild);
            ulong logChannelID = channel.Id;

            switch (logType.ToLower())
            {
            case "deletedmessages":
                server.LogDeletedMessages = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `Deleted Messages` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "messageedits":
                server.LogMessageEdits = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `Edited Messages` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "userjoins":
                server.LogWhenUserJoins = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `User Joins` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "userleaves":
                server.LogWhenUserLeaves = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `User Leaves` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "userisbanned":
                server.LogWhenUserIsBanned = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `User Banned` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "userisunbanned":
                server.LogWhenUserIsUnbanned = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `User Kicked` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "changestologsettings":
                server.LogChangesToLogSettings = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `changes to log settings` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "filteredphrases":
                server.LogWhenUserSaysFilteredPhrase = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `Filtered Phrases` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "userconnectstovoice":
                server.LogWhenUserConnectsToVoiceChannel = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `user connected to voice` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "userdisconnectsfromvoice":
                server.LogWhenUserDisconnectsFromVoiceChannel = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages for `user disconnected from voice` will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            case "all":
                server.LogDeletedMessages                     = logChannelID;
                server.LogMessageEdits                        = logChannelID;
                server.LogWhenUserJoins                       = logChannelID;
                server.LogWhenUserLeaves                      = logChannelID;
                server.LogWhenUserIsBanned                    = logChannelID;
                server.LogWhenUserIsUnbanned                  = logChannelID;
                server.LogChangesToLogSettings                = logChannelID;
                server.LogWhenUserSaysFilteredPhrase          = logChannelID;
                server.LogWhenUserConnectsToVoiceChannel      = logChannelID;
                server.LogWhenUserDisconnectsFromVoiceChannel = logChannelID;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} All log messages will be sent in channel {channel.Name}");
                embed.WithColor(Pink);
                BE(); break;

            default:
                embed.WithTitle("Invalid Log Specification");
                embed.WithDescription($"{Context.User.Mention} Invalid logging type!");
                embed.WithColor(Red);
                BE(); break;
            }
        }
예제 #18
0
 public DummyKSPAPI(FormatterProvider formatters, VesselChangeDetector vesselChangeDetector,
     Servers.AsynchronousServer.ServerConfiguration serverConfiguration)
 {
     APIHandlers.Add(new DummyHandler(formatters));
 }
예제 #19
0
        /// <summary>
        /// Return connection string by server name
        /// </summary>
        /// <param name="server">Server name</param>
        /// <returns>connection string for current server</returns>
        private String getConnStr(Servers server)
        {
            String serv = "";

            switch (server)
            {
                case Servers.Server28:
                    serv = ConnectBuilderServer28.ToString();
                    break;
            }

            return serv;
        }
 public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
 {
     cc.Send(new DiskLessTestResponse().ToString());
     return true;
 }
예제 #21
0
 public DeviceGroup(string groupName, Servers.GCMPushServer server)
 {
     _groupName = groupName;
     _server = server;
 }
예제 #22
0
		/// <summary> Initializes a new instance of the DiscordClient class. </summary>
		public DiscordClient(DiscordClientConfig config = null)
			: base(config ?? new DiscordClientConfig())
		{
			_rand = new Random();
			_api = new DiscordAPIClient(_config.LogLevel, _config.UserAgent, _config.APITimeout);
			if (Config.UseMessageQueue)
				_pendingMessages = new ConcurrentQueue<Message>();
			if (Config.EnableVoiceMultiserver)
				_voiceClients = new ConcurrentDictionary<string, DiscordSimpleClient>();

			object cacheLock = new object();
			_channels = new Channels(this, cacheLock);
			_members = new Members(this, cacheLock);
			_messages = new Messages(this, cacheLock);
			_roles = new Roles(this, cacheLock);
			_servers = new Servers(this, cacheLock);
			_users = new Users(this, cacheLock);
			_status = UserStatus.Online;

			this.Connected += async (s, e) =>
			{
				_api.CancelToken = CancelToken;
				await SendStatus();
			};

			VoiceDisconnected += (s, e) =>
			{
				foreach (var member in _members)
				{
					if (member.ServerId == e.ServerId && member.IsSpeaking)
					{
						member.IsSpeaking = false;
						RaiseUserIsSpeaking(member, false);
					}
				}
			};

			bool showIDs = _config.LogLevel > LogMessageSeverity.Debug; //Hide this for now
			if (_config.LogLevel >= LogMessageSeverity.Info)
			{
				ServerCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Server: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Destroyed Server: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Server: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerAvailable += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Unavailable: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerUnavailable += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Unavailable: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ChannelCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Channel: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId})" : ""));
				ChannelDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Destroyed Channel: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId})" : ""));
				ChannelUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Channel: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId})" : ""));
				MessageCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				MessageDeleted += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Deleted Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				MessageUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				RoleCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Role: {e.Server?.Name ?? "[Private]"}/{e.Role.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.RoleId})." : ""));
				RoleUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Role: {e.Server?.Name ?? "[Private]"}/{e.Role.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.RoleId})." : ""));
				RoleDeleted += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Deleted Role: {e.Server?.Name ?? "[Private]"}/{e.Role.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.RoleId})." : ""));
				BanAdded += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Added Ban: {e.Server?.Name ?? "[Private]"}/{e.User?.Name ?? "Unknown"}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				BanRemoved += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Removed Ban: {e.Server?.Name ?? "[Private]"}/{e.User?.Name ?? "Unknown"}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				UserAdded += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Added Member: {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				UserRemoved += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Removed Member: {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				MemberUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Member: {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				UserVoiceStateUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Member (Voice State): {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "0"}/{e.UserId})" : ""));
				UserUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated User: {e.User.Name}" +
					(showIDs ? $" ({e.UserId})." : ""));
			}
			if (_config.LogLevel >= LogMessageSeverity.Verbose)
			{
				UserIsTyping += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client,
					$"Updated User (Is Typing): {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.UserId})" : ""));
				MessageReadRemotely += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Read Message (Remotely): {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				MessageSent += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Sent Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				UserPresenceUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Updated Member (Presence): {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})" : ""));
				
				_api.RestClient.OnRequest += (s, e) =>
				{
					if (e.Payload != null)
						RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Rest, $"{e.Method.Method} {e.Path}: {Math.Round(e.ElapsedMilliseconds, 2)} ms ({e.Payload})");
					else
						RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Rest, $"{e.Method.Method} {e.Path}: {Math.Round(e.ElapsedMilliseconds, 2)} ms");
				};
			}
			if (_config.LogLevel >= LogMessageSeverity.Debug)
			{
				_channels.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Channel {e.Item?.ServerId ?? "[Private]"}/{e.Item.Id}");
				_channels.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Channel {e.Item.ServerId ?? "[Private]"}/{e.Item.Id}");
				_channels.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Channels");
				_members.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Member {e.Item.ServerId ?? "[Private]"}/{e.Item.UserId}");
				_members.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Member {e.Item.ServerId ?? "[Private]"}/{e.Item.UserId}");
				_members.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Members");
				_messages.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Message {e.Item.ServerId ?? "[Private]"}/{e.Item.ChannelId}/{e.Item.Id}");
				_messages.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Message {e.Item.ServerId ?? "[Private]"}/{e.Item.ChannelId}/{e.Item.Id}");
				_messages.ItemRemapped += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Remapped Message {e.Item.ServerId ?? "[Private]"}/{e.Item.ChannelId}/[{e.OldId} -> {e.NewId}]");
				_messages.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Messages");
				_roles.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Role {e.Item.ServerId}/{e.Item.Id}");
				_roles.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Role {e.Item.ServerId}/{e.Item.Id}");
				_roles.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Roles");
				_servers.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Server {e.Item.Id}");
				_servers.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Server {e.Item.Id}");
				_servers.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Servers");
				_users.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created User {e.Item.Id}");
				_users.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed User {e.Item.Id}");
				_users.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Users");
			}

			if (Config.UseMessageQueue)
				_pendingMessages = new ConcurrentQueue<Message>();

			_serializer = new JsonSerializer();
#if TEST_RESPONSES
			_serializer.CheckAdditionalContent = true;
			_serializer.MissingMemberHandling = MissingMemberHandling.Error;
#endif
		}
예제 #23
0
		/// <summary> Initializes a new instance of the DiscordClient class. </summary>
		public DiscordClient(DiscordClientConfig config = null)
			: base(config ?? new DiscordClientConfig())
		{
			_rand = new Random();
			_api = new DiscordAPIClient(_config);
			if (Config.UseMessageQueue)
				_pendingMessages = new ConcurrentQueue<Message>();
			if (Config.EnableVoiceMultiserver)
				_voiceClients = new ConcurrentDictionary<string, DiscordWSClient>();

			object cacheLock = new object();
			_channels = new Channels(this, cacheLock);
			_users = new Users(this, cacheLock);
			_messages = new Messages(this, cacheLock, Config.MessageCacheLength > 0);
			_roles = new Roles(this, cacheLock);
			_servers = new Servers(this, cacheLock);
			_globalUsers = new GlobalUsers(this, cacheLock);

			_status = UserStatus.Online;

			this.Connected += async (s, e) =>
			{
				_api.CancelToken = _cancelToken;
				await SendStatus().ConfigureAwait(false);
			};

			VoiceDisconnected += (s, e) =>
			{
				var server = _servers[e.ServerId];
				if (server != null)
				{
					foreach (var member in server.Members)
					{
						if (member.IsSpeaking)
						{
							member.IsSpeaking = false;
							RaiseUserIsSpeaking(member, _channels[_voiceSocket.CurrentChannelId], false);
						}
					}
				}
			};
			
			if (_config.LogLevel >= LogMessageSeverity.Info)
			{
				ServerCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Created: {e.Server?.Name ?? "[Private]"}");
				ServerDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Destroyed: {e.Server?.Name ?? "[Private]"}");
				ServerUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Updated: {e.Server?.Name ?? "[Private]"}");
				ServerAvailable += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Available: {e.Server?.Name ?? "[Private]"}");
				ServerUnavailable += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Unavailable: {e.Server?.Name ?? "[Private]"}");
				ChannelCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Channel Created: {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}");
				ChannelDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Channel Destroyed: {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}");
				ChannelUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Channel Updated: {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}");
				MessageReceived += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Message Received: {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}/{e.Message?.Id}");
				MessageDeleted += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Message Deleted: {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}/{e.Message?.Id}");
				MessageUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Message Update: {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}/{e.Message?.Id}");
				RoleCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Role Created: {e.Server?.Name ?? "[Private]"}/{e.Role?.Name}");
				RoleUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Role Updated: {e.Server?.Name ?? "[Private]"}/{e.Role?.Name}");
				RoleDeleted += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Role Deleted: {e.Server?.Name ?? "[Private]"}/{e.Role?.Name}");
				UserBanned += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Banned User: {e.Server?.Name ?? "[Private]" }/{e.UserId}");
				UserUnbanned += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Unbanned User: {e.Server?.Name ?? "[Private]"}/{e.UserId}");
				UserAdded += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"User Joined: {e.Server?.Name ?? "[Private]"}/{e.User.Name}");
				UserRemoved += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"User Left: {e.Server?.Name ?? "[Private]"}/{e.User.Name}");
				UserUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"User Updated: {e.Server?.Name ?? "[Private]"}/{e.User.Name}");
				UserVoiceStateUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"User Updated (Voice State): {e.Server?.Name ?? "[Private]"}/{e.User.Name}");
				ProfileUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					"Profile Updated");
			}
			if (_config.LogLevel >= LogMessageSeverity.Verbose)
			{
				UserIsTypingUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client,
					$"User Updated (Is Typing): {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}/{e.User?.Name}");
				MessageReadRemotely += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Read Message (Remotely): {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}/{e.Message?.Id}");
				MessageSent += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Sent Message: {e.Server?.Name ?? "[Private]"}/{e.Channel?.Name}/{e.Message?.Id}");
				UserPresenceUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"User Updated (Presence): {e.Server?.Name ?? "[Private]"}/{e.User?.Name}");
				
				_api.RestClient.OnRequest += (s, e) =>
				{
                    if (e.Payload != null)
						RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Rest, $"{e.Method.Method} {e.Path}: {Math.Round(e.ElapsedMilliseconds, 2)} ms ({e.Payload})");
					else
						RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Rest, $"{e.Method.Method} {e.Path}: {Math.Round(e.ElapsedMilliseconds, 2)} ms");
				};
			}
			if (_config.LogLevel >= LogMessageSeverity.Debug)
			{
				_channels.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Channel {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Id}");
				_channels.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Channel {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Id}");
				_channels.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Channels");
				_users.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created User {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Id}");
				_users.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed User {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Id}");
				_users.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Users");
				_messages.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Message {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Channel.Id}/{e.Item.Id}");
				_messages.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Message {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Channel.Id}/{e.Item.Id}");
				_messages.ItemRemapped += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Remapped Message {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Channel.Id}/[{e.OldId} -> {e.NewId}]");
				_messages.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Messages");
				_roles.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Role {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Id}");
				_roles.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Role {e.Item.Server?.Id ?? "[Private]"}/{e.Item.Id}");
				_roles.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Roles");
				_servers.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Server {e.Item.Id}");
				_servers.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Server {e.Item.Id}");
				_servers.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Servers");
				_globalUsers.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created User {e.Item.Id}");
				_globalUsers.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed User {e.Item.Id}");
				_globalUsers.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Users");
			}

			if (Config.UseMessageQueue)
				_pendingMessages = new ConcurrentQueue<Message>();

			_serializer = new JsonSerializer();
			_serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
#if TEST_RESPONSES
			_serializer.CheckAdditionalContent = true;
			_serializer.MissingMemberHandling = MissingMemberHandling.Error;
#endif
		}
예제 #24
0
 /// <summary>
 /// Adds the server.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="port">The port.</param>
 public void AddServer(string name, int port)
 {
     Servers.Add(new Server {
         Name = name, Port = port
     });
 }
예제 #25
0
        public async Task CanIdleDatabaseInCluster()
        {
            const int clusterSize  = 3;
            var       databaseName = GetDatabaseName();
            var       leader       = await CreateRaftClusterAndGetLeader(3, false, customSettings : new Dictionary <string, string>()
            {
                [RavenConfiguration.GetKey(x => x.Cluster.MoveToRehabGraceTime)]      = "1",
                [RavenConfiguration.GetKey(x => x.Cluster.AddReplicaTimeout)]         = "1",
                [RavenConfiguration.GetKey(x => x.Cluster.ElectionTimeout)]           = "300",
                [RavenConfiguration.GetKey(x => x.Cluster.StabilizationTime)]         = "1",
                [RavenConfiguration.GetKey(x => x.Databases.MaxIdleTime)]             = "10",
                [RavenConfiguration.GetKey(x => x.Databases.FrequencyToCheckForIdle)] = "3",
                [RavenConfiguration.GetKey(x => x.Core.RunInMemory)] = "false"
            });

            DatabasePutResult databaseResult;

            using (var store = new DocumentStore
            {
                Urls = new[] { leader.WebUrl },
                Database = databaseName
            }.Initialize())
            {
                var doc = new DatabaseRecord(databaseName);
                databaseResult = await store.Maintenance.Server.SendAsync(new CreateDatabaseOperation(doc, clusterSize));
            }
            Assert.Equal(clusterSize, databaseResult.Topology.AllNodes.Count());

            foreach (var server in Servers)
            {
                await server.ServerStore.Cluster.WaitForIndexNotification(databaseResult.RaftCommandIndex);
            }
            foreach (var server in Servers.Where(s => databaseResult.NodesAddedTo.Any(n => n == s.WebUrl)))
            {
                await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(databaseName);
            }

            var now     = DateTime.Now;
            var nextNow = now + TimeSpan.FromSeconds(300);

            while (now < nextNow && GetIdleCount() < clusterSize)
            {
                Thread.Sleep(3000);
                now = DateTime.Now;
            }

            foreach (var server in Servers)
            {
                Assert.Equal(1, server.ServerStore.IdleDatabases.Count);
                Assert.True(server.ServerStore.IdleDatabases.TryGetValue(databaseName, out var dictionary));

                // new incoming replications not saved in IdleDatabases
                Assert.Equal(0, dictionary.Count);
            }

            var rnd   = new Random();
            var index = rnd.Next(0, Servers.Count - 1);

            using (var store = new DocumentStore
            {
                Urls = new[] { Servers[index].WebUrl },
                Database = databaseName
            }.Initialize())
            {
                await store.Maintenance.SendAsync(new GetStatisticsOperation());
            }

            Assert.Equal(2, GetIdleCount());

            using (var store = new DocumentStore
            {
                Urls = new[] { Servers[index].WebUrl },
                Database = databaseName
            }.Initialize())
            {
                using (var s = store.OpenAsyncSession())
                {
                    await s.StoreAsync(new User()
                    {
                        Name = "Egor"
                    }, "foo/bar");

                    await s.SaveChangesAsync();
                }
            }

            nextNow = DateTime.Now + TimeSpan.FromSeconds(300);
            while (now < nextNow && GetIdleCount() > 0)
            {
                Thread.Sleep(3000);
                now = DateTime.Now;
            }

            Assert.Equal(0, GetIdleCount());

            foreach (var server in Servers)
            {
                using (var store = new DocumentStore
                {
                    Urls = new[] { server.WebUrl },
                    Database = databaseName
                }.Initialize())
                {
                    var docs = (await store.Maintenance.SendAsync(new GetStatisticsOperation())).CountOfDocuments;
                    Assert.Equal(1, docs);
                }
            }

            index   = rnd.Next(0, Servers.Count - 1);
            nextNow = DateTime.Now + TimeSpan.FromSeconds(300);

            using (var store = new DocumentStore
            {
                Urls = new[] { Servers[index].WebUrl },
                Database = databaseName
            }.Initialize())
            {
                while (now < nextNow && GetIdleCount() < 2)
                {
                    Thread.Sleep(3000);
                    await store.Maintenance.SendAsync(new GetStatisticsOperation());

                    now = DateTime.Now;
                }
            }

            Assert.Equal(2, GetIdleCount());
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="definition"></param>
        public ClientConfiguration(ICouchbaseClientDefinition definition)
        {
            Timer = TimingFactory.GetTimer(Log);
            NodeAvailableCheckInterval = definition.NodeAvailableCheckInterval;
            UseSsl          = definition.UseSsl;
            SslPort         = definition.SslPort;
            ApiPort         = definition.ApiPort;
            DirectPort      = definition.DirectPort;
            MgmtPort        = definition.MgmtPort;
            HttpsMgmtPort   = definition.HttpsMgmtPort;
            HttpsApiPort    = definition.HttpsApiPort;
            ObserveInterval = definition.ObserveInterval;
            ObserveTimeout  = definition.ObserveTimeout;
            MaxViewRetries  = definition.MaxViewRetries;
#pragma warning disable 618
            ViewHardTimeout       = definition.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
#pragma warning restore 618
            EnableConfigHeartBeat    = definition.EnableConfigHeartBeat;
            HeartbeatConfigInterval  = definition.HeartbeatConfigInterval;
            ViewRequestTimeout       = definition.ViewRequestTimeout;
            Expect100Continue        = definition.Expect100Continue;
            DefaultConnectionLimit   = definition.DefaultConnectionLimit;
            MaxServicePointIdleTime  = definition.MaxServicePointIdleTime;
            EnableOperationTiming    = definition.EnableOperationTiming;
            DefaultOperationLifespan = definition.OperationLifespan;
            QueryRequestTimeout      = definition.QueryRequestTimeout;
            EnableQueryTiming        = definition.EnableQueryTiming;
            SearchRequestTimeout     = definition.SearchRequestTimeout;
            VBucketRetrySleepTime    = definition.VBucketRetrySleepTime;

            IOErrorCheckInterval = definition.IOErrorCheckInterval;
            IOErrorThreshold     = definition.IOErrorThreshold;

            //transcoders, converters, and serializers...o mai.
            Serializer = definition.Serializer != null
                ? SerializerFactory.GetSerializer(definition.Serializer)
                : SerializerFactory.GetSerializer();

            Converter = definition.Converter != null
                ? ConverterFactory.GetConverter(definition.Converter)
                : ConverterFactory.GetConverter();

            Transcoder = definition.Transcoder != null
                ? TranscoderFactory.GetTranscoder(this, definition.Transcoder)
                : TranscoderFactory.GetTranscoder(this);

            IOServiceCreator = definition.IOService != null
                ? IOServiceFactory.GetFactory(definition.IOService)
                : IOServiceFactory.GetFactory();

            //to enable tcp keep-alives
            EnableTcpKeepAlives  = definition.EnableTcpKeepAlives;
            TcpKeepAliveInterval = definition.TcpKeepAliveInterval;
            TcpKeepAliveTime     = definition.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2 * 60 * 60 * 1000;

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory();

            //NOTE: this is a global setting and applies to all instances
            IgnoreRemoteCertificateNameMismatch = definition.IgnoreRemoteCertificateNameMismatch;

            UseInterNetworkV6Addresses = definition.UseInterNetworkV6Addresses;

            foreach (var server in definition.Servers ?? new[] { Defaults.Server })
            {
                Servers.Add(server);
                _serversChanged = true;
            }

            if (definition.ConnectionPool != null)
            {
                ConnectionPoolCreator = definition.ConnectionPool.Type != null
                    ? ConnectionPoolFactory.GetFactory(definition.ConnectionPool.Type)
                    : ConnectionPoolFactory.GetFactory();

                PoolConfiguration = new PoolConfiguration
                {
                    MaxSize             = definition.ConnectionPool.MaxSize,
                    MinSize             = definition.ConnectionPool.MinSize,
                    WaitTimeout         = definition.ConnectionPool.WaitTimeout,
                    ShutdownTimeout     = definition.ConnectionPool.ShutdownTimeout,
                    UseSsl              = UseSsl ? UseSsl : definition.ConnectionPool.UseSsl,
                    BufferSize          = definition.ConnectionPool.BufferSize,
                    BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                    ConnectTimeout      = definition.ConnectionPool.ConnectTimeout,
                    SendTimeout         = definition.ConnectionPool.SendTimeout,
                    EnableTcpKeepAlives =
                        keepAlivesChanged ? EnableTcpKeepAlives : definition.ConnectionPool.EnableTcpKeepAlives,
                    TcpKeepAliveInterval =
                        keepAlivesChanged ? TcpKeepAliveInterval : definition.ConnectionPool.TcpKeepAliveInterval,
                    TcpKeepAliveTime     = keepAlivesChanged ? TcpKeepAliveTime : definition.ConnectionPool.TcpKeepAliveTime,
                    CloseAttemptInterval = definition.ConnectionPool.CloseAttemptInterval,
                    MaxCloseAttempts     = definition.ConnectionPool.MaxCloseAttempts,
                    ClientConfiguration  = this
                };
            }
            else
            {
                ConnectionPoolCreator = ConnectionPoolFactory.GetFactory();
                PoolConfiguration     = new PoolConfiguration(this);
            }

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            if (definition.Buckets != null)
            {
                foreach (var bucket in definition.Buckets)
                {
                    var bucketConfiguration = new BucketConfiguration
                    {
                        BucketName               = bucket.Name,
                        UseSsl                   = bucket.UseSsl,
                        Password                 = bucket.Password,
                        ObserveInterval          = bucket.ObserveInterval,
                        DefaultOperationLifespan = bucket.OperationLifespan ?? (uint)DefaultOperationLifespan,
                        ObserveTimeout           = bucket.ObserveTimeout,
                        UseEnhancedDurability    = bucket.UseEnhancedDurability
                    };

                    //By skipping the bucket specific connection pool settings we allow inheritance from clien-wide connection pool settings.
                    if (bucket.ConnectionPool != null)
                    {
                        bucketConfiguration.PoolConfiguration = new PoolConfiguration
                        {
                            MaxSize             = bucket.ConnectionPool.MaxSize,
                            MinSize             = bucket.ConnectionPool.MinSize,
                            WaitTimeout         = bucket.ConnectionPool.WaitTimeout,
                            ShutdownTimeout     = bucket.ConnectionPool.ShutdownTimeout,
                            UseSsl              = bucket.ConnectionPool.UseSsl,
                            BufferSize          = bucket.ConnectionPool.BufferSize,
                            BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                            ConnectTimeout      = bucket.ConnectionPool.ConnectTimeout,
                            SendTimeout         = bucket.ConnectionPool.SendTimeout,
                            EnableTcpKeepAlives =
                                keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                            TcpKeepAliveInterval =
                                keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                            TcpKeepAliveTime =
                                keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                            CloseAttemptInterval  = bucket.ConnectionPool.CloseAttemptInterval,
                            MaxCloseAttempts      = bucket.ConnectionPool.MaxCloseAttempts,
                            UseEnhancedDurability = bucket.UseEnhancedDurability,
                            ClientConfiguration   = this
                        };
                    }
                    else
                    {
                        bucketConfiguration.PoolConfiguration        = PoolConfiguration;
                        bucketConfiguration.PoolConfiguration.UseSsl = bucketConfiguration.UseSsl;
                        bucketConfiguration.PoolConfiguration.UseEnhancedDurability = bucketConfiguration.UseEnhancedDurability;
                    }
                    BucketConfigs.Add(bucket.Name, bucketConfiguration);
                }
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
예제 #27
0
    //private Vector2 scrollPos = new Vector2(Screen.width / 2, Screen.height / 2);
    // Use this for initialization
    void Start()
    {
        god = (GOD)FindObjectOfType(typeof(GOD));
        server = gameObject.AddComponent<Servers>();

        refreshHostList();

        resolutions = new Resolution[20];

        resolutions[0].width = 640;
        resolutions[0].height = 480;

        resolutions[1].width = 720;
        resolutions[1].height = 576;

        resolutions[2].width = 800;
        resolutions[2].height = 600;

        resolutions[3].width = 1024;
        resolutions[3].height = 768;

        resolutions[4].width = 1152;
        resolutions[4].height = 648;

        resolutions[5].width = 1152;
        resolutions[5].height = 864;

        resolutions[6].width = 1280;
        resolutions[6].height = 720;

        resolutions[7].width = 1280;
        resolutions[7].height = 800;

        resolutions[8].width = 1280;
        resolutions[8].height = 960;

        resolutions[9].width = 1280;
        resolutions[9].height = 1024;

        resolutions[10].width = 1360;
        resolutions[10].height = 768;

        resolutions[11].width = 1360;
        resolutions[11].height = 1024;

        resolutions[12].width = 1366;
        resolutions[12].height = 768;

        resolutions[13].width = 1400;
        resolutions[13].height = 1050;

        resolutions[14].width = 1440;
        resolutions[14].height = 900;

        resolutions[15].width = 1600;
        resolutions[15].height = 900;

        resolutions[16].width = 1600;
        resolutions[16].height = 1200;

        resolutions[17].width = 1680;
        resolutions[17].height = 1050;

        resolutions[18].width = 1776;
        resolutions[18].height = 1000;

        resolutions[19].width = 1920;
        resolutions[19].height = 1080;
    }
        private void SaveSettings()
        {
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var filename = Path.Combine (documents, "proscanmobile_servers.xml");

            Servers s_tmp = new Servers ();
            s_tmp.ServerList = new List<ServerDetails> ();

            foreach (ServerDetails sd_tmp in s.ServerList) {
                s_tmp.ServerList.Add (new ServerDetails () {
                    host = XmlConvert.EncodeName(sd_tmp.host),
                    port = XmlConvert.EncodeName(sd_tmp.port),
                    desc = XmlConvert.EncodeName(sd_tmp.desc),
                    country = XmlConvert.EncodeName(sd_tmp.country),
                    state = XmlConvert.EncodeName(sd_tmp.state),
                    county = XmlConvert.EncodeName(sd_tmp.county),
                    open = XmlConvert.EncodeName(sd_tmp.open)
                });
            }

            XmlSerializer serializer = new XmlSerializer (typeof(Servers));
            TextWriter textWriter = new StreamWriter (filename);
            serializer.Serialize (textWriter, s_tmp);
            textWriter.Close ();

            s_tmp = null;

            si = new Settings ();
            si.SettingsList = new List<SettingsDetails> ();
            SettingsDetails sid = new SettingsDetails ();
            filename = Path.Combine (documents, "proscanmobile_settings.xml");
            sid.host = _txtServerHost.Text;

            int port;
            int.TryParse (_txtServerPort.Text, out port);

            sid.port = port;
            sid.auto = _swAutoConnect.On;
            #if PLUS_VERSION
            sid.pass = enc.Encrypt(_txtServerPassword.Text);
            #else
            sid.pass = string.Empty;
            #endif
            si.SettingsList.Add (sid);

            serializer = new XmlSerializer (typeof(Settings));
            textWriter = new StreamWriter (filename);
            serializer.Serialize (textWriter, si);
            textWriter.Close ();
        }
        /// <summary>
        /// Loads the most updated configuration creating any resources as needed.
        /// </summary>
        /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/>
        /// that will drive the recreation if the configuration context.</param>
        /// <param name="force">True to force the reconfiguration.</param>
        public override void LoadConfig(IBucketConfig bucketConfig, bool force = false)
        {
            try
            {
                Lock.EnterWriteLock();
                var nodes = bucketConfig.GetNodes();
                if (BucketConfig == null || !nodes.AreEqual(_bucketConfig.GetNodes()) || !Servers.Any() || force)
                {
                    var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name];
                    var servers            = new Dictionary <IPAddress, IServer>();
                    foreach (var adapter in nodes)
                    {
                        var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl);
                        try
                        {
                            Log.Info(
                                m =>
                                m("o1-Creating the Servers {0} list using rev#{1}", Servers.Count(),
                                  bucketConfig.Rev));
                            var poolConfiguration = ClientConfig.BucketConfigs[bucketConfig.Name].PoolConfiguration;

                            var connectionPool = ConnectionPoolFactory(poolConfiguration, endpoint);
                            var ioStrategy     = IOStrategyFactory(connectionPool);

                            var server = new Core.Server(ioStrategy, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache)
                            {
                                SaslFactory = SaslFactory
                            };
                            server.CreateSaslMechanismIfNotExists();
                            SupportsEnhancedDurability = ioStrategy.SupportsEnhancedDurability;

                            servers.Add(endpoint.Address, server);
                        }
                        catch (Exception e)
                        {
                            Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e);
                        }
                    }

                    UpdateServices(servers);

                    var old = Interlocked.Exchange(ref Servers, servers);
                    Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev));
                    var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap, bucketConfig.Rev);
                    Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                    Interlocked.Exchange(ref _bucketConfig, bucketConfig);

                    if (old != null)
                    {
                        foreach (var server in old.Values)
                        {
                            server.Dispose();
                        }
                        old.Clear();
                    }
                }
                else
                {
                    if (BucketConfig == null || !BucketConfig.IsVBucketServerMapEqual(bucketConfig) || force)
                    {
                        Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev));
                        var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap,
                                                                    bucketConfig.Rev);
                        Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                        Interlocked.Exchange(ref _bucketConfig, bucketConfig);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }
예제 #30
0
파일: CMClient.cs 프로젝트: ppker/SteamKit
        /// <summary>
        /// Connects this client to a Steam3 server.
        /// This begins the process of connecting and encrypting the data channel between the client and the server.
        /// Results are returned asynchronously in a <see cref="SteamClient.ConnectedCallback"/>.
        /// If the server that SteamKit attempts to connect to is down, a <see cref="SteamClient.DisconnectedCallback"/>
        /// will be posted instead.
        /// SteamKit will not attempt to reconnect to Steam, you must handle this callback and call Connect again
        /// preferrably after a short delay.
        /// </summary>
        /// <param name="cmServer">
        /// The <see cref="IPEndPoint"/> of the CM server to connect to.
        /// If <c>null</c>, SteamKit will randomly select a CM server from its internal list.
        /// </param>
        public void Connect(ServerRecord?cmServer = null)
        {
            lock ( connectionLock )
            {
                Disconnect(userInitiated: true);
                DebugLog.Assert(connection == null, nameof(CMClient), "Connection is not null");
                DebugLog.Assert(connectionSetupTask == null, nameof(CMClient), "Connection setup task is not null");
                DebugLog.Assert(connectionCancellation == null, nameof(CMClient), "Connection cancellation token is not null");

                connectionCancellation = new CancellationTokenSource();
                var token = connectionCancellation.Token;

                ExpectDisconnection = false;

                Task <ServerRecord?> recordTask;

                if (cmServer == null)
                {
                    recordTask = Servers.GetNextServerCandidateAsync(Configuration.ProtocolTypes);
                }
                else
                {
                    recordTask = Task.FromResult(( ServerRecord? )cmServer);
                }

                connectionSetupTask = recordTask.ContinueWith(t =>
                {
                    if (token.IsCancellationRequested)
                    {
                        LogDebug(nameof(CMClient), "Connection cancelled before a server could be chosen.");
                        OnClientDisconnected(userInitiated: true);
                        return;
                    }
                    else if (t.IsFaulted || t.IsCanceled)
                    {
                        LogDebug(nameof(CMClient), "Server record task threw exception: {0}", t.Exception);
                        OnClientDisconnected(userInitiated: false);
                        return;
                    }

                    var record = t.Result;

                    if (record is null)
                    {
                        LogDebug(nameof(CMClient), "Server record task returned no result.");
                        OnClientDisconnected(userInitiated: false);
                        return;
                    }

                    var newConnection = CreateConnection(record.ProtocolTypes & Configuration.ProtocolTypes);

                    var connectionRelease = Interlocked.Exchange(ref connection, newConnection);
                    DebugLog.Assert(connectionRelease == null, nameof(CMClient), "Connection was set during a connect, did you call CMClient.Connect() on multiple threads?");

                    newConnection.NetMsgReceived += NetMsgReceived;
                    newConnection.Connected      += Connected;
                    newConnection.Disconnected   += Disconnected;
                    newConnection.Connect(record.EndPoint, ( int )ConnectionTimeout.TotalMilliseconds);
                }, TaskContinuationOptions.ExecuteSynchronously).ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        LogDebug(nameof(CMClient), "Unhandled exception when attempting to connect to Steam: {0}", t.Exception);
                        OnClientDisconnected(userInitiated: false);
                    }

                    connectionSetupTask = null;
                }, TaskContinuationOptions.ExecuteSynchronously);
            }
        }
 public void UseServer(Func <BackgroundJobServer> server)
 {
     Servers.Add(server);
 }
예제 #32
0
        public async Task RavenDB_15855()
        {
            DebuggerAttachedTimeout.DisableLongTimespan = true;
            var clusterSize = 3;

            var(_, hub) = await CreateRaftCluster(clusterSize);

            var(minionNodes, minion) = await CreateRaftCluster(clusterSize);

            var hubDB    = GetDatabaseName();
            var minionDB = GetDatabaseName();

            var dstTopology = await CreateDatabaseInCluster(minionDB, clusterSize, minion.WebUrl);

            var srcTopology = await CreateDatabaseInCluster(hubDB, clusterSize, hub.WebUrl);

            using (var hubStore = new DocumentStore
            {
                Urls = new[] { hub.WebUrl },
                Database = hubDB
            }.Initialize())
                using (var minionStore = new DocumentStore
                {
                    Urls = new[] { minion.WebUrl },
                    Database = minionDB
                }.Initialize())
                {
                    using (var session = hubStore.OpenSession())
                    {
                        session.Advanced.WaitForReplicationAfterSaveChanges(timeout: TimeSpan.FromSeconds(10), replicas: clusterSize - 1);
                        session.Store(new User
                        {
                            Name = "Karmel"
                        }, "users/1");
                        session.SaveChanges();
                    }

                    var name = $"pull-replication {GetDatabaseName()}";
                    await hubStore.Maintenance.ForDatabase(hubStore.Database).SendAsync(new PutPullReplicationAsHubOperation(new PullReplicationDefinition(name)
                    {
                        MentorNode = "A"
                    }));

                    var pullReplication = new PullReplicationAsSink(hubDB, $"ConnectionString-{hubDB}", name)
                    {
                        MentorNode = "B", // this is the node were the data will be replicated to.
                    };
                    await AddWatcherToReplicationTopology((DocumentStore)minionStore, pullReplication, new[] { hub.WebUrl });

                    using (var dstSession = minionStore.OpenSession())
                    {
                        Assert.True(await WaitForDocumentInClusterAsync <User>(
                                        minionNodes,
                                        minionDB,
                                        "users/1",
                                        u => u.Name.Equals("Karmel"),
                                        TimeSpan.FromSeconds(30)));
                    }

                    var minionUrl    = minion.ServerStore.GetClusterTopology().GetUrlFromTag("B");
                    var minionServer = Servers.Single(s => s.WebUrl == minionUrl);
                    var handler      = await InstantiateOutgoingTaskHandler(minionDB, minionServer);

                    Assert.True(WaitForValue(
                                    () => ((OngoingTaskPullReplicationAsSink)handler.GetOngoingTasksInternal().OngoingTasksList.Single(t => t is OngoingTaskPullReplicationAsSink)).DestinationUrl != null,
                                    true));

                    var mentorUrl      = hub.ServerStore.GetClusterTopology().GetUrlFromTag("A");
                    var mentor         = Servers.Single(s => s.WebUrl == mentorUrl);
                    var mentorDatabase = await mentor.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(hubDB);

                    var connections = await WaitForValueAsync(() => mentorDatabase.ReplicationLoader.OutgoingConnections.Count(), 3);

                    Assert.Equal(3, connections);

                    minionServer.CpuCreditsBalance.BackgroundTasksAlertRaised.Raise();

                    Assert.Equal(1,
                                 await WaitForValueAsync(async() => (await minionStore.Maintenance.Server.SendAsync(new GetDatabaseRecordOperation(minionDB))).Topology.Rehabs.Count,
                                                         1));

                    await EnsureReplicatingAsync((DocumentStore)hubStore, (DocumentStore)minionStore);

                    connections = await WaitForValueAsync(() => mentorDatabase.ReplicationLoader.OutgoingConnections.Count(), 3);

                    Assert.Equal(3, connections);
                }
        }
예제 #33
0
 public bool process(Servers.AsynchronousServer.ClientConnection cc, HTTPRequest request)
 {
     cc.Send(new IOLessDataLinkNotFound().ToString());
     return true;
 }
예제 #34
0
 /// <summary>
 ///		Añade una conexión
 /// </summary>
 public Core.JabberConnection AddConnection(Servers.JabberServer objServer, Users.JabberUser objUser)
 {
     return Connections.Add(objServer, objUser);
 }
예제 #35
0
        public void ImportSettings(string filename)
        {
            var jsonText = File.ReadAllText(filename);
            var newSettings = PartialObject<BindableSettings>.Create(jsonText);

            // Todo: This probably isn't the best way of doing this
            //  - should probably have some method of denoting if a setting is importable, then it should run automatically

            newSettings.MergeItem((BindableSettings x) => x.RefreshInterval, _settings);

            // Note: This is a little hacky but I'm not sure how to trigger a refresh on the binding when replacing the entire list
            var servers = new Servers();
            newSettings.MergeItem(x => x.Servers, ref servers);

            if (servers.Any())
            {
                _settings.Servers.Clear();
                //_settings.CurrentServer = 0; Deprecated
                foreach (var server in servers)
                {
                    _settings.Servers.Add(server);
                }
            }
        }
예제 #36
0
        public async Task ResetLogChannel(string logType)
        {
            var server = Servers.GetServer(Context.Guild);

            switch (logType.ToLower())
            {
            case "deletedmessages":
                server.LogDeletedMessages = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `Deleted Messages` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "messageedits":
                server.LogMessageEdits = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `Edited Messages` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "userjoins":
                server.LogWhenUserJoins = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `User Joins` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "userleaves":
                server.LogWhenUserLeaves = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `User Leaves` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "userisbanned":
                server.LogWhenUserIsBanned = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `User Banned` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "userisunbanned":
                server.LogWhenUserIsUnbanned = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `User Unbanned` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "changestologsettings":
                server.LogChangesToLogSettings = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `changes to log settings` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "filteredphrases":
                server.LogWhenUserSaysFilteredPhrase = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `Filtered Phrases` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "userconnectstovoice":
                server.LogWhenUserConnectsToVoiceChannel = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `user connects to voice` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "userdisconnectsfromvoice":
                server.LogWhenUserDisconnectsFromVoiceChannel = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `user disconnects from voice` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            case "all":
                server.LogDeletedMessages                     = 0;
                server.LogMessageEdits                        = 0;
                server.LogWhenUserJoins                       = 0;
                server.LogWhenUserLeaves                      = 0;
                server.LogWhenUserIsBanned                    = 0;
                server.LogWhenUserIsUnbanned                  = 0;
                server.LogChangesToLogSettings                = 0;
                server.LogWhenUserSaysFilteredPhrase          = 0;
                server.LogWhenUserConnectsToVoiceChannel      = 0;
                server.LogWhenUserDisconnectsFromVoiceChannel = 0;
                Servers.SaveServers();
                embed.WithTitle("Log Channel Set");
                embed.WithDescription($"{Context.User.Mention} Log messages for `everything` have been disabled");
                embed.WithColor(Pink);
                BE(); break;

            default:
                embed.WithTitle("Invalid Log Specification");
                embed.WithDescription($"{Context.User.Mention} Please specify a valid logging type!");
                embed.WithColor(Red);
                BE(); break;
            }
        }
        public KSPAPI(FormatterProvider formatters, VesselChangeDetector vesselChangeDetector,
            Servers.AsynchronousServer.ServerConfiguration serverConfiguration)
        {
            APIHandlers.Add(new PausedDataLinkHandler(formatters));
            APIHandlers.Add(new FlyByWireDataLinkHandler(formatters));
            APIHandlers.Add(new FlightDataLinkHandler(formatters));
            APIHandlers.Add(new MechJebDataLinkHandler(formatters));
            APIHandlers.Add(new TimeWarpDataLinkHandler(formatters));
            APIHandlers.Add(new TargetDataLinkHandler(formatters));

            APIHandlers.Add(new CompoundDataLinkHandler(
                new List<DataLinkHandler>() {
                    new OrbitDataLinkHandler(formatters),
                    new SensorDataLinkHandler(vesselChangeDetector, formatters),
                    new VesselDataLinkHandler(formatters),
                    new BodyDataLinkHandler(formatters),
                    new ResourceDataLinkHandler(vesselChangeDetector, formatters),
                    new APIDataLinkHandler(this, formatters, serverConfiguration),
                    new NavBallDataLinkHandler(formatters),
                    new MapViewDataLinkHandler(formatters),
                    new DockingDataLinkHandler(formatters)
                    }, formatters
                ));

            APIHandlers.Add(new DefaultDataLinkHandler(formatters));
        }
예제 #38
0
 /// <summary>
 /// Add a server to the core.
 /// </summary>
 internal void Add(Server.Server server)
 {
     Servers.Add(server);
     Configure(server);
     Logger.WriteLine("Added server '" + server.Name + "'");
 }
 private static void WebSocketServerNotify(object sender, Servers.NotifyEventArgs e)
 {
     PluginLogger.debug(e.message);
 }
예제 #40
0
        public async Task FailoverOnSinkNodeFail()
        {
            var clusterSize = 3;

            var(_, hub) = await CreateRaftCluster(clusterSize);

            var(minionNodes, minion) = await CreateRaftCluster(clusterSize);

            var hubDB    = GetDatabaseName();
            var minionDB = GetDatabaseName();

            var dstTopology = await CreateDatabaseInCluster(minionDB, clusterSize, minion.WebUrl);

            var srcTopology = await CreateDatabaseInCluster(hubDB, clusterSize, hub.WebUrl);

            using (var hubStore = new DocumentStore
            {
                Urls = new[] { hub.WebUrl },
                Database = hubDB
            }.Initialize())
                using (var minionStore = new DocumentStore
                {
                    Urls = new[] { minion.WebUrl },
                    Database = minionDB
                }.Initialize())
                {
                    using (var session = hubStore.OpenSession())
                    {
                        session.Advanced.WaitForReplicationAfterSaveChanges(timeout: TimeSpan.FromSeconds(10), replicas: clusterSize - 1);
                        session.Store(new User
                        {
                            Name = "Karmel"
                        }, "users/1");
                        session.SaveChanges();
                    }

                    var name = $"pull-replication {GetDatabaseName()}";
                    await hubStore.Maintenance.ForDatabase(hubStore.Database).SendAsync(new PutPullReplicationAsHubOperation(name));

                    // add pull replication with invalid discovery url to test the failover on database topology discovery
                    var pullReplication = new PullReplicationAsSink(hubDB, $"ConnectionString-{hubDB}", name)
                    {
                        MentorNode = "B", // this is the node were the data will be replicated to.
                    };
                    await AddWatcherToReplicationTopology((DocumentStore)minionStore, pullReplication, new[] { "http://127.0.0.1:1234", hub.WebUrl });

                    using (var dstSession = minionStore.OpenSession())
                    {
                        Assert.True(await WaitForDocumentInClusterAsync <User>(
                                        minionNodes,
                                        minionDB,
                                        "users/1",
                                        u => u.Name.Equals("Karmel"),
                                        TimeSpan.FromSeconds(30)));
                    }

                    var minionUrl = minion.ServerStore.GetClusterTopology().GetUrlFromTag("B");
                    var server    = Servers.Single(s => s.WebUrl == minionUrl);
                    var handler   = await InstantiateOutgoingTaskHandler(minionDB, server);

                    Assert.True(WaitForValue(
                                    () => ((OngoingTaskPullReplicationAsSink)handler.GetOngoingTasksInternal().OngoingTasksList.Single(t => t is OngoingTaskPullReplicationAsSink)).DestinationUrl != null,
                                    true));

                    // dispose the minion node.
                    DisposeServerAndWaitForFinishOfDisposal(server);

                    using (var session = hubStore.OpenSession())
                    {
                        session.Advanced.WaitForReplicationAfterSaveChanges(timeout: TimeSpan.FromSeconds(10), replicas: clusterSize - 2);
                        session.Store(new User
                        {
                            Name = "Karmel2"
                        }, "users/2");
                        session.SaveChanges();
                    }

                    var user = WaitForDocumentToReplicate <User>(
                        minionStore,
                        "users/2",
                        30_000);

                    Assert.Equal("Karmel2", user.Name);
                }
        }
        public async Task Round_robin_load_balancing_with_failing_node_should_work()
        {
            var databaseName = "Round_robin_load_balancing_should_work" + Guid.NewGuid();
            var leader       = await CreateRaftClusterAndGetLeader(3);

            var followers = Servers.Where(x => x.ServerStore.IsLeader() == false).ToArray();

            var conventionsForLoadBalancing = new DocumentConventions
            {
                ReadBalanceBehavior = ReadBalanceBehavior.RoundRobin
            };

            using (var leaderStore = new DocumentStore
            {
                Urls = new[] { leader.WebUrl },
                Database = databaseName,
                Conventions = conventionsForLoadBalancing
            })
                using (var follower1 = new DocumentStore
                {
                    Urls = new[] { followers[0].WebUrl },
                    Database = databaseName,
                    Conventions = conventionsForLoadBalancing
                })
                    using (var follower2 = new DocumentStore
                    {
                        Urls = new[] { followers[1].WebUrl },
                        Database = databaseName,
                        Conventions = conventionsForLoadBalancing
                    })
                        using (var context = JsonOperationContext.ShortTermSingleUse())
                        {
                            leaderStore.Initialize();
                            follower1.Initialize();
                            follower2.Initialize();

                            var(index, _) = await CreateDatabaseInCluster(databaseName, 3, leader.WebUrl);
                            await WaitForRaftIndexToBeAppliedInCluster(index, TimeSpan.FromSeconds(30));

                            var leaderRequestExecutor = leaderStore.GetRequestExecutor();

                            //wait until all nodes in database cluster are members (and not promotables)
                            //GetTopologyCommand -> does not retrieve promotables
                            var topology = new Topology();
                            while (topology.Nodes?.Count != 3)
                            {
                                var topologyGetCommand = new GetTopologyCommand();
                                await leaderRequestExecutor.ExecuteAsync(topologyGetCommand, context);

                                topology = topologyGetCommand.Result;
                                Thread.Sleep(50);
                            }

                            foreach (var server in Servers)
                            {
                                await server.ServerStore.Cluster.WaitForIndexNotification(index);
                            }

                            using (var session = leaderStore.OpenSession())
                            {
                                session.Store(new User {
                                    Name = "John Dow"
                                });
                                session.Store(new User {
                                    Name = "Jack Dow"
                                });
                                session.Store(new User {
                                    Name = "Jane Dow"
                                });
                                session.Store(new User {
                                    Name = "FooBar"
                                }, "marker");
                                session.SaveChanges();

                                await WaitForDocumentInClusterAsync <User>(session as DocumentSession,
                                                                           "marker", x => true,
                                                                           leader.ServerStore.Configuration.Cluster.OperationTimeout.AsTimeSpan);
                            }

                            var requestExecutor = RequestExecutor.Create(follower1.Urls, databaseName, null, follower1.Conventions);
                            do //make sure there are three nodes in the topology
                            {
                                await Task.Delay(100);
                            } while (requestExecutor.TopologyNodes == null);

                            DisposeServerAndWaitForFinishOfDisposal(leader);

                            var failedRequests = new HashSet <(string, Exception)>();

                            requestExecutor.FailedRequest += (url, e) => failedRequests.Add((url, e));



                            using (var tmpContext = JsonOperationContext.ShortTermSingleUse())
                            {
                                for (var sessionId = 0; sessionId < 5; sessionId++)
                                {
                                    requestExecutor.Cache.Clear(); //make sure we do not use request cache
                                    await requestExecutor.ExecuteAsync(new GetStatisticsCommand(), tmpContext, CancellationToken.None, new SessionInfo(sessionId, false));
                                }
                            }
                        }
        }
예제 #42
0
        public async Task RemoveNodeWithDb()
        {
            var dbMain    = GetDatabaseName();
            var dbWatcher = GetDatabaseName();

            var fromSeconds = Debugger.IsAttached ? TimeSpan.FromSeconds(15) : TimeSpan.FromSeconds(5);

            var(_, leader) = await CreateRaftCluster(5);

            Assert.True(leader.ServerStore.LicenseManager.HasHighlyAvailableTasks());

            var db = await CreateDatabaseInCluster(dbMain, 5, leader.WebUrl);

            var watcherDb = await CreateDatabaseInCluster(dbWatcher, 1, leader.WebUrl);

            var serverNodes = db.Servers.Select(s => new ServerNode
            {
                ClusterTag = s.ServerStore.NodeTag,
                Database   = dbMain,
                Url        = s.WebUrl
            }).ToList();

            var conventions = new DocumentConventions
            {
                DisableTopologyUpdates = true
            };

            using (var watcherStore = new DocumentStore
            {
                Database = dbWatcher,
                Urls = new[] { watcherDb.Item2.Single().WebUrl },
                Conventions = conventions
            }.Initialize())
                using (var leaderStore = new DocumentStore
                {
                    Database = dbMain,
                    Urls = new[] { leader.WebUrl },
                    Conventions = conventions
                }.Initialize())
                {
                    var watcher = new ExternalReplication(dbWatcher, "Connection")
                    {
                        MentorNode = Servers.First(s => s.ServerStore.NodeTag != watcherDb.Servers[0].ServerStore.NodeTag).ServerStore.NodeTag
                    };

                    Assert.True(watcher.MentorNode != watcherDb.Servers[0].ServerStore.NodeTag);

                    var watcherRes = await AddWatcherToReplicationTopology((DocumentStore)leaderStore, watcher);

                    var tasks = new List <Task>();
                    foreach (var ravenServer in Servers)
                    {
                        tasks.Add(ravenServer.ServerStore.Cluster.WaitForIndexNotification(watcherRes.RaftCommandIndex));
                    }

                    Assert.True(await Task.WhenAll(tasks).WaitAsync(TimeSpan.FromSeconds(5)));

                    var responsibleServer = Servers.Single(s => s.ServerStore.NodeTag == watcherRes.ResponsibleNode);
                    using (var responsibleStore = new DocumentStore
                    {
                        Database = dbMain,
                        Urls = new[] { responsibleServer.WebUrl },
                        Conventions = conventions
                    }.Initialize())
                    {
                        // check that replication works.
                        using (var session = leaderStore.OpenSession())
                        {
                            session.Advanced.WaitForReplicationAfterSaveChanges(timeout: fromSeconds, replicas: 4);
                            session.Store(new User
                            {
                                Name = "Karmel"
                            }, "users/1");
                            session.SaveChanges();
                        }

                        Assert.True(WaitForDocument <User>(watcherStore, "users/1", u => u.Name == "Karmel", 30_000));

                        // remove the node from the cluster that is responsible for the external replication
                        await ActionWithLeader((l) => l.ServerStore.RemoveFromClusterAsync(watcherRes.ResponsibleNode).WaitAsync(fromSeconds));

                        Assert.True(await responsibleServer.ServerStore.WaitForState(RachisState.Passive, CancellationToken.None).WaitAsync(fromSeconds));

                        var dbInstance = await responsibleServer.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(dbMain);
                        await WaitForValueAsync(() => dbInstance.ReplicationLoader.OutgoingConnections.Count(), 0);

                        // replication from the removed node should be suspended
                        await Assert.ThrowsAsync <NodeIsPassiveException>(async() =>
                        {
                            using (var session = responsibleStore.OpenAsyncSession())
                            {
                                await session.StoreAsync(new User
                                {
                                    Name = "Karmel2"
                                }, "users/2");
                                await session.SaveChangesAsync();
                            }
                        });
                    }

                    var nodeInCluster = serverNodes.First(s => s.ClusterTag != responsibleServer.ServerStore.NodeTag);
                    using (var nodeInClusterStore = new DocumentStore
                    {
                        Database = dbMain,
                        Urls = new[] { nodeInCluster.Url },
                        Conventions = conventions
                    }.Initialize())
                    {
                        // the task should be reassinged within to another node
                        using (var session = nodeInClusterStore.OpenSession())
                        {
                            session.Advanced.WaitForReplicationAfterSaveChanges(timeout: TimeSpan.FromSeconds(30), replicas: 3);
                            session.Store(new User
                            {
                                Name = "Karmel3"
                            }, "users/3");
                            session.SaveChanges();
                        }
                    }

                    Assert.True(WaitForDocument <User>(watcherStore, "users/3", u => u.Name == "Karmel3", 30_000));

                    // rejoin the node
                    var newLeader = await ActionWithLeader(l => l.ServerStore.AddNodeToClusterAsync(responsibleServer.WebUrl, watcherRes.ResponsibleNode));

                    Assert.True(await responsibleServer.ServerStore.WaitForState(RachisState.Follower, CancellationToken.None).WaitAsync(fromSeconds));

                    using (var newLeaderStore = new DocumentStore
                    {
                        Database = dbMain,
                        Urls = new[] { newLeader.WebUrl },
                    }.Initialize())
                        using (var session = newLeaderStore.OpenAsyncSession())
                        {
                            session.Advanced.WaitForReplicationAfterSaveChanges(timeout: TimeSpan.FromSeconds(30), replicas: 3);
                            await session.StoreAsync(new User
                            {
                                Name = "Karmel4"
                            }, "users/4");

                            await session.SaveChangesAsync();
                        }

                    Assert.True(WaitForDocument <User>(watcherStore, "users/4", u => u.Name == "Karmel4", 30_000), $"The watcher doesn't have the document");
                }
        }
        public async Task Fastst_node_should_choose_the_node_without_delay()
        {
            NoTimeouts();
            var databaseName = "Fastst_node_should_choose_the_node_without_delay" + Guid.NewGuid();

            var(leader, serversToProxies) = await CreateRaftClusterWithProxiesAndGetLeader(3);

            var followers = Servers.Where(x => x.ServerStore.IsLeader() == false).ToArray();

            var conventionsForLoadBalancing = new DocumentConventions
            {
                ReadBalanceBehavior = ReadBalanceBehavior.FastestNode
            };

            //set proxies with delays to all servers except follower2
            using (var leaderStore = new DocumentStore
            {
                Urls = new[] { ReplacePort(leader.WebUrl, serversToProxies[leader].Port) },
                Database = databaseName,
                Conventions = conventionsForLoadBalancing
            })
            {
                leaderStore.Initialize();

                var(index, _) = await CreateDatabaseInCluster(databaseName, 3, leader.WebUrl);
                await WaitForRaftIndexToBeAppliedInCluster(index, TimeSpan.FromSeconds(30));

                var leaderRequestExecutor = leaderStore.GetRequestExecutor();

                //make sure we have updated topology --> more deterministic test
                await leaderRequestExecutor.UpdateTopologyAsync(new ServerNode
                {
                    ClusterTag = leader.ServerStore.NodeTag,
                    Database   = databaseName,
                    Url        = leader.WebUrl
                }, 5000);

                ApplyProxiesOnRequestExecutor(serversToProxies, leaderRequestExecutor);

                //wait until all nodes in database cluster are members (and not promotables)
                //GetTopologyCommand -> does not retrieve promotables
                using (var context = JsonOperationContext.ShortTermSingleUse())
                {
                    var topology = new Topology();
                    while (topology.Nodes?.Count != 3)
                    {
                        var topologyGetCommand = new GetTopologyCommand();
                        await leaderRequestExecutor.ExecuteAsync(topologyGetCommand, context).ConfigureAwait(false);

                        topology = topologyGetCommand.Result;
                        Thread.Sleep(50);
                    }
                }

                //set delays to all servers except follower2
                foreach (var server in Servers)
                {
                    if (server == followers[1])
                    {
                        continue;
                    }

                    serversToProxies[server].ConnectionDelay = 300;
                }

                using (var session = leaderStore.OpenSession())
                {
                    session.Store(new User {
                        Name = "John Dow"
                    }, "users/1");
                    session.SaveChanges();
                }

                while (leaderRequestExecutor.InSpeedTestPhase)
                {
                    using (var session = leaderStore.OpenSession())
                    {
                        session.Load <User>("users/1");
                    }
                }

                var fastest        = leaderRequestExecutor.GetFastestNode().Result.Node;
                var follower2Proxy = ReplacePort(followers[1].WebUrl, serversToProxies[followers[1]].Port);

                Assert.Equal(follower2Proxy, fastest.Url);
            }
        }
예제 #44
0
파일: Utility.cs 프로젝트: SinSiXX/Kaguya
        public async Task ModulesList([Remainder] string category)
        {
            var cmdPrefix = Servers.GetServer(Context.Guild).commandPrefix;

            if (category.ToLower() == "administration" || category.ToLower() == "admin")
            {
                embed.WithTitle("Module: Administration");
                embed.WithDescription("```css" +
                                      "\nAll commands in category: Administration" +
                                      "\n" +
                                      $"\n{cmdPrefix}ban [b]" +
                                      $"\n{cmdPrefix}clear [c] [purge]" +
                                      $"\n{cmdPrefix}createrole [cr]" +
                                      $"\n{cmdPrefix}deleterole [dr]" +
                                      $"\n{cmdPrefix}filteradd [fa]" +
                                      $"\n{cmdPrefix}filterclear [clearfilter]" +
                                      $"\n{cmdPrefix}filterremove [fr]" +
                                      $"\n{cmdPrefix}filterview [fv]" +
                                      $"\n{cmdPrefix}kaguyaexit" +
                                      $"\n{cmdPrefix}kick [k]" +
                                      $"\n{cmdPrefix}logtypes [loglist]" +
                                      $"\n{cmdPrefix}massban" +
                                      $"\n{cmdPrefix}massblacklist" +
                                      $"\n{cmdPrefix}masskick" +
                                      $"\n{cmdPrefix}removeallroles [rar]" +
                                      $"\n{cmdPrefix}resetlogchannel [rlog]" +
                                      $"\n{cmdPrefix}setlogchannel [log]" +
                                      $"\n{cmdPrefix}scrapeserver" +
                                      $"\n{cmdPrefix}unblacklist" +
                                      $"\n" +
                                      $"\nType {cmdPrefix}h <command> for more information on a specific command." +
                                      "\n```");
                embed.WithColor(Pink);
                BE();
            }
            else if (category.ToLower() == "exp")
            {
                embed.WithTitle("Module: EXP");
                embed.WithDescription
                    ("```css" +
                    "\nAll commands in category: Experience Points" +
                    "\n" +
                    $"\n{cmdPrefix}exp" +
                    $"\n{cmdPrefix}expadd [addexp]" +
                    $"\n{cmdPrefix}level" +
                    $"\n{cmdPrefix}globalexplb [gexplb]" +
                    $"\n{cmdPrefix}rep" +
                    $"\n{cmdPrefix}repauthor [rep author]" +
                    $"\n{cmdPrefix}serverexplb [explb]" +
                    $"\n" +
                    $"\nType {cmdPrefix}h <command> for more information on a specific command." +
                    "\n```");
                embed.WithColor(Pink);
                BE();
            }
            else if (category.ToLower() == "currency")
            {
                embed.WithTitle("Module: Currency");
                embed.WithDescription
                    ("```css" +
                    "\nAll commands in category: Currency" +
                    "\n" +
                    $"\n{cmdPrefix}awardeveryone [awardall]" +
                    $"\n{cmdPrefix}groll [gr]" +
                    $"\n{cmdPrefix}masspointsdistribute" +
                    $"\n{cmdPrefix}points" +
                    $"\n{cmdPrefix}pointsadd [addpoints]" +
                    $"\n{cmdPrefix}timely [t]" +
                    $"\n{cmdPrefix}timelyreset" +
                    $"\n" +
                    $"\nType {cmdPrefix}h <command> for more information on a specific command." +
                    $"\n```"
                    );
                embed.WithColor(Pink);
                BE();
            }
            else if (category.ToLower() == "utility")
            {
                embed.WithTitle("Module: Utility");
                embed.WithDescription
                    ("```css" +
                    "\nAll commands in category: Utility" +
                    "\n" +
                    $"\n{cmdPrefix}author" +
                    $"\n{cmdPrefix}commands [cmds]" +
                    $"\n{cmdPrefix}createtextchannel [ctc]" +
                    $"\n{cmdPrefix}createvoicechannel [cvc]" +
                    $"\n{cmdPrefix}deletetextchannel [dtc]" +
                    $"\n{cmdPrefix}deletevoicechannel [dvc]" +
                    $"\n{cmdPrefix}prefix" +
                    $"\n" +
                    $"\nType {cmdPrefix}h <command> for more information on a specific command." +
                    $"\n```");
                embed.WithColor(Pink);
                BE();
            }
            else if (category.ToLower() == "fun")
            {
                embed.WithTitle("Module: Fun");
                embed.WithDescription("```css" +
                                      "\n" +
                                      $"\n{cmdPrefix}echo" +
                                      $"\n{cmdPrefix}pick" +
                                      $"\nType {cmdPrefix}h <command> for more information on a specific command." +
                                      $"\n" +
                                      $"\n```");
                embed.WithColor(Pink);
                BE();
            }
            else if (category.ToLower() == "osu")
            {
                embed.WithTitle("Module: osu!");
                embed.WithDescription("```css" +
                                      "\n" +
                                      $"\n{cmdPrefix}createteamrole [ctr]" +
                                      $"\n{cmdPrefix}delteams" +
                                      $"\n{cmdPrefix}osuset" +
                                      $"\n{cmdPrefix}osutop" +
                                      $"\n{cmdPrefix}recent [r]" +
                                      $"\n" +
                                      $"\nType {cmdPrefix}h <command> for more information on a specific command." +
                                      $"\n```");
                embed.WithColor(Pink);
                BE();
            }
            else if (category.ToLower() == "help")
            {
                embed.WithTitle("Module: Help");
                embed.WithDescription("```css" +
                                      "\n" +
                                      $"\n{cmdPrefix}help [h]" +
                                      $"\n{cmdPrefix}helpdm [hdm]" +
                                      $"\n" +
                                      $"\nType {cmdPrefix}h <command> for more information on a specific command." +
                                      $"\n```");
                embed.WithColor(Pink);
                BE();
            }
        }
예제 #45
0
        private async void RestoreServerList()
        {
            var answer = await Application.Current.MainPage.DisplayAlert("", "Are you sure you want to restore the default server list?", "YES", "NO");

            if (answer == true)
            {
                try
                {
                    var servers = new Servers();

                    servers.MonitoredServers.Add(new Server
                    {
                        ID       = Guid.NewGuid().ToString(),
                        Name     = "Google",
                        Status   = "",
                        HostName = "https://google.com",
                        Logs     = new List <string> {
                            $"Added to list: {DateTime.Now.ToString("yyyy-MM-dd  hh:mm:ss tt")}"
                        }
                    });

                    servers.MonitoredServers.Add(new Server
                    {
                        ID       = Guid.NewGuid().ToString(),
                        Name     = "Twitter",
                        Status   = "",
                        HostName = "https://twitter.com",
                        Logs     = new List <string> {
                            $"Added to list: {DateTime.Now.ToString("yyyy-MM-dd  hh:mm:ss tt")}"
                        }
                    });


                    servers.MonitoredServers.Add(new Server
                    {
                        ID       = Guid.NewGuid().ToString(),
                        Name     = "Amazon",
                        Status   = "",
                        HostName = "https://amazon.com",
                        Logs     = new List <string> {
                            $"Added to list: {DateTime.Now.ToString("yyyy-MM-dd  hh:mm:ss tt")}"
                        }
                    });

                    servers.MonitoredServers.Add(new Server
                    {
                        ID       = Guid.NewGuid().ToString(),
                        Name     = "YouTube",
                        Status   = "",
                        HostName = "https://youtube.com",
                        Logs     = new List <string> {
                            $"Added to list: {DateTime.Now.ToString("yyyy-MM-dd  hh:mm:ss tt")}"
                        }
                    });

                    servers.MonitoredServers.Add(new Server
                    {
                        ID       = Guid.NewGuid().ToString(),
                        Name     = "Apple",
                        Status   = "",
                        HostName = "https://apple.com",
                        Logs     = new List <string> {
                            $"Added to list: {DateTime.Now.ToString("yyyy-MM-dd  hh:mm:ss tt")}"
                        }
                    });

                    servers.MonitoredServers.Add(new Server
                    {
                        ID       = Guid.NewGuid().ToString(),
                        Name     = "Netflix",
                        Status   = "",
                        HostName = "https://netflix.com",
                        Logs     = new List <string> {
                            $"Added to list: {DateTime.Now.ToString("yyyy-MM-dd  hh:mm:ss tt")}"
                        }
                    });

                    await BlobCache.UserAccount.InsertObject("Servers", servers);

                    await Application.Current.MainPage.DisplayAlert("", "Default server list restored.", "OK");

                    var serverMonitor = AppContainer.Resolve <ServerMonitorViewModel>();
                    serverMonitor.LastUpdated = "Default server list restored.";
                    serverMonitor.ServersData = new System.Collections.ObjectModel.ObservableCollection <Server>();
                }
                catch (Exception ex)
                {
                    await Application.Current.MainPage.DisplayAlert("Error", $"{ex.Message}", "OK");
                }
            }
        }
예제 #46
0
        public void Start(int ticks)
        {
            Application.targetFrameRate = ticks <= 0 ? 10 : ticks;
            if (IsStarted)
            {
                LogStartedError();
                return;
            }
            else
            {
            }

            Tester = Tester.Instance;
            Tester.Init(new TesterBaseApp());

            AssertFrameworkInit(int.MaxValue);
            AssertFrameworkInit(0);

            Notificater = NotificatonsInt.Instance.Notificater; //new Notifications<int>();//新建消息中心
            ABs         = new AssetBundles();                   //新建资源包管理器
            Servers     = new Servers();                        //新建服务容器管理器
            DataWarehouse datas = new DataWarehouse();          //新建数据管理器

            AssetsPooling = new AssetsPooling();                //新建场景资源对象池
            ECSContext    = new ShipDockComponentContext        //新建 ECS 组件上下文
            {
                FrameTimeInScene = (int)(Time.deltaTime * UpdatesCacher.UPDATE_CACHER_TIME_SCALE)
            };
            StateMachines = new StateMachines//新建有限状态机管理器
            {
                FSMFrameUpdater   = OnFSMFrameUpdater,
                StateFrameUpdater = OnStateFrameUpdater
            };
            Effects             = new Effects();            //新建特效管理器
            Locals              = new Locals();             //新建本地化管理器
            PerspectivesInputer = new PerspectiveInputer(); //新建透视物体交互器
            AppModulars         = new DecorativeModulars(); //新建装饰模块管理器
            Configs             = new ConfigHelper();       //新建配置管理器

            #region 向定制框架中填充框架功能单元
            Framework framework = Framework.Instance;
            FrameworkUnits = new IFrameworkUnit[]
            {
                framework.CreateUnitByBridge(Framework.UNIT_DATA, datas),
                framework.CreateUnitByBridge(Framework.UNIT_AB, ABs),
                framework.CreateUnitByBridge(Framework.UNIT_MODULARS, AppModulars),
                framework.CreateUnitByBridge(Framework.UNIT_ECS, ECSContext),
                framework.CreateUnitByBridge(Framework.UNIT_IOC, Servers),
                framework.CreateUnitByBridge(Framework.UNIT_CONFIG, Configs),
                framework.CreateUnitByBridge(Framework.UNIT_UI, UIs),
                framework.CreateUnitByBridge(Framework.UNIT_FSM, StateMachines),
            };
            framework.LoadUnit(FrameworkUnits);
            #endregion

            mFSMUpdaters   = new KeyValueList <IStateMachine, IUpdate>();
            mStateUpdaters = new KeyValueList <IState, IUpdate>();
            TicksUpdater   = new TicksUpdater(Application.targetFrameRate);//新建客户端心跳帧更新器

            AssertFrameworkInit(1);
            AssertFrameworkInit(2);

            IsStarted = true;
            mAppStarted?.Invoke();
            mAppStarted = default;

            ShipDockConsts.NOTICE_SCENE_UPDATE_READY.Add(OnSceneUpdateReady);
            UpdatesComponent?.Init();

            ShipDockConsts.NOTICE_APPLICATION_STARTUP.Broadcast();//框架启动完成
            AssertFrameworkInit(3);
        }
예제 #47
0
 public CommandHandler(DiscordSocketClient client, CommandService service, IConfiguration config, IServiceProvider provider, Servers servers, ServerHelper serverHelper, Images images, LavaNode lavaNode, UserProfiles userProfiles, EssentiBotContext context)
 {
     _provider     = provider;
     _client       = client;
     _service      = service;
     _config       = config;
     _servers      = servers;
     _serverHelper = serverHelper;
     _images       = images;
     _lavaNode     = lavaNode;
     _userProfiles = userProfiles;
     _context      = context;
 }
예제 #48
0
        public void New()
        {
            //// Initiate Timer
            //int intTimeout = 10;    // minutes for all registrations
            //if (Debug)
            //    oEventLog.WriteEntry(String.Format("Starting Avamar Registration Thread."), EventLogEntryType.Information);
            //Timeout timeout = new Timeout(TimeoutType.Minutes, intTimeout, oEventLog, Debug);
            //ThreadStart tTimeoutStart = new ThreadStart(timeout.Begin);
            //Thread tTimeout = new Thread(tTimeoutStart);
            //tTimeout.Start();

            try
            {
                this.Starter.Clusters = true;

                // Setup Classes
                Servers oServer = new Servers(0, dsn);
                NCC.ClearView.Application.Core.Storage oStorage = new NCC.ClearView.Application.Core.Storage(0, dsn);
                Forecast oForecast = new Forecast(0, dsn);
                Cluster  oCluster  = new Cluster(0, dsn);
                Log      oLog      = new Log(0, dsn);

                DataSet dsNew = oCluster.GetClustering();
                if (dsNew.Tables[0].Rows.Count > 0)
                {
                    oLog.AddEvent("", "", "Get clustering (" + dsNew.Tables[0].Rows.Count.ToString() + ")", LoggingType.Debug);
                    foreach (DataRow drNew in dsNew.Tables[0].Rows)
                    {
                        string error     = "";
                        int    intAnswer = Int32.Parse(drNew["answerid"].ToString());
                        //if (oStorage.GetLunDisks(intAnswer).Tables[0].Rows.Count > 0)
                        //{
                        //    oLog.AddEvent(intAnswer, "CLUSTERING", "CLUSTERING", "Disks are there. Starting clustering...", LoggingType.Debug);
                        //    DataSet dsClusters = oServer.GetAnswerClusters(intAnswer);
                        //    foreach (DataRow drCluster in dsClusters.Tables[0].Rows)
                        //    {
                        //        int intClusterID = Int32.Parse(drCluster["clusterid"].ToString());
                        //        string strCluster = oCluster.Get(intClusterID, "name");
                        //        oLog.AddEvent(intAnswer, strCluster, "CLUSTERING", "Checking cluster in DNS...", LoggingType.Debug);
                        //        // First, check to make sure it's available (pinging) in DNS
                        //        bool InDNS = false;
                        //        Ping Ping = new Ping();
                        //        string PingStatus = "";
                        //        try
                        //        {
                        //            PingReply Reply = Ping.Send(strCluster);
                        //            PingStatus = Reply.Status.ToString().ToUpper();
                        //            if (PingStatus == "SUCCESS")
                        //            {
                        //                InDNS = true;
                        //                break;
                        //            }
                        //        }
                        //        catch { }

                        //        if (InDNS == false)
                        //        {
                        //            error = "The cluster name " + strCluster + " is not responding in DNS";
                        //            oLog.AddEvent(intAnswer, strCluster, "CLUSTERING", error, LoggingType.Error);
                        //            break;
                        //        }
                        //        else
                        //        {
                        //            oLog.AddEvent(intAnswer, strCluster, "CLUSTERING", "Cluster is responding in DNS. Now check instances...", LoggingType.Debug);
                        //            DataSet dsInstances = oCluster.GetInstances(intClusterID);
                        //            foreach (DataRow drInstance in dsInstances.Tables[0].Rows)
                        //            {
                        //                string strInstance = drInstance["name"].ToString();
                        //                oLog.AddEvent(intAnswer, strCluster, strInstance, "Checking instance " + strInstance + " in DNS...", LoggingType.Debug);
                        //                // First, check to make sure it's available (pinging) in DNS
                        //                InDNS = false;
                        //                Ping = new Ping();
                        //                PingStatus = "";
                        //                try
                        //                {
                        //                    PingReply Reply = Ping.Send(strInstance);
                        //                    PingStatus = Reply.Status.ToString().ToUpper();
                        //                    if (PingStatus == "SUCCESS")
                        //                    {
                        //                        InDNS = true;
                        //                        break;
                        //                    }
                        //                }
                        //                catch { }

                        //                if (InDNS == false)
                        //                {
                        //                    error = "The cluster instance name " + strInstance + " is not responding in DNS";
                        //                    oLog.AddEvent(intAnswer, strCluster, strInstance, error, LoggingType.Error);
                        //                    break;
                        //                }
                        //                else
                        //                    oLog.AddEvent(intAnswer, strCluster, strInstance, "The cluster instance name " + strInstance + " is responding in DNS.", LoggingType.Debug);
                        //            }
                        //        }
                        //    }

                        //    if (String.IsNullOrEmpty(error))
                        //    {
                        //        // Clusterprocessing.ps1 –AnswerID [answerid] –Environment [environment] –Log [true]
                        //        string command = "Clusterprocessing.ps1 -AnswerID " + intAnswer.ToString() + " -Environment \"" + this.Starter.ScriptEnvironment + "\" –Log";
                        //        oLog.AddEvent(intAnswer, "CLUSTERING", "CLUSTERING", "Executing automated clustering script (" + command + ")...", LoggingType.Debug);

                        //        try
                        //        {
                        //            List<PowershellParameter> powershell = new List<PowershellParameter>();
                        //            Powershell oPowershell = new Powershell();
                        //            powershell.Add(new PowershellParameter("AnswerID", intAnswer.ToString()));
                        //            powershell.Add(new PowershellParameter("Environment", this.Starter.ScriptEnvironment));
                        //            powershell.Add(new PowershellParameter("Log", null));
                        //            List<PowershellParameter> results = oPowershell.Execute(this.Starter.strScripts + "\\Clusterprocessing.ps1", powershell, oLog, intAnswer.ToString());
                        //            oLog.AddEvent(intAnswer, "CLUSTERING", "CLUSTERING", "Powershell script completed!", LoggingType.Debug);
                        //            bool PowerShellError = false;
                        //            foreach (PowershellParameter result in results)
                        //            {
                        //                oLog.AddEvent(intAnswer, "CLUSTERING", "CLUSTERING", "PSOBJECT: " + result.Name + " = " + result.Value, LoggingType.Information);
                        //                if (result.Name == "ResultCode" && result.Value.ToString() != "0")
                        //                    PowerShellError = true;
                        //                else if (result.Name == "Message" && PowerShellError)
                        //                    error = result.Value.ToString();
                        //            }
                        //        }
                        //        catch (Exception exPowershell)
                        //        {
                        //            error = exPowershell.Message;
                        //        }
                        //    }
                        //}
                        //else
                        //    error = "Windows - no disk error message c0000013";

                        if (String.IsNullOrEmpty(error))
                        {
                            oLog.AddEvent(intAnswer, "CLUSTERING", "CLUSTERING", "Done.", LoggingType.Debug);
                            oCluster.UpdateClusteringCompleted(intAnswer, "", DateTime.Now.ToString(), 0);
                        }
                        else
                        {
                            oLog.AddEvent(intAnswer, "CLUSTERING", "CLUSTERING", error, LoggingType.Error);
                            oCluster.UpdateClusteringCompleted(intAnswer, error, DateTime.Now.ToString(), 1);
                            oForecast.AddError(0, 0, 0, intAnswer, (int)NCC.ClearView.Application.Core.Forecast.ForecastAnswerErrorStep.Clustering, error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message + " ~ (Source: " + ex.Source + ") (Stack Trace: " + ex.StackTrace + ")";
                oEventLog.WriteEntry(error, EventLogEntryType.Error);
            }
            finally
            {
                this.Starter.Clusters = false;
                //timeout.StopIt = true;  // Kill timeout thread.
            }
        }
예제 #49
0
        public async Task CanImportExportAndBackupWithClusterTransactions()
        {
            var file = GetTempFileName();

            var leader = await CreateRaftClusterAndGetLeader(3);

            var user1 = new User()
            {
                Name = "Karmel"
            };
            var user2 = new User()
            {
                Name = "Oren"
            };
            var user3 = new User()
            {
                Name = "Indych"
            };

            using (var store = GetDocumentStore(new Options {
                Server = leader, ReplicationFactor = 2
            }))
            {
                // we kill one server so we would not clean the pending cluster transactions.
                await DisposeAndRemoveServer(Servers.First(s => s != leader));

                using (var session = store.OpenAsyncSession(new SessionOptions
                {
                    TransactionMode = TransactionMode.ClusterWide
                }))
                {
                    session.Advanced.ClusterTransaction.CreateCompareExchangeValue("usernames/karmel", user1);
                    await session.StoreAsync(user1, "foo/bar");

                    await session.StoreAsync(new User(), "foo/bar2");

                    await session.SaveChangesAsync();

                    session.Advanced.Evict(user1);

                    session.Advanced.ClusterTransaction.CreateCompareExchangeValue("usernames/ayende", user2);
                    await session.StoreAsync(user2, "foo/bar");

                    await session.StoreAsync(new User(), "foo/bar3");

                    await session.SaveChangesAsync();

                    session.Advanced.Evict(user2);

                    session.Advanced.SetTransactionMode(TransactionMode.SingleNode);
                    await session.StoreAsync(user3, "foo/bar");

                    await session.SaveChangesAsync();

                    session.Advanced.Evict(user3);

                    var user = (await session.Advanced.ClusterTransaction.GetCompareExchangeValueAsync <User>("usernames/ayende")).Value;
                    Assert.Equal(user2.Name, user.Name);
                    user = await session.LoadAsync <User>("foo/bar");

                    Assert.Equal(user3.Name, user.Name);
                }

                var operation = await store.Smuggler.ExportAsync(new DatabaseSmugglerExportOptions(), file);

                await operation.WaitForCompletionAsync(TimeSpan.FromMinutes(1));
            }

            using (var store = GetDocumentStore(new Options {
                Server = leader, ReplicationFactor = 2
            }))
            {
                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(user1, "foo/bar");

                    await session.SaveChangesAsync();

                    session.Advanced.Evict(user1);

                    var operation = await store.Smuggler.ImportAsync(new DatabaseSmugglerImportOptions(), file);

                    await operation.WaitForCompletionAsync(TimeSpan.FromMinutes(1));

                    var user = await session.LoadAsync <User>("foo/bar");

                    session.Advanced.Evict(user);
                    Assert.Equal(user3.Name, user.Name);
                }
            }
        }
예제 #50
0
        public async Task TopologyUpdateDuringFailoverShouldntFaileCommand()
        {
            const int nodesAmount = 5;
            var       leader      = await this.CreateRaftClusterAndGetLeader(nodesAmount);

            var defaultDatabase = GetDatabaseName();

            await CreateDatabaseInCluster(defaultDatabase, nodesAmount, leader.WebUrl).ConfigureAwait(false);

            using (var store = new DocumentStore
            {
                Urls = new[] { leader.WebUrl },
                Database = defaultDatabase
            }.Initialize())
            {
                var reqEx = store.GetRequestExecutor();

                Topology topology = null;

                while (reqEx.Topology == null)
                {
                    await Task.Delay(100);
                }
                topology = reqEx.Topology;
                var serverNode1 = topology.Nodes[0];
                await reqEx.UpdateTopologyAsync(
                    node : serverNode1,
                    timeout : 10_000);

                var node1 = Servers.First(x => x.WebUrl.Equals(serverNode1.Url, StringComparison.InvariantCultureIgnoreCase));
                await DisposeServerAndWaitForFinishOfDisposalAsync(node1);

                var serverNode2 = topology.Nodes[1];
                var node2       = Servers.First(x => x.WebUrl.Equals(serverNode2.Url, StringComparison.InvariantCultureIgnoreCase));
                await DisposeServerAndWaitForFinishOfDisposalAsync(node2);

                using (reqEx.ContextPool.AllocateOperationContext(out var context))
                {
                    var command = new GetDocumentsCommand(0, 1);
                    var task    = reqEx.ExecuteAsync(command, context);

                    var mre = new ManualResetEvent(false);

                    reqEx.OnFailedRequest += (sender, args) =>
                    {
                        mre.WaitOne();
                    };

                    while (command.FailedNodes == null || command.FailedNodes.Count == 0)
                    {
                        await Task.Delay(100);
                    }
                    while (await reqEx.UpdateTopologyAsync(topology.Nodes[3], 10_000, forceUpdate: true) == false ||
                           reqEx.Topology.Etag == topology.Etag)
                    {
                        await Task.Delay(100);
                    }

                    mre.Set();
                    await task;
                }
            }
        }
        private void UpdateRangedBaseShardMap(Settings settings)
        {
            //Rollback available shards on each server for the recalculation
            foreach (var server in Servers)
            {
                if (server.MaxShardsAllowed > 0)
                {
                    //TODO: in order for this to work "right" we need an accurate calculation of available shards from the DAL.. Until then we will pretend that setting is max shards per shard set.
                    server.AvailableShards = server.MaxShardsAllowed;
                    //server.AvailableShards + ShardMap.Shards.Count(x => x.ServerInstanceName == server.ServerInstanceName);
                }
            }
            var newShardCount             = TargetShardCount - ShardMap.Shards.Count();
            IList <RangeShard> shardsUsed = new List <RangeShard>();

            if (newShardCount > 0)
            {
                //If Max Shards < 1 then unlimited shards allowed on the server.
                var availableShards = Servers.Sum(x => (x.MaxShardsAllowed < 1 ? 1000000 : x.AvailableShards));
                if (availableShards < newShardCount)
                {
                    throw new Exception("Not enough Shards available on servers used in shard set");
                }
            }
            var increment      = (long.MaxValue / TargetShardCount) * 2;
            var rangeLowValue  = Int64.MinValue;
            var rangeHighValue = Int64.MaxValue;

            if (increment != -2)
            {
                rangeHighValue = rangeLowValue + increment;
            }
            var counter         = 0;
            var currServerIndex = 0;

            var currentServer = Servers[currServerIndex];

            while (counter < TargetShardCount)
            {
                if ((currentServer.AvailableShards <= 0) &&
                    (currentServer.MaxShardsAllowed > 0))
                //unlimited shards allowed maxshardsallowed < 1 (or in this case > 0)
                {
                    currServerIndex++;
                    currentServer = Servers[currServerIndex];
                }
                else
                {
                    if (currentServer.MaxShardsAllowed > 0)
                    {
                        currentServer.AvailableShards--;
                    }
                }
                counter++;
                var databaseName = settings.ShardPrefix + ShardSetName + (counter.ToString("000000"));
                var isNewShard   = false;
                var shard        = ShardMap.Shards.FirstOrDefault(x => x.Catalog == databaseName);
                if (shard == null)
                {
                    shard = new RangeShard();
                    ShardMap.ShardMapID = -1;
                    isNewShard          = true;
                }

                //Is anything changing?
                if (
                    shard.Catalog != databaseName ||
                    shard.LowDistributionKey != rangeLowValue ||
                    shard.HighDistributionKey != rangeHighValue ||
                    shard.ServerInstanceName != currentServer.ServerInstanceName
                    )
                {
                    shard.Catalog             = databaseName;
                    shard.LowDistributionKey  = rangeLowValue;
                    shard.HighDistributionKey = rangeHighValue;
                    shard.ServerInstanceName  = currentServer.ServerInstanceName;
                    //If the shard has changed then time for a new map.
                    ShardMap.ShardMapID = -1;
                    shard.ShardID       = -1;
                }

                //Only add the shards that are new.
                if (isNewShard)
                {
                    ShardMap.Shards.Add(shard);
                }
                shardsUsed.Add(shard);

                //Either there can be a near infinite number of shards in the server, or we need to calculate how many shards remaining for the shard set
                //TODO: don't query just the current shard set, figure out total number of used shards across all work groups.
                //TODO: don't query just the current shard set, figure out total number of used shards across all work groups.
                currentServer.AvailableShards = (currentServer.MaxShardsAllowed == -1
                    ? 100000
                    : (currentServer.MaxShardsAllowed -
                       shardsUsed.Count(x => x.ServerInstanceName == currentServer.ServerInstanceName)));

                rangeLowValue = rangeHighValue + 1;
                if (counter + 1 == TargetShardCount)
                {
                    rangeHighValue = Int64.MaxValue;
                }
                else
                {
                    rangeHighValue += increment;
                }
            }
            var shardsToDelete = ShardMap.Shards.Count(x => !shardsUsed.Contains(x));

            if (shardsToDelete > 0)
            {
                //If we are deleting shards, then its time for a new shard map.
                ShardMap.ShardMapID = -1;
            }

            ShardMap.Shards = shardsUsed;

            // if the shard map is new all of the shards must be new too...
            if (ShardMap.ShardMapID == -1)
            {
                ShardMap.Shards.ToList().ForEach(x => x.ShardID = -1);
            }
        }
예제 #52
0
 /// <summary>开始</summary>
 public virtual void Start()
 {
     WriteLog("[{0}]集群地址:{1}", Name, Servers.Join(";", e => $"{e.Host}:{e.Port}"));
 }
예제 #53
0
        public async Task MissingRevisions3()
        {
            var(nodes, leader) = await CreateRaftCluster(3, watcherCluster : true);

            var database = GetDatabaseName();

            await CreateDatabaseInClusterInner(new DatabaseRecord(database), 3, leader.WebUrl, null);

            using (var store = new DocumentStore
            {
                Database = database,
                Urls = new[] { leader.WebUrl }
            }.Initialize())
            {
                var configuration = new RevisionsConfiguration
                {
                    Default = new RevisionsCollectionConfiguration
                    {
                        Disabled               = false,
                        PurgeOnDelete          = false,
                        MinimumRevisionsToKeep = 30
                    }
                };
                long index;
                using (var context = JsonOperationContext.ShortTermSingleUse())
                {
                    var configurationJson = DocumentConventions.Default.Serialization.DefaultConverter.ToBlittable(configuration, context);
                    (index, _) = await leader.ServerStore.ModifyDatabaseRevisions(context, database, configurationJson, Guid.NewGuid().ToString());
                }
                await WaitForRaftIndexToBeAppliedInCluster(index, TimeSpan.FromSeconds(15));

                var testServer = Servers.First(server => server.ServerStore.IsLeader() == false);

                await StoreInTransactionMode(store, 1);
                await StoreInRegularMode(store, 3);
                await DeleteInTransactionMode(store, 1);

                var result = await leader.ServerStore.SendToLeaderAsync(new DeleteDatabaseCommand(database, Guid.NewGuid().ToString())
                {
                    HardDelete = true,
                    FromNodes  = new[] { testServer.ServerStore.NodeTag },
                });

                await WaitForRaftIndexToBeAppliedInCluster(result.Index, TimeSpan.FromSeconds(10));

                var val = await WaitForValueAsync(async() => await GetMembersCount(store, database), 2, 20000);

                Assert.Equal(2, val);

                var delCount = await WaitForValueAsync(() =>
                {
                    var record = store.Maintenance.Server.Send(new GetDatabaseRecordOperation(database));
                    return(record.DeletionInProgress.Count);
                }, 0);

                Assert.Equal(0, delCount);

                await store.Maintenance.Server.SendAsync(new AddDatabaseNodeOperation(database, testServer.ServerStore.NodeTag));

                var documentDatabase = await testServer.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(database);

                await WaitAndAssertForValueAsync(() =>
                {
                    using (documentDatabase.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                        using (context.OpenReadTransaction())
                            return(Task.FromResult(documentDatabase.DocumentsStorage.RevisionsStorage.GetRevisionsCount(context, "users/1")));
                }, 5);
            }
        }
        internal void Initialize()
        {
            if (PoolConfiguration == null)
            {
                PoolConfiguration = new PoolConfiguration(this);
            }
            if (PoolConfiguration.ClientConfiguration == null)
            {
                PoolConfiguration.ClientConfiguration = this;
            }
            if (TcpKeepAliveTime != Defaults.TcpKeepAliveTime &&
                PoolConfiguration.TcpKeepAliveTime == Defaults.TcpKeepAliveTime)
            {
                PoolConfiguration.TcpKeepAliveTime = TcpKeepAliveTime;
            }
            if (TcpKeepAliveInterval != Defaults.TcpKeepAliveInterval &&
                PoolConfiguration.TcpKeepAliveInterval == Defaults.TcpKeepAliveInterval)
            {
                PoolConfiguration.TcpKeepAliveInterval = TcpKeepAliveInterval;
            }
            if (EnableTcpKeepAlives != Defaults.EnableTcpKeepAlives &&
                PoolConfiguration.EnableTcpKeepAlives == Defaults.EnableTcpKeepAlives)
            {
                PoolConfiguration.EnableTcpKeepAlives = EnableTcpKeepAlives;
            }

            if (_serversChanged)
            {
                for (var i = 0; i < _servers.Count(); i++)
                {
                    if (_servers[i].OriginalString.EndsWith("/pools"))
                    {
                        /*noop*/
                    }
                    else
                    {
                        var value = _servers[i].ToString();
                        value = string.Concat(value, value.EndsWith("/") ? "pools" : "/pools");
                        var uri = new Uri(value);
                        _servers[i] = uri;
                    }
                }
            }

            //Update the bucket configs
            foreach (var keyValue in BucketConfigs)
            {
                var bucketConfiguration = keyValue.Value;
                if (string.IsNullOrEmpty(bucketConfiguration.BucketName))
                {
                    if (string.IsNullOrWhiteSpace(keyValue.Key))
                    {
                        throw new ArgumentException("bucketConfiguration.BucketName is null or empty.");
                    }
                    bucketConfiguration.BucketName = keyValue.Key;
                }
                if (bucketConfiguration.PoolConfiguration == null || _poolConfigurationChanged)
                {
                    bucketConfiguration.PoolConfiguration = PoolConfiguration;
                }
                if (bucketConfiguration.Servers == null || HasServersChanged())
                {
                    bucketConfiguration.Servers = Servers.Select(x => x).ToList();
                }
                if (bucketConfiguration.Servers.Count == 0)
                {
                    bucketConfiguration.Servers.AddRange(Servers.Select(x => x).ToList());
                }
                if (bucketConfiguration.Port == (int)DefaultPorts.Proxy)
                {
                    var message = string.Format("Proxy port {0} is not supported by the .NET client.",
                                                bucketConfiguration.Port);
                    throw new NotSupportedException(message);
                }
                if (bucketConfiguration.UseSsl)
                {
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (UseSsl)
                {
                    //Setting ssl to true at parent level overrides child level ssl settings
                    bucketConfiguration.UseSsl = true;
                    bucketConfiguration.Port   = SslPort;
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (_useSslChanged)
                {
                    for (var i = 0; i < _servers.Count(); i++)
                    {
                        var useSsl = UseSsl || bucketConfiguration.UseSsl;
                        //Rewrite the URI's for bootstrapping to use SSL.
                        if (useSsl)
                        {
                            var oldUri = _servers[i];
                            var newUri = new Uri(string.Concat("https://", _servers[i].Host,
                                                               ":", HttpsMgmtPort, oldUri.PathAndQuery));
                            _servers[i] = newUri;
                        }
                    }
                }
                //operation lifespan: if it has changed at bucket level, use bucket level, else use global level
                if (_operationLifespanChanged)
                {
                    bucketConfiguration.UpdateOperationLifespanDefault(_operationLifespan);
                }
            }
        }
예제 #55
0
        public async Task MissingRevisions()
        {
            var(node, leader) = await CreateRaftCluster(3, watcherCluster : true);

            var database = GetDatabaseName();

            await CreateDatabaseInClusterInner(new DatabaseRecord(database), 3, leader.WebUrl, null);

            using (var store = new DocumentStore
            {
                Database = database,
                Urls = new[] { leader.WebUrl }
            }.Initialize())
            {
                var configuration = new RevisionsConfiguration
                {
                    Default = new RevisionsCollectionConfiguration
                    {
                        Disabled               = false,
                        PurgeOnDelete          = false,
                        MinimumRevisionsToKeep = 30
                    }
                };
                long index;
                using (var context = JsonOperationContext.ShortTermSingleUse())
                {
                    var configurationJson = DocumentConventions.Default.Serialization.DefaultConverter.ToBlittable(configuration, context);
                    (index, _) = await leader.ServerStore.ModifyDatabaseRevisions(context, database, configurationJson, Guid.NewGuid().ToString());
                }
                await WaitForRaftIndexToBeAppliedInCluster(index, TimeSpan.FromSeconds(15));

                await StoreInTransactionMode(store, 1);
                await StoreInRegularMode(store, 10);
                await DeleteInTransactionMode(store, 1);

                RavenServer testServer = Servers.FirstOrDefault(server => server.ServerStore.IsLeader() == false);

                var result = await DisposeServerAndWaitForFinishOfDisposalAsync(testServer);

                var val = await WaitForValueAsync(async() => await GetMembersCount(store, database), 2, 20000);

                Assert.Equal(2, val);
                testServer = GetNewServer(new ServerCreationOptions
                {
                    DeletePrevious = true,
                    RunInMemory    = false,
                    CustomSettings = new Dictionary <string, string>
                    {
                        [RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = result.Url
                    }
                });

                using (var session = store.OpenSession(new SessionOptions {
                }))
                {
                    session.Store(new User()
                    {
                        Name = "userT"
                    }, "users/1");
                    session.SaveChanges();
                    await WaitForDocumentInClusterAsync <User>((DocumentSession)session, "users/1", null, TimeSpan.FromSeconds(15));
                }

                var documentDatabase = await testServer.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(database);

                {
                    var res = WaitForValue(() =>
                    {
                        using (documentDatabase.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                            using (context.OpenReadTransaction())
                                return(documentDatabase.DocumentsStorage.RevisionsStorage.GetRevisionsCount(context, "users/1"));
                    }, 13, 15000);

                    Assert.Equal(13, res);
                }
            }
        }
예제 #56
0
 static void server_ServerNotify(object sender, Servers.NotifyEventArgs e)
 {
     Console.WriteLine(e.message);
 }
        private void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                StringReader reader = new StringReader (e.Result);
                string line;

                s = new Servers();
                s.ServerList = new List<ServerDetails>();

                do {
                    line = reader.ReadLine ();

                    if (line != null) {
                        string[] str = line.Split (',');
                        ServerDetails sd = new ServerDetails ();
                        sd.host = str [0].Substring (3).Trim();
                        sd.port = str [1].Substring (5).Trim();
                        sd.desc = str [2].Substring (5).Trim();
                        sd.country = str [13].Trim();
                        sd.state = str [14].Trim();
                        sd.county = str [15].Trim();
                        sd.open = str [7].Substring (6).Trim();
                        s.ServerList.Add (sd);
                    }
                } while (line != null);

                // Add list to the table view
                tableItems = new List<TableItem> ();

                s.ServerList.Sort ((x, y) => x.desc.CompareTo (y.desc));

                foreach (ServerDetails sd in s.ServerList) {
                    tableItems.Add (new TableItem (sd.host) {
                        Image = sd.open == "ON" ? UIImage.FromBundle("Images/state_on") : UIImage.FromBundle("Images/state_off"),
                        Port = sd.port,
                        Description = sd.desc.Length == 0 ? " " : sd.desc,
                        Country = sd.country,
                        State = sd.state,
                        County = sd.county
                    });
                }

                BeginInvokeOnMainThread (delegate {
                    _tvServers.Source = new TableSource (tableItems);
                });
                BeginInvokeOnMainThread (delegate {
                    _tvServers.ReloadData ();
                });
            }
            catch {
                MessageBoxShow("ProScanMobile", "Unable to fetch servers from database.");
            }

            BeginInvokeOnMainThread (delegate {
                _tvServers.AllowsSelection = true;
                _rcRefreshControl.EndRefreshing();
            });
        }