Beispiel #1
0
        public bool RegisterClient(SessionClass Session, System.Threading.Thread Thread)
        {
            int nIndex = 0;
            int nMaxClients = 0;
            nMaxClients = Int32.Parse(strMaxConnections);
            if (nMaxClients > 0 & ActiveClients >= nMaxClients)
            {
                return false;
            }
            Monitor.Enter(Client);
            for (nIndex = 0; nIndex < LastClient; nIndex++)
            {
                if (Client[nIndex].Session != null) continue;
                Client[nIndex].Session = Session;
                Client[nIndex].Thread = Thread;
                ActiveClients = ActiveClients + 1;
                SetServerStatus(ActiveClients.ToString() + " clients connected to server");
                Monitor.Exit(Client);
                return true;
            }
            Monitor.Exit(Client);
            var NewClient = new SessionInfo[LastClient + 1];
            System.Array.Copy(Client, NewClient, Math.Min(Client.Length, NewClient.Length));
            Client = NewClient;
            Client[LastClient].Session = Session;
            Client[LastClient].Thread = Thread;

            LastClient++;
            ActiveClients++;

            SetServerStatus(ActiveClients.ToString() + " clients connected to server");
            return true;
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (IsPostBack)
     {
         SessionInfo info = new SessionInfo();
         if (!info.getSessionData(IsPostBack, out address, out user, out binding, out hostNameIdentifier, out configName, out hoster, out version, out platform, out hostedID))
             home(false);
         hostNameIdentifier = (string)ViewState["name"];
         configName = (string)ViewState["configname"];
         version = (string)ViewState["version"];
         platform = (string)ViewState["platform"];
         hoster = (string)ViewState["hoster"];
     }
     else
     {
         Input.getHostData(IsPostBack, ViewState, out userid, out address, out user, out binding, out hostNameIdentifier, out configName, out version, out platform, out hoster, false);
         ViewState["name"] = hostNameIdentifier;
         ViewState["configname"] = configName;
         ViewState["version"] = version;
         ViewState["platform"] = platform;
         ViewState["hoster"] = hoster;
     }
     LabelReq.Text = "Measured Page Requests";
     LabelReqDay.Text = "Measured Page Requests Per Day";
     UTC.Text = DateTime.Now.ToUniversalTime().ToString("f") + " (UTC)";
     NodeRepeater.ItemDataBound += new RepeaterItemEventHandler(NodeRepeater_ItemDataBound);
     List<ServiceNode> myNodeMap = null;
     traversePath = DynamicTraversePath.getTraversePath(hostNameIdentifier, configName, ref configProxy, address, binding, user);
     if (traversePath != null && traversePath.Count > 0)
     {
         if (traversePath[traversePath.Count - 1].MyNode.Status == ConfigSettings.MESSAGE_OFFLINE)
         {
             myNodeMap = new List<ServiceNode>();
             myNodeMap.Add(traversePath[traversePath.Count - 1].MyNode);
             if (traversePath[traversePath.Count - 1].PeerNodes != null)
                 myNodeMap.AddRange(traversePath[traversePath.Count - 1].PeerNodes);
         }
     }
     VirtualHost myVhost=null;
     if (myNodeMap == null)
     {
         myVhost = configProxy.getServiceNodeMap(hostNameIdentifier, configName, traversePath, user);
         if (myVhost == null)
             return;
         myNodeMap = myVhost.ServiceNodes;
     }
     VNODETotalReqs.Text = " (" + myVhost.TotalRequests.ToString() + ")";
     VNODETotalReqsPerDay.Text = " (" + myVhost.RequestsPerDay.ToString() + ")";
     TopNode.PostBackUrl = ConfigSettings.PAGE_NODES;
     ServiceVersion.Text = version;
     ServicePlatform.Text = platform;
     ServiceHoster.Text = hoster;
     TopNodeName.Text = hostNameIdentifier;
     NodeRepeater.DataSource = myNodeMap;
     NodeRepeater.DataBind();
     ReturnLabel.Text = "<a class=\"Return\" href=\"" + ConfigSettings.PAGE_NODES + "\">Return to Home Page</a>";
     GetImageButton.runtimePoweredBy(platform, RuntimePlatform);
 }
Beispiel #3
0
 public SessionInfo GetSession()
 {
     if(this.context.Session["user_id"] != null)
     {
         SessionInfo info = new SessionInfo(this.context.Session["user_id"].ToString(), this.context.Session["first_name"].ToString(), this.context.Session["last_name"].ToString(), this.context.Session["is_moderator"].ToString(), this.context.Session["is_uploader"].ToString(), this.context.Session["is_admin"].ToString());
         return info;
     }
     else return null;
 }
 /// <summary>
 /// Delete a session for the given session info
 /// </summary>
 /// <param name="session">The session info.</param>
 public void DeleteSession(SessionInfo session)
 {
     lock (SessionsSyncLock)
     {
         if (session == null || string.IsNullOrWhiteSpace(session.SessionId)) return;
         if (m_Sessions.ContainsKey(session.SessionId) == false) return;
         m_Sessions.Remove(session.SessionId);
     }
 }
Beispiel #5
0
 public SessionInfo GetSession()
 {
     SessionInfo oSession = (SessionInfo)Session[AppConfig.AdminSession];
     if (oSession == null)
     {
         oSession = new SessionInfo();
         Session[AppConfig.AdminSession] = oSession;
     }
     return oSession;
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     Page.Form.DefaultFocus = ViewTypeHosts.ClientID;
     SessionInfo info = new SessionInfo();
     info.getSessionData(IsPostBack,out address, out user, out binding, out hostNameIdentifier, out configName, out hoster, out version, out platform, out hostedID);
     if (!(Request["version"] == "drilldown"))
         Input.getHostData(IsPostBack, ViewState, out userid, out address, out user, out binding, out hostNameIdentifier, out configName, out version, out platform, out hoster, false);
     else
     {
         hostNameIdentifier = Request["name"];
         configName = Request["cfgSvc"];
     }
     MSMQ.Visible = false;
     ConnectionRepeater.ItemDataBound += new RepeaterItemEventHandler(ConnectionRepeater_ItemDataBound);
     viewTheType = (string)Request["viewType"];
     if (viewTheType == null || viewTheType == "")
         viewTheType = ConfigUtility.HOST_TYPE_CONNECTED_SERVICE.ToString();
     viewType = Convert.ToInt32(viewTheType);
     switch (viewType)
     {
         case ConfigUtility.HOST_TYPE_CONNECTED_SERVICE:
             {
                 ViewTypeHosts.CssClass = "LoginButton";
                 ViewTypeClients.CssClass = "LoginButtonNonSelected";
                 AddConnection.Enabled = true;
                 break;
             }
         case ConfigUtility.HOST_TYPE_CONNECTED_CLIENT_CONFIG:
             {
                 ViewTypeClients.CssClass = "LoginButton";
                 ViewTypeHosts.CssClass = "LoginButtonNonSelected";
                 AddConnection.Enabled = false;
                 break;
             }
     }
     getData();
     postback = "?name=" + hostNameIdentifier + "&cfgSvc=" + configName + "&version=" + version + "&platform=" + platform + "&hoster=" + hoster;
     ConnectionRepeater.DataBind();
     TopNode.PostBackUrl = ConfigSettings.PAGE_NODES;
     ServiceVersion.Text = version;
     ServicePlatform.Text = platform;
     ServiceHoster.Text = hoster;
     TopNodeName.Text = hostNameIdentifier;
     ReturnLabel.Text = "<a class=\"Return\" href=\"" + ConfigSettings.PAGE_NODES + postback + "\">Return to Home Page</a>";
     ViewTypeHosts.PostBackUrl = ConfigSettings.PAGE_CONNECTIONS + postback + "&viewType=" + ConfigUtility.HOST_TYPE_CONNECTED_SERVICE.ToString();
     ViewTypeClients.PostBackUrl = ConfigSettings.PAGE_CONNECTIONS + postback + "&viewType=" + ConfigUtility.HOST_TYPE_CONNECTED_CLIENT_CONFIG.ToString();
     AddConnection.PostBackUrl = ConfigSettings.PAGE_ADD_CONNECTION + postback;
     GetImageButton.runtimePoweredBy(platform, RuntimePlatform);
 }
        public void HandleReport(SessionInfo report)
        {
            string output = JsonConvert.SerializeObject(report, Formatting.Indented);
            string dir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "sessionresults");

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            StreamWriter writer =
                new StreamWriter(
                    Path.Combine(
                        dir,
                        new DateTime(report.Timestamp, DateTimeKind.Utc).ToString("yyyyMMdd_HHmmss") + "_" + report.TrackName + "_"
                        + report.SessionName + ".json"));
            writer.Write(output);
            writer.Close();
            writer.Dispose();
        }
        public void TestSessionIssuerMethod()
        {
            SessionTokenIssuer.Instance.SetPurgeTimeout(new TimeSpan(0, 0, 5));

            var session1 = new SessionInfo { Expire = DateTime.UtcNow.AddMinutes(1), Session = Guid.NewGuid().ToString() };
            SessionTokenIssuer.Instance.AddOrUpdate(session1, Guid.NewGuid().ToString());
            var data = SessionTokenIssuer.Instance.Get(session1);
            Assert.IsFalse(string.IsNullOrEmpty(data));
            Assert.IsTrue(SessionTokenIssuer.Instance.Remove(session1));

            Task.Factory.StartNew(Producer);
            Task.Factory.StartNew(Consumer);

            Thread.Sleep(67000);

            Assert.IsTrue(SessionTokenIssuer.Instance.Count <= 10);
            Assert.IsTrue(SessionTokenIssuer.Instance.CountUser <= 10);

            SessionTokenIssuer.Instance.Dispose();
        }
        /// <summary>
        /// Creates a session ID, registers the session info in the Sessions collection, and returns the appropriate session cookie.
        /// </summary>
        /// <returns>The sessions.</returns>
        private System.Net.Cookie CreateSession()
        {
            lock (SessionsSyncLock)
            {
                var sessionId = Convert.ToBase64String(
                    System.Text.Encoding.UTF8.GetBytes(
                        Guid.NewGuid().ToString() + DateTime.Now.Millisecond.ToString() + DateTime.Now.Ticks.ToString()));
                var sessionCookie = string.IsNullOrWhiteSpace(CookiePath) ?
                new System.Net.Cookie(SessionCookieName, sessionId) :
                new System.Net.Cookie(SessionCookieName, sessionId, CookiePath);

                m_Sessions[sessionId] = new SessionInfo()
                {
                    SessionId = sessionId,
                    DateCreated = DateTime.Now,
                    LastActivity = DateTime.Now
                };

                return sessionCookie;
            }
        }
        public void HandleReport(SessionInfo report)
        {
            string dir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "sessionreports");

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            string filePath = Path.Combine(dir, new DateTime(report.Timestamp, DateTimeKind.Utc).ToString("yyyyMMdd_HHmmss") + "_" + report.TrackName + "_" + report.SessionName + ".xml");

            DataContractSerializer serializer = new DataContractSerializer(typeof(SessionInfo));

            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true,
                IndentChars = "\t"
            };

            using (XmlWriter writer = XmlWriter.Create(filePath, settings))
            {
                serializer.WriteObject(writer, report);
            }
        }
 public override void Initialize(SessionMapElement element, SessionInfo sessionInfo)
 {
     _sessionId  = sessionInfo.SessionId;
     _instanceId = element.Name;
     base.Initialize(element, sessionInfo);
 }
Beispiel #12
0
 void Start()
 {
     sessionInfo = SessionInfo.GetInstance();
     text.text   = preText + sessionInfo.GetSessionOwner() + postText;
 }
        public async Task <Operation> SendAsync(IOperation <OperationIdResult> operation, SessionInfo sessionInfo = null, CancellationToken token = default(CancellationToken))
        {
            using (GetContext(out JsonOperationContext context))
            {
                var command = operation.GetCommand(_store, _requestExecutor.Conventions, context, _requestExecutor.Cache);

                await _requestExecutor.ExecuteAsync(command, context, sessionInfo, token).ConfigureAwait(false);

                var node = command.SelectedNodeTag ?? command.Result.OperationNodeTag;
                return(new Operation(_requestExecutor, () => _store.Changes(_databaseName, node), _requestExecutor.Conventions, command.Result.OperationId, node));
            }
        }
        public static ReadDataServiceReply ReadLogixData(SessionInfo si, string tagAddress, ushort elementCount)
        {
            int requestSize = 0;
            ReadDataServiceRequest request = BuildLogixReadDataRequest(tagAddress, elementCount, out requestSize);

            EncapsRRData rrData = new EncapsRRData();
            rrData.CPF = new CommonPacket();
            rrData.CPF.AddressItem = CommonPacketItem.GetConnectedAddressItem(si.ConnectionParameters.O2T_CID);
            rrData.CPF.DataItem = CommonPacketItem.GetConnectedDataItem(request.Pack(), SequenceNumberGenerator.SequenceNumber);
            rrData.Timeout = 2000;

            EncapsReply reply = si.SendUnitData(rrData.CPF.AddressItem, rrData.CPF.DataItem);

            if (reply == null)
                return null;

            if (reply.Status != 0 && reply.Status != 0x06)
            {
                //si.LastSessionError = (int)reply.Status;
                return null;
            }

            return new ReadDataServiceReply(reply);
        }
 public override void StoreResults(CallbackEvent evt, AppInfo app, SessionInfo session, object results)
 {
 }
Beispiel #16
0
        private OperationReturn LoadCommentItem(SessionInfo session, ItemComment itemComment)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string     rentToken  = session.RentInfo.Token;
                ScoreSheet scoreSheet = itemComment.ScoreSheet;
                if (scoreSheet == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ScoreSheet is null");
                    return(optReturn);
                }
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_005_{0} WHERE C002 = {1}",
                            rentToken,
                            itemComment.ID);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_005_{0} WHERE C002 = {1}",
                            rentToken,
                            itemComment.ID);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                List <CommentItem> listCommentItems = new List <CommentItem>();
                for (int i = 0; i < objDataSet.Tables[0].Rows.Count; i++)
                {
                    DataRow     dr          = objDataSet.Tables[0].Rows[i];
                    CommentItem commentItem = new CommentItem();
                    commentItem.Type    = ScoreObjectType.CommentItem;
                    commentItem.ID      = Convert.ToInt64(dr["C001"]);
                    commentItem.Comment = itemComment;
                    commentItem.OrderID = Convert.ToInt32(dr["C003"]);
                    commentItem.Text    = dr["C005"].ToString();

                    listCommentItems.Add(commentItem);
                }
                optReturn.Data = listCommentItems;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
 public object Any(SessionInfo request)
 {
     var result = SessionAs<AuthUserSession>().ConvertTo<UserSessionInfo>();
     result.ProviderOAuthAccess = null;
     return result;
 }
