Exemple #1
0
 public RequestData GetRequestData(ClientRequest request)
 {
     //burada gelen SearchRequest sınıfındaki parametrelere göre
     //veritabanına ilgili sorgunun atılıp geriye dönen cevabı
     //RequestData sınıfına eklediğimiz düşünülüyor
     return new RequestData();
 }
        // TODO: Verify ClientRequest values.
        static async Task HandleRealmListTicketRequest(ClientRequest clientRequest, BnetSession session)
        {
            var paramIdentityValue = clientRequest.GetVariant("Param_Identity")?.BlobValue.ToStringUtf8();
            var paramClientInfoValue = clientRequest.GetVariant("Param_ClientInfo")?.BlobValue.ToStringUtf8();

            if (paramIdentityValue != null && paramClientInfoValue != null)
            {
                var realmListTicketIdentity = CreateObject<RealmListTicketIdentity>(paramIdentityValue, true);
                var realmListTicketClientInformation = CreateObject<RealmListTicketClientInformation>(paramClientInfoValue, true);

                session.GameAccount = session.Account.GameAccounts.SingleOrDefault(ga => ga.Id == realmListTicketIdentity.GameAccountId);

                if (session.GameAccount != null)
                {
                    session.RealmListSecret = realmListTicketClientInformation.Info.Secret.Select(x => Convert.ToByte(x)).ToArray();
                    session.RealmListTicket = new byte[0].GenerateRandomKey(32);

                    var realmListTicketResponse = new ClientResponse();

                    realmListTicketResponse.Attribute.Add(new Bgs.Protocol.Attribute
                    {
                        Name = "Param_RealmListTicket",
                        Value = new Variant
                        {
                            BlobValue = ByteString.CopyFrom(session.RealmListTicket)
                        }
                    });

                    await session.Send(realmListTicketResponse);
                }
            }
            else
                session.Dispose();
        }
        public ClientResponse Request(ClientRequest request)
        {
            TcpClient tcp = new TcpClient();

            try {
                tcp.Connect(request.Dns);

                Stream stream = tcp.GetStream();
                byte[] buffer = request.ToArray();
                byte[] length = BitConverter.GetBytes((ushort) buffer.Length);

                if (BitConverter.IsLittleEndian) {
                    Array.Reverse(length);
                }

                stream.Write(length, 0, length.Length);
                stream.Write(buffer, 0, buffer.Length);

                buffer = new byte[2];
                Read(stream, buffer);

                if (BitConverter.IsLittleEndian) {
                    Array.Reverse(buffer);
                }

                buffer = new byte[BitConverter.ToUInt16(buffer, 0)];
                Read(stream, buffer);

                Response response = Response.FromArray(buffer);

                return new ClientResponse(request, response, buffer);
            } finally {
                tcp.Close();
            }
        }
Exemple #4
0
        /// <summary>
        /// starts listening on the port specified.
        /// WARNING: Delegates must be thread safe
        /// </summary>
        /// <param name="ip">The IP address to listen for. Use "0.0.0.0" or "any" for all IPs</param>
        /// <param name="port">The port to listen on</param>
        /// <param name="separator">What signals the end of a message? A good choice is \n</param>
        /// <param name="clientstatechange">A delegate that is called when a client connects or disconnects</param>
        /// <param name="clientrequest">A delegate that is called when a client sends a request</param>
        // TODO: Allow other types of comms, like UDP, IPv6, etc
        public ServerSocket(string ip, int port, string separator, ClientStateChange clientstatechange, ClientRequest clientrequest)
        {
            this.clientchange = clientstatechange;
            this.clientreq = clientrequest;

            IPAddress IP;
            if (ip == "any")
                IP = IPAddress.Any;
            else
                try
                {
                    byte[] octets = new byte[4];
                    string[] exploded = ip.Split('.');
                    for (byte i = 0; i < 4; i++)
                        octets[i] = byte.Parse(exploded[i]);
                    IP = new IPAddress(octets);
                }
                catch (Exception)
                {
                    throw new Exception("IP Address malformed");
                }

            //IP Address should be valid by now, attempt a bind
            ServerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEP = new IPEndPoint(IP, port);
            ServerSock.Bind(remoteEP);

            this.separator = separator;
            Listener = new Thread(new ThreadStart(ListenAsync));
            Listener.Start();
        }
Exemple #5
0
        public override void ProcessClientRequest(IRpcController controller, ClientRequest request, Action<ClientResponse> done)
        {
            var response = new ClientResponse.Builder
                              {

                              };
            done(response.Build());
        }
        public override void ProcessClientRequest(IRpcController controller, ClientRequest request, Action<ClientResponse> done)
        {
            Logger.Trace("ProcessClientRequest()");

            // TODO: handle the request. this is where banner changing happens (CustomMessageId 4)
            // CustomMessage for banner change is a D3.GameMessages.SaveBannerConfiguration
            var builder = ClientResponse.CreateBuilder();
            done(builder.Build());
        }
Exemple #7
0
 private static IEnumerable<ulong> HandleLocation(ThreadManager TM, ClientRequest request)
 {
     var currentThread = TM.CurrentThread;
     yield return TM.Return(currentThread,
         new PointsOfInterestResponse(
             new PointOfInterest(1, 2.3, "Java City", "Coffee"),
             new PointOfInterest(4.5, 6, "Logan's", "More Coffee"),
             new PointOfInterest(7.8, 9, "Noble Roman's", "Pizza")));
 }
        public static async void HandleClientRequest(ClientRequest clientRequest, BnetSession session)
        {
            Func<ClientRequest, BnetSession, Task> clientRequestHandler;

            if (clientRequestHandlers.TryGetValue(clientRequest.Attribute[0].Name, out clientRequestHandler))
            {
                Log.Message(LogTypes.Error, $"client request '{clientRequest}'.\n");

                await clientRequestHandler(clientRequest, session);
            }
            else
                Log.Message(LogTypes.Error, $"Tried to call non existing handler for client request '{clientRequest.Attribute[0].Name}'.");
        }
    public static void startServer(int port)
    {
        try {
            TcpListener listener = new TcpListener(IPAddress.Any, port);
            listener.Start();

            while(true) {
                TcpClient client = listener.AcceptTcpClient();
                ClientRequest cr = new ClientRequest(client);
                ThreadPool.QueueUserWorkItem(cr.GetClientInput);
            }

        } catch(SocketException e) {
            Console.WriteLine("SocketException: {0}", e);
        }
    }
Exemple #10
0
        public ClientResponse Request(ClientRequest request) {
            UdpClient udp = new UdpClient();
            IPEndPoint dns = request.Dns;

            try {
                udp.Connect(dns);
                udp.Send(request.ToArray(), request.Size);

                byte[] buffer = udp.Receive(ref dns);
                Response response = Response.FromArray(buffer); //null;

                if (response.Truncated) {
                    return fallback.Request(request);
                }

                return new ClientResponse(request, response, buffer);
            } finally {
                udp.Close();
            }
        }
 private void OnClientRequest(ClientRequest request)
 {
     if ( this.ClientRequest != null )
         this.ClientRequest(this, new ClientRequestEventArgs(request));
 }
Exemple #12
0
		public override void ProcessClientRequest(Google.ProtocolBuffers.IRpcController controller, ClientRequest request, Action<ClientResponse> done) {
			var response = ClientResponse.CreateBuilder();
			done(response.Build());
		}
    // plays a match with randomly generated scores,
    // updates DB with match, and updates both player's stats as well.
    public string playMatch(ClientRequest player1, ClientRequest player2)
    {
        Random r = new Random();
        int n = r.Next(1, 10000);
        string IdNum = n.ToString("D" + 5);
        TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
        string date = ((int)t.TotalSeconds).ToString();
        string matchName = String.Format("{0}{1}",
                GameMatchingServer.nickName, IdNum);
        int p1Score = r.Next(1, 100);
        int p2Score = r.Next(1, 100);

        if (p1Score > p2Score) {
            player1.wins++;
            player2.losses++;
        } else {
            player2.wins++;
            player1.losses++;
        }
        double rank1 = (double)player1.wins / (player1.wins + player1.losses);
        double rank2 = (double)player2.wins / (player2.wins + player2.losses);
        player1.rank = Math.Round(rank1, 2);
        player2.rank = Math.Round(rank2, 2);

        addMatchToDB(matchName, date, player1.uname, player2.uname,
                p1Score, p2Score);
        updateUserEntry(player1.uname, player1.rank, player1.wins, player1.losses);
        updateUserEntry(player2.uname, player2.rank, player2.wins, player2.losses);

        return String.Format("200 ACCEPT:{0}:{1}:{2}:{3}:{4}:{5}",
                matchName, date, player1.uname, player2.uname, p1Score, p2Score);
    }
Exemple #14
0
 public static void SendClientRequest(ClientRequest request, RPCContextDelegate callback = null)
 {
     BattleNet.s_impl.SendClientRequest(request, callback);
 }
 public abstract string ComputeCounterKey(ClientRequest clientRequest, RateLimitRule rule);
Exemple #16
0
 public void SendRequestPacket(ClientRequest request, uint gem_num, float r, float g, float b)
 {
     byte[] PacketData = new byte[24];
     int request_net = System.Net.IPAddress.HostToNetworkOrder((int)request);
     int payload_size_net = System.Net.IPAddress.HostToNetworkOrder(16);
     int gem_num_net = System.Net.IPAddress.HostToNetworkOrder((int)gem_num);
     Buffer.BlockCopy(BitConverter.GetBytes(request_net), 0, PacketData, 0, 4);
     Buffer.BlockCopy(BitConverter.GetBytes(payload_size_net), 0, PacketData, 4, 4);
     Buffer.BlockCopy(BitConverter.GetBytes(gem_num_net), 0, PacketData, 8, 4);
     NetworkWriterHelper.WriteFloat(r, ref PacketData, 12);
     NetworkWriterHelper.WriteFloat(g, ref PacketData, 16);
     NetworkWriterHelper.WriteFloat(b, ref PacketData, 20);
     NetworkStream stream = _tcpClient.GetStream();
     stream.Write(PacketData, 0, PacketData.Length);
 }
Exemple #17
0
 private void retryToSendProposalToLeaders(ClientRequest request)
 {
     this.strategyContainer.ExecuteStrategy(request, this.currentReplicaState);
 }
Exemple #18
0
 private void onDecisionRejected(object sender, ClientRequest request)
 {
     retryToSendProposalToLeaders(request);
 }
Exemple #19
0
 private void onDecisionApproved(object sender, ClientRequest decision)
 {
     applyDecisionsToStateMachine();
 }
 protected override void GivenTheRequestRepositoryIs(ClientRequest request)
 {
     Repository.Setup(r => r.GetRequest()).Returns(request);
 }
Exemple #21
0
 public ServerResponse GetAllEvents(ClientRequest clientReq)
 {
     return(_serviceProvider.VIIEventsService.GetEvents());
 }
Exemple #22
0
 public string ComposeUri_Exposed(ClientRequest request)
 {
     return(ComposeUri(request));
 }
Exemple #23
0
        protected virtual async Task <IResponse> ResolveRemote(Request request)
        {
            ClientRequest remoteRequest = client.Create(request);

            return(await remoteRequest.Resolve());
        }
        // TODO: Implement loading existing realms.
        // TODO: Implement existing character counts.
        static async Task HandleRealmListRequest(ClientRequest clientRequest, BnetSession session)
        {
            var realmJoinRequest = clientRequest.GetVariant("Command_RealmListRequest_v1_b9")?.StringValue;
            var realmListTicket = clientRequest.GetVariant("Param_RealmListTicket")?.BlobValue.ToByteArray();

            if (session.RealmListTicket.Compare(realmListTicket))
            {
                var realmListResponse = new ClientResponse();
                var realmlist = new RealmListUpdates();

                realmListResponse.Attribute.Add(new Bgs.Protocol.Attribute
                {
                    Name = "Param_RealmList",
                    Value = new Variant
                    {
                        BlobValue = ByteString.CopyFrom(Deflate("JSONRealmListUpdates", realmlist))
                    }
                });

                var realmCharacterCountList = new RealmCharacterCountList();

                realmListResponse.Attribute.Add(new Bgs.Protocol.Attribute
                {
                    Name = "Param_CharacterCountList",
                    Value = new Variant
                    {
                        BlobValue = ByteString.CopyFrom(Deflate("JSONRealmCharacterCountList", realmCharacterCountList))
                    }
                });

                await session.Send(realmListResponse);
            }
        }
 public TradeDataRequest ForClient(int clientId)
 {
     ClientRequest = new ClientRequest(clientId);
     return(this);
 }
Exemple #26
0
        /// <summary>
        /// Add a new client to workspace.
        /// </summary>
        public Task <IRestResponse <ClientDto> > CreateClientAsync(string workspaceId, ClientRequest clientRequest)
        {
            if (clientRequest == null)
            {
                throw new ArgumentNullException(nameof(clientRequest));
            }

            var request = new RestRequest($"workspaces/{workspaceId}/clients", Method.POST);

            request.AddJsonBody(clientRequest);
            return(_client.ExecutePostAsync <ClientDto>(request));
        }
Exemple #27
0
 public BatchListViewModel(MerkatoDbContext context, ClientRequest activity) : this(context)
 {
 }
 public ClientResponse Request(ClientRequest request)
 {
     throw new ResponseException("Request failed");
 }
Exemple #29
0
 public override Task <Empty> Client(ClientRequest request, ServerCallContext context)
 {
     return(Task.FromResult(ExecuteClient(request)));
 }
Exemple #30
0
 public InvoiceViewModel(MerkatoDbContext context, ClientRequest activity) : this(context)
 {
 }
Exemple #31
0
        protected virtual IResponse ResolveRemote(Request request)
        {
            ClientRequest remoteRequest = client.Create(request);

            return(remoteRequest.Resolve());
        }
 public override void ProcessClientRequest(IRpcController controller, ClientRequest request, Action<ClientResponse> done)
 {
     ProtoOutputBuffer.Write(request.GetType(), request.ToString());
 }
 /// <summary>
 /// 创建并且保存请求
 /// </summary>
 /// <param name="clientRequest"></param>
 /// <param name="cancellationToken"></param>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public async Task CreateRequestForCommandAsync <T>(ClientRequest clientRequest,
                                                    CancellationToken cancellationToken)
 {
     await RequestRepository.AddAsync(clientRequest, cancellationToken);
 }
        // TODO: Implement.
        static Task HandleLastCharPlayedRequest(ClientRequest clientRequest, BnetServiceSession session)
        {
            var lastCharPlayedResponse = new ClientResponse();

            return(session.Send(lastCharPlayedResponse));
        }
Exemple #35
0
        public void RUN()
        {
            this.m_Listener = new TcpListener(PORT);
            this.m_Listener.Start();
            MusicName MusicInfo = new MusicName();

            MusicInfo.Type = (int)PacketType.SendToClient;

            Socket Client = this.m_Listener.AcceptSocket();

            if (Client.Connected) //client 처음에 listView 데이터 보냄
            {
                m_blsCientOn = true;
                this.Invoke(new MethodInvoker(delegate() { stateTxt.AppendText("Client Access !!\n"); }));
                this.m_NetStream = new NetworkStream(Client);

                foreach (FileInfo fInfo in fArray)  //파일 정보 ListView에 저장
                {
                    FolderItem mp3file = folder.ParseName(fInfo.Name);

                    MusicInfo.musicName  = (folder.GetDetailsOf(mp3file, 21));
                    MusicInfo.artistName = (folder.GetDetailsOf(mp3file, 20));
                    MusicInfo.musicTime  = (folder.GetDetailsOf(mp3file, 27));
                    MusicInfo.bitRate    = (folder.GetDetailsOf(mp3file, 28));
                    MusicInfo.path       = this.path;

                    Packet.Serialize(MusicInfo).CopyTo(sendBuffer, 0); //send buffer로 복사
                    this.Send();                                       //NetStream으로 복사
                }
            }

            int nRead = 0;

            while (this.m_blsCientOn)
            {
                try
                {
                    nRead = 0;
                    nRead = this.m_NetStream.Read(this.readBuffer, 0, readBuffer.Length);
                }
                catch
                {
                    this.m_blsCientOn = false;
                    this.m_NetStream  = null;
                }

                Packet packet = (Packet)Packet.Deserialize(readBuffer);

                switch ((int)packet.Type)
                {
                case (int)PacketType.SendToServer:      //클라이언트가 원하는 파일 얻어오기
                {
                    string        filePath  = null;
                    ClientRequest request   = (ClientRequest)Packet.Deserialize(readBuffer); //클라이언트에 파일 보내기위한 desirialize
                    MusicName     musicInfo = new MusicName();                               //클라이언트 플레이 리스트 추가

                    musicInfo.Type = (int)PacketType.서버음악정보;
                    string clientMusic = request.musicName;         //클라이언트가 원하는 음악 제목
                    int    i           = 0;
                    this.Invoke(new MethodInvoker(delegate() { stateTxt.AppendText("Download Request !!\n"); }));

                    foreach (FileInfo fInfo in fArray)          //파일 정보 ListView에 저장
                    {
                        FolderItem mp3file = folder.ParseName(fInfo.Name);
                        if (folder.GetDetailsOf(mp3file, 21).Equals(clientMusic))           //클라이언트 요청한 파일 확인
                        {
                            filePath             = fArray[i].FullName;
                            musicInfo.musicName  = (folder.GetDetailsOf(mp3file, 21));
                            musicInfo.artistName = (folder.GetDetailsOf(mp3file, 20));
                            musicInfo.musicTime  = (folder.GetDetailsOf(mp3file, 27));
                            musicInfo.bitRate    = (folder.GetDetailsOf(mp3file, 28));
                            musicInfo.path       = this.path;
                        }
                        else
                        {
                            i++;
                        }
                    }
                    this.Invoke(new MethodInvoker(delegate() { stateTxt.AppendText("Send File : " + filePath + "\n"); }));

                    FileInfo   fileInfo = new FileInfo(filePath);                                   //서버 상태 텍스트에 추가 할 해당 파일 정보
                    ClientFile cFile    = new ClientFile();                                         //서버의 파일을 보내기 위한 패킷
                    FileStream fi       = new FileStream(filePath, FileMode.Open, FileAccess.Read); //클라이언트가 원하는 파일 열고 읽기

                    cFile.FileName      = fileInfo.Name;                                            //파일 이름
                    cFile.FileNameLegth = fi.Name.Length;                                           //파일 이름 사이즈
                    cFile.FileSize      = (int)fi.Length;                                           //파일 사이즈

                    int count = (int)fi.Length / (1024 * 2);                                        // 파일 전체 크기/읽는 크기

                    cFile.FileCount = count + 1;                                                    //파일 읽는 전체 count

                    for (int j = 0; j < count; j++)
                    {
                        fi.Read(cFile.FileData, 0, 1024 * 2);
                        cFile.Type = (int)PacketType.ReceiveToServer;
                        Packet.Serialize(cFile).CopyTo(sendBuffer, 0); //send buffer로 복사
                        this.Send();                                   //NetStream으로 복사*/
                    }

                    fi.Read(cFile.FileData, 0, 1024 * 2);          //마지막 남은 스트림 보내기
                    cFile.Type = (int)PacketType.ReceiveToServer;
                    Packet.Serialize(cFile).CopyTo(sendBuffer, 0); //send buffer로 복사
                    this.Send();                                   //NetStream으로 복사*/


                    Packet.Serialize(musicInfo).CopyTo(sendBuffer, 0); //파일 전송 끝나면 클라이언트 플레이 리스트에 추가
                    this.Send();                                       //NetStream으로 복사
                }
                break;
                }
            }
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="request">The issued client request.</param>
 public ClientRequestEventArgs(ClientRequest request)
 {
     this.Request = request;
 }
        // TODO: Implement realm join function.
        static async Task HandleRealmJoinRequest(ClientRequest clientRequest, BnetSession session)
        {
            var realmJoinRequest = clientRequest.GetVariant("Command_RealmJoinRequest_v1_b9")?.StringValue;
            var realmAddress = clientRequest.GetVariant("Param_RealmAddress")?.UintValue;
            var realmListTicket = clientRequest.GetVariant("Param_RealmListTicket")?.BlobValue.ToByteArray();
            var bnetSessionKey = clientRequest.GetVariant("Param_BnetSessionKey")?.BlobValue.ToByteArray();

            // Check for valid realmlist ticket.
            if (realmListTicket.Compare(session.RealmListTicket))
            {
                var realmJoinResponse = new ClientResponse();

                await session.Send(realmJoinResponse);
            }
        }
 public IActionResult EditRequest(ClientRequest clientRequest)
 {
     _context.ClientRequests.Update(clientRequest);
     _context.SaveChanges();
     return(RedirectToAction("Index", "Admin"));
 }
 public abstract List <RateLimitRule> GetMatchingRules(ClientRequest clientRequest);
        public void AddTrace(Execute excuteObject)
        {
            ClientRequest clientRequest = excuteObject.ClientRequestEntity;

            if (clientRequest != null)
            {
                for (int i = clientRequest.Messages.Messages.Count - 1; i >= 0; i--)
                //for (int i = 0; i < clientRequest.Messages.Messages.Count ; i++)
                {
                    MessageItem messageItem  = clientRequest.Messages.Messages[i];
                    string      debugMessage = messageItem.Text.Trim();

                    //rad call.
                    if (radCallReg.IsMatch(debugMessage))
                    {
                        TraceChangedInfo changedInfo = new TraceChangedInfo();
                        changedInfo.OldRad   = currentRAD;
                        changedInfo.OldPanel = currentTrance as DebugTracePanel;

                        Match           radMatch       = radCallReg.Match(debugMessage);
                        GroupCollection groups         = radMatch.Groups;
                        string          threadId       = groups[1].Value;
                        string          currentRADName = groups[2].Value;
                        if (!followingReturn)
                        {
                            DebugTraceRADCall newRadCall = new DebugTraceRADCall();
                            newRadCall.Parent  = currentRAD;
                            newRadCall.RADName = currentRADName;

                            currentRAD.Traces.Add(newRadCall);
                            currentRAD = newRadCall;
                            radStack.Push(currentRADName);

                            currentTrance        = null;
                            changedInfo.NewRad   = currentRAD;
                            changedInfo.NewPanel = null;
                            changedInfo.Type     = TraceChangedType.NewRADCall;
                            if (OnTraceChanged != null)
                            {
                                OnTraceChanged(this, changedInfo);
                            }
                        }
                        else
                        {
                            //Check if current value is the same as the parent rad
                            if (currentRAD.RADName != currentRADName)
                            {
                                do
                                {
                                    radStack.Pop();
                                    currentRAD = currentRAD.Parent as DebugTraceRADCall;
                                }while (currentRADName != currentRAD.RADName);
                                //throw new Exception("RAD stack mismatched...");
                            }
                        }


                        followingReturn = false;
                        //nothing to do
                    }
                    else if (returnReg.IsMatch(debugMessage))
                    {
                        followingReturn = true;
                        TraceChangedInfo changedInfo = new TraceChangedInfo();
                        changedInfo.OldRad   = currentRAD;
                        changedInfo.OldPanel = currentTrance as DebugTracePanel;

                        radStack.Pop();
                        currentRAD = currentRAD.Parent as DebugTraceRADCall;

                        currentTrance        = null;
                        changedInfo.NewRad   = currentRAD;
                        changedInfo.NewPanel = null;
                        changedInfo.Type     = TraceChangedType.RADCallReturn;

                        if (OnTraceChanged != null)
                        {
                            OnTraceChanged(this, changedInfo);
                        }
                    }
                    else if (panelReg.IsMatch(debugMessage))
                    {
                        followingReturn = false;
                        TraceChangedInfo changedInfo = new TraceChangedInfo();
                        changedInfo.OldRad   = currentRAD;
                        changedInfo.OldPanel = currentTrance as DebugTracePanel;


                        Match           radMatch         = panelReg.Match(debugMessage);
                        GroupCollection groups           = radMatch.Groups;
                        string          threadId         = groups[1].Value;
                        string          currentPanelName = groups[2].Value;

                        RADPanel panel = new RADPanel();
                        panel.RADName   = currentRAD.RADName;
                        panel.PanelName = currentPanelName;

                        DebugTracePanel tracePanel = new DebugTracePanel();
                        tracePanel.PanelInfo = panel;
                        tracePanel.Parent    = currentRAD;
                        currentRAD.Traces.Add(tracePanel);
                        currentTrance = tracePanel;

                        changedInfo.NewRad   = currentRAD;
                        changedInfo.NewPanel = currentTrance as DebugTracePanel;
                        changedInfo.Type     = TraceChangedType.NewPanel;
                        if (OnTraceChanged != null)
                        {
                            OnTraceChanged(this, changedInfo);
                        }
                    }
                    else
                    {
                        //followingReturn = false;
                    }
                    //radStack.Push(messageItem);
                }
            }
        }
        public static void HandleClientRequest(AuthSession session, ClientRequest clientRequest)
        {
            string         name;
            ClientResponse clientResponse;

            if (GameUtilitiesService.smethod_0(clientRequest.Attribute[0].Name, Module.smethod_37 <string>(1549087768u)))
            {
                IEnumerator <Bgs.Protocol.Attribute> enumerator = clientRequest.Attribute.GetEnumerator();
                try
                {
                    while (true)
                    {
IL_156:
                        uint arg_11E_0 = GameUtilitiesService.smethod_2(enumerator) ? 707215618u : 982195081u;
                        while (true)
                        {
                            uint num;
                            switch ((num = (arg_11E_0 ^ 1820510042u)) % 7u)
                            {
                            case 0u:
                                arg_11E_0 = 707215618u;
                                continue;

                            case 1u:
                                goto IL_156;

                            case 2u:
                            {
                                Bgs.Protocol.Attribute current = enumerator.Current;
                                arg_11E_0 = (GameUtilitiesService.smethod_0(current.Name, Module.smethod_35 <string>(2108436570u)) ? 1292263614u : 39044470u);
                                continue;
                            }

                            case 3u:
                            {
                                Bgs.Protocol.Attribute current;
                                IEnumerable <int>      arg_C7_0 = Json.CreateObject <RealmListTicketClientInformation>(GameUtilitiesService.smethod_1(current.Value.BlobValue.ToStringUtf8(), Module.smethod_34 <string>(607107096u), "")).Info.Secret;
                                Func <int, byte>       arg_C7_1;
                                if ((arg_C7_1 = GameUtilitiesService.__c.__9__0_0) == null)
                                {
                                    arg_C7_1 = (GameUtilitiesService.__c.__9__0_0 = new Func <int, byte>(GameUtilitiesService.__c.__9.HandleClientRequestb__0_0));
                                }
                                Globals.Secret = arg_C7_0.Select(arg_C7_1).ToArray <byte>();
                                arg_11E_0      = 1388634718u;
                                continue;
                            }

                            case 4u:
                                arg_11E_0 = (num * 3357184604u ^ 1408942728u);
                                continue;

                            case 6u:
                            {
                                Bgs.Protocol.Attribute current;
                                GameUtilitiesService.smethod_0(current.Name, "");
                                arg_11E_0 = 390289400u;
                                continue;
                            }
                            }
                            goto Block_10;
                        }
                    }
                    Block_10 :;
                }
                finally
                {
                    if (enumerator != null)
                    {
                        while (true)
                        {
                            IL_19C :
                            uint arg_183_0 = 1000108845u;
                            while (true)
                            {
                                uint num;
                                switch ((num = (arg_183_0 ^ 1820510042u)) % 3u)
                                {
                                case 0u:
                                    goto IL_19C;

                                case 2u:
                                    GameUtilitiesService.smethod_3(enumerator);
                                    arg_183_0 = (num * 2856457603u ^ 3035350054u);
                                    continue;
                                }
                                goto Block_14;
                            }
                        }
                        Block_14 :;
                    }
                }
                name           = Module.smethod_35 <string>(1450915626u);
                clientResponse = new ClientResponse();
                goto IL_205;
            }
            goto IL_6F3;
            uint arg_682_0;

            while (true)
            {
IL_67D:
                uint num;
                switch ((num = (arg_682_0 ^ 1820510042u)) % 21u)
                {
                case 0u:
                {
                    ClientResponse message = new ClientResponse();
                    arg_682_0 = (num * 1960178030u ^ 3375314732u);
                    continue;
                }

                case 1u:
                    clientResponse.Attribute.Add(new Bgs.Protocol.Attribute
                    {
                        Name  = name,
                        Value = new Variant
                        {
                            BlobValue = ByteString.CopyFromUtf8(Module.smethod_36 <string>(2871343933u))
                        }
                    });
                    session.Send(clientResponse);
                    arg_682_0 = (num * 2849486171u ^ 3438062413u);
                    continue;

                case 2u:
                {
                    ClientResponse clientResponse2 = new ClientResponse();
                    arg_682_0 = (num * 1708365464u ^ 846537027u);
                    continue;
                }

                case 3u:
                {
                    ClientResponse clientResponse3;
                    clientResponse3.Attribute.Add(new Bgs.Protocol.Attribute
                        {
                            Name  = Module.smethod_35 <string>(1814716925u),
                            Value = new Variant
                            {
                                BlobValue = ByteString.CopyFromUtf8(Module.smethod_34 <string>(904052351u))
                            }
                        });
                    RealmListServerIPAddresses realmListServerIPAddresses = new RealmListServerIPAddresses();
                    arg_682_0 = (num * 1691718091u ^ 3467647916u);
                    continue;
                }

                case 4u:
                {
                    RealmListServerIPAddresses realmListServerIPAddresses;
                    realmListServerIPAddresses.Families.Add(new Family
                        {
                            Id        = 2,
                            Addresses = new List <AuthServer.AuthServer.JsonObjects.Address>()
                        });
                    arg_682_0 = (num * 78695267u ^ 2554691107u);
                    continue;
                }

                case 5u:
                    arg_682_0 = (GameUtilitiesService.smethod_0(clientRequest.Attribute[0].Name, Module.smethod_33 <string>(3445444445u)) ? 1552249222u : 2080562207u);
                    continue;

                case 6u:
                    return;

                case 7u:
                {
                    ClientResponse             clientResponse3;
                    RealmListServerIPAddresses realmListServerIPAddresses;
                    clientResponse3.Attribute.Add(new Bgs.Protocol.Attribute
                        {
                            Name  = Module.smethod_35 <string>(2074000899u),
                            Value = new Variant
                            {
                                BlobValue = ByteString.CopyFrom(GameUtilitiesService.GetCompressedData(Module.smethod_35 <string>(2339801210u), Json.CreateString <RealmListServerIPAddresses>(realmListServerIPAddresses)))
                            }
                        });
                    clientResponse3.Attribute.Add(new Bgs.Protocol.Attribute
                        {
                            Name  = Module.smethod_33 <string>(2686709168u),
                            Value = new Variant
                            {
                                BlobValue = ByteString.CopyFrom(Globals.JoinSecret)
                            }
                        });
                    session.Send(clientResponse3);
                    arg_682_0 = (num * 1149426949u ^ 1180628059u);
                    continue;
                }

                case 8u:
                {
                    ClientResponse clientResponse2;
                    session.Send(clientResponse2);
                    arg_682_0 = (num * 3033014184u ^ 922385703u);
                    continue;
                }

                case 9u:
                    return;

                case 10u:
                {
                    RealmListServerIPAddresses realmListServerIPAddresses;
                    realmListServerIPAddresses.Families = new List <Family>();
                    arg_682_0 = (num * 3674508602u ^ 631681376u);
                    continue;
                }

                case 11u:
                {
                    ClientResponse   clientResponse2;
                    RealmListUpdates realmListUpdates;
                    clientResponse2.Attribute.Add(new Bgs.Protocol.Attribute
                        {
                            Name  = Module.smethod_33 <string>(2409987499u),
                            Value = new Variant
                            {
                                BlobValue = ByteString.CopyFrom(GameUtilitiesService.GetCompressedData(Module.smethod_36 <string>(966958691u), Json.CreateString <RealmListUpdates>(realmListUpdates)))
                            }
                        });
                    RealmCharacterCountList dataObject = new RealmCharacterCountList();
                    clientResponse2.Attribute.Add(new Bgs.Protocol.Attribute
                        {
                            Name  = Module.smethod_36 <string>(4040564189u),
                            Value = new Variant
                            {
                                BlobValue = ByteString.CopyFrom(GameUtilitiesService.GetCompressedData(Module.smethod_33 <string>(2576241685u), Json.CreateString <RealmCharacterCountList>(dataObject)))
                            }
                        });
                    arg_682_0 = (num * 716287039u ^ 3546797012u);
                    continue;
                }

                case 12u:
                {
                    RealmListUpdates realmListUpdates = new RealmListUpdates();
                    realmListUpdates.Updates = new List <RealmListUpdate>
                    {
                        new RealmListUpdate
                        {
                            WowRealmAddress = 1u,
                            Update          = new Update
                            {
                                WowRealmAddress = 1,
                                CfgTimezonesID  = 2,
                                PopulationState = 1,
                                CfgCategoriesID = 1,
                                Version         = new ClientVersion
                                {
                                    Major    = 7,
                                    Minor    = 1,
                                    Revision = 0,
                                    Build    = 22996
                                },
                                CfgRealmsID    = 1,
                                Flags          = 4,
                                CfgConfigsID   = 1,
                                CfgLanguagesID = 1,
                                Name           = Module.smethod_36 <string>(4208195762u)
                            }
                        }
                    };
                    arg_682_0 = (num * 2759149309u ^ 1324415408u);
                    continue;
                }

                case 13u:
                {
                    RealmListServerIPAddresses realmListServerIPAddresses;
                    realmListServerIPAddresses.Families.Add(new Family
                        {
                            Id        = 1,
                            Addresses = new List <AuthServer.AuthServer.JsonObjects.Address>
                            {
                                new AuthServer.AuthServer.JsonObjects.Address
                                {
                                    Ip   = Module.smethod_33 <string>(1362828071u),
                                    Port = 8085
                                }
                            }
                        });
                    arg_682_0 = (num * 2455873529u ^ 3627955475u);
                    continue;
                }

                case 14u:
                {
                    ClientResponse message;
                    session.Send(message);
                    arg_682_0 = (num * 1672891969u ^ 1215791913u);
                    continue;
                }

                case 16u:
                {
                    Globals.JoinSecret = new byte[0].GenerateRandomKey(32);
                    SHA256Managed expr_226 = GameUtilitiesService.smethod_4();
                    GameUtilitiesService.smethod_5(expr_226, Globals.Secret, 0, Globals.Secret.Length, Globals.Secret, 0);
                    GameUtilitiesService.smethod_6(expr_226, Globals.JoinSecret, 0, Globals.JoinSecret.Length);
                    Globals.SessionKey = GameUtilitiesService.smethod_7(expr_226);
                    ClientResponse clientResponse3 = new ClientResponse();
                    arg_682_0 = (num * 181368554u ^ 2569788186u);
                    continue;
                }

                case 17u:
                    goto IL_205;

                case 18u:
                    return;

                case 19u:
                    arg_682_0 = ((!GameUtilitiesService.smethod_0(clientRequest.Attribute[0].Name, Module.smethod_36 <string>(2188320489u))) ? 1384141042u : 1913633765u);
                    continue;

                case 20u:
                    goto IL_6F3;
                }
                break;
            }
            return;

IL_205:
            arg_682_0 = 513478610u;
            goto IL_67D;
IL_6F3:
            arg_682_0 = ((!GameUtilitiesService.smethod_0(clientRequest.Attribute[0].Name, Module.smethod_35 <string>(2192477891u))) ? 1776235731u : 1794780940u);
            goto IL_67D;
        }
        // TODO: Implement.
        static Task HandleLastCharPlayedRequest(ClientRequest clientRequest, BnetSession session)
        {
            var lastCharPlayedResponse = new ClientResponse();

            return session.Send(lastCharPlayedResponse);
        }
Exemple #43
0
        /// <summary>
        /// Handles before save event for <see cref="SubscriberUserControl"/>.
        /// </summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Cancel event arguments.</param>
        private void SubscriberUserControl_BeforeSave(object sender, CancelEventArgs e)
        {
            try
            {
                string sharedSecret = m_dataContext.CurrentItem.SharedSecret;
                WindowsServiceClient windowsServiceClient;
                ClientRequest        request;

                if (m_dataContext.SecurityMode == SecurityMode.Gateway)
                {
                    if (string.IsNullOrWhiteSpace(sharedSecret) || string.IsNullOrWhiteSpace(m_key) || string.IsNullOrWhiteSpace(m_iv))
                    {
                        MessageBox.Show("Failed to import key and initialization vectors for associated shared secret - these fields cannot be blank.", "Crypto Key Import Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        e.Cancel = true;
                    }
                    else
                    {
                        // Import key and initialization vector for subscriber into common crypto cache
                        if (ImportCipherKey(sharedSecret.Trim(), 256, m_key.Trim() + "|" + m_iv.Trim()))
                        {
                            ReloadServiceCryptoCache();
                            Cipher.ReloadCache();
                        }
                        else
                        {
                            MessageBox.Show("Failed to import key and initialization vectors for associated shared secret.", "Crypto Key Import Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            e.Cancel = true;
                        }
                    }
                }
                else
                {
                    try
                    {
                        if (SelfSignedCheckBox.IsChecked == true)
                        {
                            // If remote certificate is self-signed, ensure that we expect
                            // UntrustedRoot error to occur during certificate validation
                            m_dataContext.CurrentItem.ValidPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
                            m_dataContext.CurrentItem.ValidChainFlags   |= X509ChainStatusFlags.UntrustedRoot;
                        }

                        if ((object)m_dataContext.RemoteCertificateData != null)
                        {
                            windowsServiceClient = CommonFunctions.GetWindowsServiceClient();
                            windowsServiceClient.Helper.ReceivedServiceResponse += WindowsServiceClient_ReceivedServiceResponse;
                            m_certificateWaitHandle.Reset();

                            // If an srq file was imported to populate the fields on this page,
                            // then we will need to copy the attached certificate file from the
                            // temp folder to the correct location
                            request           = new ClientRequest("INVOKE");
                            request.Arguments = new Arguments(string.Format("TLS!DATAPUBLISHER ImportCertificate {0}", m_dataContext.CurrentItem.RemoteCertificateFile));
                            request.Attachments.Add(m_dataContext.RemoteCertificateData);
                            windowsServiceClient.Helper.SendRequest(request);

                            if (!m_certificateWaitHandle.Wait(5000))
                            {
                                throw new InvalidOperationException("Timeout waiting for response to ImportCertificate command.");
                            }

                            m_dataContext.RemoteCertificateData = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        const string ErrorMessage = "Successfully imported subscription request, but was" +
                                                    " unable to import remote certificate. Check that the manager is properly" +
                                                    " connected to the service.";

                        CommonFunctions.LogException(null, "Import Subscription Request", ex);
                        MessageBox.Show(ErrorMessage, "Import Subscription Request Error");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to import key and initialization vectors for associated shared secret due to exception: " + ex.Message, "Crypto Key Import Error", MessageBoxButton.OK, MessageBoxImage.Error);
                e.Cancel = true;
            }
        }
Exemple #44
0
 public void SendRequestPacket(ClientRequest request, uint gem_num, uint rumble)
 {
     byte[] PacketData = new byte[16];
     int request_net = System.Net.IPAddress.HostToNetworkOrder((int)request);
     int payload_size_net = System.Net.IPAddress.HostToNetworkOrder(8);
     int gem_num_net = System.Net.IPAddress.HostToNetworkOrder((int)gem_num);
     int rumble_net = System.Net.IPAddress.HostToNetworkOrder((int)rumble);
     Buffer.BlockCopy(BitConverter.GetBytes(request_net), 0, PacketData, 0, 4);
     Buffer.BlockCopy(BitConverter.GetBytes(payload_size_net), 0, PacketData, 4, 4);
     Buffer.BlockCopy(BitConverter.GetBytes(gem_num_net), 0, PacketData, 8, 4);
     Buffer.BlockCopy(BitConverter.GetBytes(rumble_net), 0, PacketData, 12, 4);
     NetworkStream stream = _tcpClient.GetStream();
     stream.Write(PacketData, 0, PacketData.Length);
 }
 public AsyncSocketMessage(ClientRequest request)
 {
     this.m_package = request.ToString() + DEFAULT_SEPARATOR + "1" + DEFAULT_SEPARATOR + "0";
 }
Exemple #46
0
        public void SendRequestPacket(ClientRequest request, uint req_hue_0, uint req_hue_1, uint req_hue_2, uint req_hue_3)
        {
            byte[] PacketData = new byte[24];
            int request_net = System.Net.IPAddress.HostToNetworkOrder((int)request);
            int payload_size_net = System.Net.IPAddress.HostToNetworkOrder(16);
            int req_hue_0_net = System.Net.IPAddress.HostToNetworkOrder((int)req_hue_0);
            int req_hue_1_net = System.Net.IPAddress.HostToNetworkOrder((int)req_hue_1);
            int req_hue_2_net = System.Net.IPAddress.HostToNetworkOrder((int)req_hue_2);
            int req_hue_3_net = System.Net.IPAddress.HostToNetworkOrder((int)req_hue_3);

            Buffer.BlockCopy(BitConverter.GetBytes(request_net), 0, PacketData, 0, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(payload_size_net), 0, PacketData, 4, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(req_hue_0_net), 0, PacketData, 8, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(req_hue_1_net), 0, PacketData, 12, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(req_hue_2_net), 0, PacketData, 16, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(req_hue_3_net), 0, PacketData, 20, 4);
            NetworkStream stream = _tcpClient.GetStream();
            stream.Write(PacketData, 0, PacketData.Length);
        }
Exemple #47
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            Boolean B = false;

            com             = new SqlCommand();
            com.Connection  = con;
            com.CommandType = CommandType.Text;

            com.CommandText = "Select * From tbCustomer";


            dr = com.ExecuteReader();
            while (dr.Read())
            {
                if (dr[0].ToString() == txtUsername.Text && dr[1].ToString() == txtPassword.Text)
                {
                    username   = dr[0].ToString();
                    password   = dr[1].ToString();
                    RemindHour = dr[2].ToString();

                    B = true;
                }
            }

            dr.Close();
            dr.Dispose();

            if (B == true)
            {
                MessageBox.Show("Login successfully");
                ClientRequest.LoopConnect();
                InternetCafeClientProject.ClientRequest.SendLoop("in|" + username + "|" + System.Environment.MachineName);

                this.Hide();
                InternetCafeClientProject.usrInfoFrm formTime = new InternetCafeClientProject.usrInfoFrm();
                formTime.Show();
            }
            else if (B == false)
            {
                MessageBox.Show("Incorrect username or password");
            }
            dr.Close();
            com.Dispose();

            //if (txtUsername.Text == "Enter username here...") {
            //    MessageBox.Show("You must enter your username");
            //    txtUsername.Clear();
            //    txtUsername.Focus();
            //}
            //else if (txtPassword.Text == "Enter password here...") {
            //    MessageBox.Show("You must enter your password");
            //    txtPassword.PasswordChar = '\u2022';
            //    txtPassword.Clear();
            //    txtPassword.Focus();
            //}

            //else if ((txtUsername.Text != username) || (txtPassword.Text != password)) {
            //    MessageBox.Show("Incorrect username or password");
            //}
            //else if ((txtUsername.Text == username) && (txtPassword.Text == password)) {
            //    MessageBox.Show("Login successfully");
            //    this.Hide();
            //    InternetCafeClientProject.usrInfoFrm formTime = new InternetCafeClientProject.usrInfoFrm();
            //    formTime.Show();
            //}
        }
 // public method for ease of access via other client instantiation.
 public void setRival(ClientRequest rival)
 {
     this.rival = rival;
 }
        /// <summary>
        /// Manages everything related to the client <code>Socket</code>.
        /// </summary>
        /// <returns>Whether some time consuming operation was executed or not.</returns>
        private bool HandleClient()
        {
            // if we have already accepted the client
            if (this.clientAccepted)
            {
                try
                {
                    // ping it, to check connection
                    this.SendMessage(MessageID.Ping);
                }
                catch (SocketException)
                {
                    // exception, so: client disconnected
                    // cleanup
                    this.OnClientDisconnected();
                    return(false); // we didn't do anything
                }
            }

            // get the available bytes to read
            int available = this.clientSocket.Available;

            // if we have something waiting for us...
            if (available > 0)
            {
                // receive the first (message) byte
                byte messageIDByte = this.ReceiveByte();
                // convert it corresponding to the ENUM
                MessageID messageID = (MessageID)messageIDByte;

                if (this.clientAccepted)
                {
                    // only if we already have accepted the client,
                    // these messages are ok
                    switch (messageID)
                    {
                    case MessageID.Init:
                        // not relevant
                        break;

                    // any state-changing command...
                    case MessageID.Start:
                    case MessageID.Stop:
                    case MessageID.Next:
                    case MessageID.Prev:

                        // .. is to be converted into ClientRequest enum...
                        ClientRequest request = Server.ClientRequest.NextSlide;
                        switch (messageID)
                        {
                        case MessageID.Start:
                            request = Server.ClientRequest.StartPresentation;
                            break;

                        case MessageID.Stop:
                            request = Server.ClientRequest.StopPresentation;
                            break;

                        case MessageID.Next:
                            request = Server.ClientRequest.NextSlide;
                            break;

                        case MessageID.Prev:
                            request = Server.ClientRequest.PreviousSlide;
                            break;
                        }

                        // ...and sent to the listeners
                        this.OnClientRequest(request);

                        break;

                    default:
                        // unknown
                        break;
                    }
                }
                else
                {
                    // because the client is not accepted,
                    // only Init is to be expected
                    if (messageID == MessageID.Init)
                    {
                        // get the pairing code from the remote
                        String pairingCode = this.ReceiveString();

                        // check the validity of the code
                        this.clientAccepted = (this.pairingCode == pairingCode);
                        // send the init answer to the client
                        byte accepted = (this.clientAccepted) ? (byte)1 : (byte)0;
                        this.SendMessage(MessageID.Init, accepted);
                    }
                }

                // we probably did some sending or somethin', so we 'true' out
                return(true);
            }
            else
            {
                return(false); // no data, no computation
            }
        }
Exemple #50
0
        public bool execute(ClientRequest request)
        {
            try
            {
                if(!connected)
                    connect();

                if(!_setup && onSetup != null)
                {
                    onSetup();
                    _setup = true;
                }

                request();
                return true;
            }
            catch(net.ConnectionException)
            {
                disconnect();
                return false;
            }
            catch(System.IO.IOException)
            {
                disconnect();
                return false;
            }
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="request">The issued client request.</param>
 public ClientRequestEventArgs(ClientRequest request)
 {
     this.Request = request;
 }
Exemple #52
0
        public static string GetResponseForText(ClientRequest clientRequest)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(clientRequest.Url);

            webRequest.Method = clientRequest.HttpMethod;

            HttpWebResponse webResponse = null;
            Stream          stream      = null;
            string          result      = null;

            if (webRequest.Method.ToLower() == WebRequestMethods.Http.Get.ToLower())
            {
                //GET请求
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                stream      = webResponse.GetResponseStream();

                if (stream.CanRead)
                {
                    var readStream = new StreamReader(stream, Encoding.UTF8);

                    var responseContent = readStream.ReadToEnd();

                    result = responseContent;
                }
            }
            else if (webRequest.Method.ToLower() == WebRequestMethods.Http.Post.ToLower())
            {
                //POST请求
                if (clientRequest.FormData == null)
                {
                    //不带form data数据
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    stream      = webResponse.GetResponseStream();
                    if (stream.CanRead)
                    {
                        var readStream = new StreamReader(stream, Encoding.UTF8);

                        var responseContent = readStream.ReadToEnd();

                        result = responseContent;
                    }
                }
                else if (clientRequest.FormData.Count == 0)
                {
                    //不带form data数据
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    stream      = webResponse.GetResponseStream();
                    if (stream.CanRead)
                    {
                        var readStream = new StreamReader(stream, Encoding.UTF8);

                        var responseContent = readStream.ReadToEnd();

                        result = responseContent;
                    }
                }
                else
                {
                    //带form data数据
                    webRequest.ContentType = clientRequest.ContentType;

                    StringBuilder sbFormData         = new StringBuilder();
                    byte[]        formDataBytes      = null;
                    Stream        requestWriteStream = null;

                    if (webRequest.ContentType == "application/x-www-form-urlencoded")
                    {
                        //普通post提交
                        foreach (var item in clientRequest.FormData)
                        {
                            sbFormData.Append("&" + item.Key + "=" + item.Value);
                        }

                        if (sbFormData.Length > 0)
                        {
                            sbFormData.Remove(0, 1); //移除第一个&字符
                        }

                        formDataBytes            = Encoding.UTF8.GetBytes(sbFormData.ToString());
                        webRequest.ContentLength = formDataBytes.Length;

                        requestWriteStream = webRequest.GetRequestStream();
                        requestWriteStream.Write(formDataBytes, 0, formDataBytes.Length);
                        requestWriteStream.Close();

                        webResponse = (HttpWebResponse)webRequest.GetResponse();
                        stream      = webResponse.GetResponseStream();
                        if (stream.CanRead)
                        {
                            var readStream = new StreamReader(stream, Encoding.UTF8);

                            var responseContent = readStream.ReadToEnd();

                            result = responseContent;
                        }
                    }
                    else if (webRequest.ContentType.StartsWith("multipart/form-data"))
                    {
                        string         boundary       = "----------------------------" + DateTime.Now.Ticks.ToString("x");
                        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(clientRequest.Url);
                        httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                        httpWebRequest.Method      = clientRequest.HttpMethod;
                        httpWebRequest.KeepAlive   = clientRequest.KeepAlive;
                        httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

                        Stream requestStream = httpWebRequest.GetRequestStream();


                        byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");

                        foreach (var item in clientRequest.FormData)
                        {
                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                            string formData = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

                            formDataBytes = Encoding.UTF8.GetBytes(string.Format(formData, item.Key, item.Value));

                            requestStream.Write(formDataBytes, 0, formDataBytes.Length);
                        }

                        foreach (var item in clientRequest.BinaryData)
                        {
                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: {2}\r\n\r\n";

                            string header = string.Format(headerTemplate, item.Key, item.Value.FileName, item.Value.ContentType);

                            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                            requestStream.Write(headerbytes, 0, headerbytes.Length);

                            requestStream.Write(item.Value.Binary, 0, item.Value.Binary.Length);
                        }


                        boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                        requestStream.Close();



                        webResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                        Stream       responseStream = webResponse.GetResponseStream();
                        StreamReader responseReader = new StreamReader(responseStream);

                        string responseString = responseReader.ReadToEnd();

                        webResponse.Close();

                        result = responseString;
                    }
                }
            }

            return(result);
        }
 public ClientRequestPacket(ClientRequest request)
 {
     this.Request = request;
 }
        public AsyncSocketMessage(ClientRequest request, Object obj)
        {
            String message = JsonConvert.SerializeObject(obj);

            this.m_package = request.ToString() + DEFAULT_SEPARATOR + message.Length + DEFAULT_SEPARATOR + message;
        }
        public async Task <IActionResult> PutClient([FromHeader(Name = "Authorization")] string JWT, int id, ClientRequest client)
        {
            var clientEntity = RightCredentials(id).Result;

            if (id != client.Id || clientEntity == null)
            {
                return(BadRequest());
            }

            clientEntity.Birthdate = client.Birthdate;
            clientEntity.Name      = client.Name;
            clientEntity.Surname   = client.Surname;
            clientEntity.Phone     = client.Phone;
            clientEntity.Email     = client.Email;

            _context.Entry(clientEntity).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ClientExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }