예제 #1
0
 public void BuildApiCall_PerCallSettings()
 {
     var perCallSettings = CallSettings.FromCancellationToken(new CancellationTokenSource().Token);
     var helper = new ClientHelper(new DummySettings());
     var server = new DummyServer();
     var apiCall = helper.BuildApiCall<SimpleRequest, SimpleResponse>(
         server.MethodAsync, server.MethodSync, null);
     apiCall.Sync(null, perCallSettings);
     Assert.Equal(perCallSettings.CancellationToken, server.CallOptions.CancellationToken);
 }
 public CryptoCompareService()
 {
     _client = ClientHelper.GetClient(ClientHelper.CryptoCompareBase);
 }
예제 #3
0
        //کلاس-Add Or Update
        public static void SyncAddOrUpdateEducationalClass(IEducationalClassService educationalClassService, ILogService logService, ILogTypeService logTypeService, IUserService userService, User user, string termCode)
        {
            var educationalClasses = ClientHelper.GetValue <EducationalClassSyncModel>(StaticValue.EducationalClassRelativeAddress + $"/{termCode}");

            //log get From service
            SyncService.LogSync(logService, logTypeService, userService, user, (int)LogTypeValue.دریافت_کلاس_از_سرویس);

            var addOrUpdateResualt   = new Dictionary <string, int>();
            var counter              = 1;
            var preventedContentType = new List <int?> {
                10, 11, 24, 7, 6, 49, 50, 38
            };
            var preventedHoldingType = new List <decimal?> {
                5, 7
            };

            if (educationalClasses != null)
            {
                var exceptions = educationalClasses.Where(w => preventedContentType.Contains(w.ContentType) ||
                                                          preventedHoldingType.Contains(w.HoldingType) || w.HoldingExamDate == null);
                educationalClasses.Except(exceptions).ToList().ForEach(x =>
                {
                    if (x.ContentType != null && !preventedContentType.Contains(x.ContentType) &&
                        x.HoldingExamDate != null &&
                        x.HoldingType != null && !preventedHoldingType.Contains(x.HoldingType))
                    {
                        if (x != null)
                        {
                            if (HasNullProperty(x))
                            {
                                addOrUpdateResualt.Add($"{x.GroupId}-{x.CodeClass}-{x.Name}-{counter}", 4);
                            }
                            else
                            {
                                var r = educationalClassService.AddOrUpdate(x);
                                addOrUpdateResualt.Add($"{x.GroupId}-{x.CodeClass}-{x.Name}-{counter}", r);
                            }
                        }
                        ++counter;
                    }
                });
            }
            var added            = addOrUpdateResualt.Count(x => x.Value == 1);
            var updatetd         = addOrUpdateResualt.Count(x => x.Value == 2);
            var warrning         = addOrUpdateResualt.Count(x => x.Value == 3);
            var notFounded       = addOrUpdateResualt.Count(x => x.Value == 4);
            var stringWarrning   = string.Empty;
            var stringNotFounded = string.Empty;

            foreach (var s in addOrUpdateResualt.Where(x => x.Value == 3).Select(x => x.Key))
            {
                stringWarrning = $"تعداد {warrning}" + " || " + s + " | ";
            }
            foreach (var s in addOrUpdateResualt.Where(x => x.Value == 4).Select(x => x.Key))
            {
                stringNotFounded = $"تعداد {notFounded}" + " || " + s + " | ";
            }

            stringWarrning   = !string.IsNullOrEmpty(stringWarrning.Trim()) ? stringWarrning : "بدون مشکل";
            stringNotFounded = !string.IsNullOrEmpty(stringNotFounded.Trim()) ? stringNotFounded : "بدون مشکل";

            SyncService.LogSync(logService, logTypeService, userService, user, (int)LogTypeValue.کلاس_اضافه_گردید, $"تعداد {added}");
            SyncService.LogSync(logService, logTypeService, userService, user, (int)LogTypeValue.کلاس_آپدیت_گردید, $"تعداد {updatetd}");
            SyncService.LogSync(logService, logTypeService, userService, user, (int)LogTypeValue.عملیات_ناموفق_در_بروزرسانی_کلاس, stringWarrning);
            SyncService.LogSync(logService, logTypeService, userService, user, (int)LogTypeValue.عملیات_ناموفق_به_دلیل_عدم_وجود_حداقل_یک_مقدار_از_کلاس, stringNotFounded);

            //return result;
        }
예제 #4
0
 partial void OnConstruction(Speech.SpeechClient grpcClient, SpeechSettings effectiveSettings, ClientHelper clientHelper);