Beispiel #18
0
        private OperationReturn LoadComment(SessionInfo session, ScoreItem scoreItem)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string     rentToken  = session.RentInfo.Token;
                ScoreSheet scoreSheet = scoreItem.ScoreSheet;
                if (scoreSheet == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ScoreSheet is null");
                    return(optReturn);
                }
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_004_{0} WHERE C002 = {1} AND C003 = {2}",
                            rentToken,
                            scoreItem.ID,
                            scoreSheet.ID);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_004_{0} WHERE C002 = {1} AND C003 = {2}",
                            rentToken,
                            scoreItem.ID,
                            scoreSheet.ID);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                List <Comment> listComments = new List <Comment>();
                for (int i = 0; i < objDataSet.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = objDataSet.Tables[0].Rows[i];
                    Comment comment;
                    int     intCommentStyle = Convert.ToInt32(dr["C008"]);
                    switch (intCommentStyle)
                    {
                    case (int)CommentStyle.Text:
                        TextComment textComment = new TextComment();
                        textComment.Type        = ScoreObjectType.TextComment;
                        textComment.DefaultText = dr["C005"].ToString();
                        comment = textComment;
                        break;

                    case (int)CommentStyle.Item:
                        ItemComment itemComment = new ItemComment();
                        itemComment.Type = ScoreObjectType.ItemComment;
                        comment          = itemComment;
                        break;

                    default:
                        optReturn.Result  = false;
                        optReturn.Code    = Defines.RET_NOT_EXIST;
                        optReturn.Message = string.Format("CommentStyle not exist");
                        return(optReturn);
                    }
                    comment.Style      = (CommentStyle)intCommentStyle;
                    comment.ID         = Convert.ToInt64(dr["C001"]);
                    comment.ScoreItem  = scoreItem;
                    comment.ScoreSheet = scoreSheet;
                    comment.OrderID    = Convert.ToInt32(dr["C004"]);
                    comment.Title      = dr["C009"].ToString();

                    #region 样式

                    OperationReturn styleReturn;
                    styleReturn = LoadVisualStyle(session, comment, "T");
                    if (!styleReturn.Result)
                    {
                        if (styleReturn.Code != Defines.RET_NOT_EXIST)
                        {
                            return(styleReturn);
                        }
                        comment.TitleStyle = null;
                    }
                    else
                    {
                        VisualStyle style = styleReturn.Data as VisualStyle;
                        if (style != null)
                        {
                            style.ScoreSheet   = scoreSheet;
                            comment.TitleStyle = style;
                        }
                    }

                    styleReturn = LoadVisualStyle(session, comment, "P");
                    if (!styleReturn.Result)
                    {
                        if (styleReturn.Code != Defines.RET_NOT_EXIST)
                        {
                            return(styleReturn);
                        }
                        comment.PanelStyle = null;
                    }
                    else
                    {
                        VisualStyle style = styleReturn.Data as VisualStyle;
                        if (style != null)
                        {
                            style.ScoreSheet   = scoreSheet;
                            comment.PanelStyle = style;
                        }
                    }

                    #endregion


                    #region 子项

                    var temp = comment as ItemComment;
                    if (temp != null)
                    {
                        OperationReturn commentItemReturn;
                        commentItemReturn = LoadCommentItem(session, temp);
                        if (!commentItemReturn.Result)
                        {
                            return(commentItemReturn);
                        }
                        List <CommentItem> listItems = commentItemReturn.Data as List <CommentItem>;
                        if (listItems == null)
                        {
                            commentItemReturn.Result  = false;
                            commentItemReturn.Code    = Defines.RET_OBJECT_NULL;
                            commentItemReturn.Message = string.Format("ListCommentItems is null");
                            return(commentItemReturn);
                        }
                        for (int j = 0; j < listItems.Count; j++)
                        {
                            temp.ValueItems.Add(listItems[j]);
                        }
                        temp.ValueItems = temp.ValueItems.OrderBy(j => j.OrderID).ToList();
                    }


                    #endregion

                    listComments.Add(comment);
                }
                optReturn.Data = listComments;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
Beispiel #19
0
        private OperationReturn LoadVisualStyle(SessionInfo session, ScoreObject scoreObject, string type)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string rentToken = session.RentInfo.Token;
                if (scoreObject == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ScoreObject is null");
                    return(optReturn);
                }
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_012_{0} WHERE C003 = {1} AND C005 = '{2}'",
                            rentToken,
                            scoreObject.ID,
                            type);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_012_{0} WHERE C003 = {1} AND C005 = '{2}'",
                            rentToken,
                            scoreObject.ID,
                            type);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                if (objDataSet.Tables[0].Rows.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_NOT_EXIST;
                    optReturn.Message = string.Format("VisualStyle not exist");
                    return(optReturn);
                }
                DataRow     dr    = objDataSet.Tables[0].Rows[0];
                VisualStyle style = new VisualStyle();
                style.ScoreObject   = scoreObject;
                style.Type          = ScoreObjectType.VisualStyle;
                style.ID            = Convert.ToInt64(dr["C001"]);
                style.FontSize      = Convert.ToInt32(dr["C006"]);
                style.StrFontWeight = dr["C007"].ToString();
                style.StrFontFamily = dr["C008"].ToString();
                style.StrForeColor  = dr["C009"].ToString();
                style.StrBackColor  = dr["C010"].ToString();
                style.Width         = Convert.ToInt32(dr["C011"]);
                style.Height        = Convert.ToInt32(dr["C012"]);

                optReturn.Data = style;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
Beispiel #20
0
        private OperationReturn LoadScoreItem(SessionInfo session, ScoreItem parent)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string     rentToken  = session.RentInfo.Token;
                ScoreSheet scoreSheet = parent.ScoreSheet;
                if (scoreSheet == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ScoreSheet is null");
                    return(optReturn);
                }
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_002_{0} WHERE C003 = {1} AND C004 = {2}",
                            rentToken,
                            scoreSheet.ID,
                            parent.ID);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_002_{0} WHERE C003 = {1} AND C004 = {2}",
                            rentToken,
                            scoreSheet.ID,
                            parent.ID);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                List <ScoreItem> listItems = new List <ScoreItem>();
                for (int i = 0; i < objDataSet.Tables[0].Rows.Count; i++)
                {
                    DataRow   dr = objDataSet.Tables[0].Rows[i];
                    ScoreItem scoreItem;
                    bool      isStandard = dr["C009"].ToString() == "Y";
                    if (isStandard)
                    {
                        Standard     standard     = null;
                        StandardType standardType = (StandardType)Convert.ToInt32(dr["C015"]);
                        switch (standardType)
                        {
                        case StandardType.Numeric:
                            NumericStandard numericStandard = new NumericStandard();
                            numericStandard.Type         = ScoreObjectType.NumericStandard;
                            numericStandard.MaxValue     = Convert.ToDouble(dr["C027"]);
                            numericStandard.MinValue     = Convert.ToDouble(dr["C028"]);
                            numericStandard.DefaultValue = string.IsNullOrWhiteSpace(dr["C029"].ToString()) ? 0 : Convert.ToDouble(dr["C029"]);
                            numericStandard.ScoreClassic = StandardClassic.TextBox;
                            standard = numericStandard;
                            break;

                        case StandardType.YesNo:
                            YesNoStandard yesNoStandard = new YesNoStandard();
                            yesNoStandard.Type = ScoreObjectType.YesNoStandard;
                            if (string.IsNullOrWhiteSpace(dr["C029"].ToString()))
                            {
                                yesNoStandard.DefaultValue = false;
                            }
                            else
                            {
                                if (Convert.ToDouble(dr["C029"]) == 1.0)
                                {
                                    yesNoStandard.DefaultValue = true;
                                }
                                else
                                {
                                    yesNoStandard.DefaultValue = false;
                                }
                            }
                            yesNoStandard.ReverseDisplay = dr["C104"].ToString() == "1";
                            yesNoStandard.ScoreClassic   = StandardClassic.YesNo;
                            standard = yesNoStandard;
                            break;

                        case StandardType.Slider:
                            SliderStandard sliderStandard = new SliderStandard();
                            sliderStandard.Type         = ScoreObjectType.SliderStandard;
                            sliderStandard.MinValue     = Convert.ToDouble(dr["C023"]);
                            sliderStandard.MaxValue     = Convert.ToDouble(dr["C024"]);
                            sliderStandard.Interval     = Convert.ToDouble(dr["C026"]);
                            sliderStandard.DefaultValue = string.IsNullOrWhiteSpace(dr["C029"].ToString()) ? 0 : Convert.ToDouble(dr["C029"]);
                            sliderStandard.ScoreClassic = StandardClassic.Slider;
                            standard = sliderStandard;
                            break;

                        case StandardType.Item:
                            ItemStandard itemStandard = new ItemStandard();
                            itemStandard.Type         = ScoreObjectType.ItemStandard;
                            itemStandard.DefaultIndex = string.IsNullOrWhiteSpace(dr["C029"].ToString())?0: Convert.ToInt32(dr["C029"]);
                            itemStandard.ScoreClassic = StandardClassic.DropDownList;
                            standard = itemStandard;
                            break;
                        }
                        if (standard == null)
                        {
                            optReturn.Result  = false;
                            optReturn.Code    = Defines.RET_OBJECT_NULL;
                            optReturn.Message = string.Format("Standard is null");
                            return(optReturn);
                        }
                        standard.PointSystem    = Convert.ToDouble(dr["C018"]);
                        standard.StandardType   = standardType;
                        standard.IsAutoStandard = dr["C101"].ToString() == "Y";
                        string strStaID = dr["C102"].ToString();
                        long   staID;
                        if (long.TryParse(strStaID, out staID))
                        {
                            standard.StatisticalID = staID;
                        }
                        scoreItem = standard;
                    }
                    else
                    {
                        ScoreGroup scoreGroup = new ScoreGroup();
                        scoreGroup.Type  = ScoreObjectType.ScoreGroup;
                        scoreGroup.IsAvg = dr["C016"].ToString() == "Y";
                        scoreItem        = scoreGroup;
                    }
                    scoreItem.ScoreSheet     = parent.ScoreSheet;
                    scoreItem.Parent         = parent;
                    scoreItem.ItemID         = Convert.ToInt32(dr["C001"]);
                    scoreItem.ID             = Convert.ToInt64(dr["C002"]);
                    scoreItem.OrderID        = Convert.ToInt32(dr["C005"]);
                    scoreItem.Title          = dr["C006"].ToString();
                    scoreItem.Description    = dr["C007"].ToString();
                    scoreItem.TotalScore     = Convert.ToDouble(dr["C008"]);
                    scoreItem.IsAbortScore   = dr["C010"].ToString() == "Y";
                    scoreItem.ControlFlag    = dr["C011"].ToString() == "Y" ? 1 : 0;
                    scoreItem.IsKeyItem      = dr["C012"].ToString() == "Y";
                    scoreItem.IsAllowNA      = dr["C013"].ToString() == "Y";
                    scoreItem.IsJumpItem     = dr["C014"].ToString() == "Y";
                    scoreItem.IsAddtionItem  = dr["C017"].ToString() == "Y";
                    scoreItem.UsePointSystem = dr["C019"].ToString() == "Y";
                    scoreItem.ScoreType      = dr["C020"].ToString() == "F"
                        ? ScoreType.YesNo
                        : dr["C020"].ToString() == "P" ? ScoreType.Pecentage : ScoreType.Numeric;
                    scoreItem.Tip = dr["C022"].ToString();
                    scoreItem.AllowModifyScore = dr["C103"].ToString() == "Y";

                    #region 子项

                    //如果是 ScoreGroup 加载子项
                    if (!isStandard)
                    {
                        ScoreGroup scoreGroup = scoreItem as ScoreGroup;
                        optReturn = LoadScoreItem(session, scoreGroup);
                        if (!optReturn.Result)
                        {
                            return(optReturn);
                        }
                        List <ScoreItem> subItems = optReturn.Data as List <ScoreItem>;
                        if (subItems == null)
                        {
                            optReturn.Result  = false;
                            optReturn.Code    = Defines.RET_OBJECT_NULL;
                            optReturn.Message = string.Format("ListItems is null");
                            return(optReturn);
                        }
                        for (int j = 0; j < subItems.Count; j++)
                        {
                            ScoreItem subItem = subItems[j];
                            scoreGroup.Items.Add(subItem);
                        }
                        scoreGroup.Items = scoreGroup.Items.OrderBy(j => j.OrderID).ToList();
                    }

                    //如果是多值型评分标准,加载评分标准子项
                    ItemStandard temp = scoreItem as ItemStandard;
                    if (temp != null)
                    {
                        optReturn = LoadStandardItem(session, temp);
                        if (!optReturn.Result)
                        {
                            return(optReturn);
                        }
                        List <StandardItem> valueItems = optReturn.Data as List <StandardItem>;
                        if (valueItems == null)
                        {
                            optReturn.Result  = false;
                            optReturn.Code    = Defines.RET_OBJECT_NULL;
                            optReturn.Message = string.Format("ValueItems is null");
                            return(optReturn);
                        }
                        for (int j = 0; j < valueItems.Count; j++)
                        {
                            StandardItem valueItem = valueItems[j];
                            temp.ValueItems.Add(valueItem);
                        }
                        temp.ValueItems = temp.ValueItems.OrderBy(j => j.OrderID).ToList();
                    }

                    #endregion


                    #region 备注

                    OperationReturn commentReturn;
                    commentReturn = LoadComment(session, scoreItem);
                    if (!commentReturn.Result)
                    {
                        return(commentReturn);
                    }
                    List <Comment> listComments = commentReturn.Data as List <Comment>;
                    if (listComments == null)
                    {
                        optReturn.Result  = false;
                        optReturn.Code    = Defines.RET_OBJECT_NULL;
                        optReturn.Message = string.Format("listComments is null");
                        return(optReturn);
                    }
                    for (int j = 0; j < listComments.Count; j++)
                    {
                        Comment comment = listComments[j];
                        scoreItem.Comments.Add(comment);
                    }
                    scoreItem.Comments = scoreItem.Comments.OrderBy(j => j.OrderID).ToList();

                    #endregion


                    #region 样式

                    OperationReturn styleReturn;
                    styleReturn = LoadVisualStyle(session, scoreItem, "T");
                    if (!styleReturn.Result)
                    {
                        if (styleReturn.Code != Defines.RET_NOT_EXIST)
                        {
                            return(styleReturn);
                        }
                        scoreItem.TitleStyle = null;
                    }
                    else
                    {
                        VisualStyle style = styleReturn.Data as VisualStyle;
                        if (style != null)
                        {
                            style.ScoreSheet     = scoreSheet;
                            scoreItem.TitleStyle = style;
                        }
                    }

                    styleReturn = LoadVisualStyle(session, scoreItem, "P");
                    if (!styleReturn.Result)
                    {
                        if (styleReturn.Code != Defines.RET_NOT_EXIST)
                        {
                            return(styleReturn);
                        }
                        scoreItem.PanelStyle = null;
                    }
                    else
                    {
                        VisualStyle style = styleReturn.Data as VisualStyle;
                        if (style != null)
                        {
                            style.ScoreSheet     = scoreSheet;
                            scoreItem.PanelStyle = style;
                        }
                    }

                    #endregion


                    listItems.Add(scoreItem);
                }
                optReturn.Data = listItems;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
