Exemple #1
0
        } // class

        #endregion

        #region method_SubtractionPetition
        public static void SubtractionPetition(SubRequest calc, int id)
        {
            try
            {
                var httpWebRequest = HeaderBuilder("Calculator", "sub", id);

                string json = JsonConvert.SerializeObject(calc);

                SendRequest(httpWebRequest, json);

                SubResponse     response     = null;
                HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    response = JsonConvert.DeserializeObject <SubResponse>(result);
                }

                Console.WriteLine("Difference: " + response.Difference + "\n\npress enter to continue.");
                Console.ReadKey();
            }
            catch (WebException webex)
            {
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string       text   = reader.ReadToEnd();
                }
            }
        } // class
Exemple #2
0
        //Each method contains the business logic of the app


        public SubResponse Diference(SubRequest request, string trakingId)
        {
            log.Trace("this is the service -> Difference");
            SubResponse sub = new SubResponse();

            try
            {
                //thi is the logic
                sub.Difference = request.Minuend - request.Subtrahend;
                log.Trace(HttpStatusCode.OK);

                //if there is an id the operation is saved on journal
                if (trakingId != null)
                {
                    var op = new Operation()
                    {
                        name        = "Difference",
                        date        = DateTime.Now,
                        calculation = string.Join("-", request.Minuend, request.Subtrahend)
                    };
                    JournalList.Add(new KeyValuePair <string, Operation>(trakingId, op));
                }
            }
            catch (Exception e)
            {
                //
                log.Error(HttpStatusCode.InternalServerError);
                log.Error("Error in the controller Difference " + e);
                throw new Exception();
            }

            return(sub);
        }
Exemple #3
0
        public SubResponse sub([FromBody] SubRequest value)
        {
            logger.Trace("Service called: Sub");

            /* An invalid request has been received.
             * This may mean the HTTP requests and/or the HTTP body may contains some errors which should be fixed
             * */
            if (value == null)
            {
                logger.Error(HttpStatusCode.BadRequest);
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            try
            {
                SubResponse result = new SubResponse();

                // Execute operation: Sub
                String forJournal = "";

                result.Difference = value.Minuend - value.Subtrahend;
                forJournal        = value.Minuend + " - " + value.Subtrahend + " = " + result.Difference;


                if (Request != null && Request.Headers != null)
                {
                    var headers = Request.Headers;

                    if (headers.Contains("X-Evi-Tracking-Id"))
                    {
                        // Must store this request’s details inside it’s journal
                        string trackingId = headers.GetValues("X-Evi-Tracking-Id").First();
                        logger.Info("X-Evi-Tracking-Id = " + trackingId);

                        Operation operation = new Operation
                        {
                            OperationDes = "Sub",
                            Calculation  = forJournal,
                            Date         = DateTime.Now.ToString("u")
                        };

                        Journal.store(trackingId, operation);
                        logger.Trace("Sub success!!");
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                logger.Error(ex);

                /*
                 * An unexpected error condition was triggered which made impossible to fulfill the request. Please try again or contact support
                 * */
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }
        public static SubResponse Unmarshall(UnmarshallerContext context)
        {
            SubResponse subResponse = new SubResponse();

            subResponse.HttpResponse = context.HttpResponse;
            subResponse.RequestId    = context.StringValue("Sub.RequestId");
            subResponse.Success      = context.BooleanValue("Sub.Success");
            subResponse.ErrorMessage = context.StringValue("Sub.ErrorMessage");

            return(subResponse);
        }
Exemple #5
0
        public void SubResponse_CorrectlyFormatsResponseForJournal()
        {
            var difference = TestHelper.GeneratePositiveNumber();
            var expected   = difference.ToString();
            var response   = new SubResponse
            {
                Difference = difference
            };

            var formattedResponse = response.GetFormatedResponse();

            formattedResponse.Should().Be(expected);
        }
        public void Sub(string Id_Tracking)
        {
            Reqsub.Nums = new int[] { };
            Console.WriteLine("------- Operation Subtract -------");
            Console.WriteLine("Write the operation( Ej: 1-2-3 )");
            separator = '-';
            try
            {
                Console.WriteLine("Operation:");
                op = Console.ReadLine();

                string[] numbers = op.Trim().Split(separator);
                Reqsub.Nums = numbers.Select(x => int.Parse(x)).ToArray();

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create($"{url}sub");
                req.Method      = "POST";
                req.ContentType = "application/json";

                if (Id_Tracking != "")
                {
                    req.Headers.Add("X_Evi_Tracking_Id", Id_Tracking);
                }

                // Opens a stream,converts the request to Json and send it
                using (StreamWriter sw = new StreamWriter(req.GetRequestStream()))
                {
                    string jsonRequest = JsonConvert.SerializeObject(Reqsub);
                    sw.Write(jsonRequest);
                    sw.Close();
                }

                SubResponse     response = new SubResponse();
                HttpWebResponse Response = (HttpWebResponse)req.GetResponse();
                using (StreamReader sr = new StreamReader(Response.GetResponseStream(), Encoding.UTF8))
                {
                    Console.WriteLine("The server responds: ");
                    response = JsonConvert.DeserializeObject <SubResponse>(sr.ReadToEnd());
                    Console.WriteLine($"{response.Difference}");
                    sr.Close();
                    Response.Close();
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
                logger.Error(e.Message);
            }
        }
Exemple #7
0
        public string Sub(SubRequest Reqsub)
        {
            SubResponse response  = new SubResponse();
            string      operation = "";
            int         total     = 0;

            logger.Trace("----- Method Subtract -----");
            try
            {
                if (Reqsub == null || Reqsub.Nums == null)
                {
                    return(Error400().ErrorMessage.ToString());
                    //throw new ArgumentNullException();
                }
                response.Difference = Reqsub.Nums[0];

                for (int i = 1; i < Reqsub.Nums.Length; i++)
                {
                    response.Difference -= Reqsub.Nums[i];
                    operation           += $"{Reqsub.Nums[i]} - ";
                }

                // Subtracts the first number and delete the last '-'
                total    -= Reqsub.Nums[0];
                operation = $"{response.Difference} - {operation}";

                operation = operation.Substring(0, operation.Length - 3);

                logger.Trace($"{operation} = {response.Difference}");

                if (Request.Headers.GetValues("X_Evi_Tracking_Id") != null && Request.Headers.GetValues("X_Evi_Tracking_Id").Any())
                {
                    string key = Request.Headers.GetValues("X_Evi_Tracking_Id").First();

                    JournalService.StoreOperation(CreateOperation("Dif", $"{operation} = {response.Difference}", DateTime.Now, key));
                }

                string json = JsonConvert.SerializeObject(response);
                return(json);
            }
            catch (ArgumentNullException e)
            {
                logger.Error(e.Message);
                return(e.Message);
            }
            catch (Exception)
            {
                return(Error500().ErrorMessage.ToString());
            }
        }
Exemple #8
0
        public SubResponse Postsub([FromBody] SubRequest restandos)
        {
            SubResponse resta = new SubResponse
            {
                Difference = restandos.Minuend + restandos.Subtrahend
            };

            if (Request.Headers["X-Evi-Tracking-Id"].Any())
            {
                var identification = Request.Headers["X-Evi-Tracking-Id"];
                var currentUser    = UsersHandler.KnownOrNot(identification);
                currentUser.Operations.Add(new SubtractOperation(restandos, resta));
            }
            return(resta);
        }
Exemple #9
0
        public async static Task <Subreddit> GetSubreddit(string sub = "all", string after = null)
        {
            using (HttpClient client = new HttpClient())
            {
                Subreddit subreddit = null;
                try
                {
                    HttpResponseMessage response = await client.GetAsync($"{PROXY}https://reddit.com/r/{sub}.json{(after == null ? "" : $"?after={after}")}");

                    Console.WriteLine(response);
                    response.EnsureSuccessStatusCode();

                    SubResponse subResponse = null;
                    using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        subResponse = SubResponse.FromJson(reader.ReadToEnd());
                    }

                    subreddit = new Subreddit
                    {
                        Name  = sub,
                        Posts = Mapper.Map <Post[]>(subResponse.Data.Children)
                    };
                }
Exemple #10
0
        public void tsbSubUpdate_Click(object sender, EventArgs e)
        {
            // 修改为PAC代理模式
            menuGlobalPAC_Click(sender, e);

            //打出开始订阅
            AppendText(false, UIRes.I18N("MsgUpdateSubscriptionStart"));

            //查找订阅地址
            //if (config.subItem == null || config.subItem.Count <= 0)
            //{
            //    AppendText(false, UIRes.I18N("MsgNoValidSubscription"));
            //    return;
            //}

            V2rayUpdateHandle v2rayUpdateHandle3 = new V2rayUpdateHandle();

            v2rayUpdateHandle3.UpdateCompleted += (sender2, args) =>
            {
                if (args.Success)
                {
                    // 获取订阅内容成功
                    AppendText(false, UIRes.I18N("MsgGetSubscriptionSuccessfully"));

                    SubResponse result = Utils.FromJson <SubResponse>(args.Msg);

                    if (result.status != "SUCCESS")
                    {
                        login(); //引导去登录

                        AppendText(false, result.msg);
                    }

                    var subData = Utils.Base64Decode(result.data.data);
                    if (Utils.IsNullOrEmpty(subData))
                    {
                        // 解析失败
                        AppendText(false, UIRes.I18N("MsgSubscriptionDecodingFailed"));
                        return;
                    }

                    var id = Utils.GetGUID();
                    //移除所有订阅服务器
                    ConfigHandler.RemoveServerViaSubid(ref config);

                    AppendText(false, UIRes.I18N("MsgClearSubscription"));
                    // 刷新界面显示
                    RefreshServers();
                    if (AddBatchServers(subData, id) == 0)
                    {
                    }
                    else
                    {
                        AppendText(false, UIRes.I18N("MsgFailedImportSubscription"));
                    }
                    AppendText(false, UIRes.I18N("MsgUpdateSubscriptionEnd"));
                }
                else
                {
                    AppendText(false, args.Msg);
                }
            };
            v2rayUpdateHandle3.Error += (sender2, args) =>
            {
                AppendText(true, args.GetException().Message);
            };

            v2rayUpdateHandle3.WebDownloadString(Global.Subscribe);
            AppendText(false, UIRes.I18N("MsgStartGettingSubscriptions"));
        }
Exemple #11
0
 public ResponseEventArgs(SubResponse code)
 {
     ArrivedCode = code;
 }