Exemplo n.º 1
0
        public void ChangePersonalMessage(string message)
        {
            this.socket.NotNull();

            PackageRequest request = new PersonalMessageRequest(message);

            PackageResponse response = this.socket.SendAndBlock(request);
        }
Exemplo n.º 2
0
        public void PrivacySettings(bool allowBlocked)
        {
            this.socket.NotNull();

            PackageRequest request = new PrivacySettingsRequest(allowBlocked);

            PackageResponse response = this.socket.SendAndBlock(request);
        }
        public IActionResult Get()
        {
            var packages = packageReader.GetAll();

            var res = new PackageResponse
            {
                Success = true,
                Data    = packages
            };

            return(Ok(res));
        }
Exemplo n.º 4
0
        public PackageTransaction(PackageRequest request, PackageResponse response)
        {
            request.NotNull();
            response.NotNull();

            if (request.TransactionID != response.TransactionID)
            {
                throw new ArgumentException("response", "The TransactionID property does not match");
            }

            this.Request  = request;
            this.Response = response;
        }
Exemplo n.º 5
0
        private void ChallengeResponder(ChallengeResponse response)
        {
            new Thread(() =>
            {
                PackageResponse resp1           = this.socket.SendAndBlock(new ChallengeRequest(response.Challenge));
                ChallengeAchievedResponse resp2 = resp1 as ChallengeAchievedResponse;

                if (resp2 == null)
                {
                    Console.WriteLine("Error Challenge Failed");
                }
            }).Start();
        }
Exemplo n.º 6
0
        public void AcceptInvitation(string ticket)
        {
            //Nestes casos não queremos apenas uma 'response' com um transactionID igual ao enviado!
            //Queremos isso, mas também queremos um tipo de 'pacote' especial!
            PackageResponse resp1 = this.socket.SendAndBlock <AcceptedChatInvitationResponse>(new AcceptChatInvitationRequest(this.Account, ticket, this.SessionID));
            //Este cast é desnecessário!
            AcceptedChatInvitationResponse resp2 = resp1 as AcceptedChatInvitationResponse;

            if (resp2 == null)
            {
                Console.WriteLine("Error Chat Invitation Failed");
            }
        }
Exemplo n.º 7
0
        public PackageResponse GetPackages()
        {
            var response = new PackageResponse();

            response.PackageList = (from tbl in objData.PackageMasters
                                    where tbl.IsDelete == false
                                    select new PackageViewModel {
                PackageId = tbl.PackageId,
                AccessUsers = tbl.AccessUsers,
                Gender = tbl.Gender,
                IsDelete = tbl.IsDelete,
                PackageName = tbl.PackageName,
                Price = tbl.Price,
                Validity = tbl.Validity
            });
            return(response);
        }
Exemplo n.º 8
0
        private bool TryParseContent(string content, out PackageResponse packageResponse)
        {
            try
            {
                packageResponse = XmlHelper.Deserialize <PackageResponse>(content);
            }
            catch (Exception)
            {
                packageResponse = new PackageResponse()
                {
                    ErrCode = "Ошибка при парсинге ответа"
                };

                return(false);
            }

            return(true);
        }