예제 #5
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            try
            {
                var view = inflater.Inflate(Resource.Layout.activity_application_processing, container, false);

                List <Place.Field> fields = new List <Place.Field>();

                fields.Add(Place.Field.Id);
                fields.Add(Place.Field.Name);
                fields.Add(Place.Field.LatLng);
                fields.Add(Place.Field.Address);

                #region Инициализаия переменных

                SizeInputLayout      = view.FindViewById <TextInputLayout>(Resource.Id.SizeInputLayout);
                LInputCargoInsurance = view.FindViewById <TextInputLayout>(Resource.Id.ApplicationInputLayoutCargoInsurance);
                LInputTime           = view.FindViewById <TextInputLayout>(Resource.Id.ApplicationInputLayoutTime);
                LInputDate           = view.FindViewById <TextInputLayout>(Resource.Id.ApplicationInputLayoutDate);
                LInputContactPerson  = view.FindViewById <TextInputLayout>(Resource.Id.ApplicationInputLayoutContactPerson);

                btn_make_request = view.FindViewById <Button>(Resource.Id.btn_make_request);

                s_edit_from      = view.FindViewById <EditText>(Resource.Id.s_edit_from);
                s_edit_where     = view.FindViewById <EditText>(Resource.Id.s_edit_where);
                s_shipment_time  = view.FindViewById <EditText>(Resource.Id.s_shipment_time);
                s_shipping_date  = view.FindViewById <EditText>(Resource.Id.s_shipping_date);
                s_length         = view.FindViewById <EditText>(Resource.Id.s_length);
                s_width          = view.FindViewById <EditText>(Resource.Id.s_width);
                s_weight         = view.FindViewById <EditText>(Resource.Id.s_weight);
                s_height         = view.FindViewById <EditText>(Resource.Id.s_height);
                s_size           = view.FindViewById <EditText>(Resource.Id.s_size);
                s_sum_seats      = view.FindViewById <EditText>(Resource.Id.s_sum_seats);
                s_contact_person = view.FindViewById <EditText>(Resource.Id.s_contact_person);
                s_value          = view.FindViewById <EditText>(Resource.Id.s_value);

                s_cargo_characteristic = view.FindViewById <Spinner>(Resource.Id.s_cargo_characteristic);
                s_hazard_class         = view.FindViewById <Spinner>(Resource.Id.s_hazard_class);
                s_loading_methods      = view.FindViewById <Spinner>(Resource.Id.s_loading_methods);

                check_argue = view.FindViewById <CheckBox>(Resource.Id.check_argue);

                SwitchDateTime       = view.FindViewById <SwitchCompat>(Resource.Id.ApplicationSwitchDateTime);
                SwitchCargoInsurance = view.FindViewById <SwitchCompat>(Resource.Id.ApplicationSwitchCargoInsurance);
                SwitchContactPerson  = view.FindViewById <SwitchCompat>(Resource.Id.ApplicationSwitchContactPerson);
                preloader            = view.FindViewById <ProgressBar>(Resource.Id.preloader);

                s_length.SetMaxLines(8);
                s_width.SetMaxLines(8);
                s_height.SetMaxLines(8);
                s_size.Text = "1";

                #region Focusable Enabled Clickable

                SwitchDateTime.Focusable       = true;
                SwitchCargoInsurance.Focusable = true;
                SwitchContactPerson.Focusable  = true;

                //s_size.Focusable = false;
                //s_size.Enabled = false;
                s_size.Visibility = ViewStates.Visible;
                s_size.Enabled    = false;

                s_shipment_time.Focusable = false;
                s_shipment_time.Enabled   = false;

                s_shipping_date.Focusable = false;
                s_shipping_date.Enabled   = false;

                //s_value.Focusable = false;
                //s_value.LongClickable = true;
                s_value.Visibility          = ViewStates.Invisible;
                s_contact_person.Visibility = ViewStates.Invisible;
                //s_contact_person.Focusable = false;
                //s_contact_person.LongClickable = false;

                s_edit_from.Focusable  = false;
                s_edit_where.Focusable = false;
                #endregion
                #endregion


                if (Arguments != null)
                {
                    string mParam = Arguments.GetString("isDestination");
                    if (mParam == "true")
                    {
                        s_edit_where.Text = StaticOrder.Destination_address;
                    }
                    else
                    {
                        s_edit_from.Text = StaticOrder.Inception_address;
                    }
                }

                s_cargo_characteristic.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(Spinner_ItemSelected);
                //var adapter1 = new ArrayAdapter<String>(Activity, Resource.Array.array_cargo_characteristic, Android.Resource.Layout.SimpleSpinnerItem);
                var adapter1 = ArrayAdapter.CreateFromResource(Activity, Resource.Array.array_cargo_characteristic, Android.Resource.Layout.SimpleSpinnerItem);
                adapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                s_cargo_characteristic.Adapter = adapter1;

                s_hazard_class.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(SpinnerClass_ItemSelected);
                var adapter2 = ArrayAdapter.CreateFromResource(Activity, Resource.Array.array_hazard_class, Android.Resource.Layout.SimpleSpinnerItem);
                adapter2.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                s_hazard_class.Adapter = adapter2;

                s_loading_methods.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(SpinnerLoad_ItemSelected);
                var adapter3 = ArrayAdapter.CreateFromResource(Activity, Resource.Array.array_loading_methodsc, Android.Resource.Layout.SimpleSpinnerItem);
                adapter3.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                s_loading_methods.Adapter = adapter3;

                FragmentTransaction transaction2 = this.FragmentManager.BeginTransaction();

                #region Обработка нажатий на кнопки
                //s_size.Click += async delegate
                //{
                //    if (string.IsNullOrEmpty(s_length.Text) == false &&
                //    string.IsNullOrEmpty(s_width.Text) == false &&
                //    string.IsNullOrEmpty(s_height.Text) == false &&
                //    string.IsNullOrEmpty(s_sum_seats.Text) == false)
                //    {
                //        CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                //        ci.NumberFormat.CurrencyDecimalSeparator = ".";
                //        float size_calculation = float.Parse(s_length.Text, NumberStyles.Any, ci)
                //            * float.Parse(s_width.Text, NumberStyles.Any, ci)
                //            * float.Parse(s_height.Text, NumberStyles.Any, ci)
                //            * float.Parse(s_sum_seats.Text, NumberStyles.Any, ci);
                //        s_size.Text = size_calculation.ToString();
                //    }
                //    else
                //    {
                //        AlertDialog.Builder alert = new AlertDialog.Builder(Activity);
                //        alert.SetTitle("Внимание!");
                //        alert.SetMessage("Необходимо заполнить данные о длине, ширине и высоте груза !");
                //        alert.SetPositiveButton("Закрыть", (senderAlert, args) =>
                //        {
                //        });
                //        Dialog dialog = alert.Create();
                //        dialog.Show();
                //    }

                //};

                SwitchDateTime.Click       += SwitchDateTimeClick;
                SwitchCargoInsurance.Click += SwitchCargoInsuranceClick;
                SwitchContactPerson.Click  += SwitchContactPersonClick;

                s_width.TextChanged     += ValueSizeCalculation;
                s_height.TextChanged    += ValueSizeCalculation;
                s_length.TextChanged    += ValueSizeCalculation;
                s_sum_seats.TextChanged += ValueSizeCalculation;
                s_weight.TextChanged    += OnWieghtChanged;
                s_shipping_date.Click   += S_shipping_date_Click;

                //s_shipping_date.TextChanged += delegate
                //{
                //    DateTime NowDate = new DateTime();
                //    string[] NumberMonthYear = s_shipping_date.Text.Split('.');
                //    int year = Convert.ToInt32(NumberMonthYear[2]);
                //    int month = Convert.ToInt32(NumberMonthYear[1]);
                //    int number = Convert.ToInt32(NumberMonthYear[0]);
                //    DateTime ValueEntered = new DateTime(year, month, number);
                //    if (NowDate.CompareTo(ValueEntered) > 0)
                //    {
                //        Toast.MakeText(Activity, "Указанная дата позже текущей.", ToastLength.Long).Show();
                //        s_shipping_date.Text = NowDate.ToShortDateString();
                //    }
                //};

                s_shipment_time.Click += delegate
                {
                    LayoutInflater      layoutInflater = LayoutInflater.From(Activity);
                    View                view           = layoutInflater.Inflate(Resource.Layout.modal_user_time, null);
                    AlertDialog.Builder alert          = new AlertDialog.Builder(Activity);
                    alert.SetView(view);

                    #region Объявление переменных в диалоговом окне
                    var rb_first  = view.FindViewById <RadioButton>(Resource.Id.rb_first);
                    var rb_second = view.FindViewById <RadioButton>(Resource.Id.rb_second);
                    var rb_third  = view.FindViewById <RadioButton>(Resource.Id.rb_third);
                    var rb_vierth = view.FindViewById <RadioButton>(Resource.Id.rb_vierth);
                    var rb_fifth  = view.FindViewById <RadioButton>(Resource.Id.rb_fifth);
                    var rb_sixth  = view.FindViewById <RadioButton>(Resource.Id.rb_sixth);
                    #endregion

                    #region Обработка событий кнопок

                    rb_first.Click += delegate
                    {
                        s_shipment_time.Text = rb_first.Text;
                    };

                    rb_second.Click += delegate
                    {
                        s_shipment_time.Text = rb_second.Text;
                    };

                    rb_third.Click += delegate
                    {
                        s_shipment_time.Text = rb_third.Text;
                    };

                    rb_vierth.Click += delegate
                    {
                        s_shipment_time.Text = rb_vierth.Text;
                    };

                    rb_fifth.Click += delegate
                    {
                        s_shipment_time.Text = rb_fifth.Text;
                    };

                    rb_sixth.Click += delegate
                    {
                        s_shipment_time.Text = rb_sixth.Text;
                    };

                    #endregion

                    alert.SetCancelable(false)
                    .SetPositiveButton("Выбрать", delegate
                    {
                    })
                    .SetNegativeButton("Отмена", delegate
                    {
                        alert.Dispose();
                    });
                    Dialog dialog = alert.Create();
                    dialog.Show();
                };

                check_argue.Click += async delegate
                {
                    if (check_argue.Checked == true)
                    {
                        using (var client = ClientHelper.GetClient())
                        {
                            WebService.Home.HomeService.InitializeClient(client);
                            var o_data = await WebService.Home.HomeService.Offer();

                            if (o_data.Status == HttpStatusCode.OK)
                            {
                                AgreementResponse o_user_data = new AgreementResponse();
                                o_user_data = o_data.ResponseData;

                                Android.App.FragmentTransaction transaction1 = this.FragmentManager.BeginTransaction();
                                AlertDialog.Builder             alert        = new AlertDialog.Builder(Activity);
                                alert.SetTitle("Согласие с договором офертой");
                                alert.SetMessage(o_user_data.Agreement);
                                check_argue.Checked = false;
                                alert.SetPositiveButton("Принимаю", (senderAlert, args) =>
                                {
                                    check_argue.Checked = true;
                                });
                                alert.SetNegativeButton("Не принимаю", (senderAlert, args) =>
                                {
                                    check_argue.Checked = false;
                                });
                                Dialog dialog = alert.Create();
                                dialog.Show();
                            }
                            else
                            {
                                Toast.MakeText(Activity, o_data.Message, ToastLength.Long).Show();
                            }
                        };
                    }
                };

                s_edit_from.Click += async delegate
                {
                    //GooglePlacesResult fragment = new GooglePlacesResult();
                    //Bundle args = new Bundle();
                    //args.PutString("isDestination", "false");
                    //fragment.Arguments = args;

                    //transaction2.Replace(Resource.Id.framelayout, fragment).AddToBackStack(null).Commit();

                    Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.Overlay, fields)
                                    .SetCountry("RUS")
                                    .Build(Activity);

                    myCity = "false";

                    StartActivityForResult(intent, 0);
                };

                s_edit_where.Click += async delegate
                {
                    Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.Overlay, fields)
                                    .SetCountry("RUS")
                                    .Build(Activity);
                    myCity = "true";
                    StartActivityForResult(intent, 0);
                    //GooglePlacesResult fragment = new GooglePlacesResult();
                    //Bundle args = new Bundle();
                    //args.PutString("isDestination", "true");
                    //fragment.Arguments = args;
                    //transaction2.Replace(Resource.Id.framelayout, fragment).AddToBackStack(null).Commit();
                };

                btn_make_request.Click += async delegate
                {
                    try
                    {
                        string InputErrorMessage = "";
                        if (ValidationValues(ref InputErrorMessage))
                        {
                            AlertDialogCall(InputErrorMessage);
                        }
                        else
                        {
                            preloader.Visibility = Android.Views.ViewStates.Visible;
                            MakeOrderModel model = new MakeOrderModel()
                            {
                                destination_address = s_edit_where.Text,
                                for_date            = s_shipping_date.Text,
                                for_time            = s_shipment_time.Text,
                                height            = s_height.Text,
                                inception_address = s_edit_from.Text,
                                cargo_class       = a_hazard_class,
                                cargo_loading     = a_loading_methodsc,
                                cargo_type        = a_cargo_characteristic,
                                destination_lat   = StaticOrder.Destination_lat, /*"47.232032",*/
                                destination_lng   = StaticOrder.Destination_lng, /*"39.731523",*/
                                inception_lat     = StaticOrder.Inception_lat,   /*"47.243221",*/
                                inception_lng     = StaticOrder.Inception_lng,   /*"39.668781",*/
                                insurance         = s_value.Text,
                                receiver          = s_contact_person.Text,
                                length            = s_length.Text,
                                qty    = s_sum_seats.Text,
                                weight = s_weight.Text,
                                width  = s_width.Text,
                                volume = s_size.Text
                            };

                            using (var client = ClientHelper.GetClient())
                            {
                                OrderService.InitializeClient(client);
                                var o_data = await OrderService.GetOrderPrice(model);

                                if (o_data.Status == HttpStatusCode.OK)
                                {
                                    //o_data.Message = "Успешно авторизован!";
                                    Toast.MakeText(Activity, o_data.Message, ToastLength.Long).Show();

                                    AmountResponse order_data = new AmountResponse();
                                    order_data = o_data.ResponseData;
                                    if (IsFieldsEmptyOrNull(o_data.ResponseData))
                                    {
                                        string ErrorMessage = "Не удалось оформить заказ. Скорее всего " +
                                                              "Вы ввели неверные пункт отправления и/или пункт назначения ";
                                        AlertDialogCall(ErrorMessage);
                                        preloader.Visibility = Android.Views.ViewStates.Invisible;
                                    }
                                    else
                                    {
                                        StaticOrder.AddInfoOrder(model);
                                        StaticOrder.AddInfoAmount(order_data);

                                        preloader.Visibility = Android.Views.ViewStates.Invisible;

                                        StaticUser.OrderInStageOfBid = true;

                                        try
                                        {
                                            Android.App.FragmentTransaction transaction1 = this.FragmentManager.BeginTransaction();
                                            ActivityOrderPreis content = new ActivityOrderPreis();
                                            transaction1.Replace(Resource.Id.framelayout, content);
                                            transaction1.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            Toast.MakeText(Activity, ex.Message, ToastLength.Long);
                                        }
                                    }
                                }
                                else
                                {
                                    Toast.MakeText(Activity, o_data.Message, ToastLength.Long).Show();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Activity, ex.Message, ToastLength.Long).Show();
                    }
                };

                #endregion

                return(view);
            }
            catch (Exception ex)
            {
                var view = inflater.Inflate(Resource.Layout.activity_errors_handling, container, false);
                Toast.MakeText(Activity, ex.Message, ToastLength.Long).Show();
                return(view);
            }
        }
예제 #6
0
        public static async Task CommentsThreaded_SetupAsync(TestContext context)
        {
            _clientAuth = await ClientHelper.GetAuthenticatedWordPressClient();

            var IsValidToken = await _clientAuth.IsValidJWToken();

            Assert.IsTrue(IsValidToken);

            var post = await _clientAuth.Posts.Create(new Post()
            {
                Title   = new Title("Title 1"),
                Content = new Content("Content PostCreate")
            });

            await Task.Delay(1000);

            var comment0 = await _clientAuth.Comments.Create(new Comment()
            {
                PostId  = post.Id,
                Content = new Content("orem ipsum dolor sit amet")
            });

            var comment00 = await _clientAuth.Comments.Create(new Comment()
            {
                PostId  = post.Id,
                Content = new Content("r sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam non")
            });

            var comment1 = await _clientAuth.Comments.Create(new Comment()
            {
                PostId   = post.Id,
                ParentId = comment0.Id,
                Content  = new Content("onsetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna ali")
            });

            var comment2 = await _clientAuth.Comments.Create(new Comment()
            {
                PostId   = post.Id,
                ParentId = comment1.Id,
                Content  = new Content("ro eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem i")
            });

            var comment3 = await _clientAuth.Comments.Create(new Comment()
            {
                PostId   = post.Id,
                ParentId = comment2.Id,
                Content  = new Content("tetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam e")
            });

            var comment4 = await _clientAuth.Comments.Create(new Comment()
            {
                PostId   = post.Id,
                ParentId = comment1.Id,
                Content  = new Content("t ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum do")
            });

            postid      = post.Id;
            comment0id  = comment0.Id;
            comment00id = comment00.Id;
            comment1id  = comment1.Id;
            comment2id  = comment2.Id;
            comment3id  = comment3.Id;
            comment4id  = comment4.Id;
        }
예제 #7
0
 //Variation
 //1.GetEndpointAddress for the service
 //2.CreateChannelFactory
 //2.1:Add the custom behavior - Optional
 //3.Get the BehaviorAttribute instance in the ChannelDescription
 //4.Open the ChannelFactory
 //5.Check the Behavior static flags
 //6.Check the Behavior instance flags
 //7.Send a message to the server
 public static ChannelFactory <T> GetChannelFactory <T>()
 {
     System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding();
     return(new ChannelFactory <T>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/ContractBehaviorService.svc"))));
 }
 public ResultProcessing Get(string code = "")
 {
     return(ClientHelper.Get <string>(Uri, ""));
 }
예제 #9
0
        private string Variation_Service_XMLReservedCharacters(string clientString)
        {
            // Create the proxy
            ClientContract.IServiceContractName_784749_XMLReservedCharacters_Service clientProxy = ClientHelper.GetProxy <ClientContract.IServiceContractName_784749_XMLReservedCharacters_Service>();
            // Send the two way message
            _output.WriteLine("Testing [Variation_Service_XMLReservedCharacters]");
            string response = clientProxy.Method7(clientString);

            _output.WriteLine("Testing [Variation_Service_XMLReservedCharacters] returned <{0}>", response);
            return(response);
        }
예제 #10
0
 public LeaveOneOutMethod()
 {
     InitializeComponent();
     this.client = ClientHelper.GetClient();
 }
예제 #11
0
 private void btnExcel_Click(object sender, System.EventArgs e)
 {
     ClientHelper.ExportExcel(saveFileDialog1, ultraGridExcelExporter1, ultraGrid1, "云南人才市场缴费报表", this.oper.cnvcOperName);
 }
예제 #12
0
        private void btnQuery_Click(object sender, System.EventArgs e)
        {
            //
            try
            {
                //string strSql = "select cnnJobID,'' as cnvcJobName,cnvcMemberCardNo,cnvcPaperNo,'' as cnvcMemberName,cnnPrepay,cnnReturn,cnnBalance,cnvcState,cnvcOperName,cndOperDate from tbPrepay where 1=1 ";
                string strSql = "select a.cnnPrepayID,a.cnnJobID,b.cnvcJobName,a.cnvcPaperNo,"
                                + " d.cnvcMemberName,a.cnnPrepay,a.cnnReturn,a.cnnBalance,a.cnvcState,a.cnvcOperName,a.cndOperDate "
                                + " from tbPrepay a"
                                + " left outer join tbJob b on a.cnnJobID=b.cnnJobID";
                //strSql += " left outer join tbMember c on a.cnvcMemberCardNo = c.cnvcMemberCardNo";
                strSql += " left outer join tbFMember d on a.cnvcPaperNo=d.cnvcPaperNo and a.cnvcMemberCardNo is null";
                strSql += " where 1=1";
                if (cmbShow.Text.Trim().Length > 0)
                {
                    strSql += " and b.cnvcJobName like '%" + cmbShow.Text + "%'";
                }
//				if (txtMemberCardNo.Text.Trim().Length > 0)
//				{
//					strSql += " and c.cnvcMemberCardNo like '%"+txtMemberCardNo.Text+"%'";
//				}
                if (txtMemberName.Text != "")
                {
                    strSql += " and d.cnvcMemberName like '%" + txtMemberName.Text + "%'";
                }
                if (txtPaperNo.Text.Trim().Length > 0)
                {
                    strSql += " and d.cnvcPaperNo like '%" + txtPaperNo.Text + "%'";
                }
                if (cmbOperName.Text.Trim().Length > 0)
                {
                    strSql += " and a.cnvcOperName like '%" + cmbOperName.Text + "%'";
                }
                if (chkBeginDate.Checked)
                {
                    strSql += " and a.cndOperDate >= '" + cmbBeginDate.Value.ToString() + "'";
                }
                if (chkEndDate.Checked)
                {
                    strSql += " and a.cndOperDate <= '" + cmbEndDate.Value.ToString() + "'";
                }
                if (cmbFeeDirection.Text.Trim() == "缴费")
                {
                    strSql += "and a.cnnReturn =0 ";
                }
                else if (cmbFeeDirection.Text.Trim() == "退费")
                {
                    strSql += "and a.cnnReturn >0 ";
                }

                DataTable dtPrepay = Helper.Query(strSql);
                this.ultraGrid1.DataSource = null;
                this.ultraGrid1.DataSource = dtPrepay;
                this.ultraGrid1.DataBind();

                ClientHelper.AddGridColumn(this.ultraGrid1, this.oper.cnvcOperName);
                Helper.AddGridSummary(this.ultraGrid1, SummaryType.Count, "会员数量:{0}", "cnvcPaperNo");
                Helper.AddGridSummary(this.ultraGrid1, SummaryType.Sum, "展位费总额:{0}", "cnnPrepay");
                Helper.AddGridSummary(this.ultraGrid1, SummaryType.Sum, "退费总额:{0}", "cnnReturn");
                Helper.AddGridSummary(this.ultraGrid1, SummaryType.Sum, "余额总额:{0}", "cnnBalance");
            }
            catch (BusinessException bex)
            {
                MessageBox.Show(this, bex.Message, bex.Type, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(this, ex.Message, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #13
0
        public async Task WhenISendARequestToUsingClientAndGetTheResponse(string apiRequestType, string uri, HttpClient client, string responseKey)
        {
            HttpResponseMessage response = await ClientHelper.GetResponse(uri, apiRequestType, client, null);

            m_scenarioContext.Add(responseKey, response);
        }
예제 #14
0
        protected override void ProcessRecord()
        {
            using (var vlt = Util.VaultHelper.GetVault(VaultProfile))
            {
                vlt.OpenStorage();
                var v = vlt.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                {
                    throw new InvalidOperationException("No certificates found");
                }

                var ci = v.Certificates.GetByRef(CertificateRef, throwOnMissing: false);
                if (ci == null)
                {
                    throw new Exception("Unable to find a Certificate for the given reference");
                }

                // If we're renaming the Alias, do that
                // first in case there are any problems
                if (NewAlias != null)
                {
                    v.Certificates.Rename(CertificateRef, NewAlias);
                    ci.Alias = NewAlias == "" ? null : NewAlias;
                }

                if (!LocalOnly)
                {
                    if (ci.CertificateRequest == null)
                    {
                        throw new Exception("Certificate has not been submitted yet; cannot update status");
                    }

                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        c.RefreshCertificateRequest(ci.CertificateRequest, UseBaseUri);
                    }

                    if ((Repeat || string.IsNullOrEmpty(ci.CrtPemFile)) &&
                        !string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                    {
                        var crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

                        var crtDerAsset = vlt.ListAssets(crtDerFile, VaultAssetType.CrtDer).FirstOrDefault();
                        var crtPemAsset = vlt.ListAssets(crtPemFile, VaultAssetType.CrtPem).FirstOrDefault();

                        if (crtDerAsset == null)
                        {
                            crtDerAsset = vlt.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                        }
                        if (crtPemAsset == null)
                        {
                            crtPemAsset = vlt.CreateAsset(VaultAssetType.CrtPem, crtPemFile);
                        }

                        using (var cp = PkiHelper.GetPkiTool(
                                   StringHelper.IfNullOrEmpty(PkiTool, v.PkiTool)))
                        {
                            var bytes = ci.CertificateRequest.GetCertificateContent();

                            using (Stream source = new MemoryStream(bytes),
                                   derTarget = vlt.SaveAsset(crtDerAsset),
                                   pemTarget = vlt.SaveAsset(crtPemAsset))
                            {
                                var crt = cp.ImportCertificate(EncodingFormat.DER, source);

                                // We're saving the DER format cert "through"
                                // the CP in order to validate its content
                                cp.ExportCertificate(crt, EncodingFormat.DER, derTarget);
                                ci.CrtDerFile = crtDerFile;

                                cp.ExportCertificate(crt, EncodingFormat.PEM, pemTarget);
                                ci.CrtPemFile = crtPemFile;
                            }
                        }

                        var x509 = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber       = x509.SerialNumber;
                        ci.Thumbprint         = x509.Thumbprint;
                        ci.SignatureAlgorithm = x509.SignatureAlgorithm?.FriendlyName;
                        ci.Signature          = x509.GetCertHashString();
                    }

                    if (Repeat || string.IsNullOrEmpty(ci.IssuerSerialNumber))
                    {
                        var linksEnum = ci.CertificateRequest.Links;
                        if (linksEnum != null)
                        {
                            var links  = new LinkCollection(linksEnum);
                            var upLink = links.GetFirstOrDefault("up");
                            if (upLink != null)
                            {
                                // We need to save the ICA certificate to a local
                                // temp file so that we can read it in and store
                                // it properly as a vault asset through a stream
                                var tmp = Path.GetTempFileName();
                                try
                                {
                                    using (var web = new WebClient())
                                    {
                                        if (v.Proxy != null)
                                        {
                                            web.Proxy = v.Proxy.GetWebProxy();
                                        }

                                        var uri = new Uri(new Uri(v.BaseUri), upLink.Uri);
                                        web.DownloadFile(uri, tmp);
                                    }

                                    var cacert = new X509Certificate2(tmp);
                                    var sernum = cacert.GetSerialNumberString();
                                    var tprint = cacert.Thumbprint;
                                    var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                                    var sigval = cacert.GetCertHashString();

                                    if (v.IssuerCertificates == null)
                                    {
                                        v.IssuerCertificates = new OrderedNameMap <IssuerCertificateInfo>();
                                    }
                                    if (Repeat || !v.IssuerCertificates.ContainsKey(sernum))
                                    {
                                        var cacertDerFile  = $"ca-{sernum}-crt.der";
                                        var cacertPemFile  = $"ca-{sernum}-crt.pem";
                                        var issuerDerAsset = vlt.ListAssets(cacertDerFile,
                                                                            VaultAssetType.IssuerDer).FirstOrDefault();
                                        var issuerPemAsset = vlt.ListAssets(cacertPemFile,
                                                                            VaultAssetType.IssuerPem).FirstOrDefault();

                                        if (Repeat || issuerDerAsset == null)
                                        {
                                            if (issuerDerAsset == null)
                                            {
                                                issuerDerAsset = vlt.CreateAsset(VaultAssetType.IssuerDer, cacertDerFile);
                                            }
                                            using (Stream fs = new FileStream(tmp, FileMode.Open),
                                                   s = vlt.SaveAsset(issuerDerAsset))
                                            {
                                                fs.CopyTo(s);
                                            }
                                        }
                                        if (Repeat || issuerPemAsset == null)
                                        {
                                            if (issuerPemAsset == null)
                                            {
                                                issuerPemAsset = vlt.CreateAsset(VaultAssetType.IssuerPem, cacertPemFile);
                                            }

                                            using (var cp = PkiHelper.GetPkiTool(
                                                       StringHelper.IfNullOrEmpty(PkiTool, v.PkiTool)))
                                            {
                                                using (Stream source = vlt.LoadAsset(issuerDerAsset),
                                                       target = vlt.SaveAsset(issuerPemAsset))
                                                {
                                                    var crt = cp.ImportCertificate(EncodingFormat.DER, source);
                                                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                                                }
                                            }
                                        }

                                        v.IssuerCertificates[sernum] = new IssuerCertificateInfo
                                        {
                                            SerialNumber       = sernum,
                                            Thumbprint         = tprint,
                                            SignatureAlgorithm = sigalg,
                                            Signature          = sigval,
                                            CrtDerFile         = cacertDerFile,
                                            CrtPemFile         = cacertPemFile,
                                        };
                                    }

                                    ci.IssuerSerialNumber = sernum;
                                }
                                finally
                                {
                                    if (File.Exists(tmp))
                                    {
                                        File.Delete(tmp);
                                    }
                                }
                            }
                        }
                    }
                }

                ci.Label = StringHelper.IfNullOrEmpty(Label);
                ci.Memo  = StringHelper.IfNullOrEmpty(Memo);

                vlt.SaveVault(v);

                WriteObject(ci);
            }
        }
예제 #15
0
        private async void GetBoxes()
        {
            try
            {
                var o_data = new ServiceResponseObject <ListBoxResponse>();
                using (var client = ClientHelper.GetClient(CrossSettings.Current.GetValueOrDefault("token", "")))
                {
                    //надо было сначала клиента указать, а потом вызывать метод
                    //и обязательно с токеном
                    BoxService.InitializeClient(client);
                    o_data = await BoxService.GetContainers();

                    if (o_data.Status == HttpStatusCode.OK)
                    {
                        Toast.MakeText(Activity, o_data.Message, ToastLength.Long).Show();
                        boxlist = new List <BoxBookModel>();
                        List <ContainerResponse> containers = new List <ContainerResponse>();
                        if (isDepot)
                        {
                            containers = o_data.ResponseData.DEPOT_CONTAINERS;
                        }
                        else
                        {
                            containers = o_data.ResponseData.CONTAINERS;
                        }

                        if (containers == null || containers.Count == 0)
                        {
                            StaticUser.NamePadeAbsenceSomething = "BoxListActivity";
                            Android.App.FragmentTransaction transaction1 = this.FragmentManager.BeginTransaction();
                            NotFoundOrdersActivity          content      = new NotFoundOrdersActivity();
                            transaction1.Replace(Resource.Id.frameDriverlayout, content);
                            transaction1.Commit();
                        }

                        int id = 1;
                        foreach (var box in containers)
                        {
                            boxlist.Add(new BoxBookModel
                            {
                                Id               = box.id,
                                ImageView        = (box.sensors_status.fold == "0") ? Resource.Drawable.open_box : Resource.Drawable.close_box,
                                BoxId            = "Контейнер: " + box.id,
                                AlarmDescription = (box.alarms_status.Count == 0) ? "" : "На контейнере обнаружена тревога!",
                                OrderId          = (box.order_id == null) ? "нет заказа" : box.order_id
                            }
                                        );
                        }

                        UpdateList();
                        lstBox.ItemClick += ListBoxes_ItemClick;
                    }
                    else
                    {
                        StaticUser.NamePadeAbsenceSomething = "BoxListActivity";
                        Android.App.FragmentTransaction transaction1 = this.FragmentManager.BeginTransaction();
                        NotFoundOrdersActivity          content      = new NotFoundOrdersActivity();
                        transaction1.Replace(Resource.Id.frameDriverlayout, content);
                        transaction1.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(Application.Context, ex.Message, ToastLength.Long);
            }
        }
예제 #16
0
        //[InlineData("Http2Binding")] //Fail
        //[InlineData("Http3Binding")]
        public void RequestReplyStreaming(string binding)
        {
            Startup.binding = binding;
            IWebHost host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build();

            using (host)
            {
                host.Start();
                System.ServiceModel.ChannelFactory <ClientContract.IStream> channelFactory = null;
                switch (binding)
                {
                case "Http1Binding":
                    channelFactory = new System.ServiceModel.ChannelFactory <ClientContract.IStream>(ClientHelper.GetBufferedModHttp1Binding(),
                                                                                                     new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService1/RequestReplyTests.svc")));
                    break;

                //case "Http2Binding":
                //    channelFactory = new System.ServiceModel.ChannelFactory<ClientContract.IStream>(ClientHelper.GetBufferedModHttp2Binding(),
                //  new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService2/RequestReplyTests.svc")));
                //    break;
                //case "Http3Binding":
                //    channelFactory = new System.ServiceModel.ChannelFactory<ClientContract.IStream>(ClientHelper.GetBufferedModHttp3Binding(),
                //  new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService3/RequestReplyTests.svc")));
                //    break;
                default:
                    throw new Exception("Unknown binding");
                }
                IStream  stream2     = channelFactory.CreateChannel();
                long     messageSize = 0;
                long     num2        = 20000;
                MyStream input       = new MyStream(messageSize);
                Stream   stream      = stream2.Echo(input);
                int      num3        = 0;
                byte[]   buffer      = new byte[5000];
                int      num4;
                while ((num4 = stream.Read(buffer, 0, 370)) != 0)
                {
                    num3 = num4 + num3;
                }
                Assert.Equal(num2, (long)num3);
            }
        }
예제 #17
0
 partial void OnConstruction(ErrorGroupService.ErrorGroupServiceClient grpcClient, ErrorGroupServiceSettings effectiveSettings, ClientHelper clientHelper);
예제 #18
0
 partial void OnConstruction(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings effectiveSettings, ClientHelper clientHelper);
예제 #19
0
 partial void OnConstruction(LanguageService.LanguageServiceClient grpcClient, LanguageServiceSettings effectiveSettings, ClientHelper clientHelper);
예제 #20
0
 partial void OnConstruction(Firestore.FirestoreClient grpcClient, FirestoreSettings effectiveSettings, ClientHelper clientHelper)
 {
     Settings = effectiveSettings;
 }
예제 #21
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Identifiers == null || v.Identifiers.Count < 1)
                {
                    throw new InvalidOperationException("No identifiers found");
                }

                var ii = v.Identifiers.GetByRef(Ref);
                if (ii == null)
                {
                    throw new Exception("Unable to find an Identifier for the given reference");
                }

                var authzState = ii.Authorization;

                if (ii.Challenges == null)
                {
                    ii.Challenges = new Dictionary <string, AuthorizeChallenge>();
                }

                if (ii.ChallengeCompleted == null)
                {
                    ii.ChallengeCompleted = new Dictionary <string, DateTime?>();
                }

                if (v.ProviderConfigs == null || v.ProviderConfigs.Count < 1)
                {
                    throw new InvalidOperationException("No provider configs found");
                }

                var pc = v.ProviderConfigs.GetByRef(ProviderConfig);
                if (pc == null)
                {
                    throw new InvalidOperationException("Unable to find a Provider Config for the given reference");
                }
                var pcFilePath = Path.GetFullPath($"{pc.Id}.json");

                AuthorizeChallenge challenge         = null;
                DateTime?          challengCompleted = null;
                ii.Challenges.TryGetValue(Challenge, out challenge);
                ii.ChallengeCompleted.TryGetValue(Challenge, out challengCompleted);

                if (challenge == null || Regenerate)
                {
                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        challenge = c.GenerateAuthorizeChallengeAnswer(authzState, Challenge);
                        ii.Challenges[Challenge] = challenge;
                    }
                }

                if (Repeat || challengCompleted == null)
                {
                    if (Challenge == "dns")
                    {
                        if (string.IsNullOrEmpty(pc.DnsProvider))
                        {
                            throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge");
                        }

                        var dnsName   = challenge.ChallengeAnswer.Key;
                        var dnsValue  = Regex.Replace(challenge.ChallengeAnswer.Value, "\\s", "");
                        var dnsValues = Regex.Replace(dnsValue, "(.{100,100})", "$1\n").Split('\n');

                        using (var fs = new FileStream(pcFilePath, FileMode.Open))
                        {
                            var dnsInfo = DnsInfo.Load(fs);
                            dnsInfo.Provider.EditTxtRecord(dnsName, dnsValues);
                            ii.ChallengeCompleted[Challenge] = DateTime.Now;
                        }
                    }
                    else if (Challenge == "simpleHttp")
                    {
                        if (string.IsNullOrEmpty(pc.WebServerProvider))
                        {
                            throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge");
                        }

                        var wsFilePath = challenge.ChallengeAnswer.Key;
                        var wsFileBody = challenge.ChallengeAnswer.Value;
                        var wsFileUrl  = new Uri($"http://{authzState.Identifier}/{wsFilePath}");

                        using (var fs = new FileStream(pcFilePath, FileMode.Open))
                        {
                            var webServerInfo = WebServerInfo.Load(fs);
                            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(wsFileBody)))
                            {
                                webServerInfo.Provider.UploadFile(wsFileUrl, ms);
                                ii.ChallengeCompleted[Challenge] = DateTime.Now;
                            }
                        }
                    }
                }

                vp.SaveVault(v);

                WriteObject(authzState);
            }
        }
예제 #22
0
        private void SavePayment()
        {
            bool willContinue = true;

            //If payment is more than due, confirm
            if (totalPayment > totalAmountDue)
            {
                if (ClientHelper.ShowConfirmMessage("Total payment is greater than total amount due.\nDo you want to continue?")
                    != DialogResult.Yes)
                {
                    willContinue = false;
                }
            }

            if (willContinue)
            {
                PaymentDetail payment = new PaymentDetail()
                {
                    Id                = PaymentId,
                    CustomerId        = (int)SupplierDropdown.SelectedValue,
                    VoucherNumber     = VoucherNumberTextbox.Text,
                    PaymentDate       = PaymentDatePicker.Value,
                    RecordedBy        = UserInfo.UserId,
                    ApprovedBy        = approver,
                    TotalCashPayment  = CashPaymentCheckbox.Checked ? decimal.Parse(TotalCashTextbox.Text) : 0,
                    TotalCheckPayment = CheckPaymentCheckbox.Checked ? decimal.Parse(TotalCheckTextbox.Text) : 0,
                    IsDeleted         = false,
                    WitholdingTax     = WitholdingTaxTextbox.Text.ToDecimal(),
                    GovtForm          = GovtFormCheckbox.Checked,
                    TotalAmountDue    = totalAmountDue,
                    Discount          = DiscountTextbox.Value,
                    Remarks           = RemarksTextbox.Text,
                    Misc              = MiscTextbox.Text,
                    MiscAmount        = MiscAmountTextbox.Value
                };

                if (poList != null)
                {
                    poList.ToList().ForEach(a =>
                                            payment.PurchasePayments.Add(new PurchasePayment()
                    {
                        Amount                 = a.Amount,
                        PurchaseId             = a.PurchaseId,
                        PurchaseReturnDetailId = a.ReturnId
                    })
                                            );
                }

                if (CheckPaymentCheckbox.Checked)
                {
                    checksList.ForEach(a =>
                                       payment.Check.Add(new Check()
                    {
                        Amount       = a.Amount,
                        Bank         = a.Bank,
                        Branch       = a.Branch,
                        CheckDate    = a.CheckDate,
                        CheckNumber  = a.CheckNumber,
                        ClearingDate = a.ClearingDate,
                        IsDeleted    = false
                    }));
                }

                ToggleButtons(false);

                LoadImage.Visible = true;

                if (!worker.IsBusy)
                {
                    worker.RunWorkerAsync(payment);
                }
            }
        }
예제 #23
0
 partial void OnConstruction(TraceService.TraceServiceClient grpcClient, TraceServiceSettings effectiveSettings, ClientHelper clientHelper);
예제 #24
0
 public static async Task Init(TestContext testContext)
 {
     _client     = ClientHelper.GetWordPressClient();
     _clientAuth = await ClientHelper.GetAuthenticatedWordPressClient();
 }
예제 #25
0
 partial void OnConstruction(Bigtable.BigtableClient grpcClient, BigtableSettings effectiveSettings, ClientHelper clientHelper)
 {
     _idempotentMutateRowSettings = effectiveSettings.IdempotentMutateRowSettings;
 }
예제 #26
0
        public bool MoveNext()
        {
            lock (this.client)
            {
                if (resultIndex < results.Count)
                {
                    this.current = results[resultIndex++];
                    return(true);
                }
                else
                {
                    ResponsePull response;
                    if (this.context == null)
                    {
                        if (resultIndex > 0)
                        {
                            // case: previous pull returned an invalid context
                            return(false);
                        }
                        RequestEnumeration request = new RequestEnumeration(filter);
                        if (attributes != null)
                        {
                            request.Selection = new List <string>();
                            request.Selection.AddRange(this.attributes);
                        }

                        Message msgRequest  = requestFactory.CreateEnumerationRequest(request);
                        Message msgResponse = client.Enumerate(msgRequest);
                        if (msgResponse.IsFault)
                        {
                            ClientHelper.HandleFault(msgResponse);
                        }

                        response           = responseFactory.CreateEnumerationResponse(msgResponse);
                        this.endOfSequence = response.EndOfSequence != null;
                    }
                    else
                    {
                        if (this.endOfSequence == true)
                        {
                            // case: previous pull returned an end of sequence flag
                            this.current = null;
                            return(false);
                        }

                        RequestPull request = new RequestPull();
                        request.EnumerationContext = this.context;

                        Message msgRequest  = requestFactory.CreatePullRequest(request);
                        Message msgResponse = client.Pull(msgRequest);
                        if (msgResponse.IsFault)
                        {
                            ClientHelper.HandleFault(msgResponse);
                        }

                        response = responseFactory.CreatePullResponse(msgResponse);
                    }

                    if (response == null)
                    {
                        return(false);
                    }

                    resultIndex        = 0;
                    this.results       = resourceFactory.CreateResource(response, true);
                    this.context       = response.EnumerationContext;
                    this.endOfSequence = response.IsEndOfSequence;

                    if (this.results.Count > 0)
                    {
                        this.current = results[resultIndex++];
                        return(true);
                    }
                    else
                    {
                        this.current = null;
                        return(false);
                    }
                }
            }
        }
        //
        // GET: /Item/

        public ActionResult Index(string agency, Guid id)
        {
            MultilingualString.CurrentCulture = "en-US";

            var client = ClientHelper.GetClient();

            // Retrieve the requested item from the Repository.
            // Populate the item's children, so we can display information about them.
            IVersionable item = client.GetLatestItem(id, agency,
                                                     ChildReferenceProcessing.Populate);

            // To populate more than one level of children, you can use the GraphPopulator.
            //GraphPopulator populator = new GraphPopulator(client);
            //item.Accept(populator);

            // The type of model and the view we want depends on the item type.
            // This sample only provides specific support for a few item types,
            // so we will just hard-code the type checking below.
            ItemModel model    = null;
            string    viewName = string.Empty;

            if (item is CategoryScheme)
            {
                var categoryList = item as CategoryScheme;

                // Create the model and set the item as a property, so it's contents can be displayed
                var categorySchemeModel = new CategorySchemeModel();
                categorySchemeModel.CategoryScheme = categoryList;

                model    = categorySchemeModel;
                viewName = "CategoryList";
            }
            else if (item is StudyUnit)
            {
                var studyUnit = item as StudyUnit;

                // Create the model and set the item as a property, so it's contents can be displayed
                var studyModel = new StudyUnitModel();
                studyModel.StudyUnit = studyUnit;

                foreach (var qualityStatement in studyUnit.QualityStatements)
                {
                    client.PopulateItem(qualityStatement);
                }

                // Use a set search to get a list of all questions that are referenced
                // by the study. A set search will return items that may be several steps
                // away.
                SetSearchFacet setFacet = new SetSearchFacet();
                setFacet.ItemTypes.Add(DdiItemType.QuestionItem);

                var matches = client.SearchTypedSet(studyUnit.CompositeId,
                                                    setFacet);
                var infoList = client.GetRepositoryItemDescriptions(matches.ToIdentifierCollection());

                foreach (var info in infoList)
                {
                    studyModel.Questions.Add(info);
                }

                model    = studyModel;
                viewName = "StudyUnit";
            }
            else if (item is CodeList)
            {
                var codeList = item as CodeList;

                // Create the model and set the item as a property, so it's contents can be displayed
                var codeListModel = new CodeListModel();
                codeListModel.CodeList = codeList;

                model    = codeListModel;
                viewName = "CodeList";
            }
            else if (item is QualityStatement)
            {
                var qualityStatement = item as QualityStatement;

                var qualityStatementModel = new QualityStatementModel(qualityStatement);

                model    = qualityStatementModel;
                viewName = "QualityStatement";
            }
            else
            {
                model    = new ItemModel();
                viewName = "GenericItem";
            }

            // Fopr all item types, get the version history of the item,
            // and add the information to the model.
            var history = client.GetVersionHistory(id, agency);

            foreach (var version in history)
            {
                model.History.Add(version);
            }

            // Use a graph search to find a list of all items that
            // directly reference this item.
            GraphSearchFacet facet = new GraphSearchFacet();

            facet.TargetItem            = item.CompositeId;
            facet.UseDistinctResultItem = true;

            var referencingItemsDescriptions = client.GetRepositoryItemDescriptionsByObject(facet);

            // Add the list of referencing items to the model.
            foreach (var info in referencingItemsDescriptions)
            {
                model.ReferencingItems.Add(info);
            }

            // Return the appropriate view, sending in the model.
            return(View(viewName, model));
        }
 partial void OnConstruction(Operations.OperationsClient grpcClient, OperationsSettings effectiveSettings, ClientHelper clientHelper)
 {
     _clock     = clientHelper.Clock;
     _scheduler = clientHelper.Scheduler;
 }
예제 #29
0
        private static void Run(int timeout)
        {
            _messagesRcvd = new BitArray(_expected, false);
            _received     = 0;
            string pid = Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture);

            ILogCollector  server     = CollectorHelper.CreateCollector();
            string         host       = Dns.GetHostName();
            PropertyFilter hostFilter = new PropertyFilter
            {
                comparison   = ComparisonOperator.eq,
                value        = host,
                propertyName = Property.Host
            };
            FacilityEqualsFilter facFilter = new FacilityEqualsFilter {
                facility = SyslogFacility.Local4
            };
            PropertyFilter pidFilter = new PropertyFilter
            {
                comparison   = ComparisonOperator.eq,
                value        = pid,
                propertyName = Property.ProcessID
            };
            PropertyFilter idFilter = new PropertyFilter
            {
                value        = "BENCH",
                comparison   = ComparisonOperator.eq,
                propertyName = Property.MessageID
            };
            SeverityFilter sevFilter = new SeverityFilter
            {
                comparison = ComparisonOperator.eq,
                severity   = SyslogSeverity.Notice
            };

            using (ILogClient client = ClientHelper.CreateReliableClient(hostFilter & pidFilter & idFilter & sevFilter & facFilter))
            {
                client.MessageReceived += client_MessageReceived;
                client.Start();

                for (int i = 0; i < _expected; i++)
                {
                    if (timeout > 0)
                    {
                        Nanosleep(timeout);
                    }
                    SyslogMessage message = new SyslogMessage
                    {
                        Timestamp = DateTime.Now,
                        Facility  = SyslogFacility.Local4,
                        Severity  = SyslogSeverity.Notice,
                        Host      = host,
                        ProcessID = pid,
                        MessageId = "BENCH",
                        Text      = i.ToString()
                    };

                    server.SubmitMessage(message);
                }
                silenceTimer = new Timer(state => Stop.Set(), null, 40000, Timeout.Infinite);
                Console.WriteLine("Waiting up to 30 seconds after last message received...");
                Stop.WaitOne();
            }

            if (_expected == _received)
            {
                Console.WriteLine("Received all messaged");
            }
            else
            {
                Console.WriteLine("Lost {0} messages", _expected - _received);
            }
        }
예제 #30
0
 private void Given_a_monitor_api_client()
 {
     _client = ClientHelper.Build();
 }
예제 #31
0
        private async Task <TaskStatus> GetTasks()
        {
            using (var client = ClientHelper.GetClient(CrossSettings.Current.GetValueOrDefault("token", "")))
            {
                TaskService.InitializeClient(client);
                var o_data = await TaskService.GetTasks();

                if (o_data.Status == System.Net.HttpStatusCode.OK)
                {
                    //o_data.Message = "Успешно авторизован!";
                    Toast.MakeText(Activity, o_data.Message, ToastLength.Long).Show();
                    StaticDriver.AddInfoDriver(o_data.ResponseData.DRIVER);

                    if (o_data.ResponseData.TASKS.Count == 0)
                    {
                        return(TaskStatus.NotFound);
                    }


                    var firstTask = o_data.ResponseData.TASKS.First();
                    StaticTask.AddInfoTask(firstTask);

                    var boxes_id = o_data.ResponseData.CONTAINERS.Select(s => s.id).ToList();
                    StaticTask.AddContainersID(boxes_id);

                    var way_points = o_data.ResponseData.MAP_WAYPOINTS;
                    StaticTask.AddWayPoints(way_points);

                    List <IViewItemType> tasks = new List <IViewItemType>();
                    tasks.Add(new CurrentTaskModel
                    {
                        Description = StaticTask.title,
                        Order_Id    = StaticTask.order_id
                    });

                    o_data.ResponseData.TASKS.Remove(firstTask);
                    foreach (var task in o_data.ResponseData.TASKS)
                    {
                        tasks.Add(new TaskBookModel
                        {
                            address  = task.address,
                            order_id = task.order_id,
                            priority = task.priority,
                            title    = task.title
                        }
                                  );
                    }
                    //TaskBookModel p2 = new TaskBookModel()
                    //{
                    //    order_id = "OP5887450402",
                    //    priority = "2",
                    //    address = "Славный переулок, 5, Новошахтинск",
                    //    title = "г Ростов-на-Дону, ул Орбитальная, д 76. Доставить пустой контейнер."
                    //};
                    //TaskBookModel p3 = new TaskBookModel()
                    //{
                    //    order_id = "OP5887450402",
                    //    priority = "3",
                    //    address = "Славный переулок, 5, Новошахтинск",
                    //    title = "г Ростов-на-Дону, ул Орбитальная, д 76. Доставить пустой контейнер."
                    //};

                    tasklist = tasks;
                    UpdateList();
                    lstTask.ItemClick += ListOrders_ItemClick;
                    return(TaskStatus.OK);
                }
                else
                {
                    Toast.MakeText(Activity, o_data.Message, ToastLength.Long).Show();//"Unexpected character encountered while parsing value: {. Path 'ORDERS[0].last_stage_at', line 2, position 1086."
                    return(TaskStatus.ServerError);
                }
            }
        }