Exemplo n.º 1
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="dataToken"></param>
 /// <param name="buffer"></param>
 /// <param name="messageList"></param>
 /// <returns></returns>
 public override bool TryReadMeaage(DataToken dataToken, byte[] buffer, out List<DataMeaage> messageList)
 {
     messageList = new List<DataMeaage>();
     int offset = 0;
     do
     {
         //check close flag
         if (CheckCloseFlag(buffer, ref offset))
         {
             messageList.Add(new DataMeaage() { Data = buffer, OpCode = OpCode.Close });
             dataToken.Reset(true);
             return true;
         }
         //receive buffer is complated
         if (!CheckPrefixHeadComplated(dataToken, buffer, ref offset) ||
             !CheckDataComplated(dataToken, buffer, ref offset))
         {
             return false;
         }
         byte[] data = dataToken.byteArrayForMessage;
         if (data != null)
         {
             messageList.Add(new DataMeaage() { Data = data, OpCode = OpCode.Text });
         }
         dataToken.Reset(true);
     } while (offset < buffer.Length);
     return true;
 }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dataToken"></param>
        /// <param name="buffer"></param>
        /// <param name="messageList"></param>
        /// <returns></returns>
        public override bool TryReadMeaage(DataToken dataToken, byte[] buffer, out List <DataMessage> messageList)
        {
            messageList = new List <DataMessage>();
            int offset = 0;

            do
            {
                //check close flag
                if (CheckCloseFlag(buffer, ref offset))
                {
                    messageList.Add(new DataMessage()
                    {
                        Data = buffer, OpCode = OpCode.Close
                    });
                    dataToken.Reset(true);
                    return(true);
                }
                //receive buffer is complated
                if (!CheckPrefixHeadComplated(dataToken, buffer, ref offset) ||
                    !CheckDataComplated(dataToken, buffer, ref offset))
                {
                    return(false);
                }
                byte[] data = dataToken.byteArrayForMessage;
                if (data != null)
                {
                    messageList.Add(new DataMessage()
                    {
                        Data = data, OpCode = OpCode.Text
                    });
                }
                dataToken.Reset(true);
            } while (offset < buffer.Length);
            return(true);
        }
Exemplo n.º 3
0
        public static void UpdateContact(DataToken dataToken)
        {
            DataToken = dataToken;
            Contact newContact = CreateContactWithFirstAndLastName("Maitland", "Marshall");

            UpdateContactWithAddress(newContact.ContactID, "123 Fake Street");
        }
Exemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dataToken"></param>
        /// <param name="buffer"></param>
        /// <param name="messageList"></param>
        /// <returns>true: message is complate</returns>
        public override bool TryReadMeaage(DataToken dataToken, byte[] buffer, out List <DataMeaage> messageList)
        {
            if (CheckVersion(dataToken.Socket))
            {
                return(base.TryReadMeaage(dataToken, buffer, out messageList));
            }
            messageList = new List <DataMeaage>();
            int offset = 0;

            do
            {
                //receive buffer is complated
                if (!CheckPrefixHeadComplated(dataToken, buffer, ref offset) ||
                    !dataToken.HeadFrame.CheckRSV ||
                    !CheckPayloadHeadComplated(dataToken, buffer, ref offset) ||
                    !CheckPayloadDataComplated(dataToken, buffer, ref offset))
                {
                    return(false);
                }
                byte[] data = dataToken.HeadFrame.HasMask
                        ? DecodeMask(dataToken.byteArrayForMessage, dataToken.byteArrayMask, 0, dataToken.messageLength)
                        : dataToken.byteArrayForMessage;

                if (!dataToken.HeadFrame.FIN)
                {
                    dataToken.DataFrames.Add(new DataSegmentFrame()
                    {
                        Head = dataToken.HeadFrame,
                        Data = new ArraySegment <byte>(data)
                    });
                }
                else
                {
                    //frame complated
                    sbyte opCode;
                    if (dataToken.DataFrames.Count > 0)
                    {
                        dataToken.DataFrames.Add(new DataSegmentFrame()
                        {
                            Head = dataToken.HeadFrame,
                            Data = new ArraySegment <byte>(data)
                        });
                        opCode = dataToken.DataFrames[0].Head.OpCode;
                        data   = CombineDataFrames(dataToken.DataFrames);
                    }
                    else
                    {
                        opCode = dataToken.HeadFrame.OpCode;
                    }
                    messageList.Add(new DataMeaage()
                    {
                        Data = data, OpCode = opCode
                    });
                    dataToken.DataFrames.Clear();
                }
                dataToken.Reset(true);
            } while (offset < buffer.Length);

            return(true);
        }
Exemplo n.º 5
0
        public static void ProcessReading(DataToken dataToken)
        {
            DataToken = dataToken;
            const string exampleAssetNumber = "ADMIN";

            ProcessReadingForAsset(exampleAssetNumber);
        }
Exemplo n.º 6
0
        private bool CheckDataComplated(DataToken dataToken, byte[] buffer, ref int offset)
        {
            byte[] data;
            int    endMaskIndex = MathUtils.IndexOf(buffer, offset, buffer.Length - offset + 1, new[] { EndByte });

            if (endMaskIndex < 0)
            {
                data = new byte[buffer.Length - offset];
                Buffer.BlockCopy(buffer, offset, data, 0, data.Length);
                if (dataToken.byteArrayForMessage == null)
                {
                    dataToken.byteArrayForMessage = data;
                }
                else
                {
                    dataToken.byteArrayForMessage = BufferUtils.MergeBytes(dataToken.byteArrayForMessage, data);
                }
                offset += data.Length;
                return(false);
            }
            //end mask not received
            if (endMaskIndex == 0)
            {
                offset += 1;
                return(true);
            }
            data = new byte[endMaskIndex - offset];
            Buffer.BlockCopy(buffer, offset, data, 0, data.Length);
            dataToken.byteArrayForMessage = BufferUtils.MergeBytes(dataToken.byteArrayForMessage, data);
            offset += data.Length + 1;
            return(true);
        }
Exemplo n.º 7
0
        private bool CheckPrefixHeadComplated(DataToken dataToken, byte[] buffer, ref int offset)
        {
            if (dataToken.byteArrayForPrefix == null || dataToken.byteArrayForPrefix.Length != PreByteLength)
            {
                dataToken.byteArrayForPrefix = new byte[PreByteLength];
            }
            if (PreByteLength - dataToken.prefixBytesDone > buffer.Length - offset)
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix, dataToken.prefixBytesDone, buffer.Length - offset);
                dataToken.prefixBytesDone += buffer.Length - offset;
                return(false);
            }

            int count = dataToken.byteArrayForPrefix.Length - dataToken.prefixBytesDone;

            if (count > 0)
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix, dataToken.prefixBytesDone, count);
                dataToken.prefixBytesDone += count;
                offset += count;
            }
            if (dataToken.HeadFrame == null)
            {
                //build message head
                dataToken.HeadFrame = MessageHeadFrame.Parse(dataToken.byteArrayForPrefix);
            }
            return(true);
        }
        public RegionListViewModel(DataToken dataToken)
        {
            DataToken  = dataToken;
            AllRegions = new ObservableCollection <Region>(DataToken.Regions.Where(region => region.RegionID != 1).OrderBy(region => region.RegionName).ToList());

            SelectedIndex = 0;
            OnSelectedIndexChanged(0);
        }