Exemplo n.º 9
0
        private static void PrintReceivedCommand(PackageResponse response)
        {
            if (response is DeclarationResponse || response is InboxMessageResponse || response is ProfileInformationResponse)
            {
                return;
            }

            lock (Console.Out)
            {
                ConsoleColor backup = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Yellow;
                const int length = 32;
                Console.WriteLine(new string('<', length));
                Console.WriteLine(response);
                Console.WriteLine(new string('-', length));
                Console.ForegroundColor = backup;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 查询订单包裹信息
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <returns></returns>
        /// <remarks>2016-09-22 周 创建</remarks>
        private PackageResponse SearchOrderPackage(string orderNo)
        {
            WebUtils.HttpPacket packet = WebUtils.DoGet(ApiConfig.ApiUrl + "Order/SearchOrderPackage?" + CommonUtils.GetUrlParameter(new SortedDictionary <string, string>()
            {
                { "orderNo", orderNo }
            }));
            PackageResponse response = null;

            try
            {
                ApiResponse apiResponse = JsonConvert.DeserializeObject <ApiResponse>(packet.ResponseBody);
                if (apiResponse.State)
                {
                    response = JsonConvert.DeserializeObject <PackageResponse>(apiResponse.Content.ToString());
                }
            }
            catch (Exception)
            {
                // ignored
            }
            return(response);
        }
Exemplo n.º 11
0
        public async Task <IActionResult> SendMessages([FromBody] PackageRequest packageRequest)
        {
            if (ModelState.IsValid)
            {
                var res = new PackageResponse
                {
                    Send = new List <ResponseMsg>
                    {
                        new ResponseMsg {
                            Id = 1, MsgErrorCode = "test"
                        },
                        new ResponseMsg {
                            Id = 2, ServerId = "1", Value = "test"
                        }
                    }
                };

                return(Ok(res));
            }

            return(BadRequest(ErrorResponse.GetError(ErrorCodes.BAD_XML)));
        }
Exemplo n.º 12
0
 public MessageEventArgs(PackageResponse package)
 {
     this.Package = package;
 }
        /// <summary>
        /// Downloads discovered package hashes and starts download.
        /// </summary>
        /// <param name="packageToDownload">Discovered package to download.</param>
        /// <param name="startDownloadTask">Task that completed when download is started/failed.</param>
        /// <returns>
        /// Return true if download has started. False if it was already in progress.
        /// Throws en exception if failed to download hashes or start download.
        /// </returns>
        public bool GetDiscoveredPackageAndStartDownloadPackage(DiscoveredPackage packageToDownload, out Task startDownloadTask)
        {
            lock (syncLock)
            {
                // ignore already in progress
                if (!packageDataDownloads.Add(packageToDownload.PackageId))
                {
                    startDownloadTask = null;
                    return(false);
                }

                // already in progress, exit
                if (packageRegistry.TryGetPackage(packageToDownload.PackageId, out var _))
                {
                    startDownloadTask = null;
                    return(false);
                }
            }

            startDownloadTask = Task.Run(() =>
            {
                try
                {
                    PackageResponse response = null;

                    // download package segments
                    while (true)
                    {
                        var peers = peerRegistry.ImmutablePeers.Where(p => p.KnownPackages.ContainsKey(packageToDownload.PackageId)).ToArray();

                        if (!peers.Any())
                        {
                            throw new InvalidOperationException("No peers left to download package data.");
                        }

                        var peer = peers[ThreadSafeRandom.Next(0, peers.Length)];

                        // download package
                        logger.LogInformation($"Downloading hashes of package \"{packageToDownload.Name}\" {packageToDownload.PackageId:s} from peer {peer.PeerId:s} at {peer.ServiceEndPoint}.");
                        try
                        {
                            response = client.GetPackage(peer.ServiceEndPoint, new PackageRequest(packageToDownload.PackageId));
                            peer.ClientHasSuccess(); // responded = working
                            if (response.Found)
                            {
                                break;                                            // found
                            }
                            peer.RemoveKnownPackage(packageToDownload.PackageId); // don't have it anymore
                        }
                        catch (Exception e)
                        {
                            peer.ClientHasFailed(); // mark as failed - this will remove peer from peer list if hit fail limit
                            logger.LogTrace(e, $"Error contacting client {peer.ServiceEndPoint} {peer.PeerId:s}.");
                        }
                    }

                    // save to local storage
                    var package = packageRegistry.SaveRemotePackage(response.Hashes, packageToDownload.Meta);
                    StartDownloadPackage(package);
                }
                catch (Exception e)
                {
                    logger.LogError(e, "Can't download package data of \"{0}\" {1:s}", packageToDownload.Name, packageToDownload.PackageId);
                    throw;
                }
                finally
                {
                    lock (syncLock)
                    {
                        packageDataDownloads.Remove(packageToDownload.PackageId);
                    }
                }
            });

            return(true);
        }
Exemplo n.º 14
0
        private void tbWeight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(tbWeight.Text.Trim()))
                    {
                        MessageBox.Show("请录入重量!");
                        tbWeight.Focus();
                        return;
                    }

                    decimal weight = 0;
                    decimal.TryParse(tbWeight.Text.Trim(), out weight);
                    if (weight <= 0)
                    {
                        MessageBox.Show("录入重量必须大于0!");
                        tbWeight.Focus();
                        return;
                    }

                    curWeight = Util.ConvertGToJin(weight);

                    //if (curWeight<downWeight)
                    //{
                    //    MessageBox.Show("重量不能小于浮动下限");
                    //    return;
                    //}

                    //if (curWeight>upWeight)
                    //{
                    //      MessageBox.Show("重量不能大于浮动上限");
                    //    return;
                    //}


                    tbWeight.Enabled = false;

                    PackageRequest request = new PackageRequest();
                    request.packTaskDetailId = curTaskDetailId;
                    request.processUser      = UserInfo.RealName;

                    request.weight           = curWeight;
                    request.packTaskCode     = taskCode;
                    request.outboundTaskCode = curOutStockCode;
                    request.skuCode          = curSkuCode;
                    request.createUser       = UserInfo.RealName;
                    request.updateUser       = UserInfo.RealName;
                    request.partnerCode      = UserInfo.PartnerCode;
                    request.partnerName      = UserInfo.PartnerName;



                    PackageResponse response = client.Execute(request);
                    if (!response.IsError)
                    {
                        curPackageCode = response.result;
                        PrintDocument document = new PrintDocument();
                        document.DefaultPageSettings.PaperSize = new PaperSize("Custum", 270, 180);

#if (!DEBUG)
                        PrintDialog dialog = new PrintDialog();
                        document.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
                        dialog.Document     = document;
#else
                        PrintPreviewDialog dialog = new PrintPreviewDialog();
                        document.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
                        dialog.Document     = document;
#endif
                        try
                        {
                            document.Print();
                        }
                        catch (Exception exception)
                        {
                            MessageBox.Show("打印异常" + exception);
                            document.PrintController.OnEndPrint(document, new PrintEventArgs());
                        }
                        //打印,加载下一个
                        ClearForm();
                        tbWeight.Text = "";
                        ShowDetail();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    tbWeight.Enabled = true;
                    tbWeight.Focus();
                }
            }
        }