Beispiel #21
0
        private OperationReturn LoadScoreSheet(SessionInfo session, string scoreSheetID)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string  rentToken = session.RentInfo.Token;
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_001_{0} WHERE C001 = {1}",
                            rentToken,
                            scoreSheetID);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_001_{0} WHERE C001 = {1}",
                            rentToken,
                            scoreSheetID);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                if (objDataSet.Tables[0].Rows.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_NOT_EXIST;
                    optReturn.Message = string.Format("ScoreSheet not exist");
                    return(optReturn);
                }
                DataRow    dr         = objDataSet.Tables[0].Rows[0];
                ScoreSheet scoreSheet = new ScoreSheet();
                scoreSheet.Type          = ScoreObjectType.ScoreSheet;
                scoreSheet.ScoreSheet    = scoreSheet;
                scoreSheet.ID            = Convert.ToInt64(dr["C001"]);
                scoreSheet.Title         = dr["C002"].ToString();
                scoreSheet.ViewClassic   = dr["C003"].ToString() == "C" ? ScoreItemClassic.Table : ScoreItemClassic.Tree;
                scoreSheet.TotalScore    = Convert.ToDouble(dr["C004"]);
                scoreSheet.Creator       = Convert.ToInt64(dr["C005"]);
                scoreSheet.CreateTime    = Convert.ToDateTime(dr["C006"]);
                scoreSheet.DateFrom      = Convert.ToDateTime(dr["C009"]);
                scoreSheet.DateTo        = Convert.ToDateTime(dr["C010"]);
                scoreSheet.QualifiedLine = Convert.ToDouble(dr["C011"]);
                scoreSheet.ScoreType     = dr["C014"].ToString() == "F"
                    ? ScoreType.YesNo
                    : dr["C014"].ToString() == "P" ? ScoreType.Pecentage : ScoreType.Numeric;
                scoreSheet.UseTag            = Convert.ToInt32(dr["C017"]);
                scoreSheet.Description       = dr["C019"].ToString();
                scoreSheet.CalAdditionalItem = dr["C020"].ToString() != "N";
                scoreSheet.UsePointSystem    = dr["C021"].ToString() != "N";
                string strScoreWidth = dr["C101"].ToString();
                string strTipWidth = dr["C102"].ToString();
                double intScoreWidth, intTipWidth;
                if (double.TryParse(strScoreWidth, out intScoreWidth))
                {
                    scoreSheet.ScoreWidth = intScoreWidth;
                }
                if (double.TryParse(strTipWidth, out intTipWidth))
                {
                    scoreSheet.TipWidth = intTipWidth;
                }
                scoreSheet.HasAutoStandard  = dr["C103"].ToString() != "N";
                scoreSheet.AllowModifyScore = dr["C104"].ToString() != "N";

                #region 子项

                //加载子项
                optReturn = LoadScoreItem(session, scoreSheet);
                if (!optReturn.Result)
                {
                    return(optReturn);
                }
                List <ScoreItem> listItems = optReturn.Data as List <ScoreItem>;
                if (listItems == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ListItems is null");
                    return(optReturn);
                }
                for (int i = 0; i < listItems.Count; i++)
                {
                    ScoreItem scoreItem = listItems[i];
                    scoreSheet.Items.Add(scoreItem);
                }
                scoreSheet.Items = scoreSheet.Items.OrderBy(i => i.OrderID).ToList();

                #endregion


                #region 样式

                OperationReturn styleReturn;
                styleReturn = LoadVisualStyle(session, scoreSheet, "T");
                if (!styleReturn.Result)
                {
                    if (styleReturn.Code != Defines.RET_NOT_EXIST)
                    {
                        return(styleReturn);
                    }
                    scoreSheet.TitleStyle = null;
                }
                else
                {
                    VisualStyle style = styleReturn.Data as VisualStyle;
                    if (style != null)
                    {
                        style.ScoreSheet      = scoreSheet;
                        scoreSheet.TitleStyle = style;
                    }
                }

                styleReturn = LoadVisualStyle(session, scoreSheet, "P");
                if (!styleReturn.Result)
                {
                    if (styleReturn.Code != Defines.RET_NOT_EXIST)
                    {
                        return(styleReturn);
                    }
                    scoreSheet.PanelStyle = null;
                }
                else
                {
                    VisualStyle style = styleReturn.Data as VisualStyle;
                    if (style != null)
                    {
                        style.ScoreSheet      = scoreSheet;
                        scoreSheet.PanelStyle = style;
                    }
                }

                #endregion


                #region 备注

                OperationReturn commentReturn;
                commentReturn = LoadComment(session, scoreSheet);
                if (!commentReturn.Result)
                {
                    return(commentReturn);
                }
                List <Comment> listComments = commentReturn.Data as List <Comment>;
                if (listComments == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("listComments is null");
                    return(optReturn);
                }
                for (int i = 0; i < listComments.Count; i++)
                {
                    Comment comment = listComments[i];
                    scoreSheet.Comments.Add(comment);
                }
                scoreSheet.Comments = scoreSheet.Comments.OrderBy(j => j.OrderID).ToList();

                #endregion


                #region 控制项

                OperationReturn controlReturn;
                controlReturn = LoadControlItem(session, scoreSheet);
                if (!controlReturn.Result)
                {
                    return(controlReturn);
                }
                List <ControlItem> listControlItems = controlReturn.Data as List <ControlItem>;
                if (listControlItems == null)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("ListCotnrolItems is null");
                    return(optReturn);
                }
                for (int i = 0; i < listControlItems.Count; i++)
                {
                    ControlItem controlItem = listControlItems[i];
                    scoreSheet.ControlItems.Add(controlItem);
                }
                scoreSheet.ControlItems = scoreSheet.ControlItems.OrderBy(j => j.OrderID).ToList();

                #endregion

                optReturn.Data = scoreSheet;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
Beispiel #22
0
        private OperationReturn LoadControlItem(SessionInfo session, ScoreSheet scoreSheet)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                string  rentToken = session.RentInfo.Token;
                string  strSql;
                DataSet objDataSet;
                switch (session.DBType)
                {
                case 2:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_007_{0} WHERE C002 = {1}",
                            rentToken,
                            scoreSheet.ID);
                    optReturn = MssqlOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                case 3:
                    strSql =
                        string.Format(
                            "SELECT * FROM T_31_007_{0} WHERE C002 = {1}",
                            rentToken,
                            scoreSheet.ID);
                    optReturn = OracleOperation.GetDataSet(session.DBConnectionString, strSql);
                    if (!optReturn.Result)
                    {
                        return(optReturn);
                    }
                    objDataSet = optReturn.Data as DataSet;
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_PARAM_INVALID;
                    optReturn.Message = string.Format("DBType invalid");
                    return(optReturn);
                }
                if (objDataSet == null || objDataSet.Tables.Count <= 0)
                {
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_OBJECT_NULL;
                    optReturn.Message = string.Format("DataSet is null or DataTables empty");
                    return(optReturn);
                }
                List <ControlItem> listControlItems = new List <ControlItem>();
                for (int i = 0; i < objDataSet.Tables[0].Rows.Count; i++)
                {
                    DataRow     dr          = objDataSet.Tables[0].Rows[i];
                    ControlItem controlItem = new ControlItem();
                    controlItem.Type       = ScoreObjectType.ControlItem;
                    controlItem.ID         = Convert.ToInt64(dr["C001"]);
                    controlItem.ScoreSheet = scoreSheet;
                    controlItem.SourceID   = Convert.ToInt64(dr["C003"]);
                    controlItem.JugeType   = (JugeType)Convert.ToInt32(dr["C004"]);
                    controlItem.JugeValue1 = Convert.ToDouble(dr["C005"]);
                    controlItem.JugeValue2 = string.IsNullOrEmpty(dr["C006"].ToString())
                        ? 0
                        : Convert.ToDouble(dr["C006"]);
                    controlItem.UsePonitSystem = dr["C007"].ToString() == "2";
                    controlItem.TargetID       = Convert.ToInt64(dr["C008"]);
                    controlItem.TargetType     = Convert.ToInt32(dr["C009"]);
                    controlItem.ChangeType     = (ChangeType)Convert.ToInt32(dr["C010"]);
                    controlItem.ChangeValue    = Convert.ToDouble(dr["C011"]);
                    controlItem.OrderID        = Convert.ToInt32(dr["C012"]);
                    controlItem.Title          = dr["C013"].ToString();

                    listControlItems.Add(controlItem);
                }
                optReturn.Data = listControlItems;
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
            }
            return(optReturn);
        }
Beispiel #23
0
 /// <summary>
 /// Updates ping of a session.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="request">The update.</param>
 private void HandlePingUpdateRequest(SessionInfo session, PlaybackRequest request)
 {
     // Collected pings are used to account for network latency when unpausing playback
     _group.UpdatePing(session, request.Ping ?? _group.DefaulPing);
 }
Beispiel #24
0
        // 读者登记
        public ActionResult PatronEdit(string code, string state)
        {
            string strError = "";
            int    nRet     = 0;

            // 检查当前是否已经选择了图书馆绑定了帐号
            WxUserItem activeUser = null;

            nRet = this.GetActive(code, state,
                                  out activeUser,
                                  out strError);
            if (nRet == -1)
            {
                goto ERROR1;
            }
            if (nRet == 0)
            {
                ViewBag.RedirectInfo = dp2WeiXinService.GetSelLibLink(state, "/Library/PatronEdit");
                return(View());
            }



            //绑定的工作人员账号 需要有权限
            string weixinId = ViewBag.weixinId;//(string)Session[WeiXinConst.C_Session_WeiXinId];
            string libId    = ViewBag.LibId;


            if (activeUser == null || activeUser.type != WxUserDatabase.C_Type_Worker ||
                activeUser.userName == "public")
            {
                ViewBag.RedirectInfo = dp2WeiXinService.GetLinkHtml("读者登记", "/Library/PatronEdit", true);
                return(View());
            }
            ViewBag.userName = activeUser.userName;

            // 读者类别
            string[] libraryList = activeUser.libraryCode.Split(new [] { ',' });

            SessionInfo sessionInfo = this.GetSessionInfo1();
            string      types       = sessionInfo.readerTypes;
            string      typesHtml   = "";

            if (String.IsNullOrEmpty(types) == false)
            {
                string[] typeList = types.Split(new char[] { ',' });
                foreach (string type in typeList)
                {
                    // 如果这个类型的分馆 是当前帐户可用的分馆,才列出来
                    if (activeUser.libraryCode != "")
                    {
                        int nIndex = type.LastIndexOf("}");
                        if (nIndex > 0)
                        {
                            string left = type.Substring(0, nIndex);
                            nIndex = left.IndexOf("{");
                            if (nIndex != -1)
                            {
                                left = left.Substring(nIndex + 1);

                                if (libraryList.Contains(left) == true)
                                {
                                    typesHtml += "<option value='" + type + "'>" + type + "</option>";
                                }
                            }
                        }
                    }
                    else
                    {
                        typesHtml += "<option value='" + type + "'>" + type + "</option>";
                    }
                }
            }

            typesHtml = "<select id='selReaderType' name='selReaderType' class='selArrowRight'>"
                        + "<option value=''>请选择</option>"
                        + typesHtml
                        + "</select>";

            ViewBag.readerTypeHtml = typesHtml;

            // 目标数据库
            string dbs     = sessionInfo.readerDbnames;
            string dbsHtml = "";

            if (String.IsNullOrEmpty(dbs) == false)
            {
                string[] dbList = dbs.Split(new char[] { ',' });
                foreach (string db in dbList)
                {
                    dbsHtml += "<option value='" + db + "'>" + db + "</option>";
                }
            }
            if (dbsHtml != "")
            {
                dbsHtml = "<select id='selDbName' name='selDbName' class='selArrowRight'>"
                          + "<option value=''>请选择</option>"
                          + dbsHtml
                          + "</select>";
            }
            ViewBag.readerDbnamesHtml = dbsHtml;



            return(View());


ERROR1:
            ViewBag.Error = strError;
            return(View());
        }
Beispiel #25
0
 public SessionInfo findSessionType(SessionInfo.sessionType type)
 {
     int index = sessions.FindIndex(s => s.Type.Equals(type));
     if (index >= 0)
     {
         return SessionList[index];
     }
     else
     {
         return new SessionInfo();
     }
 }
Beispiel #26
0
        /// <inheritdoc />
        public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            ResumePlaying = true;

            var setQueueStatus = context.SetPlayQueue(request.PlayingQueue, request.PlayingItemPosition, request.StartPositionTicks);

            if (!setQueueStatus)
            {
                _logger.LogError("Unable to set playing queue in group {GroupId}.", context.GroupId.ToString());

                // Ignore request and return to previous state.
                IGroupState newState = prevState switch {
                    GroupStateType.Playing => new PlayingGroupState(LoggerFactory),
                    GroupStateType.Paused => new PausedGroupState(LoggerFactory),
                    _ => new IdleGroupState(LoggerFactory)
                };

                context.SetState(newState);
                return;
            }

            var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
            var update          = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);

            context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);

            // Reset status of sessions and await for all Ready events.
            context.SetAllBuffering(true);

            _logger.LogDebug("Session {SessionId} set a new play queue in group {GroupId}.", session.Id, context.GroupId.ToString());
        }