Exemplo n.º 9
0
    public DataToken GetDataToken()
    {
        var data = new DataToken {
            Token = token, Use = useToken, Art = artToken
        };

        return(data);
    }
Exemplo n.º 10
0
        public static void CloseWorkOrder(DataToken dataToken)
        {
            DataToken = dataToken;
            const string exampleAssetNumber = "ADMIN";

            WorkOrder newWorkOrder = CreateWorkOrderWithAssetAndWorkOrderDescription(exampleAssetNumber, "Fix cuboard");

            CloseWorkOrderWithWorkOrderNumber(newWorkOrder.WorkOrderNumber);
        }
        public string Save(string value)
        {
            var dataToken = new DataToken();

            dataToken.Value = value;
            this._repositoryService.AddOnCommit(AppCoreDbContextNames.Core, dataToken);

            return(dataToken.Id.ToString("D").ToLower());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataToken"></param>
        /// <param name="buffer"></param>
        /// <param name="messageList"></param>
        /// <returns>true: message is complate</returns>
        public override bool TryReadMeaage(DataToken dataToken, byte[] buffer, out List<DataMeaage> messageList)
        {
            if (CheckVersion(dataToken.Socket))
            {
                return base.TryReadMeaage(dataToken, buffer, out messageList);
            }
            messageList = new List<DataMeaage>();
            int offset = 0;
            do
            {
                //receive buffer is complated
                if (!CheckPrefixHeadComplated(dataToken, buffer, ref offset) ||
                    !dataToken.HeadFrame.CheckRSV ||
                    !CheckPayloadHeadComplated(dataToken, buffer, ref offset) ||
                    !CheckPayloadDataComplated(dataToken, buffer, ref offset))
                {
                    return false;
                }
                byte[] data = dataToken.HeadFrame.HasMask
                        ? DecodeMask(dataToken.byteArrayForMessage, dataToken.byteArrayMask, 0, dataToken.messageLength)
                        : dataToken.byteArrayForMessage;

                if (!dataToken.HeadFrame.FIN)
                {
                    dataToken.DataFrames.Add(new DataSegmentFrame()
                    {
                        Head = dataToken.HeadFrame,
                        Data = new ArraySegment<byte>(data)
                    });
                }
                else
                {
                    //frame complated
                    sbyte opCode;
                    if (dataToken.DataFrames.Count > 0)
                    {
                        dataToken.DataFrames.Add(new DataSegmentFrame()
                        {
                            Head = dataToken.HeadFrame,
                            Data = new ArraySegment<byte>(data)
                        });
                        opCode = dataToken.DataFrames[0].Head.OpCode;
                        data = CombineDataFrames(dataToken.DataFrames);
                    }
                    else
                    {
                        opCode = dataToken.HeadFrame.OpCode;
                    }
                    messageList.Add(new DataMeaage() { Data = data, OpCode = opCode });
                    dataToken.DataFrames.Clear();
                }
                dataToken.Reset(true);
            } while (offset < buffer.Length);

            return true;
        }
Exemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        protected override string CreateHandshakeData(DataToken dataToken)
        {
            ClientWebSocket webSocket = Handler.AppServer as ClientWebSocket;

            if (webSocket == null)
            {
                throw new Exception("ISocket is not WebSocket client");
            }
            string host    = webSocket.Settings.RemoteEndPoint.ToString();
            string urlPath = webSocket.Settings.UrlPath;
            string origin  = webSocket.Settings.Origin;

            origin = !string.IsNullOrEmpty(origin) ? origin : host;
            string protocol   = webSocket.Settings.Protocol;
            string extensions = webSocket.Settings.Extensions;
            string cookie     = ToCookiesString(webSocket.Settings.Cookies);

            string secKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString("N").Substring(0, 16)));

            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecSignKey] = GenreateKey(secKey);
            dataToken.Socket.Handshake.UriSchema        = webSocket.Settings.Scheme;
            dataToken.Socket.Handshake.Host             = host;
            dataToken.Socket.Handshake.UrlPath          = urlPath;
            dataToken.Socket.Handshake.Protocol         = protocol;
            dataToken.Socket.Handshake.HttpVersion      = HandshakeHeadKeys.HttpVersion;
            dataToken.Socket.Handshake.Method           = HandshakeHeadKeys.Method;
            dataToken.Socket.Handshake.WebSocketVersion = _version;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.Origin] = origin;
            ParseCookies(dataToken.Socket.Handshake, cookie);

            StringBuilder result = new StringBuilder();

            result.AppendLine(string.Format("{0} {1} {2}", HandshakeHeadKeys.Method, urlPath, HandshakeHeadKeys.HttpVersion));
            result.AppendLine(HandshakeHeadKeys.RespUpgrade);
            result.AppendLine(HandshakeHeadKeys.RespConnection);
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Host, host));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Origin, origin));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecKey, secKey));
            if (!string.IsNullOrEmpty(protocol))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecProtocol, protocol));
            }
            if (!string.IsNullOrEmpty(extensions))
            {
                dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecExtensions] = extensions;
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecExtensions, extensions));
            }
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecVersion, _version));
            if (!string.IsNullOrEmpty(cookie))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Cookie, cookie));
            }

            result.AppendLine();
            return(result.ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override string CreateHandshakeData(DataToken dataToken)
        {
            ClientWebSocket webSocket = Handler.AppServer as ClientWebSocket;
            if (webSocket == null)
            {
                throw new Exception("ISocket is not WebSocket client");
            }
            string host = webSocket.Settings.RemoteEndPoint.ToString();
            string urlPath = webSocket.Settings.UrlPath;
            string origin = webSocket.Settings.Origin;
            origin = !string.IsNullOrEmpty(origin) ? origin : host;
            string protocol = webSocket.Settings.Protocol;
            string extensions = webSocket.Settings.Extensions;
            string cookie = ToCookiesString(webSocket.Settings.Cookies);

            string secKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString("N").Substring(0, 16)));
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecSignKey] = GenreateKey(secKey);
            dataToken.Socket.Handshake.UriSchema = webSocket.Settings.Scheme;
            dataToken.Socket.Handshake.Host = host;
            dataToken.Socket.Handshake.UrlPath = urlPath;
            dataToken.Socket.Handshake.Protocol = protocol;
            dataToken.Socket.Handshake.HttpVersion = HandshakeHeadKeys.HttpVersion;
            dataToken.Socket.Handshake.Method = HandshakeHeadKeys.Method;
            dataToken.Socket.Handshake.WebSocketVersion = _version;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.Origin] = origin;
            ParseCookies(dataToken.Socket.Handshake, cookie);

            StringBuilder result = new StringBuilder();
            result.AppendLine(string.Format("{0} {1} {2}", HandshakeHeadKeys.Method, urlPath, HandshakeHeadKeys.HttpVersion));
            result.AppendLine(HandshakeHeadKeys.RespUpgrade);
            result.AppendLine(HandshakeHeadKeys.RespConnection);
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Host, host));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Origin, origin));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecKey, secKey));
            if (!string.IsNullOrEmpty(protocol))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecProtocol, protocol));
            }
            if (!string.IsNullOrEmpty(extensions))
            {
                dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecExtensions] = extensions;
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecExtensions, extensions));
            }
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecVersion, _version));
            if (!string.IsNullOrEmpty(cookie))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Cookie, cookie));
            }

            result.AppendLine();
            return result.ToString();
        }
        internal HandshakeResult Send(DataToken dataToken)
        {
            string handshakeData = CreateHandshakeData(dataToken);

            try
            {
                Handler.SendMessage(dataToken.Socket, handshakeData, Encoding, result => { });
                return(HandshakeResult.Success);
            }
            catch (Exception)
            {
                return(HandshakeResult.Close);
            }
        }
