private void SaveToSite()
        {
            err.Clear();
            if (string.IsNullOrWhiteSpace(txtAccessPoint.Text))
            {
                err.SetError(txtAccessPoint, "主機位置不可空白");
                return;
            }

            XElement result = GetAppDeployElement();

            Connection con = new Connection();

            try
            {
                con.Connect(txtAccessPoint.Text, txtContract.Text, txtUserName.Text, txtPassword.Text);
                XmlHelper h = new XmlHelper(result.ToString(SaveOptions.None));
                con.SendRequest("Server.DeployApplication", new Envelope(h));
                con.SendRequest("LoadBalance.ReloadServer", new Envelope());
            }
            catch (Exception ex)
            {
                MessageBox.Show("部署時發生錯誤\n" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("儲存完成", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        internal static void Deploy(XmlElement siteElement, string url)
        {
            Connection connection = DeployConnect(siteElement);
            Envelope   rsp        = connection.SendRequest("UDMService.ListModules", new Envelope());
            XmlHelper  rspHelper  = new XmlHelper(rsp.Body);

            string projectName = MainForm.CurrentProject.Name;
            bool   contains    = false;

            foreach (XmlElement nameElement in rspHelper.GetElements("Module/Name"))
            {
                string name = nameElement.InnerText;
                if (name == projectName)
                {
                    contains = true;
                    break;
                }
            }

            if (contains)
            {
                XmlHelper h = new XmlHelper("<Request/>");
                h.AddElement(".", "ModuleName", projectName);
                connection.SendRequest("UDMService.UpdateModule", new Envelope(h));
                //rspHelper = new XmlHelper(rsp.Body);
            }
            else
            {
                XmlHelper h = new XmlHelper("<Request/>");
                h.AddElement(".", "URL", url);

                connection.SendRequest("UDMService.ForceRegistry", new Envelope(h));
            }
        }
Example #3
0
        private void btnSendOrderReq_Click(object sender, EventArgs e)
        {
            if (connection == null)
            {
                return;
            }
            var id1 = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            LogSafe($"Sending a new order request");
            connection.SendRequest(new OrderRequest
            {
                Amount            = int.Parse(tbAmount.Text),
                Price             = long.Parse(tbPrice.Text),
                Comment           = tbComment.Text,
                AutoCancel        = (AutoCancel)cbAutoCancel.SelectedItem,
                OrderType         = (OrderType)cbType.SelectedItem,
                OrderSide         = (OrderSide)cbSide.SelectedItem,
                TimeInForce       = (TimeInForce)cbTimeInForce.SelectedItem,
                InstrumentId      = int.Parse(tbInstrument.Text),
                ClearingAccountId = tbClearingAcc.Text,
                TraderAccountId   = tbTradingApp.Text,
                Flags             = ulong.Parse(tbFlags.Text),
                RequestId         = id1
            });
        }
        public Task <VoidResult <ResponseError> > RegisterCapability(RegistrationParams @params)
        {
            TaskCompletionSource <VoidResult <ResponseError> > tcs = new TaskCompletionSource <VoidResult <ResponseError> >();

            connection.SendRequest(
                new RequestMessage <RegistrationParams>
            {
                Id     = IdGenerator.instance.Next(),
                Method = "client/registerCapability",
                Params = @params
            },
                (VoidResponseMessage <ResponseError> res) => tcs.TrySetResult(Message.ToResult(res)));
            return(tcs.Task);
        }
Example #5
0
 /// <summary>
 /// send a new order request to the matching server through connection
 /// </summary>
 private void SendNewOrderRequest(OrderRequest req)
 {
     requestsSentByType[req.GetType()] = requestsSentByType[req.GetType()] + 1;
     statistics.IncrementOrderRequestsSend();
     try
     {
         if (connection.SendRequest(req))
         {
             statistics.IncrementSendRequestErrorCount();
         }
     }
     catch
     {
     }
 }
        private void btnTest_Click(object sender, EventArgs e)
        {
            txtInfo.Text     = string.Empty;
            txtUserInfo.Text = string.Empty;
            txtPassport.Text = string.Empty;

            Connection con = new Connection();

            con.EnableSession      = false;
            con.EnableSecureTunnel = true;
            SecurityToken stt = null;

            try
            {
                stt = this.GetSecurityToken();
                con.Connect(MainForm.CurrentProject.DevSite.AccessPoint, _contract.Name, stt);
                txtInfo.Text = "連線成功";
            }
            catch (Exception ex)
            {
                txtInfo.Text = "連線失敗 : \n" + ex.Message;
                return;
            }

            try
            {
                Envelope env = con.SendRequest("DS.Base.Connect", new Envelope());
                txtUserInfo.Text = env.Headers["UserInfo"];
                xmlSyntaxLanguage1.FormatDocument(txtUserInfo.Document);
            }
            catch
            {
            }
        }
        internal async Task Close()
        {
            GenericCommand request = NewCommand(CommandType.Session, OpType.Close);
            await Connection.SendRequest(request);

            Connection.UnRegister(Client);
        }
Example #8
0
        internal async Task <Dictionary <string, object> > UpdateInfo(string convId,
                                                                      Dictionary <string, object> attributes)
        {
            ConvCommand conv = new ConvCommand {
                Cid = convId,
            };

            conv.Attr = new JsonObjectMessage {
                Data = JsonConvert.SerializeObject(attributes)
            };
            GenericCommand request = NewCommand(CommandType.Conv, OpType.Update);

            request.ConvMessage = conv;
            GenericCommand response = await Connection.SendRequest(request);

            JsonObjectMessage attr = response.ConvMessage.AttrModified;

            // 更新自定义属性
            if (attr != null)
            {
                Dictionary <string, object> updatedAttr = JsonConvert.DeserializeObject <Dictionary <string, object> >(attr.Data);
                return(updatedAttr);
            }
            return(null);
        }
        internal static Connection DeployConnect(XmlElement siteElement)
        {
            XmlHelper h           = new XmlHelper(siteElement);
            string    accesspoint = h.GetText("AccessPoint");
            string    contract    = h.GetText("Contract");
            string    authType    = h.GetText("Authentication/@Type").ToLower();
            string    username    = h.GetText("Authentication/UserName");
            string    password    = h.GetText("Authentication/Password");
            string    issuer      = h.GetText("Authentication/Issuer");

            string url = ConvertDSNS(accesspoint);

            Connection con = new Connection();

            con.EnableSecureTunnel = true;

            SecurityToken st;

            if (authType == "basic")
            {
                st = new BasicSecurityToken(username, password);
            }
            else
            {
                Connection c = new Connection();
                c.EnableSecureTunnel = true;
                c.Connect(issuer, "", username, password);
                Envelope env = c.SendRequest("DS.Base.GetPassportToken", new Envelope());
                st = new PassportSecurityToken(env.Body.XmlString);
            }

            con.Connect(url, contract, st);
            return(con);
        }
Example #10
0
        /// <summary>
        /// Pages through LDAP results filtered by Linq spec.
        /// Caveats:
        /// (1) paging iterates through all prior pages - a limitation of LDAP,
        /// (2) sorting can only take one attribute, and that attribute must be
        /// indexed in LDAP, or the server-side sort will fail.
        /// </summary>
        /// <typeparam name="T">The mapped type.</typeparam>
        /// <param name="spec">The filter specification.</param>
        /// <param name="offsetPage">How many pages into the results. 0 = first page.</param>
        /// <param name="pageSize">Size of a page. Default = 10.</param>
        /// <param name="sortKeys">Sorting options.</param>
        /// <returns></returns>
        public virtual IEnumerable <T> PageWithPageControl <T>(
            Specification <T> spec,
            int offsetPage     = 0, int pageSize = 10,
            SortKey[] sortKeys = null
            )
            where T : IEntry, new()
        {
            ILinqSearchResponse <T> result = null;
            int curPage = 0;

            while (curPage++ <= offsetPage)
            {
                var search      = new LinqSearchRequest <T>(DistinguishedName, spec.AsExpression(), Scope);
                var pageControl = new PageResultRequestControl(pageSize);
                var soc         = new SearchOptionsControl(SearchOption.DomainScope);
                search.Controls.Add(pageControl);
                search.Controls.Add(soc);
                if (sortKeys != null)
                {
                    var sortControl = new SortRequestControl(sortKeys);
                    search.Controls.Add(sortControl);
                }
                result = Connection.SendRequest(search);
            }

            return(result?.Entries);
        }
        private void btnTest_Click(object sender, EventArgs e)
        {
            txtInfo.Text = string.Empty;
            txtUserInfo.Text = string.Empty;
            txtPassport.Text = string.Empty;

            Connection con = new Connection();
            con.EnableSession = false;
            con.EnableSecureTunnel = true;
            SecurityToken stt = null;
            try
            {
                stt = this.GetSecurityToken();
                con.Connect(MainForm.CurrentProject.DevSite.AccessPoint, _contract.Name, stt);
                txtInfo.Text = "連線成功";                
            }
            catch (Exception ex)
            {
                txtInfo.Text = "連線失敗 : \n" + ex.Message;
                return;
            }
                        
            try
            {
                Envelope env = con.SendRequest("DS.Base.Connect", new Envelope());
                txtUserInfo.Text = env.Headers["UserInfo"];
                xmlSyntaxLanguage1.FormatDocument(txtUserInfo.Document);
            }
            catch 
            {               
            }
        }
        private void ImportFromSite()
        {
            err.Clear();
            if (string.IsNullOrWhiteSpace(txtAccessPoint.Text))
            {
                err.SetError(txtAccessPoint, "主機位置不可空白");
                return;
            }

            Connection connection = new Connection();

            connection.EnableSecureTunnel = true;
            try
            {
                connection.Connect(txtAccessPoint.Text, txtContract.Text, txtUserName.Text, txtPassword.Text);
            }
            catch (Exception ex)
            {
                err.SetError(txtAccessPoint, "主機連線失敗 : \n" + ex.Message);
                return;
            }

            XmlHelper h = new XmlHelper();

            h.AddElement(".", "ApplicationName", "shared");
            Envelope env = new Envelope(h);

            env = connection.SendRequest("Server.ExportApplication", env);
            h   = new XmlHelper(env.Body);
            Console.WriteLine(h.XmlString);
            this.Import(h.GetElement("."));
        }
Example #13
0
        private void Test()
        {
            string url = this.ConvertDSNS(txtAccessPoint.Text);

            Connection con = new Connection();

            con.EnableSecureTunnel = true;

            SecurityToken st;

            if (rbBasic.Checked)
            {
                st = new BasicSecurityToken(txtBasicAccount.Text, txtBasicPassword.Text);
            }
            else
            {
                Connection c = new Connection();
                c.EnableSecureTunnel = true;
                c.Connect(txtIssuer.Text, "", txtIssuerAccount.Text, txtIssuerPassword.Text);
                Envelope env = c.SendRequest("DS.Base.GetPassportToken", new Envelope());
                st = new PassportSecurityToken(env.Body.XmlString);
            }

            con.Connect(url, txtContract.Text, st);
        }
Example #14
0
        internal async Task <LCIMPartiallySuccessResult> RemoveMembers(string convId,
                                                                       IEnumerable <string> removeIds)
        {
            ConvCommand conv = new ConvCommand {
                Cid = convId,
            };

            conv.M.AddRange(removeIds);
            // 签名参数
            if (Client.SignatureFactory != null)
            {
                LCIMSignature signature = await Client.SignatureFactory.CreateConversationSignature(convId,
                                                                                                    Client.Id,
                                                                                                    removeIds,
                                                                                                    LCIMSignatureAction.Kick);

                conv.S = signature.Signature;
                conv.T = signature.Timestamp;
                conv.N = signature.Nonce;
            }
            GenericCommand request = NewCommand(CommandType.Conv, OpType.Remove);

            request.ConvMessage = conv;
            GenericCommand response = await Connection.SendRequest(request);

            List <string>       allowedIds = response.ConvMessage.AllowedPids.ToList();
            List <ErrorCommand> errors     = response.ConvMessage.FailedPids.ToList();

            return(NewPartiallySuccessResult(allowedIds, errors));
        }
Example #15
0
        private string ConvertDSNS(string name)
        {
            if (name.StartsWith("http://", true, CultureInfo.CurrentCulture))
            {
                return(name);
            }

            if (name.StartsWith("https://", true, CultureInfo.CurrentCulture))
            {
                return(name);
            }

            Connection con = new Connection();

            con.EnableSession      = false;
            con.EnableSecureTunnel = false;
            con.Connect("http://dsns1.ischool.com.tw/dsns/", "dsns", new PublicSecurityToken());

            XmlHelper h   = new XmlHelper("<a>" + name + "</a>");
            Envelope  env = con.SendRequest("DS.NameService.GetDoorwayURL", new Envelope(h));

            h = new XmlHelper(env.Body);
            string value = h.GetText(".");

            if (string.IsNullOrWhiteSpace(value))
            {
                throw new Exception("DSNS 名稱解析失敗");
            }
            return(value);
        }
        /// <summary>
        /// 取得學生清單
        /// </summary>
        public Dictionary <string, OnlineStudent> GetStuentList(Connection me, Dictionary <string, OnlineSCJoin> SCJoinDic)
        {
            Envelope rsp      = me.SendRequest("_.GetStudentsCanChoose", new Envelope(RunService.GetRequest(null, null)));
            XElement students = XElement.Parse(rsp.Body.XmlString);

            Dictionary <string, OnlineStudent> StudentDic = new Dictionary <string, OnlineStudent>();

            foreach (XElement stud in students.Elements("Student"))
            {
                OnlineStudent os = new OnlineStudent(stud);
                os.School = me.AccessPoint.Name;

                if (!StudentDic.ContainsKey(os.Id))
                {
                    StudentDic.Add(os.Id, os);
                }

                //是否有社團參與記錄
                if (SCJoinDic.ContainsKey(os.Id))
                {
                    os.原有社團 = SCJoinDic[os.Id];
                }
            }
            return(StudentDic);
        }
        private void CallTransferInWS()
        {
            TransferInRecord record = Record;

            try
            {
                string contract = "StudentTransferHsinchuSpecial";
                string service  = "SyncTransferIn";

                SecurityToken token    = (DSAServices.DefaultDataSource.SecurityToken as SessionToken).OriginToken;
                Connection    conn     = DSAServices.DefaultDataSource.AsContract(contract, token);
                XElement      econtent = XElement.Parse(record.ModifiedContent);

                FISCA.DSAClient.XmlHelper req = new FISCA.DSAClient.XmlHelper("<Request/>");
                req.AddElement(".", "TargetSchool", GetSchoolCode());
                req.AddElement(".", "Writer", string.Format("{0}:{1}", DSAServices.AccessPoint, DSAServices.UserAccount));
                req.AddElement(".", "StudentID", econtent.XPathSelectElement("Student").ElementText("IDNumber"));
                req.AddElement(".", "StudentNumber", SRecord.StudentNumber);
                req.AddElement(".", "Grade", SRecord.Class.GradeYear + "");
                req.AddElement(".", "ClassName", SRecord.Class.Name.Substring(1));

                RTOut.WriteLine(req.XmlString);
                RTOut.WriteLine(conn.SendRequest(service, new Envelope(req)).XmlString);
            }
            catch (Exception ex)
            {
                RTOut.WriteError(ex);
            }
        }
Example #18
0
        internal async Task <List <LCIMTemporaryConversation> > GetTemporaryConversations(IEnumerable <string> convIds)
        {
            if (convIds == null || convIds.Count() == 0)
            {
                return(null);
            }
            ConvCommand convMessage = new ConvCommand();

            convMessage.TempConvIds.AddRange(convIds);
            GenericCommand request = NewCommand(CommandType.Conv, OpType.Query);

            request.ConvMessage = convMessage;
            GenericCommand response = await Connection.SendRequest(request);

            JsonObjectMessage results = response.ConvMessage.Results;
            List <object>     convs   = JsonConvert.DeserializeObject <List <object> >(results.Data,
                                                                                       LCJsonConverter.Default);
            List <LCIMTemporaryConversation> convList = convs.Select(item => {
                LCIMTemporaryConversation temporaryConversation = new LCIMTemporaryConversation(Client);
                temporaryConversation.MergeFrom(item as Dictionary <string, object>);
                return(temporaryConversation);
            }).ToList();

            return(convList);
        }
Example #19
0
        internal async Task <LCIMPartiallySuccessResult> UnblockMembers(string convId,
                                                                        IEnumerable <string> clientIds)
        {
            BlacklistCommand blacklist = new BlacklistCommand {
                SrcCid = convId,
            };

            blacklist.ToPids.AddRange(clientIds);
            if (Client.SignatureFactory != null)
            {
                LCIMSignature signature = await Client.SignatureFactory.CreateBlacklistSignature(convId,
                                                                                                 Client.Id,
                                                                                                 clientIds,
                                                                                                 LCIMSignatureAction.ConversationUnblockClients);

                blacklist.S = signature.Signature;
                blacklist.T = signature.Timestamp;
                blacklist.N = signature.Nonce;
            }
            GenericCommand request = NewCommand(CommandType.Blacklist, OpType.Unblock);

            request.BlacklistMessage = blacklist;
            GenericCommand response = await Connection.SendRequest(request);

            return(NewPartiallySuccessResult(response.BlacklistMessage.AllowedPids, response.BlacklistMessage.FailedPids));
        }
Example #20
0
        internal async Task Unmute(string convId)
        {
            ConvCommand conv = new ConvCommand {
                Cid = convId
            };
            GenericCommand request = NewCommand(CommandType.Conv, OpType.Unmute);

            request.ConvMessage = conv;
            await Connection.SendRequest(request);
        }
Example #21
0
 private static void Server_IdleTimeout(Connection connection)
 {
     connection.SendRequest <S2C_Ping, C2S_Ping>(S2C_Ping.Instance, TimeSpan.FromMilliseconds(Config.Dfs.PingInterval / 2))
     .ContinueWith(t =>
     {
         if (t.IsFaulted || t.IsCanceled)
         {
             connection.Close();
         }
     });
 }
        private async Task Refresh()
        {
            SessionCommand session = await NewSessionCommand();

            GenericCommand request = NewCommand(CommandType.Session, OpType.Refresh);

            request.SessionMessage = session;
            GenericCommand response = await Connection.SendRequest(request);

            UpdateSession(response.SessionMessage);
        }
Example #23
0
        internal async Task <int> GetMembersCount(string convId)
        {
            ConvCommand conv = new ConvCommand {
                Cid = convId,
            };
            GenericCommand command = NewCommand(CommandType.Conv, OpType.Count);

            command.ConvMessage = conv;
            GenericCommand response = await Connection.SendRequest(command);

            return(response.ConvMessage.Count);
        }
Example #24
0
        public T[] FindAll <T>(Specification <T> spec, int?limit = null)
            where T : IEntry, new()
        {
            var search = new LinqSearchRequest <T>(DistinguishedName, spec.AsExpression(), Scope);

            if (limit != null)
            {
                search.SizeLimit = limit.Value;
            }
            var result = Connection.SendRequest(search);

            return(result.Entries.ToArray());
        }
        private SearchResultEntry FindUser(IAdIdentifier identifier, IEnumerable <AdAttribute> properties)
        {
            string searchProperty;
            string searchTerm = string.Empty;

            switch (identifier)
            {
            case UpnIdentifier upn:
                searchProperty = "userPrincipalName";
                searchTerm     = upn.Upn;
                break;

            case DistinguishedName dn:
                searchProperty = "distinguishedName";
                searchTerm     = dn.Dn;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(identifier), identifier, "Not a supported identifier type");
            }

            Logger?.Debug($"Finding user by {searchProperty}, {searchTerm}, under {BaseDn.Dn}");

            var propertyList = properties.Select(p => p.Name).ToArray();

            var request = new SearchRequest(BaseDn.Dn, "(" + searchProperty + "=" + searchTerm + ")", SearchScope.Subtree, propertyList);

            // ensure these fields are always requested
            if (!request.Attributes.Contains("distinguishedName"))
            {
                request.Attributes.Add("distinguishedName");
            }
            if (!request.Attributes.Contains("objectGUID"))
            {
                request.Attributes.Add("objectGUID");
            }
            if (!request.Attributes.Contains("userPrincipalName"))
            {
                request.Attributes.Add("userPrincipalName");
            }

            // do the search
            if (Connection.SendRequest(request) is SearchResponse response && response.Entries.Count > 0)
            {
                // get the first
                var entry = response.Entries[0];

                Logger?.Debug("Found User DN: " + entry.DistinguishedName);

                return(entry);
            }
        /// <summary>
        /// 取得志願序內容
        /// </summary>
        static public List <OnlineVolunteer> GetVolunteer(Connection me, LoginSchool login, string SchoolYear, string Semester)
        {
            Envelope rsp        = me.SendRequest("_.GetStudentVolunteer", new Envelope(GetRequest(SchoolYear, Semester)));
            XElement Volunteers = XElement.Parse(rsp.Body.XmlString);
            List <OnlineVolunteer> VolunteerList = new List <OnlineVolunteer>();

            foreach (XElement Volunteer in Volunteers.Elements("K12.volunteer.universal"))
            {
                OnlineVolunteer cr = new OnlineVolunteer(Volunteer);
                cr.School = login.School_Name;
                VolunteerList.Add(cr);
            }
            return(VolunteerList);
        }
Example #27
0
        public Task <Result <ApplyWorkspaceEditResponse, ResponseError> > ApplyEdit(ApplyWorkspaceEditParams @params)
        {
            TaskCompletionSource <Result <ApplyWorkspaceEditResponse, ResponseError> > tcs = new TaskCompletionSource <Result <ApplyWorkspaceEditResponse, ResponseError> >();

            connection.SendRequest(
                new RequestMessage <ApplyWorkspaceEditParams>
            {
                Id     = IdGenerator.instance.Next(),
                Method = "workspace/applyEdit",
                Params = @params
            },
                (ResponseMessage <ApplyWorkspaceEditResponse, ResponseError> res) => tcs.TrySetResult(Message.ToResult(res)));
            return(tcs.Task);
        }
Example #28
0
        public Task <Result <MessageActionItem, ResponseError> > ShowMessageRequest(ShowMessageRequestParams @params)
        {
            var tcs = new TaskCompletionSource <Result <MessageActionItem, ResponseError> >();

            _connection.SendRequest(
                new RequestMessage <ShowMessageRequestParams>
            {
                id      = IdGenerator.Instance.Next(),
                method  = "window/showMessageRequest",
                @params = @params
            },
                (ResponseMessage <MessageActionItem, ResponseError> res) => tcs.TrySetResult(Message.ToResult(res)));
            return(tcs.Task);
        }
Example #29
0
        internal async Task <LCIMPartiallySuccessResult> UnmuteMembers(string convId,
                                                                       IEnumerable <string> clientIds)
        {
            ConvCommand conv = new ConvCommand {
                Cid = convId
            };

            conv.M.AddRange(clientIds);
            GenericCommand request = NewCommand(CommandType.Conv, OpType.RemoveShutup);

            request.ConvMessage = conv;
            GenericCommand response = await Connection.SendRequest(request);

            return(NewPartiallySuccessResult(response.ConvMessage.AllowedPids, response.ConvMessage.FailedPids));
        }
Example #30
0
        /// <summary>
        /// Retrieves current state of LDAP database and reflects it to the CMS.
        /// </summary>
        public void Synchronize()
        {
            try
            {
                var request = new SearchRequest(DefaultNamingContext, "(&(|(objectClass=user)(objectClass=group))(usnchanged>=" + (Dispatcher.HighestUsnChanged + 1) + "))", SearchScope.Subtree, null);
                request.Controls.Add(new ShowDeletedControl());

                // Page result
                var prc = new PageResultRequestControl(5);
                request.Controls.Add(prc);
                var soc = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);
                request.Controls.Add(soc);

                while (true)
                {
                    var searchResponse = (SearchResponse)Connection.SendRequest(request);

                    if (searchResponse != null)
                    {
                        // Find the returned page response control
                        foreach (DirectoryControl control in searchResponse.Controls)
                        {
                            if (control is PageResultResponseControl)
                            {
                                //update the cookie for next set
                                prc.Cookie = ((PageResultResponseControl)control).Cookie;
                                break;
                            }
                        }

                        Dispatcher.AddToQueue(searchResponse.Entries.Cast <SearchResultEntry>().Where(p => LdapHelper.IsUser(p, PersonObjectCategory) || LdapHelper.IsGroup(p, GroupObjectCategory)).ToList());

                        if (prc.Cookie.Length == 0)
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogError("Full synchronization failed.", ex);
            }
        }
        internal async Task Open(bool force)
        {
            await Connection.Connect();

            SessionCommand session = await NewSessionCommand();

            session.R            = !force;
            session.ConfigBitmap = 0xAB;
            GenericCommand request = NewCommand(CommandType.Session, OpType.Open);

            request.SessionMessage = session;
            GenericCommand response = await Connection.SendRequest(request);

            UpdateSession(response.SessionMessage);
            Connection.Register(Client);
        }
        private void buttonX1_Click(object sender, EventArgs e)
        {
            //FISCA.Authentication.DSAServices.p

            Connection con = new Connection();

            //取得局端登入後Greening發的Passport,並登入指定的Contract
            con.Connect(FISCA.Authentication.DSAServices.DefaultDataSource.AccessPoint, "ischool.kh.central_office.user", FISCA.Authentication.DSAServices.PassportToken);

            //取得該Contract所發的Passport
            Envelope Response = con.SendRequest("DS.Base.GetPassportToken", new Envelope());
            PassportToken Passport = new PassportToken(Response.Body);

            //TODO:拿此Passport登入各校
            Connection conSchool = new Connection();
            conSchool.Connect("dev.jh_kh", "ischool.kh.central_office", Passport);
        }
        internal SecurityToken GetSecurityToken()
        {
            if (!chkPassport.Checked)
            {
                return new BasicSecurityToken(txtUser.Text, txtPwd.Text);
            }
            else
            {
                Connection greenCon = new Connection();
                greenCon.EnableSecureTunnel = true;
                greenCon.EnableSession = true;
                greenCon.Connect(txtProvider.Text, string.Empty, txtUser.Text.Trim(), txtPwd.Text);

                Envelope rsp = greenCon.SendRequest("DS.Base.GetPassportToken", new Envelope());
                txtPassport.Text = rsp.Body.XmlString;
                xmlSyntaxLanguage1.FormatDocument(txtPassport.Document);
                PassportSecurityToken stt = new PassportSecurityToken(rsp.Body.XmlString);
                return stt;
            }
        }
Example #34
0
        private void Login()
        {
            string greeningURL = "http://10.1.1.163/greening2/shared";
            string moduleURL = "http://10.1.1.163/modules/shared";

            XmlDocument doc = new XmlDocument();
            string filename = Path.Combine(Environment.CurrentDirectory, "Setup.config");
            this.ShowMessage("載入設定檔");

            if (File.Exists(filename))
            {
                doc.Load(filename);
                XmlHelper config = new XmlHelper(doc.DocumentElement);
                greeningURL = config.GetText("GreeningAccessPoint");
                moduleURL = config.GetText("ModuleAccessPoint");
            }

            try
            {
                this.ShowMessage("登入 ischool ....");
                Connection greenCon = new Connection();
                greenCon.EnableSecureTunnel = true;
                greenCon.EnableSession = false;
                try 
                {
                    greenCon.Connect(greeningURL, "user", txtUser.Text.Trim(), txtPassword.Text);
                }
                catch (Exception ex)
                {
                    throw new Exception("ischool Account 認證失敗" + ex.Message);
                }

                Envelope rsp = greenCon.SendRequest("DS.Base.GetPassportToken", new Envelope());
                PassportSecurityToken stt = new PassportSecurityToken(rsp.Body.XmlString);

                XmlHelper h1 = new XmlHelper(rsp.Body);
                string id = h1.GetText("Content/Attributes/ID");

                string ftpUser = string.Empty;
                string ftpPassword = string.Empty;
                string ftpUrl = string.Empty;
                bool succeedLoginModuleService = false;
                Connection modCon = null;
                try
                {
                    this.ShowMessage("載入線上儲存空間設定...");

                    modCon = new Connection();
                    modCon.EnableSession = true;
                    modCon.EnableSecureTunnel = true;

                    modCon.Connect(moduleURL, "developer", stt);

                    Envelope env = modCon.SendRequest("GetFTPInfo", new Envelope());
                    XmlHelper h = new XmlHelper(env.Body);
                    ftpUser = TripleDESHelper.Decrypt(h.GetText("User"), USE_KEY);
                    ftpPassword = TripleDESHelper.Decrypt(h.GetText("Password"), USE_KEY);
                    ftpUrl = TripleDESHelper.Decrypt(h.GetText("FTP"), USE_KEY);
                    succeedLoginModuleService = true;
                }
                catch
                {
                    this.ShowMessage("載入失敗!");
                    succeedLoginModuleService = false;
                }
                string pwd = string.Empty;
                if (chkRemember.Checked)
                    pwd = txtPassword.Text;
                MainForm.Storage.SetPropertyValues("LoginName", txtUser.Text, pwd);
                MainForm.Storage.SetProperty("LastLoginName", txtUser.Text);
                MainForm.Storage.SetProperty("LastLoginPassword", pwd);
                MainForm.Storage.SetProperty("RememberPassword", chkRemember.Checked.ToString().ToLower());

                if (Logined != null)
                {
                    this.ShowMessage("登入開發站台...");
                    LoginEventArgs arg = new LoginEventArgs();
                    arg.FtpPassword = ftpPassword;
                    arg.FtpUser = ftpUser;
                    arg.FtpURL = ftpUrl;
                    arg.GreeningConnection = greenCon;
                    arg.ModuleConnection = modCon;
                    arg.SetModuleConnectionInfo(moduleURL);
                    arg.LoginUser = txtUser.Text;
                    arg.GreeningID = id;
                    arg.SucceedModuleLogin = succeedLoginModuleService;

                    this.ShowMessage("載入開發站台資訊");
                    Logined.Invoke(this, arg);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.ShowMessage("※請輸入 ischool Account 密碼");
            }
        }
        internal static Connection DeployConnect(XmlElement siteElement)
        {
            XmlHelper h = new XmlHelper(siteElement);
            string accesspoint = h.GetText("AccessPoint");
            string contract = h.GetText("Contract");
            string authType = h.GetText("Authentication/@Type").ToLower();
            string username = h.GetText("Authentication/UserName");
            string password = h.GetText("Authentication/Password");
            string issuer = h.GetText("Authentication/Issuer");

            string url = ConvertDSNS(accesspoint);
            
            Connection con = new Connection();
            con.EnableSecureTunnel = true;

            SecurityToken st;
            if (authType == "basic")
            {                
                st = new BasicSecurityToken(username, password);
            }
            else
            {
                Connection c = new Connection();
                c.EnableSecureTunnel = true;
                c.Connect(issuer, "", username, password);
                Envelope env = c.SendRequest("DS.Base.GetPassportToken", new Envelope());                
                st = new PassportSecurityToken(env.Body.XmlString);
            }

            con.Connect(url, contract, st);
            return con;
        }
Example #36
0
        private void buttonX1_Click(object sender, EventArgs e)
        {
            string SelectedDSNS = "" + cmbSchool.SelectedValue;
            string School = (cmbSchool.SelectedItem as School).Title;

            try
            {
                Connection con = new Connection();

                //取得局端登入後Greening發的Passport,並登入指定的Contract
                con.Connect(FISCA.Authentication.DSAServices.DefaultDataSource.AccessPoint, "ischool.kh.central_office.user", FISCA.Authentication.DSAServices.PassportToken);

                //取得該Contract所發的Passport
                Envelope Response = con.SendRequest("DS.Base.GetPassportToken", new Envelope());
                PassportToken Passport = new PassportToken(Response.Body);

                //TODO:拿此Passport登入各校
                Connection conSchool = new Connection();
                conSchool.Connect(SelectedDSNS, "ischool.kh.central_office", Passport);

                Response = conSchool.SendRequest("_.GetStudentHighConcern", new Envelope());

                //<Class>
                //  <ClassName>101</ClassName>
                //  <StudentCount>25</StudentCount>
                //  <Lock />
                //  <Comment />
                //  <NumberReduceSum />
                //  <ClassStudentCount>25</ClassStudentCount>
                //</Class>

                //班級名稱、實際人數、編班人數、編班順位、編班鎖定、鎖定備註

                XElement elmResponse = XElement.Load(new StringReader(Response.Body.XmlString));

                grdClassOrder.Rows.Clear();

                foreach (XElement elmStudent in elmResponse.Elements("Student"))
                {
                    string ClassName = elmStudent.ElementText("ClassName");
                    string StudentName = elmStudent.ElementText("StudentName");
                    string SeatNo = elmStudent.ElementText("SeatNo");
                    string HighConcern = elmStudent.ElementText("HighConcern");
                    string NumberReduce = elmStudent.ElementText("NumberReduce");
                    string DocNo = elmStudent.ElementText("DocNo");

                    grdClassOrder.Rows.Add(
                        School,
                        StudentName,
                        ClassName,
                        SeatNo,
                        NumberReduce,
                        DocNo
                    );
                }
            }
            catch (Exception ve)
            {
                MessageBox.Show(ve.Message);
            }
        }
        private void buttonX1_Click(object sender, EventArgs e)
        {
            string SelectedDSNS = "" + cmbSchool.SelectedValue;
            string School = (cmbSchool.SelectedItem as School).Title;

            try
            {

                Connection con = new Connection();

                //取得局端登入後Greening發的Passport,並登入指定的Contract
                con.Connect(FISCA.Authentication.DSAServices.DefaultDataSource.AccessPoint, "ischool.kh.central_office.user", FISCA.Authentication.DSAServices.PassportToken);

                //取得該Contract所發的Passport
                Envelope Response = con.SendRequest("DS.Base.GetPassportToken", new Envelope());
                PassportToken Passport = new PassportToken(Response.Body);

                //TODO:拿此Passport登入各校
                Connection conSchool = new Connection();
                conSchool.Connect(SelectedDSNS, "ischool.kh.central_office", Passport);

                Response = conSchool.SendRequest("_.GetClassStudentCount", new Envelope());

                //<Class>
                //  <ClassName>101</ClassName>
                //  <StudentCount>25</StudentCount>
                //  <Lock />
                //  <Comment />
                //  <NumberReduceSum />
                //  <ClassStudentCount>25</ClassStudentCount>
                //</Class>

                //班級名稱、實際人數、編班人數、編班順位、編班鎖定、鎖定備註

                XElement elmResponse = XElement.Load(new StringReader(Response.Body.XmlString));

                grdClassOrder.Rows.Clear();

                List<ClassOrder> ClassOrders = new List<ClassOrder>();

                foreach (XElement elmClass in elmResponse.Elements("Class"))
                {
                    ClassOrder vClassOrder = new ClassOrder();

                    ClassOrders.Add(vClassOrder);

                    string ClassName = elmClass.ElementText("ClassName");
                    string StudentCount = elmClass.ElementText("StudentCount");
                    string ClassStudentCount = elmClass.ElementText("ClassStudentCount");
                    string NumberReduceSum = elmClass.ElementText("NumberReduceSum");

                    if (!string.IsNullOrWhiteSpace(NumberReduceSum))
                        ClassStudentCount = ClassStudentCount + "(" + StudentCount + "+" + NumberReduceSum + ")";

                    string NumberReduceCount = elmClass.ElementText("NumberReduceCount");
                    string Lock = elmClass.ElementText("Lock");
                    string Comment = elmClass.ElementText("Comment");
                    string ClassOrder = string.Empty;

                    vClassOrder.ClassName = ClassName;
                    vClassOrder.StudentCount = StudentCount;
                    vClassOrder.ClassStudentCount = ClassStudentCount;
                    vClassOrder.NumberReduceSum = NumberReduceSum;
                    vClassOrder.NumberReduceCount = NumberReduceCount;
                    vClassOrder.Lock = Lock;
                    vClassOrder.Comment = Comment;
                    vClassOrder.ClassOrderNumber = ClassOrder;
                    vClassOrder.ClassStudentCountValue = StudentCount.GetInt() + NumberReduceSum.GetInt();
                }

                ClassOrders.CalculateClassOrder();

                foreach(ClassOrder vClassOrder in ClassOrders)
                {
                    grdClassOrder.Rows.Add(
                        School,
                        vClassOrder.ClassName,
                        vClassOrder.StudentCount,
                        vClassOrder.ClassStudentCount,
                        vClassOrder.NumberReduceCount,
                        vClassOrder.ClassOrderNumber,
                        vClassOrder.Lock,
                        vClassOrder.Comment);
                }
            }
            catch (Exception ve)
            {
                MessageBox.Show(ve.Message);
            }
        }
        private string ConvertDSNS(string name)
        {
            if(name.StartsWith("http://",true,CultureInfo.CurrentCulture))
                return name;

            if(name.StartsWith("https://",true,CultureInfo.CurrentCulture))
                return name;

            Connection con = new Connection();
            con.EnableSession = false;
            con.EnableSecureTunnel = false;
            con.Connect("http://dsns1.ischool.com.tw/dsns/", "dsns", new PublicSecurityToken());

            XmlHelper h = new XmlHelper("<a>" + name + "</a>");
            Envelope env = con.SendRequest("DS.NameService.GetDoorwayURL", new Envelope(h));
            h = new XmlHelper(env.Body);
            string value = h.GetText(".");
            if (string.IsNullOrWhiteSpace(value))
                throw new Exception("DSNS 名稱解析失敗");
            return value;
        }
        private void Test()
        {
            string url = this.ConvertDSNS(txtAccessPoint.Text);
            
            Connection con = new Connection();
            con.EnableSecureTunnel = true;

            SecurityToken st;
            if (rbBasic.Checked)
            {
                st = new BasicSecurityToken(txtBasicAccount.Text, txtBasicPassword.Text);
            }
            else
            {
                Connection c = new Connection();
                c.EnableSecureTunnel = true;
                c.Connect(txtIssuer.Text, "", txtIssuerAccount.Text, txtIssuerPassword.Text);
                Envelope env = c.SendRequest("DS.Base.GetPassportToken", new Envelope());                
                st = new PassportSecurityToken(env.Body.XmlString);
            }

            con.Connect(url, txtContract.Text, st);
        }
        private void ImportFromSite()
        {
            err.Clear();
            if (string.IsNullOrWhiteSpace(txtAccessPoint.Text))
            {
                err.SetError(txtAccessPoint, "主機位置不可空白");
                return;
            }

            Connection connection = new Connection();
            connection.EnableSecureTunnel= true;
            try
            {
                connection.Connect(txtAccessPoint.Text, txtContract.Text, txtUserName.Text, txtPassword.Text);
            }
            catch (Exception ex)
            {
                err.SetError(txtAccessPoint, "主機連線失敗 : \n" + ex.Message);
                return;
            }

            XmlHelper h = new XmlHelper();
            h.AddElement(".","ApplicationName","shared");
            Envelope env = new Envelope(h);
            
            env = connection.SendRequest("Server.ExportApplication", env);
            h = new XmlHelper(env.Body);
            Console.WriteLine(h.XmlString);
            this.Import(h.GetElement("."));
        }
        private void SaveToSite()
        {
            err.Clear();
            if (string.IsNullOrWhiteSpace(txtAccessPoint.Text))
            {
                err.SetError(txtAccessPoint, "主機位置不可空白");
                return;
            }

            XElement result = GetAppDeployElement();

            Connection con = new Connection();
            try
            {
                con.Connect(txtAccessPoint.Text, txtContract.Text, txtUserName.Text, txtPassword.Text);
                XmlHelper h = new XmlHelper(result.ToString(SaveOptions.None));
                con.SendRequest("Server.DeployApplication", new Envelope(h));
                con.SendRequest("LoadBalance.ReloadServer", new Envelope());
            }
            catch (Exception ex)
            {
                MessageBox.Show("部署時發生錯誤\n" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("儲存完成", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void Execute()
        {
            Connection con = new Connection();
            con.EnableSecureTunnel = cmSSLEnable.Checked;
            SecurityToken stt = null;
            try
            {
                stt = _sttForm.GetSecurityToken();
                con.Connect(txtSiteURL.Text, txtContract.Text, stt); ;
            }
            catch
            {
                DialogResult dr = MessageBox.Show("Service 認證失敗 ! \n 是否開啟認證設定畫面? ", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
                if (dr == System.Windows.Forms.DialogResult.Yes)
                    _sttForm.ShowDialog();
                return;
            }
            Stopwatch w = new Stopwatch();
            w.Start();
            XmlHelper req = new XmlHelper();
            if (!string.IsNullOrWhiteSpace(txtRequest.Text))
                req = XmlHelper.ParseAsHelper(txtRequest.Text);

            XmlHelper h = new XmlHelper();
            try
            {
                Envelope re = new Envelope(req);
                Envelope env = con.SendRequest(txtService.Text, re);
                txtResponse.Text = env.Body.XmlString;

                try
                {
                    h = new XmlHelper(env.Body);
                    txtResponse.Text = h.XmlString;
                    txtRequest.FormatXml();
                }
                catch { }

                txtHeader.Text = env.Headers.XmlString;
                txtHeader.FormatXml();
            }
            catch (DSAServerException ex)
            {
                txtResponse.Text = ex.Response;
                txtResponse.FormatXml();
            }
            catch (Exception ex)
            {
                txtResponse.Text = ex.Message;
            }
            w.Stop();
            tsLabelTime.Text = w.ElapsedMilliseconds.ToString();

            try
            {
                string dir = Path.Combine(Environment.CurrentDirectory, "TestServiceConfig");
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                string filename = Path.Combine(dir, this.ServiceUniqName);
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(txtRequest.Text);
                doc.Save(filename);
            }
            catch { }
        }
        internal SecurityToken GetSecurityToken()
        {
            if (_inited)
            {
                if (rbBasic.Checked)
                {
                    return new BasicSecurityToken(txtUser.Text, txtPwd.Text);
                }
                else
                {
                    Connection greenCon = new Connection();
                    greenCon.EnableSecureTunnel = true;
                    greenCon.EnableSession = true;
                    greenCon.Connect(txtProvider.Text, string.Empty, txtUser.Text.Trim(), txtPwd.Text);

                    Envelope rsp = greenCon.SendRequest("DS.Base.GetPassportToken", new Envelope());
                    PassportSecurityToken stt = new PassportSecurityToken(rsp.Body.XmlString);
                    return stt;
                }
            }
            else
            {
                XmlHelper xml = MainForm.Storage.GetPropertyXml("ServiceTestTemp", _contractUniqName);
                if (xml == null)
                {
                    return new BasicSecurityToken(MainForm.CurrentProject.DevSite.User, MainForm.CurrentProject.DevSite.Password);
                }
                else
                {
                    bool passport = xml.TryGetBoolean("UsePassport", false);
                    if (passport)
                    {
                        Connection greenCon = new Connection();
                        greenCon.EnableSecureTunnel = true;
                        greenCon.EnableSession = true;
                        greenCon.Connect(xml.GetText("Auth"), string.Empty, xml.GetText("User"), xml.GetText("Password"));

                        Envelope rsp = greenCon.SendRequest("DS.Base.GetPassportToken", new Envelope());
                        return new PassportSecurityToken(rsp.Body.XmlString);
                    }
                    else
                    {
                        return new BasicSecurityToken(xml.GetText("User"), xml.GetText("Password"));
                    }
                }
            }
        }