Beispiel #27
0
 protected void Page_Load(object sender, EventArgs e)
 {
     string hostedID = null;
     Page.Form.DefaultFocus = SoaMapButton.ClientID;
     Input.getHostData(IsPostBack, ViewState, out userid, out address, out user, out binding,out hostNameIdentifier, out configName, out theVersion, out thePlatform, out theHoster, true);
     if (IsPostBack)
     {
         SessionInfo info = new SessionInfo();
         info.getSessionData(false, out address, out user, out binding, out hostNameIdentifier, out configName, out theHoster, out theVersion, out thePlatform, out hostedID);
     }
     InProcessRepeater.ItemDataBound += new RepeaterItemEventHandler(InProcessRepeater_ItemDataBound);
     CompositeServicesRepeater.ItemDataBound += new RepeaterItemEventHandler(CompositeServicesRepeater_ItemDataBound);
     List<ServiceConfigurationData> blankData = new List<ServiceConfigurationData>();
     ServiceConfigurationData blankItem = new ServiceConfigurationData();
     blankItem.ServiceHost = "-";
     blankItem.ServiceContract = "-";
     blankItem.Status = "-";
     blankData.Add(blankItem);
     int level;
     string levelString = (string)Request["level"];
     if (levelString == null)
         level = ConfigUtility.CONFIG_LEVEL_BASIC;
     else
     {
         level = Convert.ToInt32(levelString);
     }
     TopNode.PostBackUrl = ConfigSettings.PAGE_NODES;
     string action = Request["action"];
     if (action != "navigate")
     {
         traversePath = DynamicTraversePath.getTraversePath(hostNameIdentifier, configName, ref configProxy, address, binding, user);
         compositeServiceData = configProxy.getServiceConfiguration(hostNameIdentifier, configName, level, true, traversePath, user);
         if (compositeServiceData != null)
         {
             if (compositeServiceData.Count > 0 && compositeServiceData[0] != null)
             {
                 string postback = "?name=" + compositeServiceData[0].ServiceHost + "&cfgSvc=" + compositeServiceData[0].ConfigServiceImplementationClassName + "&version=" + compositeServiceData[0].ServiceVersion + "&platform=" + compositeServiceData[0].RunTimePlatform + "&hoster=" + compositeServiceData[0].ServiceHoster;
                 Hosted.PostBackUrl = ConfigSettings.PAGE_VHOSTS + postback;
                 Connected.PostBackUrl = ConfigSettings.PAGE_CONNECTED_SERVICES + postback;
                 Connections.PostBackUrl = ConfigSettings.PAGE_CONNECTIONS + postback;
                 Logs.PostBackUrl = ConfigSettings.PAGE_AUDIT + postback;
                 Users.PostBackUrl = ConfigSettings.PAGE_USERS + postback;
                 InProcessRepeater.DataSource = compositeServiceData;
                 InProcessRepeater.DataBind();
                 TopNodeName.Text = hostNameIdentifier;
                 ServiceVersion.Text = theVersion;
                 ServiceHoster.Text = "" + theHoster;
                 ServicePlatform.Text = "" + thePlatform;
                 GetImageButton.runtimePoweredBy(thePlatform, RuntimePlatform);
                 if (compositeServiceData[0].ConnectedServiceConfigurationData != null && compositeServiceData[0].ConnectedServiceConfigurationData.Count > 0)
                 {
                     CompositeServicesRepeater.DataSource = compositeServiceData[0].ConnectedServiceConfigurationData;
                 }
                 else
                 {
                     CompositeServicesRepeater.DataSource = blankData;
                 }
                 CompositeServicesRepeater.DataBind();
             }
             else
                 Response.Redirect(ConfigSettings.PAGE_NODES,true);
         }
         else
         {
             Response.Redirect(ConfigSettings.PAGE_LOGOUT,true);
         }
     }
 }
Beispiel #28
0
        /// <inheritdoc />
        public override void HandleRequest(SetPlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            ResumePlaying = true;

            var result = context.SetPlayingItem(request.PlaylistItemId);

            if (result)
            {
                var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem);
                var update          = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
                context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);

                // Reset status of sessions and await for all Ready events.
                context.SetAllBuffering(true);
            }
            else
            {
                // Return to old state.
                IGroupState newState = prevState switch
                {
                    GroupStateType.Playing => new PlayingGroupState(LoggerFactory),
                    GroupStateType.Paused => new PausedGroupState(LoggerFactory),
                    _ => new IdleGroupState(LoggerFactory)
                };

                context.SetState(newState);

                _logger.LogDebug("Unable to change current playing item in group {GroupId}.", context.GroupId.ToString());
            }
        }
		public static WriteDataServiceReply WriteLogixData(SessionInfo si, string tagAddress, ushort dataType, ushort elementCount, byte[] data, ushort structHandle)
Beispiel #30
0
        // DoOperChange()和DoOperMove()的下级函数
        // 合并新旧记录
        // return:
        //      -1  出错
        //      0   正确
        //      1   有部分修改没有兑现。说明在strError中
        public override int MergeTwoItemXml(
            SessionInfo sessioninfo,
            XmlDocument domExist,
            XmlDocument domNew,
            out string strMergedXml,
            out string strError)
        {
            strMergedXml = "";
            strError = "";
            int nRet = 0;

            if (sessioninfo != null
&& sessioninfo.Account != null
&& sessioninfo.UserType == "reader")
            {
                strError = "期库记录不允许读者进行修改";
                return -1;
            }

            // 算法的要点是, 把"新记录"中的要害字段, 覆盖到"已存在记录"中

            /*
            // 要害元素名列表
            string[] element_names = new string[] {
                "parent",
                "state",    // 状态
                "publishTime",  // 出版时间
                "issue",    // 当年期号
                "zong",   // 总期号
                "volume",   // 卷号
                "orderInfo",    // 订购信息
                "comment",  // 注释
                "batchNo"   // 批次号
            };
             * */

            bool bControlled = true;
            {
                XmlNode nodeExistRoot = domExist.DocumentElement.SelectSingleNode("orderInfo");
                if (nodeExistRoot != null)
                {
                    // 是否全部订购信息片断中的馆藏地点都在当前用户管辖之下?
                    // return:
                    //      -1  出错
                    //      0   不是全部都在管辖范围内
                    //      1   都在管辖范围内
                    nRet = IsAllOrderControlled(nodeExistRoot,
                        sessioninfo.LibraryCodeList,
                        out strError);
                    if (nRet == -1)
                        return -1;
                    if (nRet == 0)
                        bControlled = false;
                }

                if (bControlled == true)
                {
                    // 再看新内容是不是也全部在管辖之下
                    XmlNode nodeNewRoot = domNew.DocumentElement.SelectSingleNode("orderInfo");
                    if (nodeNewRoot != null)
                    {
                        // 是否全部订购信息片断中的馆藏地点都在当前用户管辖之下?
                        // return:
                        //      -1  出错
                        //      0   不是全部都在管辖范围内
                        //      1   都在管辖范围内
                        nRet = IsAllOrderControlled(nodeNewRoot,
                            sessioninfo.LibraryCodeList,
                            out strError);
                        if (nRet == -1)
                            return -1;
                        if (nRet == 0)
                            bControlled = false;
                    }
                }
            }

            if (bControlled == true // 控制了全部用到的馆藏地点的情形,也可以修改基本字段。并且具有删除 <orderInfo> 中某些片断的能力,只要新记录中不包含这些片断,就等于删除了
                || sessioninfo.GlobalUser == true) // 只有全局用户才能修改基本字段
            {
                for (int i = 0; i < core_issue_element_names.Length; i++)
                {
                    /*
                    string strTextNew = DomUtil.GetElementText(domNew.DocumentElement,
                        element_names[i]);

                    DomUtil.SetElementText(domExist.DocumentElement,
                        element_names[i], strTextNew);
                     * */
                    // 2009/10/24 changed inner-->outer
                    string strTextNew = DomUtil.GetElementOuterXml(domNew.DocumentElement,
                        core_issue_element_names[i]);

                    DomUtil.SetElementOuterXml(domExist.DocumentElement,
                        core_issue_element_names[i], strTextNew);
                }
            }

            // 分馆用户要特意单独处理<orderInfo>元素
            if (sessioninfo.GlobalUser == false
                && bControlled == false)
            {
                // 分馆用户提交的<orderInfo>元素内可能包含的<root>元素个数要较少,但并不意味着要删除多余的<root>元素
                XmlNode nodeNewRoot = domNew.DocumentElement.SelectSingleNode("orderInfo");
                XmlNode nodeExistRoot = domExist.DocumentElement.SelectSingleNode("orderInfo");
                if (nodeNewRoot != null && nodeExistRoot == null)
                {
                    //strError = "不允许分馆用户为期记录增补<orderInfo>元素";    // 必须以前的记录就存在<orderInfo>元素
                    //return -1;
                    // 增补
                    nodeExistRoot = domExist.CreateElement("orderInfo");
                    domExist.DocumentElement.AppendChild(nodeExistRoot);
                }

                if (nodeNewRoot == null || nodeExistRoot == null)
                    goto END1;

                // 在已经存在的记录中找出当前用户能管辖的订购片断
                List<XmlNode> exists_overwriteable_nodes = new List<XmlNode>();
                XmlNodeList exist_nodes = nodeExistRoot.SelectNodes("*");
                foreach (XmlNode exist_node in exist_nodes)
                {
                    string strRefID = DomUtil.GetElementText(exist_node, "refID");
                    if (string.IsNullOrEmpty(strRefID) == true)
                        continue;   // 无法定位,所以跳过?
                    string strDistribute = DomUtil.GetElementText(exist_node, "distribute");
                    if (string.IsNullOrEmpty(strDistribute) == true)
                        continue;

                    // 观察一个馆藏分配字符串,看看是否在当前用户管辖范围内
                    // return:
                    //      -1  出错
                    //      0   超过管辖范围。strError中有解释
                    //      1   在管辖范围内
                    nRet = DistributeInControlled(strDistribute,
                sessioninfo.LibraryCodeList,
                out strError);
                    if (nRet == -1)
                        return -1;
                    if (nRet == 1)
                    {
                        exists_overwriteable_nodes.Add(exist_node);
                    }
                }

                // 对新提交的记录中的每个订购片断进行循环
                XmlNodeList new_nodes = nodeNewRoot.SelectNodes("*");
                foreach (XmlNode new_node in new_nodes)
                {
                    string strRefID = DomUtil.GetElementText(new_node, "refID");
                    if (string.IsNullOrEmpty(strRefID) == true)
                    {
                        // 前端提交的一个订购片断refid为空
                        strError = "期记录中的订购XML片断其<refID>元素内容不能为空";
                        return -1;
                    }
                    XmlNode exist_node = nodeExistRoot.SelectSingleNode("*[./refID[text()='" + strRefID + "']]");
                    if (exist_node == null)
                    {
                        // 前端提交的一个订购片断匹配不上refid
                        // 如果新增的XML片断,其中distribute字符串表明全部在管辖范围,还是允许新增
                        string strDistribute = DomUtil.GetElementText(new_node, "distribute");
                        if (string.IsNullOrEmpty(strDistribute) == false)
                        {

                            // 观察一个馆藏分配字符串,看看是否在当前用户管辖范围内
                            // return:
                            //      -1  出错
                            //      0   超过管辖范围。strError中有解释
                            //      1   在管辖范围内
                            nRet = DistributeInControlled(strDistribute,
                        sessioninfo.LibraryCodeList,
                        out strError);
                            if (nRet == -1)
                                return -1;
                            if (nRet == 0)
                            {
                                strError = "受当前用户的分馆用户身份限制,期记录中不允许新增(包括了超出管辖范围馆代码的)订购XML片断。(refID='" + strRefID + "')";
                                return -1;
                            }
                        }

                        // 在domExit中追加
                        XmlNode new_frag = domExist.CreateElement("root");
                        new_frag.InnerXml = new_node.InnerXml;
                        nodeExistRoot.AppendChild(new_frag);
                        continue;
                    }

                    Debug.Assert(exist_node != null, "");

                    string strTempMergedXml = "";
                    // 将两个订购XML片断合并
                    // parameters:
                    //      strLibraryCodeList  当前用户管辖的分馆代码列表
                    // return:
                    //      -1  出错
                    //      0   正常
                    //      1   发生了超越范围的修改
                    nRet = MergeOrderNode(exist_node,
            new_node,
            sessioninfo.LibraryCodeList,
            out strTempMergedXml,
            out strError);
                    if (nRet != 0)
                    {
                        strError = "对期记录中 refid 为 '" + strRefID + "' 的订购片断数据修改超过权限范围: " + strError;
                        return -1;
                    }
                    exist_node.InnerXml = strTempMergedXml;

                    exists_overwriteable_nodes.Remove(exist_node);  // 已经修改过的已存在节点,从数组中去掉
                }

                // 删除那些在新记录中没有出现的,但当前用户实际上能管辖的节点
                foreach (XmlNode node in exists_overwriteable_nodes)
                {
                    node.ParentNode.RemoveChild(node);
                }
            }

        END1:
            strMergedXml = domExist.OuterXml;
            return 0;
        }
Beispiel #31
0
        /// <summary>
        /// 获得会话
        /// </summary>
        /// <returns></returns>
        public string GetSession()
        {
            string returnStr = "";

            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return(returnStr);
            }

            if (GetParam("auth_token") == null)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return(returnStr);
            }

            string auth_token = GetParam("auth_token").ToString().Replace("[", "+");
            string a          = Discuz.Common.DES.Decode(auth_token, Secret.Substring(0, 10));

            string[] userstr = a.Split(',');
            if (userstr.Length != 3)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return(returnStr);
            }

            int            olid   = Utils.StrToInt(userstr[0], -1);
            OnlineUserInfo oluser = OnlineUsers.GetOnlineUser(olid);

            if (oluser == null)
            {
                ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
                return(returnStr);
            }
            string time = DateTime.Parse(oluser.Lastupdatetime).ToString("yyyy-MM-dd HH:mm:ss");

            if (time != userstr[1])
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return(returnStr);
            }
            byte[] md5_result = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(olid.ToString() + Secret));

            StringBuilder sessionkey_builder = new StringBuilder();

            foreach (byte b in md5_result)
            {
                sessionkey_builder.Append(b.ToString("x2"));
            }

            string      sessionkey = string.Format("{0}-{1}", sessionkey_builder.ToString(), oluser.Userid.ToString());
            SessionInfo session    = new SessionInfo();

            session.SessionKey = sessionkey;
            session.UId        = oluser.Userid;
            session.UserName   = oluser.Username;
            session.Expires    = Utils.StrToInt(userstr[2], 0);

            if (Format == FormatType.JSON)
            {
                returnStr = string.Format(@"{{""session_key"":""{0}"",""uid"":{1},""user_name"":""{2}"",""expires"":{3}}}", sessionkey, Uid, session.UserName, session.Expires);
            }
            else
            {
                returnStr = SerializationHelper.Serialize(session);
            }

            OnlineUsers.UpdateAction(olid, UserAction.Login.ActionID, 0, GeneralConfigs.GetConfig().Onlinetimeout);

            return(returnStr);
        }
Beispiel #32
0
        // parameters:
        //      strBrowseInfoStyle  返回的特性。cols 返回实体记录的浏览列
        public LibraryServerResult GetCallNumberSearchResult(
            SessionInfo sessioninfo,
            string strArrangeGroupName,
            string strResultSetName,
            long lStart,
            long lCount,
            string strBrowseInfoStyle,
            string strLang,
            out CallNumberSearchResult[] searchresults)
        {
            string strError = "";
            searchresults = null;

            LibraryServerResult result = new LibraryServerResult();
            // int nRet = 0;
            long lRet = 0;

            if (String.IsNullOrEmpty(strArrangeGroupName) == true)
            {
                strError = "strArrangeGroupName参数值不能为空";
                goto ERROR1;
            }

            if (strArrangeGroupName[0] == '!')
            {
                string strTemp = GetArrangeGroupName(strArrangeGroupName.Substring(1));

                if (strTemp == null)
                {
                    strError = "馆藏地点名 " + strArrangeGroupName.Substring(1) + " 没有找到对应的排架体系名";
                    goto ERROR1;
                }
                strArrangeGroupName = strTemp;
            }

            RmsChannel channel = sessioninfo.Channels.GetChannel(this.WsUrl);
            if (channel == null)
            {
                result.Value = -1;
                result.ErrorInfo = "get channel error";
                result.ErrorCode = ErrorCode.SystemError;
                return result;
            }


            if (String.IsNullOrEmpty(strResultSetName) == true)
                strResultSetName = "default";

            bool bCols = StringUtil.IsInList("cols", strBrowseInfoStyle);

            string strBrowseStyle = "keyid,id,key";
            if (bCols == true)
                strBrowseStyle += ",cols,format:cfgs/browse_callnumber";

            Record[] origin_searchresults = null; //

            lRet = channel.DoGetSearchResult(
                strResultSetName,
                lStart,
                lCount,
                strBrowseStyle, // "id",
                strLang,
                null,
                out origin_searchresults,
                out strError);
            if (lRet == -1)
                goto ERROR1;

            long lResultCount = lRet;


            searchresults = new CallNumberSearchResult[origin_searchresults.Length];

            for (int i = 0; i < origin_searchresults.Length; i++)
            {
                CallNumberSearchResult item = new CallNumberSearchResult();

                Record record = origin_searchresults[i];
                item.ItemRecPath = record.Path;
                searchresults[i] = item;

                string strLocation = "";
                item.CallNumber = BuildAccessNoKeyString(record.Keys, out strLocation);

                if (bCols == true && record.Cols != null)
                {
                    if (record.Cols.Length > 0)
                        item.ParentID = record.Cols[0];
                    if (record.Cols.Length > 1)
                        item.Location = record.Cols[1];
                    if (record.Cols.Length > 2)
                        item.Barcode = record.Cols[2];
                }

                if (string.IsNullOrEmpty(item.Location) == true)
                    item.Location = strLocation;    // 用从keys中得来的代替。可能有大小写的差异 --- keys中都是大写
#if NO
                if (bCols == true)
                {
                    // 继续填充其余成员
                    string strXml = "";
                    string strMetaData = "";
                    byte[] timestamp = null;
                    string strOutputPath = "";

                    lRet = channel.GetRes(item.ItemRecPath,
                        out strXml,
                        out strMetaData,
                        out timestamp,
                        out strOutputPath,
                        out strError);
                    if (lRet == -1)
                    {
                        item.ErrorInfo = "获取记录 '" + item.ItemRecPath + "' 出错: " + strError;
                        continue;
                    }

                    XmlDocument dom = new XmlDocument();
                    try
                    {
                        dom.LoadXml(strXml);
                    }
                    catch (Exception ex)
                    {
                        item.ErrorInfo = "记录 '" + item.ItemRecPath + "' XML装载到DOM时出错: " + ex.Message;
                        continue;
                    }

                    /*
                    item.CallNumber = DomUtil.GetElementText(dom.DocumentElement,
                        "accessNo");
                     * */
                    item.ParentID = DomUtil.GetElementText(dom.DocumentElement,
                        "parent");
                    item.Location = DomUtil.GetElementText(dom.DocumentElement,
                        "location");
                    item.Barcode = DomUtil.GetElementText(dom.DocumentElement,
                        "barcode");
                }
#endif
            }

            result.Value = lResultCount;
            return result;
        ERROR1:
            result.Value = -1;
            result.ErrorCode = ErrorCode.SystemError;
            result.ErrorInfo = strError;
            return result;
        }
 public override object Invoke(AppInfo app, SessionInfo session, AbstractCallback.EventListener listener)
 {
     return(null);
 }
Beispiel #34
0
        // 设置种次号尾号
        public LibraryServerResult SetOneClassTailNumber(
            SessionInfo sessioninfo,
            string strAction,
            string strArrangeGroupName,
            string strClass,
            string strTestNumber,
            out string strOutputNumber)
        {
            strOutputNumber = "";

            string strError = "";

            LibraryServerResult result = new LibraryServerResult();

            RmsChannel channel = sessioninfo.Channels.GetChannel(this.WsUrl);
            if (channel == null)
            {
                strError = "get channel error";
                goto ERROR1;
            }

            string strPath = "";
            string strXml = "";
            byte[] timestamp = null;
            // 检索尾号记录的路径和记录体
            // return:
            //      -1  error
            //      0   not found
            //      1   found
            int nRet = SearchOneClassTailNumberPathAndRecord(
                // sessioninfo.Channels,
                channel,
                strArrangeGroupName,
                strClass,
                out strPath,
                out strXml,
                out timestamp,
                out strError);
            if (nRet == -1)
                goto ERROR1;

            string strZhongcihaoDbName = GetTailDbName(strArrangeGroupName);
            if (String.IsNullOrEmpty(strZhongcihaoDbName) == true)
            {
                // TODO: 这里报错还需要精确一些,对于带有'!'的馆藏地点名
                strError = "无法通过排架体系名 '" + strArrangeGroupName + "' 获得种次号库名";
                goto ERROR1;
            }

            // byte[] baOutputTimestamp = null;
            bool bNewRecord = false;
            long lRet = 0;

#if NO
            RmsChannel channel = sessioninfo.Channels.GetChannel(this.WsUrl);
            if (channel == null)
            {
                strError = "get channel error";
                goto ERROR1;
            }
#endif

            byte[] output_timestamp = null;
            string strOutputPath = "";

            if (strAction == "conditionalpush")
            {

                if (nRet == 0)
                {
                    // 新创建记录
                    strPath = strZhongcihaoDbName + "/?";
                    strXml = "<r c='" + strClass + "' v='" + strTestNumber + "'/>";

                    bNewRecord = true;
                }
                else
                {
                    string strPartXml = "/xpath/<locate>@v</locate><action>Push</action>";
                    strPath += strPartXml;
                    strXml = strTestNumber;

                    bNewRecord = false;
                }

                lRet = channel.DoSaveTextRes(strPath,
                    strXml,
                    false,
                    "content",
                    timestamp,   // timestamp,
                    out output_timestamp,
                    out strOutputPath,
                    out strError);
                if (lRet == -1)
                {
                    strError = "保存尾号记录时出错: " + strError;
                    goto ERROR1;
                }

                if (bNewRecord == true)
                {
                    strOutputNumber = strTestNumber;
                }
                else
                {
                    strOutputNumber = strError;
                }

                goto END1;
            }
            else if (strAction == "increase")
            {
                string strDefaultNumber = strTestNumber;

                if (nRet == 0)
                {
                    // 新创建记录
                    strPath = strZhongcihaoDbName + "/?";
                    strXml = "<r c='" + strClass + "' v='" + strDefaultNumber + "'/>";

                    bNewRecord = true;
                }
                else
                {
                    string strPartXml = "/xpath/<locate>@v</locate><action>+AddInteger</action>";
                    strPath += strPartXml;
                    strXml = "1";

                    bNewRecord = false;
                }

                // 
                lRet = channel.DoSaveTextRes(strPath,
                    strXml,
                    false,
                    "content",
                    timestamp,   // timestamp,
                    out output_timestamp,
                    out strOutputPath,
                    out strError);
                if (lRet == -1)
                {
                    strError = "保存尾号记录时出错: " + strError;
                    goto ERROR1;
                }

                if (bNewRecord == true)
                {
                    strOutputNumber = strDefaultNumber;
                }
                else
                {
                    strOutputNumber = strError;
                }

                goto END1;
            }
            else if (strAction == "save")
            {
                string strTailNumber = strTestNumber;

                if (nRet == 0)
                {
                    strPath = strZhongcihaoDbName + "/?";
                }
                else
                {
                    // 覆盖记录
                    if (String.IsNullOrEmpty(strPath) == true)
                    {
                        strError = "记录存在时strPath居然为空";
                        goto ERROR1;
                    }
                }

                strXml = "<r c='" + strClass + "' v='" + strTailNumber + "'/>";

                lRet = channel.DoSaveTextRes(strPath,
    strXml,
    false,
    "content",
    timestamp,   // timestamp,
    out output_timestamp,
    out strOutputPath,
    out strError);
                if (lRet == -1)
                {
                    if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch)
                    {
                        strError = "尾号记录时间戳不匹配,说明可能被他人修改过。详细原因: " + strError;
                        goto ERROR1;
                    }

                    strError = "保存尾号记录时出错: " + strError;
                    goto ERROR1;
                }

            }
            else
            {
                strError = "无法识别的strAction参数值 '" + strAction + "'";
                goto ERROR1;
            }

        END1:
            result.Value = 1;
            return result;
        ERROR1:
            result.Value = -1;
            result.ErrorCode = ErrorCode.SystemError;
            result.ErrorInfo = strError;
            return result;
        }
 public Operation Send(IOperation <OperationIdResult> operation, SessionInfo sessionInfo = null)
 {
     return(AsyncHelpers.RunSync(() => SendAsync(operation, sessionInfo)));
 }
Beispiel #36
0
        // [外部调用]
        // 创建内存和物理存储对象
        public int CreateCommentColumn(
            SessionInfo sessioninfo,
            System.Web.UI.Page page,
            out string strError)
        {
            this.m_lockCommentColumn.AcquireWriterLock(m_nCommentColumnLockTimeout);
            try
            {
                strError = "";
                int nRet = 0;

                if (sessioninfo.Account == null
    || StringUtil.IsInList("managecache", sessioninfo.RightsOrigin) == false)
                {
                    strError = "当前帐户不具备 managecache 权限,不能创建栏目缓存";
                    return -1;
                }

                this.CloseCommentColumn();

                if (page != null
                    && page.Response.IsClientConnected == false)	// 灵敏中断
                {
                    strError = "中断";
                    return -1;
                }

                if (this.CommentColumn == null)
                    this.CommentColumn = new ColumnStorage();

                this.CommentColumn.ReadOnly = false;
                this.CommentColumn.m_strBigFileName = this.StorageFileName;
                this.CommentColumn.m_strSmallFileName = this.StorageFileName + ".index";

                this.CommentColumn.Open(true);
                this.CommentColumn.Clear();
                // 检索
                nRet = SearchTopLevelArticles(
                    sessioninfo,
                    page,
                    out strError);
                if (nRet == -1)
                    return -1;

                // 排序
                if (page != null)
                {
                    page.Response.Write("--- begin sort ...<br/>");
                    page.Response.Flush();
                }

                DateTime time = DateTime.Now;

                this.CommentColumn.Sort();

                if (page != null)
                {
                    TimeSpan delta = DateTime.Now - time;
                    page.Response.Write("sort end. time=" + delta.ToString() + "<br/>");
                    page.Response.Flush();
                }

                // 保存物理文件
                string strTemp1;
                string strTemp2;
                this.CommentColumn.Detach(out strTemp1,
                    out strTemp2);

                this.CommentColumn.ReadOnly = true;

                this.CloseCommentColumn();

                // 重新装载
                nRet = LoadCommentColumn(
                    this.StorageFileName,
                    out strError);
                if (nRet == -1)
                    return -1;

                return 0;
            }
            finally
            {
                this.m_lockCommentColumn.ReleaseWriterLock();
            }
        }