Exemplo n.º 16
0
        public bool NextResult()
        {
            _resultSetIndex++;

            if (_resultSets != null && _resultSets.Count > _resultSetIndex)
            {
                _currentResultSet = _resultSets[_resultSetIndex];
                _rowIndex         = -1;
                _currentRow       = null;
                return(true);
            }
            else
            {
                Close();
                return(false);
            }
        }
Exemplo n.º 17
0
        public async Task <IHttpActionResult> RefreshToken([FromBody] RefreshData refreshData)
        {
            try
            {
                DataToken dataToken = await _userRepository.RefreshToken(refreshData.RefreshToken);

                if (dataToken == null)
                {
                    return(new HttpJsonApiResult <string>("Not Found", Request, HttpStatusCode.NotFound));
                }
                return(new HttpJsonApiResult <DataToken>(dataToken, Request, HttpStatusCode.OK));
            }
            catch (Exception)
            {
                return(new HttpJsonApiResult <string>(
                           "Internal Server Error", Request, HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 18
0
        private bool CheckPayloadDataComplated(DataToken dataToken, byte[] buffer, ref int offset)
        {
            int copyByteCount = dataToken.RemainByte;

            if (buffer.Length - offset >= copyByteCount)
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, copyByteCount);
                dataToken.messageBytesDone += copyByteCount;
                offset += copyByteCount;
            }
            else
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, buffer.Length - offset);
                dataToken.messageBytesDone += buffer.Length - offset;
                offset += buffer.Length - offset;
            }
            return(dataToken.IsMessageReady);
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            // included in this project is a service reference generated on a build 70 database
            // use this tool: https://marketplace.visualstudio.com/items?itemName=laylaliu.ODataConnectedService#overview if you would like to generate your own service reference

            // after generating a service reference, you can use the MEXEntities class to query, insert and update records in MEX
            DataToken = new DataToken(new Uri(MEXURL));

            // below are some examples of querying, modifying and inserting records into the database
            BasicExamples.CloseWorkOrder(DataToken);
            BasicExamples.UpdateContact(DataToken);
            BasicExamples.ProcessReading(DataToken);
            BasicExamples.GetSupplierListing(DataToken);
            BasicExamples.CreateRequest(DataToken);

            // Asset Reading Example
            AssetReadingImport.AssetReadingImportExample(DataToken);
        }
Exemplo n.º 20
0
        public bool Read()
        {
            if (_currentResultSet == null)
            {
                return(false);
            }
            _rowIndex++;

            if (_currentResultSet.Item2.Count > _rowIndex)
            {
                _currentRow = _currentResultSet.Item2[_rowIndex];
                return(true);
            }
            else
            {
                Close();
                return(false);
            }
        }
Exemplo n.º 21
0
        public MainPageViewModel()
        {
            // Set the connection details to use
            ConnectionDetails connection = Trial;

            DataToken = new DataToken(connection.URL, connection.Username, connection.Password);

            DataToken.SaveChangesDefaultOptions = System.Data.Services.Client.SaveChangesOptions.Batch;
            AssetHierarchy = new HierarchyViewModel(DataToken);
            RegionList     = new RegionListViewModel(DataToken);

            if (RegionList.AllRegions.Count > 0)
            {
                AssetHierarchy.CurrentRegionID = RegionList.AllRegions[0].RegionID;
            }

            RegionList.OnSelectedIndexChanged += (newID) => {
                AssetHierarchy.CurrentRegionID = RegionList.AllRegions[newID].RegionID;
            };
        }
Exemplo n.º 22
0
        public ActionResult Create(CreateTemplateModel.CreateDataTokensModel model)
        {
            if (!_permissionService.Authorize("ManageDataTokens"))
            {
                return(AccessDeniedView());
            }

            var user = _userContext.CurrentUser;
            // Check for duplicate tokens, if any
            var checktoken = _templateService.GetDataTokenByName(model.Name);

            if (checktoken != null)
            {
                ModelState.AddModelError("Name", "A Data Token with the same name already exists. Please choose a different name.");
            }

            if (ModelState.IsValid)
            {
                var token = new DataToken
                {
                    Value           = model.Value,
                    Name            = model.Name,
                    SystemName      = model.SystemName,
                    UserId          = user.Id,
                    IsDeleted       = false,
                    CreatedOn       = DateTime.Now,
                    ModifiedOn      = DateTime.Now,
                    IsSystemDefined = model.IsSystemDefined
                };
                _templateService.Insert(token);
            }
            else
            {
                ErrorNotification("An error occured while creating event. Please try again.");
                return(View(model));
            }

            SuccessNotification("Data Token saved successfully.");
            return(RedirectToAction("DataTokens"));
        }
Exemplo n.º 23
0
        private bool CheckPrefix2Complated(DataToken dataToken, byte[] buffer, ref int offset, int size)
        {
            if (dataToken.byteArrayForPrefix2 == null || dataToken.byteArrayForPrefix2.Length != size)
            {
                dataToken.byteArrayForPrefix2 = new byte[size];
            }
            if (size - dataToken.prefixBytesDone2 > buffer.Length - offset)
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix2, dataToken.prefixBytesDone2, buffer.Length - offset);
                dataToken.prefixBytesDone2 += buffer.Length - offset;
                return(false);
            }
            int count = dataToken.byteArrayForPrefix2.Length - dataToken.prefixBytesDone2;

            if (count > 0)
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix2, dataToken.prefixBytesDone2, count);
                dataToken.prefixBytesDone2 += count;
                offset += count;
            }
            return(true);
        }
        public ActionResult Index(DataToken data)
        {
            if (data.IsAnyNullOrEmpty())
            {
                return(RedirectToAction("Notificacion", "ErrorHandler", new { id = "401" }));
            }

            Session.Clear();

            string codigoRetorno;

            ServicioToken.TokenValida tokenValida = _tokenRepo.RecuperarInfToken(data.token, data.canal, data.aplicacion, out codigoRetorno);

            if (tokenValida.meta.Code == "000")
            {
                string   str_json = tokenValida.data.metajson;
                InfToken json     = JsonConvert.DeserializeObject <InfToken>(str_json);

                DatosCliente datosCliente = new DatosCliente();
                datosCliente.Cedula = json.identificacion;

                if (json.producto == _settings.ProductoSG.IdProductoNeo.ToString())
                {
                    Session["datosCliente"] = datosCliente;
                    return(RedirectToAction("Solicitud", "SobreGiro"));
                }

                if (json.producto == _settings.ProductoCP.IdProductoNeo.ToString())
                {
                    var obj = new DatosClientePy(); obj.Cedula = json.identificacion;
                    Session["datosClienteCP"] = obj;
                    return(RedirectToAction("Simulador", "CreditoPyme"));
                }
            }


            return(RedirectToAction("Notificacion", "ErrorHandler", new { id = codigoRetorno }));
        }
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 protected abstract string CreateHandshakeData(DataToken dataToken);
Exemplo n.º 26
0
 internal HandshakeResult Send(DataToken dataToken)
 {
     string handshakeData = CreateHandshakeData(dataToken);
     try
     {
         Handler.SendMessage(dataToken.Socket, handshakeData, Encoding, result => { });
         return HandshakeResult.Success;
     }
     catch (Exception)
     {
         return HandshakeResult.Close;
     }
 }