Exemplo n.º 15
0
        private Dictionary <int, PackageTransaction> SendRangeAndBlock <T>(IEnumerable <PackageRequest> request, int timeoutP)
        {
            if (timeoutP < 0)
            {
                throw new ArgumentOutOfRangeException("timeoutP", "parameter is less than 0");
            }

            //Enviar comandos!
            List <int> sent = new List <int>(this.SendRange(request));
            //Guardar as respostas aqui!
            Dictionary <int, PackageResponse> responses = new Dictionary <int, PackageResponse>(sent.Count);

            #region Callback/Listener

            EventHandler <MessageEventArgs> method = null;
            //MessengerReader.MessageEventHandler method = null;
            method = delegate(object o, MessageEventArgs e)
            {
                lock (sent)
                {
                    if (sent.Contains(e.Package.TransactionID))
                    {
                        lock (responses)
                        {
                            if (!responses.ContainsKey(e.Package.TransactionID) && e.Package is T)
                            {
                                responses.Add(e.Package.TransactionID, e.Package);
                                if (responses.Count == request.Count())
                                {
                                    lock (this.Reader)
                                    {
                                        this.Reader.MessageReceived -= method;
                                        timeoutP = 0;
                                    }
                                }
                            }
                        }
                    }
                }
            };

            #endregion

            this.Reader.MessageReceived += method;
            this.Flush();

            //Agora vem a parte mesmo lixada!
            //Queremos bloquear a execução do programa até que tenhamos o output desejado!
            //Ou até que ocorra timeoutP!

            #region Block

            //Por enquanto vamos usar esta técnica!
            //Que é uma grande MERDA!
            //Mas enquanto eu não aprendo uma melhor...
            int start = Environment.TickCount;
            while ((Environment.TickCount - start) < timeoutP)
            {
                Thread.Sleep(100);
            }

            this.Reader.MessageReceived -= method;

            #endregion

            //Vamos associar a cada envio uma resposta!
            Dictionary <int, PackageTransaction> result = new Dictionary <int, PackageTransaction>();
            int i = 0;
            foreach (PackageRequest item in request)
            {
                if (!responses.ContainsKey(sent[i]))
                {
                    continue;
                }
                PackageResponse rsp = responses[sent[i]];
                if (rsp == null)
                {
                    continue;
                }
                result.Add(sent[i++], new PackageTransaction(item, rsp));
            }

            return(result);
        }