Beispiel #37
0
        // DoOperChange()和DoOperMove()的下级函数
        // 合并新旧记录
        // return:
        //      -1  出错
        //      0   正确
        //      1   有部分修改没有兑现。说明在strError中
        public override int MergeTwoItemXml(
            SessionInfo sessioninfo,
            XmlDocument domExist,
            XmlDocument domNew,
            out string strMergedXml,
            out string strError)
        {
            strMergedXml = "";
            strError     = "";

            string[] element_table = core_comment_element_names;

            if (sessioninfo != null &&
                sessioninfo.Account != null &&
                sessioninfo.UserType == "reader")
            {
                element_table = readerchangeable_comment_element_names;
            }

            // 算法的要点是, 把"新记录"中的要害字段, 覆盖到"已存在记录"中

            /*
             * // 要害元素名列表
             * string[] element_names = new string[] {
             *  "parent",   // 父记录ID。也就是所从属的上一级评注记录的id
             *  "index",    // 编号
             *  "state",    // 状态
             *  "title",    // 标题
             *  "creator",  // 创建者
             *  "createTime",   // 创建时间
             *  "lastModifyTime",    // 最后修改时间
             *  "root",   // 根记录ID。也就是所从属的书目记录ID
             *  "content", // 文字内容
             * };*/

            for (int i = 0; i < element_table.Length; i++)
            {
                /*
                 * string strTextNew = DomUtil.GetElementText(domNew.DocumentElement,
                 *  core_comment_element_names[i]);
                 *
                 * DomUtil.SetElementText(domExist.DocumentElement,
                 *  core_comment_element_names[i], strTextNew);
                 * */
                string strTextNew = DomUtil.GetElementOuterXml(domNew.DocumentElement,
                                                               element_table[i]);

                DomUtil.SetElementOuterXml(domExist.DocumentElement,
                                           element_table[i], strTextNew);
            }

            // 清除以前的<dprms:file>元素
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

            nsmgr.AddNamespace("dprms", DpNs.dprms);

            XmlNodeList nodes = domExist.DocumentElement.SelectNodes("//dprms:file", nsmgr);

            foreach (XmlNode node in nodes)
            {
                node.ParentNode.RemoveChild(node);
            }
            // 兑现新记录中的 dprms:file 元素
            nodes = domNew.DocumentElement.SelectNodes("//dprms:file", nsmgr);
            foreach (XmlElement node in nodes)
            {
                XmlDocumentFragment frag = domExist.CreateDocumentFragment();
                frag.InnerXml = node.OuterXml;
                domExist.DocumentElement.AppendChild(frag);
            }

            /*
             * // 2012/10/3
             * // 当前用户所管辖的馆代码
             * DomUtil.SetElementText(domExist.DocumentElement,
             *  "libraryCode",
             *  sessioninfo.LibraryCodeList);
             * */
            // 修改者不能改变最初的馆代码
            strMergedXml = domExist.OuterXml;
            return(0);
        }
Beispiel #38
0
        // 将更新卡户信息完整表(AccountsCompleteInfo_yyyymmdd.xml)写入读者库
        // return:
        //      -1  error
        //      0   succeed
        //      1   中断
        int WriteToReaderDb(string strLocalFilePath,
            out string strError)
        {
            strError = "";
            int nRet = 0;

            XmlNode node = this.App.LibraryCfgDom.DocumentElement.SelectSingleNode("//zhengyuan/replication");

            if (node == null)
            {
                strError = "尚未配置<zhangyuan><replication>参数";
                return -1;
            }

            string strMapDbName = DomUtil.GetAttr(node, "mapDbName");
            if (String.IsNullOrEmpty(strMapDbName) == true)
            {
                strError = "尚未配置<zhangyuan/replication>元素的mapDbName属性";
                return -1;
            }

            Stream file = File.Open(strLocalFilePath,
                FileMode.Open,
                FileAccess.Read);

            if (file.Length == 0)
                return 0;

            try
            {

                XmlTextReader reader = new XmlTextReader(file);

                bool bRet = false;

                // 临时的SessionInfo对象
                SessionInfo sessioninfo = new SessionInfo(this.App);

                // 模拟一个账户
                Account account = new Account();
                account.LoginName = "replication";
                account.Password = "";
                account.Rights = "setreaderinfo";

                account.Type = "";
                account.Barcode = "";
                account.Name = "replication";
                account.UserID = "replication";
                account.RmsUserName = this.App.ManagerUserName;
                account.RmsPassword = this.App.ManagerPassword;

                sessioninfo.Account = account;

                // 找到根
                while (true)
                {
                    try
                    {
                        bRet = reader.Read();
                    }
                    catch (Exception ex)
                    {
                        strError = "读XML文件发生错误: " + ex.Message;
                        return -1;
                    }

                    if (bRet == false)
                    {
                        strError = "没有根元素";
                        return -1;
                    }
                    if (reader.NodeType == XmlNodeType.Element)
                        break;
                }

                for (int i = 0; ; i++)
                {
                    if (this.Stopped == true)
                        return 1;


                    bool bEnd = false;
                    // 第二级元素
                    while (true)
                    {
                        bRet = reader.Read();
                        if (bRet == false)
                        {
                            bEnd = true;  // 结束
                            break;
                        }
                        if (reader.NodeType == XmlNodeType.Element)
                            break;
                    }

                    if (bEnd == true)
                        break;

                    this.AppendResultText("处理 " + (i + 1).ToString() + "\r\n");

                    // 记录体
                    string strXml = reader.ReadOuterXml();

                    // return:
                    //      -1  error
                    //      0   已经写入
                    //      1   没有必要写入
                    nRet = WriteOneReaderInfo(
                        sessioninfo,
                        strMapDbName,
                        strXml,
                        out strError);
                    if (nRet == -1)
                        return -1;

                }

                return 0;
            }
            finally
            {
                file.Close();
            }
        }
Beispiel #39
0
        /// <inheritdoc />
        public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            if (prevState.Equals(GroupStateType.Idle))
            {
                ResumePlaying = true;
                context.RestartCurrentItem();

                var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
                var update          = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
                context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);

                // Reset status of sessions and await for all Ready events.
                context.SetAllBuffering(true);

                _logger.LogDebug("Group {GroupId} is waiting for all ready events.", context.GroupId.ToString());
            }
            else
            {
                if (ResumePlaying)
                {
                    _logger.LogDebug("Forcing the playback to start in group {GroupId}. Group-wait is disabled until next state change.", context.GroupId.ToString());

                    // An Unpause request is forcing the playback to start, ignoring sessions that are not ready.
                    context.SetAllBuffering(false);

                    // Change state.
                    var playingState = new PlayingGroupState(LoggerFactory)
                    {
                        IgnoreBuffering = true
                    };
                    context.SetState(playingState);
                    playingState.HandleRequest(request, context, Type, session, cancellationToken);
                }
                else
                {
                    // Group would have gone to paused state, now will go to playing state when ready.
                    ResumePlaying = true;

                    // Notify relevant state change event.
                    SendGroupStateUpdate(context, request, session, cancellationToken);
                }
            }
        }
 public override string RetrieveContentInjection(AppInfo app, SessionInfo session, CallbackPageContext context)
 {
     return(string.Empty);
 }
Beispiel #41
0
        // 记录是否允许删除?
        // return:
        //      -1  出错。不允许删除。
        //      0   不允许删除,因为权限不够等原因。原因在strError中
        //      1   可以删除
        public override int CanDelete(
            SessionInfo sessioninfo,
            XmlDocument domExist,
            out string strError)
        {
            strError = "";
            if (sessioninfo == null)
            {
                strError = "sessioninfo == null";
                return -1;
            }

            if (sessioninfo.GlobalUser == false)
            {
                XmlNode nodeExistRoot = domExist.DocumentElement.SelectSingleNode("orderInfo");
                if (nodeExistRoot != null)
                {
                    // 是否全部订购信息片断中的馆藏地点都在当前用户管辖之下?
                    // return:
                    //      -1  出错
                    //      0   不是全部都在管辖范围内
                    //      1   都在管辖范围内
                    int nRet = IsAllOrderControlled(nodeExistRoot,
                        sessioninfo.LibraryCodeList,
                        out strError);
                    if (nRet == -1)
                        return -1;
                    if (nRet == 0)
                    {
                        strError = "因出现了超越当前用户管辖范围的分馆馆藏信息,删除期记录的操作被拒绝:" + strError;
                        return 0;
                    }
                }
            }
            return 1;
        }
Beispiel #42
0
        /// <inheritdoc />
        public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            // Wait for sessions to be ready, then switch to paused state.
            ResumePlaying = false;

            // Notify relevant state change event.
            SendGroupStateUpdate(context, request, session, cancellationToken);
        }
Beispiel #43
0
        // 获得种次号尾号
        public LibraryServerResult GetOneClassTailNumber(
            SessionInfo sessioninfo,
            string strArrangeGroupName,
            string strClass,
            out string strTailNumber)
        {
            strTailNumber = "";

            string strError = "";

            LibraryServerResult result = new LibraryServerResult();

            if (String.IsNullOrEmpty(strArrangeGroupName) == true)
            {
                strError = "strArrangeGroupName参数值不能为空";
                goto ERROR1;
            }

            RmsChannel channel = sessioninfo.Channels.GetChannel(this.WsUrl);
            if (channel == null)
            {
                strError = "get channel error";
                goto ERROR1;
            }

            string strPath = "";
            string strXml = "";
            byte[] timestamp = null;
            // 检索尾号记录的路径和记录体
            // return:
            //      -1  error
            //      0   not found
            //      1   found
            int nRet = SearchOneClassTailNumberPathAndRecord(
                // sessioninfo.Channels,
                channel,
                strArrangeGroupName,
                strClass,
                out strPath,
                out strXml,
                out timestamp,
                out strError);
            if (nRet == -1)
                goto ERROR1;

            if (nRet == 0)
            {
                result.ErrorCode = ErrorCode.NotFound;
                result.ErrorInfo = strError;
                result.Value = 0;
                return result;
            }

            XmlDocument dom = new XmlDocument();
            try
            {
                dom.LoadXml(strXml);
            }
            catch (Exception ex)
            {
                strError = "尾号记录 '" + strPath + "' XML装入DOM时发生错误: " + ex.Message;
                goto ERROR1;
            }

            strTailNumber = DomUtil.GetAttr(dom.DocumentElement, "v");

            result.Value = 1;
            return result;
        ERROR1:
            result.Value = -1;
            result.ErrorCode = ErrorCode.SystemError;
            result.ErrorInfo = strError;
            return result;
        }
Beispiel #44
0
        /// <inheritdoc />
        public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            // Change state.
            var idleState = new IdleGroupState(LoggerFactory);

            context.SetState(idleState);
            idleState.HandleRequest(request, context, Type, session, cancellationToken);
        }
Beispiel #45
0
        // (根据一定排架体系)检索出某一类的同类书的索取号
        // parameters:
        //      strArrangeGroupName 排架体系名。如果为"!xxx"形式,表示通过馆藏地点名来暗示排架体系名
        public LibraryServerResult SearchOneClassCallNumber(
            SessionInfo sessioninfo,
            string strArrangeGroupName,
            string strClass,
            string strResultSetName,
            out string strQueryXml)
        {
            strQueryXml = "";

            string strError = "";

            LibraryServerResult result = new LibraryServerResult();

            if (String.IsNullOrEmpty(strArrangeGroupName) == true)
            {
                strError = "strArrangeGroupName参数值不能为空";
                goto ERROR1;
            }

            if (strArrangeGroupName[0] == '!')
            {
                string strTemp = GetArrangeGroupName(strArrangeGroupName.Substring(1));

                if (strTemp == null)
                {
                    strError = "馆藏地点名 " + strArrangeGroupName.Substring(1) + " 没有找到对应的排架体系名";
                    goto ERROR1;
                }
                strArrangeGroupName = strTemp;
            }

            // <location>元素数组
            XmlNodeList nodes = this.LibraryCfgDom.DocumentElement.SelectNodes("//callNumber/group[@name='" + strArrangeGroupName + "']/location");
            if (nodes.Count == 0)
            {
                strError = "library.xml中尚未配置有关 '" + strArrangeGroupName + "' 的<callNumber>/<group>/<location>相关参数";
                goto ERROR1;
            }

            string strTargetList = "";

            // 遍历所有实体库
            for (int i = 0; i < this.ItemDbs.Count; i++)
            {
                string strItemDbName = this.ItemDbs[i].DbName;

                if (String.IsNullOrEmpty(strItemDbName) == true)
                    continue;

                if (String.IsNullOrEmpty(strTargetList) == false)
                    strTargetList += ";";
                strTargetList += strItemDbName + ":索取类号";
            }

            int nCount = 0;
            // 构造检索式
            for (int i = 0; i < nodes.Count; i++)
            {
                XmlNode node = nodes[i];
                string strLocationName = DomUtil.GetAttr(node, "name");

                if (String.IsNullOrEmpty(strLocationName) == true)
                    continue;

                if (nCount > 0)
                {
                    Debug.Assert(String.IsNullOrEmpty(strQueryXml) == false, "");
                    strQueryXml += "<operator value='OR'/>";
                }

                strLocationName = strLocationName.Replace("*", "%");

                /*
                strQueryXml += "<item><word>"
                    + StringUtil.GetXmlStringSimple(strLocationName + "|" + strClass)
                    + "</word><match>exact</match><relation>=</relation><dataType>string</dataType><maxCount>-1</maxCount></item><lang>zh</lang>";
                 * */
                strQueryXml += "<item><word>"
    + StringUtil.GetXmlStringSimple(strLocationName + "|" + strClass + "/")
    + "</word><match>left</match><relation>=</relation><dataType>string</dataType><maxCount>-1</maxCount></item><lang>zh</lang>";

                nCount++;
            }

            strQueryXml = "<target list='"
                    + StringUtil.GetXmlStringSimple(strTargetList)       // 2007/9/14
                    + "'>" + strQueryXml + "</target>";

            RmsChannel channel = sessioninfo.Channels.GetChannel(this.WsUrl);
            if (channel == null)
            {
                strError = "get channel error";
                goto ERROR1;
            }

            long lRet = channel.DoSearch(strQueryXml,
                strResultSetName,   // "default",
                "keyid", // "", // strOuputStyle
                out strError);
            if (lRet == -1)
                goto ERROR1;

            if (lRet == 0)
            {
                result.Value = 0;
                result.ErrorInfo = "not found";
                result.ErrorCode = ErrorCode.NotFound;
                return result;
            }


            result.Value = lRet;
            return result;
        ERROR1:
            result.Value = -1;
            result.ErrorCode = ErrorCode.SystemError;
            result.ErrorInfo = strError;
            return result;
        }
Beispiel #46
0
        /// <inheritdoc />
        public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            if (prevState.Equals(GroupStateType.Playing))
            {
                ResumePlaying = true;
            }
            else if (prevState.Equals(GroupStateType.Paused))
            {
                ResumePlaying = false;
            }

            // Sanitize PositionTicks.
            var ticks = context.SanitizePositionTicks(request.PositionTicks);

            // Seek.
            context.PositionTicks = ticks;
            context.LastActivity  = DateTime.UtcNow;

            var command = context.NewSyncPlayCommand(SendCommandType.Seek);

            context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);

            // Reset status of sessions and await for all Ready events.
            context.SetAllBuffering(true);

            // Notify relevant state change event.
            SendGroupStateUpdate(context, request, session, cancellationToken);
        }
Beispiel #47
0
        // 检索顶层文章
        // return:
        //		-1	error
        //		其他 命中数
        private int SearchTopLevelArticles(
            SessionInfo sessioninfo,
            System.Web.UI.Page page,
            out string strError)
        {
            strError = "";

            if (page != null
                && page.Response.IsClientConnected == false)	// 灵敏中断
            {
                strError = "中断";
                return -1;
            }

            // 检索全部评注文章 一定时间范围内的?
            List<string> dbnames = new List<string>();
            for (int i = 0; i < this.ItemDbs.Count; i++)
            {
                ItemDbCfg cfg = this.ItemDbs[i];
                string strDbName = cfg.CommentDbName;
                if (String.IsNullOrEmpty(strDbName) == true)
                    continue;
                dbnames.Add(strDbName);
            }

            DateTime now = DateTime.Now;
            DateTime oneyearbefore = now - new TimeSpan(365, 0, 0, 0);
            string strTime = DateTimeUtil.Rfc1123DateTimeString(oneyearbefore.ToUniversalTime());

            string strQueryXml = "";
            for (int i = 0; i < dbnames.Count; i++)
            {
                string strDbName = dbnames[i];
                string strOneQueryXml = "<target list='" + strDbName + ":" + "最后修改时间'><item><word>"    // <order>DESC</order>
                    + strTime + "</word><match>exact</match><relation>" + StringUtil.GetXmlStringSimple(">=") + "</relation><dataType>number</dataType><maxCount>"
                    + "-1"// Convert.ToString(m_nMaxLineCount)
                    + "</maxCount></item><lang>zh</lang></target>";

                if (i > 0)
                    strQueryXml += "<operator value='OR' />";
                strQueryXml += strOneQueryXml;
            }

            if (dbnames.Count > 0)
                strQueryXml = "<group>" + strQueryXml + "</group>";

            RmsChannel channel = sessioninfo.Channels.GetChannel(this.WsUrl);
            Debug.Assert(channel != null, "Channels.GetChannel 异常");

            if (page != null)
            {
                page.Response.Write("--- begin search ...<br/>");
                page.Response.Flush();
            }

            DateTime time = DateTime.Now;

            long nRet = channel.DoSearch(strQueryXml,
                "default",
                out strError);
            if (nRet == -1)
            {
                strError = "检索时出错: " + strError;
                return -1;
            }

                TimeSpan delta = DateTime.Now - time;
            if (page != null)
            {
                page.Response.Write("search end. hitcount=" + nRet.ToString() + ", time=" + delta.ToString() + "<br/>");
                page.Response.Flush();
            }


            if (nRet == 0)
                return 0;	// not found



            if (page != null
                && page.Response.IsClientConnected == false)	// 灵敏中断
            {
                strError = "中断";
                return -1;
            }
            if (page != null)
            {
                page.Response.Write("--- begin get search result ...<br/>");
                page.Response.Flush();
            }

            time = DateTime.Now;

            List<string> aPath = null;
            nRet = channel.DoGetSearchResult(
                "default",
                -1,
                "zh",
                null,	// stop,
                out aPath,
                out strError);
            if (nRet == -1)
            {
                strError = "获得检索结果时出错: " + strError;
                return -1;
            }

            if (page != null)
            {
                delta = DateTime.Now - time;
                page.Response.Write("get search result end. lines=" + aPath.Count.ToString() + ", time=" + delta.ToString() + "<br/>");
                page.Response.Flush();
            }


            if (aPath.Count == 0)
            {
                strError = "获取的检索结果为空";
                return -1;
            }

            if (page != null
                && page.Response.IsClientConnected == false)	// 灵敏中断
            {
                strError = "中断";
                return -1;
            }


            if (page != null)
            {
                page.Response.Write("--- begin build storage ...<br/>");
                page.Response.Flush();
            }

            time = DateTime.Now;


            this.CommentColumn.Clear();	// 清空集合

            // 加入新行对象。新行对象中,只初始化了m_strRecPath参数
            for (int i = 0; i < Math.Min(aPath.Count, 1000000); i++)	// <Math.Min(aPath.Count, 10)
            {
                Line line = new Line();
                // line.Container = this;
                line.m_strRecPath = aPath[i];

                nRet = line.InitialInfo(
                    page,
                    channel,
                    out strError);
                if (nRet == -1)
                    return -1;
                if (nRet == 1)
                    return -1;	// 灵敏中断


                TopArticleItem item = new TopArticleItem();
                item.Line = line;
                this.CommentColumn.Add(item);

                if (page != null 
                    && (i % 100) == 0)
                {
                    page.Response.Write("process " + Convert.ToString(i) + "<br/>");
                    page.Response.Flush();
                }

            }

            if (page != null)
            {
                delta = DateTime.Now - time;
                page.Response.Write("build storage end. time=" + delta.ToString() + "<br/>");
                page.Response.Flush();
            }

            return 1;
        }
Beispiel #48
0
        /// <inheritdoc />
        public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            // Make sure the client is playing the correct item.
            if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId()))
            {
                _logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString());

                var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem);
                var updateSession   = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
                context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
                context.SetBuffering(session, true);

                return;
            }

            if (prevState.Equals(GroupStateType.Playing))
            {
                // Resume playback when all ready.
                ResumePlaying = true;

                context.SetBuffering(session, true);

                // Pause group and compute the media playback position.
                var currentTime = DateTime.UtcNow;
                var elapsedTime = currentTime - context.LastActivity;
                context.LastActivity = currentTime;
                // Elapsed time is negative if event happens
                // during the delay added to account for latency.
                // In this phase clients haven't started the playback yet.
                // In other words, LastActivity is in the future,
                // when playback unpause is supposed to happen.
                // Seek only if playback actually started.
                context.PositionTicks += Math.Max(elapsedTime.Ticks, 0);

                // Send pause command to all non-buffering sessions.
                var command = context.NewSyncPlayCommand(SendCommandType.Pause);
                context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken);
            }
            else if (prevState.Equals(GroupStateType.Paused))
            {
                // Don't resume playback when all ready.
                ResumePlaying = false;

                context.SetBuffering(session, true);

                // Send pause command to buffering session.
                var command = context.NewSyncPlayCommand(SendCommandType.Pause);
                context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
            }
            else if (prevState.Equals(GroupStateType.Waiting))
            {
                // Another session is now buffering.
                context.SetBuffering(session, true);

                if (!ResumePlaying)
                {
                    // Force update for this session that should be paused.
                    var command = context.NewSyncPlayCommand(SendCommandType.Pause);
                    context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
                }
            }

            // Notify relevant state change event.
            SendGroupStateUpdate(context, request, session, cancellationToken);
        }
Beispiel #49
0
        // 写入一条数据
        // return:
        //      -1  error
        //      0   已经写入
        //      1   没有必要写入
        int WriteOneReaderInfo(
            SessionInfo sessioninfo,
            string strReaderDbName,
            string strZhengyuanXml,
            out string strError)
        {
            strError = "";

            XmlDocument zhengyuandom = new XmlDocument();

            try
            {
                zhengyuandom.LoadXml(strZhengyuanXml);
            }
            catch (Exception ex)
            {
                strError = "从正元数据中读出的XML片段装入DOM失败: " + ex.Message;
                return -1;
            }

            // AccType
            // 卡户类型
            // 1正式卡,2 临时卡
            string strAccType = DomUtil.GetElementText(zhengyuandom.DocumentElement,
                "ACCTYPE");
            if (strAccType != "1")
            {
                return 1;
            }

            string strBarcode = DomUtil.GetElementText(zhengyuandom.DocumentElement,
                "ACCNUM");
            if (String.IsNullOrEmpty(strBarcode) == true)
            {
                strError = "缺乏<ACCNUM>元素";
                return -1;
            }

            strBarcode = strBarcode.PadLeft(10, '0');

            int nRet = 0;
            string strReaderXml = "";
            string strOutputPath = "";
            byte[] baTimestamp = null;

            // 加读锁
            // 可以避免拿到读者记录处理中途的临时状态
#if DEBUG_LOCK_READER
            this.App.WriteErrorLog("WriteOneReaderInfo 开始为读者加读锁 '" + strBarcode + "'");
#endif
            this.App.ReaderLocks.LockForRead(strBarcode);

            try
            {

                RmsChannel channel = this.RmsChannels.GetChannel(this.App.WsUrl);
                if (channel == null)
                {
                    strError = "get channel error";
                    return -1;
                }

                // 获得读者记录
                // return:
                //      -1  error
                //      0   not found
                //      1   命中1条
                //      >1  命中多于1条
                nRet = this.App.GetReaderRecXml(
                    // this.RmsChannels, // sessioninfo.Channels,
                    channel,
                    strBarcode,
                    out strReaderXml,
                    out strOutputPath,
                    out baTimestamp,
                    out strError);

            }
            finally
            {
                this.App.ReaderLocks.UnlockForRead(strBarcode);
#if DEBUG_LOCK_READER
                this.App.WriteErrorLog("WriteOneReaderInfo 结束为读者加读锁 '" + strBarcode + "'");
#endif
            }

            if (nRet == -1)
                return -1;
            if (nRet > 1)
            {
                strError = "条码号 " + strBarcode + "在读者库群中检索命中 " + nRet.ToString() + " 条,请尽快更正此错误。";
                return -1;
            }

            string strAction = "";
            string strRecPath = "";

            string strNewXml = "";  // 修改后的记录

            if (nRet == 0)
            {
                // 没有命中,创建新记录
                strAction = "new";
                strRecPath = strReaderDbName + "/?";
                strReaderXml = "";  // 2009/7/17 changed // "<root />";
            }
            else
            {
                Debug.Assert(nRet == 1, "");
                // 命中,修改后覆盖原记录

                strAction = "change";
                strRecPath = strOutputPath;
            }

            XmlDocument readerdom = new XmlDocument();
            try
            {
                readerdom.LoadXml(strReaderXml);
            }
            catch (Exception ex)
            {
                strError = "读者XML记录装入DOM发生错误: " + ex.Message;
                return -1;
            }

            nRet = ModifyReaderRecord(ref readerdom,
                zhengyuandom,
                out strError);
            if (nRet == -1)
                return -1;

            if (nRet == 1)  // 没有必要写入
            {
                Debug.Assert(strAction == "change", "");
                return 1;
            }

            if (nRet == 2) // 没有必要写入
            {
                return 1;
            }

            strNewXml = readerdom.OuterXml;

            string strExistingXml = "";
            string strSavedXml = "";
            string strSavedRecPath = "";
            byte [] baNewTimestamp = null;
            DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue kernel_errorcode = DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue.NoError;

            LibraryServerResult result = this.App.SetReaderInfo(
                    sessioninfo,
                    strAction,
                    strRecPath,
                    strNewXml,
                    strReaderXml,
                    baTimestamp,
                    out strExistingXml,
                    out strSavedXml,
                    out strSavedRecPath,
                    out baNewTimestamp,
                    out kernel_errorcode);
            if (result.Value == -1)
            {
                strError = result.ErrorInfo;
                return -1;
            }



            return 0;   // 正常写入了
        }