Exemplo n.º 27
0
        /// <summary>
        /// Receive handshake
        /// </summary>
        /// <param name="ioEventArgs"></param>
        /// <param name="dataToken"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        internal HandshakeResult Receive(SocketAsyncEventArgs ioEventArgs, DataToken dataToken, byte[] data)
        {
            if (dataToken.byteArrayForHandshake == null)
            {
                dataToken.byteArrayForHandshake = new List<byte>(data);
            }
            else
            {
                dataToken.byteArrayForHandshake.AddRange(data);
            }
            var buffer = dataToken.byteArrayForHandshake.ToArray();
            int headLength = MathUtils.IndexOf(buffer, HandshakeEndBytes);
            if (headLength < 0)
            {
                //data not complate, wait receive
                return HandshakeResult.Wait;
            }
            headLength += HandshakeEndBytes.Length;
            byte[] headBytes = new byte[headLength];
            Buffer.BlockCopy(buffer, 0, headBytes, 0, headBytes.Length);

            string message = Encoding.GetString(headBytes);
            HandshakeData handshakeData = dataToken.Socket.Handshake;
            string error;
            if (TryParseHandshake(message, handshakeData, out error))
            {
                if (handshakeData.ParamItems.ContainsKey(HandshakeHeadKeys.SecKey1) &&
                    handshakeData.ParamItems.ContainsKey(HandshakeHeadKeys.SecKey2))
                {
                    int remainBytesNum = buffer.Length - headLength;
                    if (!handshakeData.IsClient && remainBytesNum == 8)
                    {
                        byte[] secKey3Bytes = new byte[remainBytesNum];
                        Buffer.BlockCopy(buffer, headBytes.Length, secKey3Bytes, 0, secKey3Bytes.Length);
                        handshakeData.ParamItems[HandshakeHeadKeys.SecKey3] = secKey3Bytes;
                    }
                    else if (handshakeData.IsClient && remainBytesNum == 16)
                    {
                        byte[] secKey3Bytes = new byte[remainBytesNum];
                        Buffer.BlockCopy(buffer, headBytes.Length, secKey3Bytes, 0, secKey3Bytes.Length);
                        handshakeData.ParamItems[HandshakeHeadKeys.SecAccept] = secKey3Bytes;
                    }
                    else
                    {
                        //data not complate, wait receive
                        return HandshakeResult.Wait;
                    }
                }
                if (!handshakeData.IsClient)
                {
                    bool result = ResponseHandshake(dataToken.Socket, handshakeData);
                    if (!result)
                    {
                        TraceLog.ReleaseWriteDebug("Client {0} handshake fail, message:\r\n{2}", dataToken.Socket.RemoteEndPoint, message);
                        return HandshakeResult.Close;
                    }
                    dataToken.byteArrayForHandshake = null;
                    dataToken.Socket.Handshake.Handshaked = true;
                    return HandshakeResult.Success;
                }
                if (CheckSignKey(handshakeData))
                {
                    dataToken.byteArrayForHandshake = null;
                    dataToken.Socket.Handshake.Handshaked = true;
                    return HandshakeResult.Success;
                }
                return HandshakeResult.Close;
            }
            TraceLog.WriteWarn("Client {0} handshake {1}error, detail\r\n{2}", dataToken.Socket.RemoteEndPoint, error, message);
            return HandshakeResult.Close;
        }
Exemplo n.º 28
0
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 protected abstract string CreateHandshakeData(DataToken dataToken);
        /// <summary>
        /// Receive handshake
        /// </summary>
        /// <param name="ioEventArgs"></param>
        /// <param name="dataToken"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        internal HandshakeResult Receive(SocketAsyncEventArgs ioEventArgs, DataToken dataToken, byte[] data)
        {
            if (dataToken.byteArrayForHandshake == null)
            {
                dataToken.byteArrayForHandshake = new List <byte>(data);
            }
            else
            {
                dataToken.byteArrayForHandshake.AddRange(data);
            }
            var buffer     = dataToken.byteArrayForHandshake.ToArray();
            int headLength = MathUtils.IndexOf(buffer, HandshakeEndBytes);

            if (headLength < 0)
            {
                //data not complate, wait receive
                return(HandshakeResult.Wait);
            }
            headLength += HandshakeEndBytes.Length;
            byte[] headBytes = new byte[headLength];
            Buffer.BlockCopy(buffer, 0, headBytes, 0, headBytes.Length);

            string        message       = Encoding.GetString(headBytes);
            HandshakeData handshakeData = dataToken.Socket.Handshake;
            string        error;

            if (TryParseHandshake(message, handshakeData, out error))
            {
                if (handshakeData.ParamItems.ContainsKey(HandshakeHeadKeys.SecKey1) &&
                    handshakeData.ParamItems.ContainsKey(HandshakeHeadKeys.SecKey2))
                {
                    int remainBytesNum = buffer.Length - headLength;
                    if (!handshakeData.IsClient && remainBytesNum == 8)
                    {
                        byte[] secKey3Bytes = new byte[remainBytesNum];
                        Buffer.BlockCopy(buffer, headBytes.Length, secKey3Bytes, 0, secKey3Bytes.Length);
                        handshakeData.ParamItems[HandshakeHeadKeys.SecKey3] = secKey3Bytes;
                    }
                    else if (handshakeData.IsClient && remainBytesNum == 16)
                    {
                        byte[] secKey3Bytes = new byte[remainBytesNum];
                        Buffer.BlockCopy(buffer, headBytes.Length, secKey3Bytes, 0, secKey3Bytes.Length);
                        handshakeData.ParamItems[HandshakeHeadKeys.SecAccept] = secKey3Bytes;
                    }
                    else
                    {
                        //data not complate, wait receive
                        return(HandshakeResult.Wait);
                    }
                }
                if (!handshakeData.IsClient)
                {
                    bool result = ResponseHandshake(dataToken.Socket, handshakeData);
                    if (!result)
                    {
                        TraceLog.ReleaseWriteDebug("Client {0} handshake fail, message:\r\n{2}", dataToken.Socket.RemoteEndPoint, message);
                        return(HandshakeResult.Close);
                    }
                    dataToken.byteArrayForHandshake       = null;
                    dataToken.Socket.Handshake.Handshaked = true;
                    return(HandshakeResult.Success);
                }
                if (CheckSignKey(handshakeData))
                {
                    dataToken.byteArrayForHandshake       = null;
                    dataToken.Socket.Handshake.Handshaked = true;
                    return(HandshakeResult.Success);
                }
                return(HandshakeResult.Close);
            }
            TraceLog.WriteWarn("Client {0} handshake {1}error, detail\r\n{2}", dataToken.Socket.RemoteEndPoint, error, message);
            return(HandshakeResult.Close);
        }