Beispiel #50
0
        /// <inheritdoc />
        public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            // Make sure the client is playing the correct item.
            if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId()))
            {
                _logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString());

                var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem);
                var update          = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
                context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken);
                context.SetBuffering(session, true);

                return;
            }

            // Compute elapsed time between the client reported time and now.
            // Elapsed time is used to estimate the client position when playback is unpaused.
            // Ideally, the request is received and handled without major delays.
            // However, to avoid waiting indefinitely when a client is not reporting a correct time,
            // the elapsed time is ignored after a certain threshold.
            var currentTime            = DateTime.UtcNow;
            var elapsedTime            = currentTime.Subtract(request.When);
            var timeSyncThresholdTicks = TimeSpan.FromMilliseconds(context.TimeSyncOffset).Ticks;

            if (Math.Abs(elapsedTime.Ticks) > timeSyncThresholdTicks)
            {
                _logger.LogWarning("Session {SessionId} is not time syncing properly. Ignoring elapsed time.", session.Id);

                elapsedTime = TimeSpan.Zero;
            }

            // Ignore elapsed time if client is paused.
            if (!request.IsPlaying)
            {
                elapsedTime = TimeSpan.Zero;
            }

            var requestTicks           = context.SanitizePositionTicks(request.PositionTicks);
            var clientPosition         = TimeSpan.FromTicks(requestTicks) + elapsedTime;
            var delayTicks             = context.PositionTicks - clientPosition.Ticks;
            var maxPlaybackOffsetTicks = TimeSpan.FromMilliseconds(context.MaxPlaybackOffset).Ticks;

            _logger.LogDebug("Session {SessionId} is at {PositionTicks} (delay of {Delay} seconds) in group {GroupId}.", session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds, context.GroupId.ToString());

            if (ResumePlaying)
            {
                // Handle case where session reported as ready but in reality
                // it has no clue of the real position nor the playback state.
                if (!request.IsPlaying && Math.Abs(delayTicks) > maxPlaybackOffsetTicks)
                {
                    // Session not ready at all.
                    context.SetBuffering(session, true);

                    // Correcting session's position.
                    var command = context.NewSyncPlayCommand(SendCommandType.Seek);
                    context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);

                    // Notify relevant state change event.
                    SendGroupStateUpdate(context, request, session, cancellationToken);

                    _logger.LogWarning("Session {SessionId} got lost in time, correcting.", session.Id);
                    return;
                }

                // Session is ready.
                context.SetBuffering(session, false);

                if (context.IsBuffering())
                {
                    // Others are still buffering, tell this client to pause when ready.
                    var command = context.NewSyncPlayCommand(SendCommandType.Pause);
                    command.When = currentTime.AddTicks(delayTicks);
                    context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);

                    _logger.LogInformation("Session {SessionId} will pause when ready in {Delay} seconds. Group {GroupId} is waiting for all ready events.", session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds, context.GroupId.ToString());
                }
                else
                {
                    // If all ready, then start playback.
                    // Let other clients resume as soon as the buffering client catches up.
                    if (delayTicks > context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond)
                    {
                        // Client that was buffering is recovering, notifying others to resume.
                        context.LastActivity = currentTime.AddTicks(delayTicks);
                        var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
                        var filter  = SyncPlayBroadcastType.AllExceptCurrentSession;
                        if (!request.IsPlaying)
                        {
                            filter = SyncPlayBroadcastType.AllGroup;
                        }

                        context.SendCommand(session, filter, command, cancellationToken);

                        _logger.LogInformation("Session {SessionId} is recovering, group {GroupId} will resume in {Delay} seconds.", session.Id, context.GroupId.ToString(), TimeSpan.FromTicks(delayTicks).TotalSeconds);
                    }
                    else
                    {
                        // Client, that was buffering, resumed playback but did not update others in time.
                        delayTicks = context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond;
                        delayTicks = Math.Max(delayTicks, context.DefaultPing);

                        context.LastActivity = currentTime.AddTicks(delayTicks);

                        var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
                        context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);

                        _logger.LogWarning("Session {SessionId} resumed playback, group {GroupId} has {Delay} seconds to recover.", session.Id, context.GroupId.ToString(), TimeSpan.FromTicks(delayTicks).TotalSeconds);
                    }

                    // Change state.
                    var playingState = new PlayingGroupState(LoggerFactory);
                    context.SetState(playingState);
                    playingState.HandleRequest(request, context, Type, session, cancellationToken);
                }
            }
            else
            {
                // Check that session is really ready, tolerate player imperfections under a certain threshold.
                if (Math.Abs(context.PositionTicks - requestTicks) > maxPlaybackOffsetTicks)
                {
                    // Session still not ready.
                    context.SetBuffering(session, true);
                    // Session is seeking to wrong position, correcting.
                    var command = context.NewSyncPlayCommand(SendCommandType.Seek);
                    context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);

                    // Notify relevant state change event.
                    SendGroupStateUpdate(context, request, session, cancellationToken);

                    _logger.LogWarning("Session {SessionId} is seeking to wrong position, correcting.", session.Id);
                    return;
                }
                else
                {
                    // Session is ready.
                    context.SetBuffering(session, false);
                }

                if (!context.IsBuffering())
                {
                    _logger.LogDebug("Session {SessionId} is ready, group {GroupId} is ready.", session.Id, context.GroupId.ToString());

                    // Group is ready, returning to previous state.
                    var pausedState = new PausedGroupState(LoggerFactory);
                    context.SetState(pausedState);

                    if (InitialState.Equals(GroupStateType.Playing))
                    {
                        // Group went from playing to waiting state and a pause request occured while waiting.
                        var pauseRequest = new PauseGroupRequest();
                        pausedState.HandleRequest(pauseRequest, context, Type, session, cancellationToken);
                    }
                    else if (InitialState.Equals(GroupStateType.Paused))
                    {
                        pausedState.HandleRequest(request, context, Type, session, cancellationToken);
                    }
                }
            }
        }
        private SessionInfo GetSessionInfo(uint appID)
        {
            SessionInfo info;

            if (SessionMap.TryGetValue(appID, out info))
            {
                return info;
            }

            info = new SessionInfo
            {
                AppID = appID,
                Status = GCConnectionStatus.GCConnectionStatus_NO_SESSION
            };

            SessionMap.Add(appID, info);

            return info;
        }
Beispiel #52
0
        /// <inheritdoc />
        public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            if (prevState.Equals(GroupStateType.Playing))
            {
                ResumePlaying = true;
                // Pause group and compute the media playback position.
                var currentTime = DateTime.UtcNow;
                var elapsedTime = currentTime - context.LastActivity;
                context.LastActivity = currentTime;
                // Elapsed time is negative if event happens
                // during the delay added to account for latency.
                // In this phase clients haven't started the playback yet.
                // In other words, LastActivity is in the future,
                // when playback unpause is supposed to happen.
                // Seek only if playback actually started.
                context.PositionTicks += Math.Max(elapsedTime.Ticks, 0);
            }

            // Prepare new session.
            var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
            var update          = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);

            context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken);

            context.SetBuffering(session, true);

            // Send pause command to all non-buffering sessions.
            var command = context.NewSyncPlayCommand(SendCommandType.Pause);

            context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken);
        }
Beispiel #53
0
        SessionInfo GetTempSessionInfo()
        {
            if (this.m_tempSessionInfo != null)
                return this.m_tempSessionInfo;

            // 临时的SessionInfo对象
            SessionInfo sessioninfo = new SessionInfo(this.App);

            // 模拟一个账户
            Account account = new Account();
            account.LoginName = "replication";
            account.Password = "";
            account.Rights = "setreaderinfo,devolvereaderinfo";

            account.Type = "";
            account.Barcode = "";
            account.Name = "replication";
            account.UserID = "replication";
            account.RmsUserName = this.App.ManagerUserName;
            account.RmsPassword = this.App.ManagerPassword;

            sessioninfo.Account = account;

            this.m_tempSessionInfo = sessioninfo;

            return sessioninfo;
        }
Beispiel #54
0
        /// <inheritdoc />
        public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            ResumePlaying = true;

            // Make sure the client knows the playing item, to avoid duplicate requests.
            if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId()))
            {
                _logger.LogDebug("Session {SessionId} provided the wrong playlist item for group {GroupId}.", session.Id, context.GroupId.ToString());
                return;
            }

            var newItem = context.PreviousItemInQueue();

            if (newItem)
            {
                // Send playing-queue update.
                var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.PreviousItem);
                var update          = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
                context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);

                // Reset status of sessions and await for all Ready events.
                context.SetAllBuffering(true);
            }
            else
            {
                // Return to old state.
                IGroupState newState = prevState switch
                {
                    GroupStateType.Playing => new PlayingGroupState(LoggerFactory),
                    GroupStateType.Paused => new PausedGroupState(LoggerFactory),
                    _ => new IdleGroupState(LoggerFactory)
                };

                context.SetState(newState);

                _logger.LogDebug("No previous item available in group {GroupId}.", context.GroupId.ToString());
            }
        }
Beispiel #55
0
        // 将读者记录数据从XML格式转换为HTML格式
        // parameters:
        //      strRecPath  读者记录路径 2009/10/18
        //      strLibraryCode  读者记录所从属的读者库的馆代码
        //      strResultType  细节格式。为了 '|' 间隔的若干名称字符串
        public int ConvertReaderXmlToHtml(
            SessionInfo sessioninfo,
            string strCsFileName,
            string strRefFileName,
            string strLibraryCode,
            string strXml,
            string strRecPath,
            OperType opertype,
            string[] saBorrowedItemBarcode,
            string strCurrentItemBarcode,
            string strResultType,
            out string strResult,
            out string strError)
        {
            strResult = "";
            strError = "";
            int nRet = 0;

            // TODO: ParseTwoPart
            string strSubType = "";
            nRet = strResultType.IndexOf(":");
            if (nRet != -1)
                strSubType = strResultType.Substring(nRet + 1).Trim();

            LibraryApplication app = this;

            // 转换为html格式
            Assembly assembly = null;
            nRet = app.GetXml2HtmlAssembly(
                strCsFileName,
                strRefFileName,
                app.BinDir,
                out assembly,
                out strError);
            if (nRet == -1)
            {
                goto ERROR1;
            }

            // 得到Assembly中Converter派生类Type
            Type entryClassType = ScriptManager.GetDerivedClassType(
                assembly,
                "DigitalPlatform.LibraryServer.ReaderConverter");

            if (entryClassType == null)
            {
                strError = "从DigitalPlatform.LibraryServer.ReaderConverter派生的类 type entry not found";
                goto ERROR1;
            }

            // new一个Converter派生对象
            ReaderConverter obj = (ReaderConverter)entryClassType.InvokeMember(null,
                BindingFlags.DeclaredOnly |
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Instance | BindingFlags.CreateInstance, null, null,
                null);

            // 为Converter派生类设置参数
            // obj.MainForm = this;
            obj.BorrowedItemBarcodes = saBorrowedItemBarcode;
            obj.CurrentItemBarcode = strCurrentItemBarcode;
            obj.OperType = opertype;
            obj.App = app;
            obj.SessionInfo = sessioninfo;
            obj.RecPath = strRecPath;
            obj.LibraryCode = strLibraryCode;   // 2012/9/8
            obj.Formats = strSubType.Replace("|", ",");

            // 调用关键函数Convert
            try
            {
                strResult = obj.Convert(strXml);
            }
            catch (Exception ex)
            {
                strError = "脚本执行时抛出异常: " + ExceptionUtil.GetDebugText(ex);
                goto ERROR1;
            }

            return 0;
        ERROR1:
            return -1;
        }
Beispiel #56
0
        /// <inheritdoc />
        public override void HandleRequest(IgnoreWaitGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            context.SetIgnoreGroupWait(session, request.IgnoreWait);

            if (!context.IsBuffering())
            {
                _logger.LogDebug("Ignoring session {SessionId}, group {GroupId} is ready.", session.Id, context.GroupId.ToString());

                if (ResumePlaying)
                {
                    // Client, that was buffering, stopped following playback.
                    var playingState = new PlayingGroupState(LoggerFactory);
                    context.SetState(playingState);
                    var unpauseRequest = new UnpauseGroupRequest();
                    playingState.HandleRequest(unpauseRequest, context, Type, session, cancellationToken);
                }
                else
                {
                    // Group is ready, returning to previous state.
                    var pausedState = new PausedGroupState(LoggerFactory);
                    context.SetState(pausedState);
                }
            }
        }
		public static WriteDataServiceReply WriteLogixData(SessionInfo si, string tagAddress, ushort dataType, ushort elementCount, byte[] data)
		{
			return WriteLogixData(si, tagAddress, dataType, elementCount, data, 0x0000);
		}
Beispiel #58
0
        /// <inheritdoc />
        public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Save state if first event.
            if (!InitialStateSet)
            {
                InitialState    = prevState;
                InitialStateSet = true;
            }

            context.SetBuffering(session, false);

            if (!context.IsBuffering())
            {
                if (ResumePlaying)
                {
                    _logger.LogDebug("Session {SessionId} left group {GroupId}, notifying others to resume.", session.Id, context.GroupId.ToString());

                    // Client, that was buffering, left the group.
                    var playingState = new PlayingGroupState(LoggerFactory);
                    context.SetState(playingState);
                    var unpauseRequest = new UnpauseGroupRequest();
                    playingState.HandleRequest(unpauseRequest, context, Type, session, cancellationToken);
                }
                else
                {
                    _logger.LogDebug("Session {SessionId} left group {GroupId}, returning to previous state.", session.Id, context.GroupId.ToString());

                    // Group is ready, returning to previous state.
                    var pausedState = new PausedGroupState(LoggerFactory);
                    context.SetState(pausedState);
                }
            }
        }
        public static WriteDataServiceReply WriteLogixData(SessionInfo si, string tagAddress, ushort dataType, ushort elementCount, byte[] data, ushort structHandle = 0x0000)
#endif
		{
            WriteDataServiceRequest request = BuildLogixWriteDataRequest(tagAddress, dataType, elementCount, data, structHandle);

            EncapsRRData rrData = new EncapsRRData();
            rrData.CPF = new CommonPacket();
            rrData.CPF.AddressItem = CommonPacketItem.GetConnectedAddressItem(si.ConnectionParameters.O2T_CID);
            rrData.CPF.DataItem = CommonPacketItem.GetConnectedDataItem(request.Pack(), SequenceNumberGenerator.SequenceNumber);
            rrData.Timeout = 2000;

            EncapsReply reply = si.SendUnitData(rrData.CPF.AddressItem, rrData.CPF.DataItem);

            if (reply == null)
                return null;

            if (reply.Status != 0)
            {
                return null;
            }

            return new WriteDataServiceReply(reply);
        }
Beispiel #60
0
        /// <summary>
        /// Get an Access Token in order to call an API.
        /// </summary>
        /// <param name="httpClient">A <see cref="HttpClient"/> param.</param>
        /// <param name="auth0domain">The Auth0's tenant domain.</param>
        /// <param name="auth0ClientId">The Auth0's client id.</param>
        /// <param name="code">The code received from Auth0.</param>
        /// <param name="audience">The Auth0's audience domain.</param>
        /// <param name="codeVerifier">The code verification token used in the authentication flow</param>
        /// <param name="redirectUri">URL to redirect the user after the logout.</param>
        /// <param name="secret">The Auth0's client secret</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
        public static async Task <SessionInfo> GetAccessToken(
            HttpClient httpClient,
            string auth0domain,
            string auth0ClientId,
            string code,
            string audience     = null,
            string codeVerifier = null,
            string redirectUri  = null,
            string secret       = null)
        {
            if (httpClient is null)
            {
                throw new ArgumentNullException(nameof(httpClient));
            }

            if (string.IsNullOrEmpty(auth0domain))
            {
                throw new ArgumentException(Resources.NullArgumentExceptionError, nameof(auth0domain));
            }

            if (string.IsNullOrEmpty(auth0ClientId))
            {
                throw new ArgumentException(Resources.NullArgumentExceptionError, nameof(auth0ClientId));
            }

            if (string.IsNullOrEmpty(codeVerifier) && string.IsNullOrEmpty(secret))
            {
                throw new ArgumentException(Resources.MissingPKCERequiredParamError, $"{nameof(secret)} or {nameof(codeVerifier)}");
            }

            if (!string.IsNullOrEmpty(codeVerifier) && !string.IsNullOrEmpty(secret))
            {
                throw new ArgumentException(Resources.DuplicatedPKCERequiredParamError, $"{nameof(secret)} and {nameof(codeVerifier)}");
            }

            SessionInfo response = null;

            using (HttpContent content = new StringContent(
                       JsonSerializer.Serialize(
                           new
            {
                grant_type = "authorization_code",
                client_id = auth0ClientId,
                audience,
                code,
                code_verifier = codeVerifier,
                redirect_uri = redirectUri,
                client_secret = secret,
            },
                           new JsonSerializerOptions
            {
                IgnoreNullValues = true,
            }), Encoding.UTF8,
                       Resources.ApplicationJsonMediaType
                       )
                   )
            {
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync($@"https://{auth0domain}/oauth/token", content).ConfigureAwait(false);

                string responseText = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

                if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    response = JsonSerializer.Deserialize <SessionInfo>(responseText);
                }
            }

            return(response);
        }