Exemplo n.º 30
0
        public ActionResult Create(CreateTemplateModel model, FormCollection frm)
        {
            if (!_permissionService.Authorize("ManageTemplates"))
            {
                return(AccessDeniedView());
            }

            // Check for duplicate templates, if any
            var _template = _templateService.GetTemplateByName(model.Name);

            if (_template != null)
            {
                ModelState.AddModelError("Name", "A Template with the same name already exists. Please choose a different name.");
            }

            if (ModelState.IsValid)
            {
                var template = new Template
                {
                    BodyHtml        = model.BodyHtml,
                    IsActive        = model.IsActive,
                    Name            = model.Name,
                    UserId          = _userContext.CurrentUser.Id,
                    IsDeleted       = false,
                    CreatedOn       = DateTime.Now,
                    ModifiedOn      = DateTime.Now,
                    Url             = "",
                    IsSystemDefined = false,
                    Subject         = model.Subject
                };

                var dtTokens = _templateService.GetAllDataTokens().ToList();
                if (dtTokens.Count > 0)
                {
                    foreach (DataToken dToken in dtTokens)
                    {
                        if (template.BodyHtml.Contains("[" + dToken.Name + "]"))
                        {
                            var dtToken = new DataToken()
                            {
                                Id         = dToken.Id,
                                Name       = dToken.Name,
                                UserId     = dToken.UserId,
                                Value      = dToken.Value,
                                CreatedOn  = dToken.CreatedOn,
                                ModifiedOn = dToken.ModifiedOn,
                                IsActive   = dToken.IsActive,
                                IsDeleted  = false
                            };
                            template.Tokens.Add(dtToken);
                        }
                    }
                }

                _templateService.Insert(template);
            }
            else
            {
                return(View(model));
            }

            SuccessNotification("Template created successfully.");
            return(RedirectToAction("List"));
        }
Exemplo n.º 31
0
        private bool CheckPrefixHeadComplated(DataToken dataToken, byte[] buffer, ref int offset)
        {
            if (dataToken.byteArrayForPrefix == null || dataToken.byteArrayForPrefix.Length != PreByteLength)
            {
                dataToken.byteArrayForPrefix = new byte[PreByteLength];
            }
            if (PreByteLength - dataToken.prefixBytesDone > buffer.Length - offset)
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix, dataToken.prefixBytesDone, buffer.Length - offset);
                dataToken.prefixBytesDone += buffer.Length - offset;
                return false;
            }

            int count = dataToken.byteArrayForPrefix.Length - dataToken.prefixBytesDone;
            if (count > 0)
            {
                Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix, dataToken.prefixBytesDone, count);
                dataToken.prefixBytesDone += count;
                offset += count;
            }
            return true;
        }
 private bool CheckPrefix2Complated(DataToken dataToken, byte[] buffer, ref int offset, int size)
 {
     if (dataToken.byteArrayForPrefix2 == null || dataToken.byteArrayForPrefix2.Length != size)
     {
         dataToken.byteArrayForPrefix2 = new byte[size];
     }
     if (size - dataToken.prefixBytesDone2 > buffer.Length - offset)
     {
         Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix2, dataToken.prefixBytesDone2, buffer.Length - offset);
         dataToken.prefixBytesDone2 += buffer.Length - offset;
         return false;
     }
     int count = dataToken.byteArrayForPrefix2.Length - dataToken.prefixBytesDone2;
     if (count > 0)
     {
         Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForPrefix2, dataToken.prefixBytesDone2, count);
         dataToken.prefixBytesDone2 += count;
         offset += count;
     }
     return true;
 }
        private bool CheckPayloadHeadComplated(DataToken dataToken, byte[] buffer, ref int offset)
        {
            try
            {

                if (dataToken.byteArrayForMessage == null)
                {
                    int size = 0;
                    int payloadLenght = dataToken.HeadFrame.PayloadLenght;
                    switch (payloadLenght)
                    {
                        case 126:
                            size = 2; //uint16 2bit
                            if (!CheckPrefix2Complated(dataToken, buffer, ref offset, size)) return false;
                            UInt16 len = (UInt16)(dataToken.byteArrayForPrefix2[0] << 8 | dataToken.byteArrayForPrefix2[1]);
                            dataToken.byteArrayForMessage = new byte[len];
                            break;
                        case 127:
                            size = 8; //uint64 8bit
                            if (!CheckPrefix2Complated(dataToken, buffer, ref offset, size)) return false;
                            UInt64 len64 = BitConverter.ToUInt64(dataToken.byteArrayForPrefix2.Reverse().ToArray(), 0);
                            dataToken.byteArrayForMessage = new byte[len64];
                            break;
                        default:
                            dataToken.byteArrayForMessage = new byte[payloadLenght];
                            break;
                    }
                    dataToken.messageLength = dataToken.byteArrayForMessage.Length;
                }
                if (dataToken.HeadFrame.HasMask)
                {
                    if (dataToken.byteArrayMask == null || dataToken.byteArrayMask.Length != MaskLength)
                    {
                        dataToken.byteArrayMask = new byte[MaskLength];
                    }
                    if (MaskLength - dataToken.maskBytesDone > buffer.Length - offset)
                    {
                        Buffer.BlockCopy(buffer, offset, dataToken.byteArrayMask, dataToken.maskBytesDone, buffer.Length - offset);
                        dataToken.maskBytesDone += buffer.Length - offset;
                        return false;
                    }
                    int count = dataToken.byteArrayMask.Length - dataToken.maskBytesDone;
                    if (count > 0)
                    {
                        Buffer.BlockCopy(buffer, offset, dataToken.byteArrayMask, dataToken.maskBytesDone, count);
                        dataToken.maskBytesDone += count;
                        offset += count;
                    }
                }
                return true;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 private bool CheckPayloadDataComplated(DataToken dataToken, byte[] buffer, ref int offset)
 {
     int copyByteCount = dataToken.RemainByte;
     if (buffer.Length - offset >= copyByteCount)
     {
         Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, copyByteCount);
         dataToken.messageBytesDone += copyByteCount;
         offset += copyByteCount;
     }
     else
     {
         Buffer.BlockCopy(buffer, offset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, buffer.Length - offset);
         dataToken.messageBytesDone += buffer.Length - offset;
         offset += buffer.Length - offset;
     }
     return dataToken.IsMessageReady;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataToken"></param>
        /// <returns></returns>
        protected override string CreateHandshakeData(DataToken dataToken)
        {
            ClientWebSocket webSocket = Handler.AppServer as ClientWebSocket;
            if (webSocket == null)
            {
                throw new Exception("ISocket is not WebSocket client");
            }
            string host = webSocket.Settings.RemoteEndPoint.ToString();
            string urlPath = webSocket.Settings.UrlPath;
            string origin = webSocket.Settings.Origin;
            string secKey1 = Encoding.ASCII.GetString(GenerateSecKey());
            string secKey2 = Encoding.ASCII.GetString(GenerateSecKey());
            byte[] secKey3 = GenerateSecKey(8);
            string protocol = webSocket.Settings.Protocol;
            string extensions = webSocket.Settings.Extensions;
            string cookie = ToCookiesString(webSocket.Settings.Cookies);

            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecSignKey] = GetResponseSecurityKey(secKey1, secKey2, secKey3);
            dataToken.Socket.Handshake.UriSchema = webSocket.Settings.Scheme;
            dataToken.Socket.Handshake.Host = host;
            dataToken.Socket.Handshake.UrlPath = urlPath;
            dataToken.Socket.Handshake.Protocol = protocol;
            dataToken.Socket.Handshake.HttpVersion = HandshakeHeadKeys.HttpVersion;
            dataToken.Socket.Handshake.Method = HandshakeHeadKeys.Method;
            dataToken.Socket.Handshake.WebSocketVersion = _version;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.Origin] = origin;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecKey1] = secKey1;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecKey2] = secKey2;
            ParseCookies(dataToken.Socket.Handshake, cookie);

            StringBuilder result = new StringBuilder();
            result.AppendLine(string.Format("{0} {1} {2}", HandshakeHeadKeys.Method, urlPath, HandshakeHeadKeys.HttpVersion));
            result.AppendLine(HandshakeHeadKeys.RespUpgrade00);
            result.AppendLine(HandshakeHeadKeys.RespConnection);
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecKey1, secKey1));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecKey2, secKey2));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Host, host));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Origin, !string.IsNullOrEmpty(origin) ? origin : host));

            if (!string.IsNullOrEmpty(protocol))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecProtocol, protocol));
            }
            if (!string.IsNullOrEmpty(extensions))
            {
                dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecExtensions] = extensions;
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecExtensions, extensions));
            }
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecVersion, _version));
            if (!string.IsNullOrEmpty(cookie))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Cookie, cookie));
            }

            result.AppendLine();
            result.Append(Encoding.GetString(secKey3, 0, secKey3.Length));
            return result.ToString();
        }
Exemplo n.º 36
0
        private dynamic ExtractField(ISelectable item, Page page, DataToken field, int index)
        {
            ISelector selector = SelectorUtil.Parse(field.Selector);
            if (selector == null)
            {
                return null;
            }

            var f = field as Field;
            List<Formatter.Formatter> formatters = GenerateFormatter(f?.Formatters);

            bool isEntity = field is Entity;

            if (!isEntity)
            {
                string tmpValue;
                if (selector is EnviromentSelector)
                {
                    var enviromentSelector = selector as EnviromentSelector;
                    tmpValue = GetEnviromentValue(enviromentSelector.Field, page, index);
                    foreach (var formatter in formatters)
                    {
                        tmpValue = formatter.Formate(tmpValue);
                    }
                    return tmpValue;
                }
                else
                {
                    bool needPlainText = (((Field)field).Option == PropertyExtractBy.ValueOption.PlainText);
                    if (field.Multi)
                    {
                        var propertyValues = item.SelectList(selector).Nodes();

                        List<string> results = new List<string>();
                        foreach (var propertyValue in propertyValues)
                        {
                            string tmp = propertyValue.GetValue(needPlainText);
                            foreach (var formatter in formatters)
                            {
                                tmp = formatter.Formate(tmp);
                            }
                            results.Add(tmp);
                        }
                        return new JArray(results);
                    }
                    else
                    {
                        bool needCount = (((Field)field).Option == PropertyExtractBy.ValueOption.Count);
                        if (needCount)
                        {
                            var propertyValues = item.SelectList(selector).Nodes();
                            return propertyValues != null ? propertyValues.Count.ToString() : "-1";
                        }
                        else
                        {
                            tmpValue = item.Select(selector)?.GetValue(needPlainText);
                            tmpValue = formatters.Aggregate(tmpValue, (current, formatter) => formatter.Formate(current));
                            return tmpValue;
                        }
                    }
                }
            }
            else
            {
                if (field.Multi)
                {
                    var propertyValues = item.SelectList(selector).Nodes();
                    JArray objs = new JArray();
                    var selectables = item.SelectList(selector).Nodes();
                    foreach (var selectable in selectables)
                    {
                        JObject obj = new JObject();

                        foreach (var child in ((Entity)field).Fields)
                        {
                            obj.Add(child.Name, ExtractField(selectable, page, child, 0));
                        }
                        objs.Add(obj);
                    }
                    return objs;
                }
                else
                {
                    JObject obj = new JObject();
                    var selectable = item.Select(selector);
                    foreach (var child in ((Entity)field).Fields)
                    {
                        obj.Add(child.Name, ExtractField(selectable, page, field, 0));
                    }
                    return obj;
                }
            }
        }
Exemplo n.º 37
0
        private dynamic ExtractField(ISelectable item, Page page, DataToken field, int index)
        {
            ISelector selector = SelectorUtil.GetSelector(field.Selector);

            if (selector == null)
            {
                return(null);
            }

            var f = field as Field;
            List <Formatter.Formatter> formatters = GenerateFormatter(f?.Formatters);

            bool isEntity = field is Entity;

            if (!isEntity)
            {
                string tmpValue;
                if (selector is EnviromentSelector)
                {
                    var enviromentSelector = selector as EnviromentSelector;
                    tmpValue = GetEnviromentValue(enviromentSelector.Field, page, index);
                    foreach (var formatter in formatters)
                    {
                        tmpValue = formatter.Formate(tmpValue);
                    }
                    return(tmpValue);
                }
                else
                {
                    if (field.Multi)
                    {
                        var propertyValues = item.SelectList(selector).Nodes();
                        if (((Field)field).Option == PropertyExtractBy.ValueOption.Count)
                        {
                            var tempValue = propertyValues != null?propertyValues.Count.ToString() : "-1";

                            return(tempValue);
                        }
                        else
                        {
                            List <string> results = new List <string>();
                            foreach (var propertyValue in propertyValues)
                            {
                                string tmp = propertyValue.GetValue(((Field)field).Option == PropertyExtractBy.ValueOption.PlainText);
                                foreach (var formatter in formatters)
                                {
                                    tmp = formatter.Formate(tmp);
                                }
                                results.Add(tmp);
                            }
                            return(new JArray(results));
                        }
                    }
                    else
                    {
                        tmpValue = item.Select(selector)?.GetValue(((Field)field).Option == PropertyExtractBy.ValueOption.PlainText);
                        if (((Field)field).Option == PropertyExtractBy.ValueOption.Count)
                        {
                            return(tmpValue == null ? 0 : 1);
                        }
                        else
                        {
                            tmpValue = formatters.Aggregate(tmpValue, (current, formatter) => formatter.Formate(current));
                            return(tmpValue);
                        }
                    }
                }
            }
            else
            {
                if (field.Multi)
                {
                    var    propertyValues = item.SelectList(selector).Nodes();
                    JArray objs           = new JArray();
                    var    selectables    = item.SelectList(selector).Nodes();
                    foreach (var selectable in selectables)
                    {
                        JObject obj = new JObject();

                        foreach (var child in ((Entity)field).Fields)
                        {
                            obj.Add(child.Name, ExtractField(selectable, page, child, 0));
                        }
                        objs.Add(obj);
                    }
                    return(objs);
                }
                else
                {
                    JObject obj        = new JObject();
                    var     selectable = item.Select(selector);
                    foreach (var child in ((Entity)field).Fields)
                    {
                        obj.Add(child.Name, ExtractField(selectable, page, field, 0));
                    }
                    return(obj);
                }
            }
        }
Exemplo n.º 38
0
        public void ParseDDSCData(SocketAsyncEventArgs S, byte[] buffer)
        {
            DataToken Token    = S.UserToken as DataToken;
            string    RemoteIP = Token.Ip;
            string    port     = Token.Port;

            try
            {
                switch (buffer[0])
                {
                case 0xFF:
                    if (_DataEncode)
                    {
                        buffer = SocketRaw.DecodeData(buffer);
                    }
                    // WriteLog("SAEAServerLogRCV" + S.AcceptSocket.RemoteEndPoint.ToString().Replace(":", ";"), buffer);
                    WriteLog("SAEAServerLogRCV" + RemoteIP, buffer);
                    ParseMA(S, buffer);
                    break;

                case SocketRaw.Alive:
                    if (_DataEncode)
                    {
                        buffer = SocketRaw.DecodeData(buffer);
                    }
                    // WriteLog("SAEAServerLogRCV" + S.AcceptSocket.RemoteEndPoint.ToString().Replace(":", ";"), buffer);
                    WriteLog("SAEAServerLogRCV" + RemoteIP, buffer);
                    ParseAlive(S, buffer);
                    break;

                case SocketRaw.RegTradeAct:
                    if (_DataEncode)
                    {
                        buffer = SocketRaw.DecodeData(buffer);
                    }
                    //WriteLog("SAEAServerLogRCV" + S.AcceptSocket.RemoteEndPoint.ToString().Replace(":", ";"), buffer);
                    WriteLog("SAEAServerLogRCV" + RemoteIP, buffer);
                    ParseRegTradeAct(S, buffer);
                    break;

                case SocketRaw.Connecting:
                    if (_DataEncode)
                    {
                        buffer = SocketRaw.DecodeData(buffer);
                    }
                    //WriteLog("SAEAServerLogRCV" + S.AcceptSocket.RemoteEndPoint.ToString().Replace(":", ";"), buffer);
                    WriteLog("SAEAServerLogRCV" + RemoteIP, buffer);
                    ParseConnecting(S, buffer);
                    break;

                case SocketRaw.GeneralTrade:

                    if (_DataEncode)
                    {
                        buffer = SocketRaw.DecodeData(buffer);
                    }
                    //WriteLog("SAEAServerLogRCV" + S.AcceptSocket.RemoteEndPoint.ToString().Replace(":", ";"), buffer);
                    WriteLog("SAEAServerLogRCV" + RemoteIP, buffer);

                    //if (buffer[0] == SocketRaw.GeneralTrade)
                    //    ParseGeneralTrade(Token, S, buffer);

                    break;



                default:



                    WriteLog("DataAgentLog", "ParseDDSCData:" + "length=" + buffer.Length + RemoteIP + ":" + port.ToString() + "format error!");
                    WriteLog("DataAgentLog", "ParseDDSCData:" + ASCIIEncoding.ASCII.GetString(buffer));
                    WriteLog("DataAgentLog", "ParseDDSCData:" + ASCIIEncoding.ASCII.GetString(_DataEncode ? SocketRaw.DecodeData(buffer) : buffer));
                    _SAEA.CloseClientSocket(S);
                    break;
                }
            }
            catch (Exception ex)
            {
                WriteLog("DataAgentLog", "ParseDDSCData:" + "length=" + buffer.Length + "-" + ex.Message + ex.StackTrace.ToString() + ex.Source.ToString() + RemoteIP + ":" + port.ToString());
                WriteLog("DataAgentLog", "ParseDDSCData:" + ASCIIEncoding.ASCII.GetString(buffer));
                WriteLog("DataAgentLog", "ParseDDSCData:" + ASCIIEncoding.ASCII.GetString(_DataEncode ? SocketRaw.DecodeData(buffer) : buffer));
                _SAEA.CloseClientSocket(S);
            }
        }
Exemplo n.º 39
0
        public bool AddSAEA(string UserId, SocketAsyncEventArgs SAEA)
        {
            try
            {
                if (!_UI.ContainsKey(UserId))
                {
                    return(false);
                }
                Dictionary <string, string> U = (Dictionary <string, string>)_UI[UserId];
                DataToken tk = (DataToken)SAEA.UserToken;
                foreach (string UKey in U.Keys)
                {
                    lock (_IS)
                    {
                        if (!_IS.ContainsKey(UKey))
                        {
                            Dictionary <int, SocketAsyncEventArgs> SS = new Dictionary <int, SocketAsyncEventArgs>();
                            SS.Add(tk.TokenId, SAEA);

                            _IS[UKey] = SS;
                        }
                        else
                        {
                            Dictionary <int, SocketAsyncEventArgs> SS = (Dictionary <int, SocketAsyncEventArgs>)_IS[UKey];
                            if (!SS.ContainsKey(tk.TokenId))
                            {
                                SS.Add(tk.TokenId, SAEA);
                            }
                        }
                    }

                    lock (_SI)
                    {
                        if (!_SI.ContainsKey(SAEA))
                        {
                            Dictionary <string, string> InvestorAcnos = new Dictionary <string, string>();
                            InvestorAcnos.Add(UKey, UKey);
                            _SI[SAEA] = InvestorAcnos;
                        }
                        else
                        {
                            Dictionary <string, string> InvestorAcno = (Dictionary <string, string>)_SI[SAEA];
                            if (!InvestorAcno.ContainsKey(UKey))
                            {
                                InvestorAcno.Add(UKey, UKey);
                            }
                        }
                    }
                }
                lock (_US)
                {
                    if (!_US.ContainsKey(UserId))
                    {
                        Dictionary <int, SocketAsyncEventArgs> SS = new Dictionary <int, SocketAsyncEventArgs>();
                        SS.Add(tk.TokenId, SAEA);
                        _US[UserId] = SS;
                    }
                    else
                    {
                        Dictionary <int, SocketAsyncEventArgs> SS = (Dictionary <int, SocketAsyncEventArgs>)_US[UserId];
                        if (!SS.ContainsKey(tk.TokenId))
                        {
                            SS.Add(tk.TokenId, SAEA);
                        }
                    }
                }
                lock (_SU)
                {
                    if (!_SU.ContainsKey(SAEA))
                    {
                        Dictionary <string, string> UserIds = new Dictionary <string, string>();
                        UserIds.Add(UserId, UserId);
                        _SU[SAEA] = UserIds;
                    }
                    else
                    {
                        Dictionary <string, string> UserIds = (Dictionary <string, string>)_SU[SAEA];
                        if (!UserIds.ContainsKey(UserId))
                        {
                            UserIds.Add(UserId, UserId);
                        }
                    }
                }

                lock (_SUSERIDFO)
                {
                    if (!_SUSERIDFO.ContainsKey(SAEA))
                    {
                        UserInfo u = new UserInfo();
                        u.UserId    = UserId;
                        u.LoginTime = DateTime.Now.ToString("HH:mm:ss");
                        _SUSERIDFO.Add(SAEA, u);
                    }
                    else
                    {
                        _SUSERIDFO[SAEA].UserId = UserId;

                        _SUSERIDFO[SAEA].LoginTime = DateTime.Now.ToString("HH:mm:ss");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(true);
        }
Exemplo n.º 40
0
 private bool CheckDataComplated(DataToken dataToken, byte[] buffer, ref int offset)
 {
     byte[] data;
     int endMaskIndex = MathUtils.IndexOf(buffer, offset, buffer.Length - offset + 1, new[] { EndByte });
     if (endMaskIndex < 0)
     {
         data = new byte[buffer.Length - offset];
         Buffer.BlockCopy(buffer, offset, data, 0, data.Length);
         if (dataToken.byteArrayForMessage == null)
         {
             dataToken.byteArrayForMessage = data;
         }
         else
         {
             dataToken.byteArrayForMessage = BufferUtils.MergeBytes(dataToken.byteArrayForMessage, data);
         }
         offset += data.Length;
         return false;
     }
     //end mask not received
     if (endMaskIndex == 0)
     {
         offset += 1;
         return true;
     }
     data = new byte[endMaskIndex - offset];
     Buffer.BlockCopy(buffer, offset, data, 0, data.Length);
     dataToken.byteArrayForMessage = BufferUtils.MergeBytes(dataToken.byteArrayForMessage, data);
     offset += data.Length + 1;
     return true;
 }
Exemplo n.º 41
0
        public void RemoveSAEA(SocketAsyncEventArgs SAEA)
        {
            try
            {
                DataToken tk = (DataToken)SAEA.UserToken;
                Dictionary <string, string> SItemp = null;
                lock (_SI)
                {
                    if (_SI == null)
                    {
                        return;
                    }
                    if (!_SI.ContainsKey(SAEA))
                    {
                        return;
                    }
                    Dictionary <string, string> SI = (Dictionary <string, string>)_SI[SAEA];
                    SItemp = new Dictionary <string, string>(SI);
                    _SI.Remove(SAEA);
                }
                lock (_IS)
                {
                    if (SItemp != null)
                    {
                        foreach (string SIkey in SItemp.Keys)
                        {
                            Dictionary <int, SocketAsyncEventArgs> SS = (Dictionary <int, SocketAsyncEventArgs>)_IS[SIkey];
                            SS.Remove(tk.TokenId);
                        }
                    }
                }
                lock (_SU)
                {
                    if (!_SU.ContainsKey(SAEA))
                    {
                        return;
                    }
                    Dictionary <string, string> SU = (Dictionary <string, string>)_SU[SAEA];



                    foreach (string SUkey in SU.Keys)
                    {
                        Dictionary <int, SocketAsyncEventArgs> SS = (Dictionary <int, SocketAsyncEventArgs>)_US[SUkey];
                        SS.Remove(tk.TokenId);
                    }
                    _SU.Remove(SAEA);
                }
                lock (_SUSERIDFO)
                {
                    if (_SUSERIDFO.ContainsKey(SAEA))
                    {
                        _SUSERIDFO.Remove(SAEA);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 42
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dataToken"></param>
        /// <returns></returns>
        protected override string CreateHandshakeData(DataToken dataToken)
        {
            ClientWebSocket webSocket = Handler.AppServer as ClientWebSocket;

            if (webSocket == null)
            {
                throw new Exception("ISocket is not WebSocket client");
            }
            string host    = webSocket.Settings.RemoteEndPoint.ToString();
            string urlPath = webSocket.Settings.UrlPath;
            string origin  = webSocket.Settings.Origin;
            string secKey1 = Encoding.ASCII.GetString(GenerateSecKey());
            string secKey2 = Encoding.ASCII.GetString(GenerateSecKey());

            byte[] secKey3    = GenerateSecKey(8);
            string protocol   = webSocket.Settings.Protocol;
            string extensions = webSocket.Settings.Extensions;
            string cookie     = ToCookiesString(webSocket.Settings.Cookies);

            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecSignKey] = GetResponseSecurityKey(secKey1, secKey2, secKey3);
            dataToken.Socket.Handshake.UriSchema        = webSocket.Settings.Scheme;
            dataToken.Socket.Handshake.Host             = host;
            dataToken.Socket.Handshake.UrlPath          = urlPath;
            dataToken.Socket.Handshake.Protocol         = protocol;
            dataToken.Socket.Handshake.HttpVersion      = HandshakeHeadKeys.HttpVersion;
            dataToken.Socket.Handshake.Method           = HandshakeHeadKeys.Method;
            dataToken.Socket.Handshake.WebSocketVersion = _version;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.Origin]  = origin;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecKey1] = secKey1;
            dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecKey2] = secKey2;
            ParseCookies(dataToken.Socket.Handshake, cookie);

            StringBuilder result = new StringBuilder();

            result.AppendLine(string.Format("{0} {1} {2}", HandshakeHeadKeys.Method, urlPath, HandshakeHeadKeys.HttpVersion));
            result.AppendLine(HandshakeHeadKeys.RespUpgrade00);
            result.AppendLine(HandshakeHeadKeys.RespConnection);
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecKey1, secKey1));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecKey2, secKey2));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Host, host));
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Origin, !string.IsNullOrEmpty(origin) ? origin : host));

            if (!string.IsNullOrEmpty(protocol))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecProtocol, protocol));
            }
            if (!string.IsNullOrEmpty(extensions))
            {
                dataToken.Socket.Handshake.ParamItems[HandshakeHeadKeys.SecExtensions] = extensions;
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecExtensions, extensions));
            }
            result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.SecVersion, _version));
            if (!string.IsNullOrEmpty(cookie))
            {
                result.AppendLine(string.Format("{0}: {1}", HandshakeHeadKeys.Cookie, cookie));
            }

            result.AppendLine();
            result.Append(Encoding.GetString(secKey3, 0, secKey3.Length));
            return(result.ToString());
        }
Exemplo n.º 43
0
        private bool CheckPayloadHeadComplated(DataToken dataToken, byte[] buffer, ref int offset)
        {
            try
            {
                if (dataToken.byteArrayForMessage == null)
                {
                    int size          = 0;
                    int payloadLenght = dataToken.HeadFrame.PayloadLenght;
                    switch (payloadLenght)
                    {
                    case 126:
                        size = 2;     //uint16 2bit
                        if (!CheckPrefix2Complated(dataToken, buffer, ref offset, size))
                        {
                            return(false);
                        }
                        UInt16 len = (UInt16)(dataToken.byteArrayForPrefix2[0] << 8 | dataToken.byteArrayForPrefix2[1]);
                        dataToken.byteArrayForMessage = new byte[len];
                        break;

                    case 127:
                        size = 8;     //uint64 8bit
                        if (!CheckPrefix2Complated(dataToken, buffer, ref offset, size))
                        {
                            return(false);
                        }
                        UInt64 len64 = BitConverter.ToUInt64(dataToken.byteArrayForPrefix2.Reverse().ToArray(), 0);
                        dataToken.byteArrayForMessage = new byte[len64];
                        break;

                    default:
                        dataToken.byteArrayForMessage = new byte[payloadLenght];
                        break;
                    }
                    dataToken.messageLength = dataToken.byteArrayForMessage.Length;
                }
                if (dataToken.HeadFrame.HasMask)
                {
                    if (dataToken.byteArrayMask == null || dataToken.byteArrayMask.Length != MaskLength)
                    {
                        dataToken.byteArrayMask = new byte[MaskLength];
                    }
                    if (MaskLength - dataToken.maskBytesDone > buffer.Length - offset)
                    {
                        Buffer.BlockCopy(buffer, offset, dataToken.byteArrayMask, dataToken.maskBytesDone, buffer.Length - offset);
                        dataToken.maskBytesDone += buffer.Length - offset;
                        return(false);
                    }
                    int count = dataToken.byteArrayMask.Length - dataToken.maskBytesDone;
                    if (count > 0)
                    {
                        Buffer.BlockCopy(buffer, offset, dataToken.byteArrayMask, dataToken.maskBytesDone, count);
                        dataToken.maskBytesDone += count;
                        offset += count;
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }