Example #1
0
        private void GetAllRound(double radius, string categoriesID, MapElement entity, string value)
        {
            ContainerManager.ToastTip.Text     = "正在加载..";
            ContainerManager.ToastTip.IsOpened = true;

            WebAPIHelper dt = new WebAPIHelper();

            dt.GetDataCompleted += (s, args) =>
            {
                List <MapElement> currentList = args.DataResult as List <MapElement>;

                //   listWindow.DataSource = currentList;

                foreach (MapElement obj in currentList)
                {
                    MarkerMapElement element = new MarkerMapElement(obj.ID, obj.MapElementCategoryID, obj.ReservedField1, new Point((double)obj.X, (double)obj.Y), 0, ContainerManager.Map, LayerManager.ElementLayer);
                    element.AddToMap();
                    _currentMarkerMapElementList.Add(element);
                }

                //ContainerManager.Map.Extent = Helper.GpsHelper.MapExtent4Road(currentList);
            };

            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("MapElementCategoryIDArr", categoriesID);
            string url = String.Format(@"api/MapElementCoord/GetNearList?x={0}&y={1}&radius={2}", (double)entity.X, (double)entity.Y, radius);

            dt.GetDataAsync <List <MapElement> >(url, dic);
        }
Example #2
0
        public void BindRadTreeView()
        {
            WebAPIHelper dt1 = new WebAPIHelper();

            dt1.GetDataCompleted += (s, args) =>
            {
                IList <Region> RL  = args.DataResult as IList <Region>;
                List <Region>  pRL = RL.Where(a => a.ParentID == 0 && a.Code != "-100").ToList();
                foreach (var c in pRL)
                {
                    RadTreeViewItem parentitem = new RadTreeViewItem();
                    parentitem.Style  = App.Current.Resources["RadTreeViewItemStyle1"] as Style;
                    parentitem.Header = c.Name;
                    List <Region> cRL = RL.Where(a => a.ParentID == c.ID).ToList();
                    foreach (var child in cRL)
                    {
                        RadTreeViewItem childitem = new RadTreeViewItem();
                        childitem.Style           = App.Current.Resources["RadTreeViewItemStyle1"] as Style;
                        childitem.Header          = child.Name;
                        childitem.DefaultImageSrc = "/Techzen.ICS.CS.Controls;component/Images/sousuo.png";

                        parentitem.Items.Add(childitem);
                    }
                    radTreeView.Items.Add(parentitem);
                }
            };
            string statUrl1 = "/api/Region/Query";

            dt1.GetDataAsync <List <Region> >(statUrl1);
        }
Example #3
0
        private void SearchArtikal_Click(object sender, EventArgs e)
        {
            var sifra  = sifraTextBox.Text;
            var apiUrl = "";

            if (!String.IsNullOrEmpty(sifra))
            {
                apiUrl = "api/ponuda/GetProizvodBySifra/" + sifra;
                WebAPIHelper        getProizvod     = new WebAPIHelper(Resources.apiUrlDevelopment, apiUrl);
                HttpResponseMessage responseMessage = getProizvod.GetResponse();
                if (responseMessage.IsSuccessStatusCode)
                {
                    var content = responseMessage.Content.ReadAsStringAsync().Result;
                    item = JsonConvert.DeserializeObject <PonudaVM.PonudaInfo>(content);
                    if (item.Id.HasValue)
                    {
                        prikaziPronadjenjiProizvod(item);
                    }
                    else
                    {
                        toggleVisibility(false);
                        this.sifraTextBox.Focus();
                        item = null;
                        MessageBox.Show("Nazalost, ne postoji proizvod sa navedenom sifrom");
                    }
                }
            }
        }
Example #4
0
        // POST: api/BusinessDocuments
        public IHttpActionResult Post([FromBody] BusinessDocumentViewModel value)
        {
            string validationError = null;

            if (!ValidateModel(value, out validationError))
            {
                return(BadRequest(validationError));
            }

            using (var clientContext = WebAPIHelper.GetClientContext(this.ControllerContext))
            {
                // Get the documents from the Business Documents library
                List businessDocsLib = clientContext.Web.GetListByUrl("/BusinessDocs");
                // Ensure the root folder is loaded
                Folder   rootFolder = businessDocsLib.EnsureProperty(l => l.RootFolder);
                ListItem newItem    = businessDocsLib.CreateDocument(value.Name, rootFolder, DocumentTemplateType.Word);

                // Update the new document metadata
                newItem[DocumentPurposeField] = value.Purpose;
                newItem[InChargeField]        = FieldUserValue.FromUser(value.InCharge);
                newItem.Update();

                // Ensure the needed metadata are loaded
                clientContext.Load(newItem, item => item.Id,
                                   item => item[FileLeafRefField],
                                   item => item[InChargeField],
                                   item => item[DocumentPurposeField]);

                newItem.File.CheckIn("", CheckinType.MajorCheckIn);
                clientContext.ExecuteQuery();

                BusinessDocumentViewModel viewModel = ListItemToViewModel(newItem);
                return(Created($"/api/BusinessDocuments/{viewModel.Id}", viewModel));
            }
        }
        /// <summary>
        /// 请求云通信接口
        /// 作者:郭明
        /// 日期:2016年8月20日
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        string Post(dynamic obj, string method, Func <int, bool> match = null, string url = "https://console.tim.qq.com/v4/")
        {
            var requestParamters = JsonHelper.ToJson(obj);
            var requestBeginTime = DateTime.Now;
            var response         = "";

            try
            {
                var userSig = Tencent.TSLHelper.GetSig(uint.Parse(Configuration.IMConfig.sdkAppID), Configuration.IMConfig.adminAccount, uint.Parse(Configuration.IMConfig.accountType));
                int random  = GlobalRandom;

                url = string.Format(url + "/{4}?usersig={0}&identifier={1}&sdkappid={2}&random={3}&contenttype=json", userSig, Configuration.IMConfig.adminAccount, Configuration.IMConfig.sdkAppID, random, method);

                //请求腾讯云接口
                return(WebAPIHelper.HttpPost(url, requestParamters));
            }
            catch (Exception E)
            {
                LogHelper.DefaultLogger.Error(E.Message, E);
                throw E;
            }
            finally
            {
                //WriteTrackLog(url, method, requestParamters, requestBeginTime, response);
            }

            return("");
        }
Example #6
0
        public async Task <string> ChageToUser(IFormCollection formData)
        {
            // Claimを取得する。
            MyBaseAsyncApiController.GetClaims(
                out string userName, out string roles, out string scopes, out string ipAddress);

            // ユーザの検索
            ApplicationUser user = await UserManager.FindByNameAsync(userName);

            if (user != null)
            {
                // 変数
                string currency = formData["currency"];
                string amount   = formData["amount"];

                if (Config.CanEditPayment &&
                    Config.EnableEditingOfUserAttribute)
                {
                    // 課金の処理
                    JObject jobj = await WebAPIHelper.GetInstance()
                                   .ChargeToOnlinePaymentCustomersAsync(user.PaymentInformation, currency, amount);

                    return("OK");
                }
            }

            return("NG");
        }
        public ActionResult Index()
        {
            User spUser = null;

            var accessTokenInfo = WebAPIHelper.GetAccessTokenInfo(Request);


            using (var clientContext = accessTokenInfo.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    spUser = clientContext.Web.CurrentUser;

                    clientContext.Load(spUser, user => user.Title);

                    clientContext.ExecuteQuery();

                    ViewBag.UserName = spUser.Title;
                }
            }
            HttpCookie cookie = new HttpCookie("CacheKey", accessTokenInfo.CacheKey);

            Response.SetCookie(cookie);
            return(View());
        }
Example #8
0
        /// <summary>
        /// 极速达取消订单
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task <ResultData <string> > CancelOrder(HttpCancelOrderParameter param)
        {
            Dictionary <string, string> dirList = new Dictionary <string, string>();

            dirList.Add("OrderCode", param.OrderCode);
            dirList.Add("cancelBy", param.cancelBy);

            dirList.Add("app_id", "jsd");
            dirList.Add("timestamp", StaticFunction.GetTimestamp(0).ToString() + "000");
            dirList.Add("ecOrderNumber", param.OrderCode);
            var str  = StaticFunction.GetEcoParamSrc(dirList);
            var sign = MD5Utils.MD5Encrypt(eco_app_token + str + eco_app_token).ToUpper();


            dirList.Add("sign", sign);

            var returnStr = await WebAPIHelper.HttpPostAsync(ECOUrl + "/api/order/cancelOrder", JsonConvert.SerializeObject(dirList));

            var result = JsonConvert.DeserializeObject <HttpCancelOrderResult>(returnStr);

            if (result.success)
            {
                this._logger.LogInformation("订单号为:" + param.OrderCode + "取消成功");
                return(ResultData <string> .CreateResultDataSuccess("成功"));
            }
            this._logger.LogWarning("订单号为:" + param.OrderCode + "取消失败,原因:" + (result.errorMsg ?? "调用极速达取消接口失败"));
            return(ResultData <string> .CreateResultDataFail(result.errorMsg ?? "调用极速达取消接口失败"));
        }
Example #9
0
        private void btnSignin_Click(object sender, EventArgs e)
        {
            Service = new WebAPIHelper("http://localhost:61732/", "api/Employees");

            HttpResponseMessage Response = Service.GetResponse(txtUsername.Text);

            if (Response.IsSuccessStatusCode)
            {
                dynamic Emp = Response.Content.ReadAsAsync <Object>().Result;

                if (Emp.PasswordHash == UIHelper.GenerateHash(txtPassword.Text, Emp.PasswordSalt))
                {
                    MessageBox.Show("Welcome " + Emp.FirstName + " " + Emp.LastName + "!");
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("Username or password is incorrect!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("Error status code: " + Response.StatusCode + " Message: " + Response.ReasonPhrase);
            }
        }
Example #10
0
        private async Task <bool> OcjeniProizvod()
        {
            var ocjenaVM = new OcjeneVM();

            ocjenaVM.Ocjena     = (int)ocjenaSlider.Value;
            ocjenaVM.ProizvodId = Convert.ToInt32(proizvodId.Text);
            ocjenaVM.KupacId    = Convert.ToInt32(ApplicationProperties.KorisnikId);
            if (IsJelo.Text == "Jela")
            {
                ocjenaVM.IsJelo = 1;
            }
            else
            {
                ocjenaVM.IsJelo = 0;
            }

            var ocjeniService = new WebAPIHelper("api/Proizvodi/OcjeniProizvod");
            var response      = await ocjeniService.PostResponse(ocjenaVM);

            if (response.IsSuccessStatusCode)
            {
                await this.DisplayAlert("Uspjesno", "Uspjesno ocnjenjen proizvod. Vasa ocjena je " + ocjenaVM.Ocjena, "U redu");

                btnOcjeni.IsVisible    = false;
                ocjenaSlider.IsVisible = false;
                return(true);
            }
            else
            {
                await this.DisplayAlert("Neuspjesno", "Neuspjesno ocnjenjen proizvod", "U redu");

                return(false);
            }
        }
Example #11
0
        private void GetAllPersons(string value)
        {
            ContainerManager.ToastTip.Text     = "正在加载..";
            ContainerManager.ToastTip.IsOpened = true;

            WebAPIHelper dt = new WebAPIHelper();

            dt.GetDataCompleted += (s, args) =>
            {
                List <MapElement> _currentList  = args.DataResult as List <MapElement>;
                List <MapElement> _positionList = _currentList.Where(m => m.X != null).ToList();
                //var list = _positionList.Where(m => m.MapElementCategoryID == _mapElementCategoryID).Distinct(new SchoolComparer()).ToList();
                //List<Image> img = getImage(_mapElementCategoryID);
                Dictionary <int, Image> imglist = GetIconUrl(_mapElementCategoryID);
                foreach (MapElement obj in _positionList)
                {
                    if (obj.X == null)
                    {
                        continue;
                    }
                    //MarkerMapElement element = new MarkerMapElement(obj, 0, ContainerManager.Map, LayerManager.ElementLayer);
                    MarkerMapElement element = new MarkerMapElement(obj, 0, ContainerManager.Map, LayerManager.ElementLayer, imglist);
                    element.AddToMap();
                    _currentMapElementList.Add(element);
                }

                //ContainerManager.Map.Extent = GpsHelper.MapExtent4Road(_currentList);
            };

            _results["ReservedField1"] = value;
            string url = "api/MapElement/Query";

            dt.GetDataAsync <List <MapElement> >(url, _results);
        }
Example #12
0
        public IEnumerable <Item> GetItems()
        {
            using (var clientContext = WebAPIHelper.GetClientContext(ControllerContext))
            {
                if (clientContext != null)
                {
                    List      demoList  = clientContext.Web.Lists.GetByTitle("WebAPIDemo");
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = "<View><Query></Query></View>";
                    ListItemCollection demoItems = demoList.GetItems(camlQuery);
                    clientContext.Load(demoItems);
                    clientContext.ExecuteQuery();

                    Item[] items = new Item[demoItems.Count];

                    int i = 0;
                    foreach (ListItem item in demoItems)
                    {
                        items[i] = new Item()
                        {
                            Id = item.Id, Title = item["Title"].ToString()
                        };
                        i++;
                    }

                    return(items);
                }
                else
                {
                    return(new Item[0]);
                }
            }
        }
Example #13
0
        public static List <DoubanHouseInfo> GetDataFromAPI(string groupID, string cityName, int pageIndex)
        {
            List <DoubanHouseInfo> lstHouseInfo = new List <DoubanHouseInfo>();
            var apiURL      = $"https://api.douban.com/v2/group/{groupID}/topics?start={pageIndex * 50}";
            var doubanTopic = WebAPIHelper.GetAPIResult <DoubanTopic>(apiURL);

            if (doubanTopic != null && doubanTopic.topics != null)
            {
                foreach (var topic in doubanTopic.topics)
                {
                    if (DataContent.DoubanHouseInfos.Any(h => h.HouseOnlineURL == topic.share_url))
                    {
                        continue;
                    }
                    var housePrice = JiebaTools.GetHousePrice(topic.content);
                    var house      = new DoubanHouseInfo()
                    {
                        HouseLocation    = topic.title,
                        HouseTitle       = topic.title,
                        HouseOnlineURL   = topic.share_url,
                        HouseText        = topic.content,
                        HousePrice       = JiebaTools.GetHousePrice(topic.content),
                        IsAnalyzed       = true,
                        DisPlayPrice     = housePrice > 0 ? $"{housePrice}元" : "",
                        Source           = ConstConfigurationName.Douban,
                        LocationCityName = cityName,
                        Status           = 1,
                        PubTime          = DateTime.Parse(topic.created),
                        DataCreateTime   = DateTime.Now,
                    };
                    lstHouseInfo.Add(house);
                }
            }
            return(lstHouseInfo);
        }
Example #14
0
 public static void Main(string[] args)
 {
     //mongo
     try
     {
         Log.WriteLine("1.正在连接DB!", ConsoleColor.Yellow);
         Log.WriteLine("---->DB启动成功! [1/5]", ConsoleColor.Green);
     }
     catch (Exception e)
     {
         Log.WriteLine("\n 数据库连接失败! \n" + e.ToString(), ConsoleColor.Red);
     }
     //web
     try
     {
         Log.WriteLine("2.启动Web服务器", ConsoleColor.Yellow);
         WebAPIHelper.StartWebService();
         Log.WriteLine("---->web服务器启动成功! [2/5]", ConsoleColor.Green);
     }
     catch (Exception e)
     {
         Log.WriteLine("web服务器启动失败! \n" + e.ToString(), ConsoleColor.Red);
     }
     //Test
     try
     {
         Log.WriteLine("3.测试服务可用性", ConsoleColor.Yellow);
         Log.WriteLine("---->测试服务可用性成功! [2/5]", ConsoleColor.Green);
     }
     catch (Exception e)
     {
         Log.WriteLine("测试服务可用性失败! \n" + e.ToString(), ConsoleColor.Red);
     }
 }
Example #15
0
        public void DrowGraphical(string url)
        {
            WebAPIHelper  dt       = new WebAPIHelper();
            GraphicsLayer Cityrode = map.Layers["GraphicsLayerCq"] as GraphicsLayer;

            dt.GetDataCompleted += (s, args) =>
            {
                List <MapGraphical> list = args.DataResult as List <MapGraphical>;
                foreach (var model in list)
                {
                    SimpleFillSymbol style        = new SimpleFillSymbol();
                    string[]         str          = model.colour.Split(',');
                    List <MapPoint>  MapPointList = new List <MapPoint>();
                    foreach (var po in model.MapPointList)
                    {
                        MapPointList.Add(new MapPoint {
                            X = po.X, Y = po.Y
                        });
                    }
                    //Color ColorFill = ConvertToHtml(model.colour);
                    Graphic graphic = new Graphic();
                    style.Fill = new SolidColorBrush(Color.FromArgb(0x7f, Convert.ToByte(str[0]), Convert.ToByte(str[1]), Convert.ToByte(str[2])));
                    ESRI.ArcGIS.Client.Geometry.PointCollection pCollection = new ESRI.ArcGIS.Client.Geometry.PointCollection(MapPointList);
                    ESRI.ArcGIS.Client.Geometry.Polygon         g           = new ESRI.ArcGIS.Client.Geometry.Polygon();
                    g.Rings.Add(pCollection);
                    graphic.Geometry = g;
                    graphic.Symbol   = style;
                    //ESRI.ArcGIS.Client.Geometry.Polygon polygon = (ESRI.ArcGIS.Client.Geometry.Polygon)graphic.Geometry;
                    //GraphicsLayerCq
                    Cityrode.Graphics.Add(graphic);
                }
            };
            dt.GetDataAsync <List <MapGraphical> >(url);
        }
Example #16
0
        public IActionResult Index()
        {
            this._logger.LogWarning("first Run!");
            using (ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri("http://localhost:8500/");
                c.Datacenter = "dc1";
            }))
            {
                var dictionary = client.Agent.Services().Result.Response;
                foreach (var keyValuePair in dictionary)
                {
                    AgentService agentService = keyValuePair.Value;
                    this._logger.LogWarning($"{agentService.Address}:{agentService.Port} {agentService.ID} {agentService.Service}");
                }
            }
//            base.ViewBag.Students = new List<string>()
//            {
//                "AAA", "BBB", "CCC"
//            };
            string url = "http://localhost:22221/api/students";
//            string url = "http://localhost:22221/api/students";
//            string url = "http://localhost:22221/api/students";
            string content = WebAPIHelper.InvokeAPI(url);

            base.ViewBag.Students = Newtonsoft.Json.JsonConvert.DeserializeObject <List <string> >(content);
            return(View());
        }
Example #17
0
        private async Task <bool> RegisterUser()
        {
            var kor = new KlijentVM()

            {
                Adresa       = adresa.Text,
                Email        = email.Text,
                Ime          = ime.Text,
                Prezime      = prezime.Text,
                Username     = userName.Text,
                Password     = password.Text,
                TipKorisnika = (int)TipKorisnikaVM.Klijent,
                Telefon      = telefon.Text,
                DatumPrijave = DateTime.Now
            };

            var registerService = new WebAPIHelper("api/Nalog/PostKlijent");

            var response = await registerService.PostResponse(kor);

            if (response.IsSuccessStatusCode)
            {
                return(true);
            }
            return(false);
        }
Example #18
0
        // PUT: api/BusinessDocuments/5
        public IHttpActionResult Put(int id, [FromBody] BusinessDocumentViewModel value)
        {
            string validationError = null;

            if (!ValidateModel(value, out validationError))
            {
                return(BadRequest(validationError));
            }

            using (var clientContext = WebAPIHelper.GetClientContext(this.ControllerContext))
            {
                // Get the documents from the Business Documents library
                List     businessDocsLib = clientContext.Web.GetListByUrl("/BusinessDocs");
                ListItem businessDocItem = TryGetListItemById(businessDocsLib, id);

                // If not found, return the appropriate status code
                if (businessDocItem == null)
                {
                    return(NotFound());
                }

                // Update the list item properties
                MapToListItem(value, businessDocItem);
                businessDocItem.Update();
                clientContext.ExecuteQuery();

                return(Ok());
            }
        }
Example #19
0
        public static ApiResult <T> Post <T>(string path, string param)
        {
            var requestTime = DateTime.Now;
            var response    = "";

            try
            {
                response = WebAPIHelper.HttpPost(path, param);
                return(JsonDeserialize <ApiResult <T> >(response));
            }
            catch (Exception ex)
            {
                response = JsonSerialize(ex.GetDetailException());

                return(new ApiResult <T>()
                {
                    resultCode = 1,
                    resultData = default(T),
                    msg = ex.Message
                });
            }
            finally
            {
                WriteTrackLog(path, "", param, requestTime, response);
            }
        }
Example #20
0
        private async Task <bool> postPromotion()
        {
            var promocijeService = new WebAPIHelper(Resources.apiUrlDevelopment, "api/promocija/promovisi");

            if (item.Id != 0 && double.TryParse(promocijeCijenaTextBox.Text, out double novaCijena))
            {
                var promocija = new PromocijaVM()
                {
                    DatumOd          = DateTime.SpecifyKind(datumOdDate.Value, DateTimeKind.Utc),
                    DatumDo          = DateTime.SpecifyKind(datumDoDate.Value, DateTimeKind.Utc),
                    PromotivnaCijena = novaCijena,
                    StaraCijena      = item.Cijena
                };

                if (item.IsJelo)
                {
                    promocija.JeloId = item.Id;
                }
                else
                {
                    promocija.ProizvodId = item.Id;
                }

                var response = promocijeService.PostResponse(promocija);
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("Proizvod je promovisan");
                    return(true);
                }
            }
            MessageBox.Show("Nazalost, nismo uspjelo promovisat proizvod.");;

            return(false);
        }
Example #21
0
        // GET: api/BusinessDocuments/5
        public IHttpActionResult Get(int id)
        {
            using (var clientContext = WebAPIHelper.GetClientContext(this.ControllerContext))
            {
                // Get the documents from the Business Documents library
                List     businessDocsLib = clientContext.Web.GetListByUrl("/BusinessDocs");
                ListItem businessDocItem = TryGetListItemById(businessDocsLib, id);
                if (businessDocItem == null)
                {
                    return(NotFound());
                }

                // Ensure the needed metadata are loaded
                clientContext.Load(businessDocItem, item => item.Id,
                                   item => item[FileLeafRefField],
                                   item => item[InChargeField],
                                   item => item[DocumentPurposeField]);
                clientContext.ExecuteQuery();

                // Create a view model object from the list item
                BusinessDocumentViewModel viewModel = ListItemToViewModel(businessDocItem);

                return(Ok(viewModel));
            }
        }
Example #22
0
        public IEnumerable <BusinessDocumentViewModel> MyBusinessDocuments()
        {
            using (var clientContext = WebAPIHelper.GetClientContext(this.ControllerContext))
            {
                // Get the documents from the Business Documents library
                List businessDocsLib = clientContext.Web.GetListByUrl("/BusinessDocs");
                var  camlQuery       = new CamlQuery
                {
                    ViewXml = $@"<View><Query><Where>
    <Eq>
        <FieldRef Name='{InChargeField}' LookupId='TRUE' />
        <Value Type = 'Integer'><UserID /></Value>
     </Eq>
 </Where></Query></View>"
                };
                ListItemCollection businessDocItems = businessDocsLib.GetItems(camlQuery);

                clientContext.Load(businessDocItems, items => items.Include(
                                       item => item.Id,
                                       item => item[FileLeafRefField],
                                       item => item[InChargeField],
                                       item => item[DocumentPurposeField]));
                clientContext.ExecuteQuery();

                // Create collection of view models from list item collection
                List <BusinessDocumentViewModel> viewModels = businessDocItems.Select(ListItemToViewModel).ToList();

                return(viewModels);
            }
        }
Example #23
0
        /// <summary>
        /// //Metodo che chiama la web api per inviare gli eventi. I due parametri verrano usati per creare I due eventi
        /// </summary>
        /// <param name="summaryModel"></param>
        /// <param name="streamModel"></param>
        /// <returns></returns>


        private bool CallWebApi(PECMailErrorSummaryModel summaryModel, PECMailErrorStreamModel streamModel)
        {
            try
            {
                EventErrorStreamPECMail eventStream = new EventErrorStreamPECMail(streamModel.CorrelatedId,
                                                                                  DocSuiteContext.Current.CurrentTenant.TenantName, DocSuiteContext.Current.CurrentTenant.TenantId,
                                                                                  new IdentityContext(DocSuiteContext.Current.User.FullUserName), streamModel);

                EventErrorSummaryPECMail eventSummary = new EventErrorSummaryPECMail(streamModel.CorrelatedId,
                                                                                     DocSuiteContext.Current.CurrentTenant.TenantName, DocSuiteContext.Current.CurrentTenant.TenantId,
                                                                                     new IdentityContext(DocSuiteContext.Current.User.FullUserName), summaryModel);

                var webApiHelper = new WebAPIHelper();

                #region Spedizione Evento summary alle web api

                FileLogger.Info(_moduleName, "Spedizione dell\'evento summary alle WebAPI");
                bool sended = webApiHelper.SendRequest(DocSuiteContext.Current.CurrentTenant.WebApiClientConfig, DocSuiteContext.Current.CurrentTenant.WebApiClientConfig, eventSummary, string.Empty);
                if (!sended)
                {
                    FileLogger.Warn(_moduleName, "La fase di invio dell\'evento alle Web API non è avvenuta correttamente. Vedere log specifico per maggiori dettagli");
                    FileLogger.Info(_moduleName, "E' avvenuto un errore durante la fase di invio dell'evento EventErrorSummaryPecMail alle WebAPI");
                }
                FileLogger.Info(_moduleName, "Spedizione dell\'evento EventErrorSummaryPecMail alle WebAPI avvenuto correttamente");

                #region old (working) implementation
                //using (HttpClient _client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
                //{
                //    var content = new ObjectContent<EventErrorSummaryPECMail>(eventSummary, new JsonMediaTypeFormatter()
                //    {
                //        SerializerSettings = DocSuiteContext.DefaultWebAPIJsonSerializerSettings
                //    });
                //    var httpResponseMessage = _client.PostAsync("http://10.11.1.65:90/DSW.WebAPI/api/sb/Topic", content).Result;
                //};
                #endregion

                #endregion

                #region Spedizione Evento stream alle web api

                FileLogger.Info(_moduleName, "Spedizione dell\'evento stream alle WebAPI");
                sended = webApiHelper.SendRequest(DocSuiteContext.Current.CurrentTenant.WebApiClientConfig, DocSuiteContext.Current.CurrentTenant.WebApiClientConfig, eventStream, string.Empty);
                if (!sended)
                {
                    FileLogger.Warn(_moduleName, "La fase di invio dell\'evento alle Web API non è avvenuta correttamente. Vedere log specifico per maggiori dettagli");
                    FileLogger.Info(_moduleName, "E' avvenuto un errore durante la fase di invio dell'evento EventErrorStreamPecMail alle WebAPI");
                }
                FileLogger.Info(_moduleName, "Spedizione dell\'evento EventErrorStreamPecMail alle WebAPI avvenuto correttamente");

                #endregion

                return(true);
            }
            catch (Exception e)
            {
                FileLogger.Error(_moduleName, $"Error occured: " + e.Message);
                return(false);
            }
        }
        public MoneyTransferBl(Wallet wallet, TransactionClient trClient)
        {
            _wallet   = wallet;
            _trClient = trClient;

            _bitcoinConverter = new WebAPIHelper();
            _bitcoinConverter.Run(APIUrls.BitcoinRateAPIUrl);
        }
Example #25
0
        public async Task <RootObject> GetWeatherDataUsingCityId(UInt16 cityId)
        {
            Dictionary <string, string> parameter = new Dictionary <string, string>();

            parameter.Add("id", Convert.ToString(cityId));
            RootObject data = await WebAPIHelper.GetAsync <RootObject>(string.Empty, parameter);

            return(data);
        }
Example #26
0
        private async Task <List <int> > GetRecommendedMovies(int userID)
        {
            var service  = new WebAPIHelper(Domains.APIDomain, "api/RecommendationSystem");
            var response = service.GetResponse("GetRecommendedMovies", userID);

            var result = JsonConvert.DeserializeObject <Dictionary <int, float> > (await response.Content.ReadAsStringAsync());

            return(result.Keys.ToList());
        }
Example #27
0
        public void LoadProxyIPInfo()
        {
            var avAPIData = WebAPIHelper.GetAPIResult <AVAPIResult>(ConfigInfo.AVAPIURL
                                                                    + $"?usedSign=&checkUrl={CheckURL}&domain={CheckDomain}&num={APIQueryPageCount}");

            if (avAPIData != null && avAPIData.data != null && avAPIData.data.data != null)
            {
                Console.WriteLine("" + avAPIData.data.data.Count);
            }
        }
Example #28
0
        public void SendMail(MailInfo mailInfo)
        {
            var helper = new WebAPIHelper();
            var result = helper.Post <Stream>("SendMail", mailInfo);

            if (result != null)
            {
                result.Dispose();
            }
        }
Example #29
0
        private ApiResponse <TokenResultApiRequest> VerifyTokenByTokenSystem(string api_key, string token)
        {
            Dictionary <string, string> headerData = new Dictionary <string, string>();

            headerData.Add("api_key", api_key);
            headerData.Add("Token", token);
            string responseString = WebAPIHelper.SendRequestWithHeader(tokenConfig.VerifyTokenSystemURL, RequestMethod.POST, headerData);
            ApiResponse <TokenResultApiRequest> responseObj = JsonConvert.DeserializeObject <ApiResponse <TokenResultApiRequest> >(responseString);

            return(responseObj);
        }
Example #30
0
        private void _tzPlayback_Playing(object sender, EventArgs e)
        {
            if (this._tzPlayback.IsPaused)
            {
                this._tzPlayback.Play(this._gpsPointList);
            }
            else
            {
                this.rbiLoad.IsBusy        = true;
                this._tzPlayback.IsEnabled = false;

                WebAPIHelper dt = new WebAPIHelper();

                dt.GetDataCompleted += (s, args) =>
                {
                    this.rbiLoad.IsBusy        = false;
                    this._tzPlayback.IsEnabled = true;

                    List <GPSPoint> list = args.DataResult as List <GPSPoint>;

                    //if (list == null || list.Count == 0)
                    //{
                    //    this.toastTip.Text = "暂无定位数据";
                    //    this.toastTip.IsOpened = true;
                    //    return;
                    //}

                    this._gpsPointList = list;//list.Where(t => t.Longitude != null && t.Latitude != null && t.X != null & t.Y != null)
                    //.Select(t => new GPSPoint()
                    //{
                    //    Longitude = (double)t.Latitude,
                    //    Latitude = (double)t.Latitude,
                    //    X = (double)t.X,
                    //    Y = (double)t.Y,
                    //    Speed = t.Speed == null ? 0 : (int)t.Speed,
                    //    StartTime = t.SatelliteTime,
                    //    EndTime = t.SatelliteTime
                    //}).ToList();

                    //double x1 = (double)list.Min(m => m.X);
                    //double y1 = (double)list.Min(m => m.Y);
                    //double x2 = (double)list.Max(m => m.X);
                    //double y2 = (double)list.Max(m => m.Y);
                    //new ESRI.ArcGIS.Client.Geometry.Envelope(x1, y1, x2, y2);

                    this._tzPlayback.Play(this._gpsPointList);
                };
                string url = string.Format(_url, Convert.ToDateTime(_tzPlayback.StartTime).ToString("yyyy-MM-dd HH:mm:ss"), Convert.ToDateTime(_tzPlayback.EndTime).ToString("yyyy-MM-dd HH:mm:ss"));
                dt.GetDataAsync <List <GPSPoint> >(url);
            }

            //this._tzPlayback.Play(GetTestGPSPoints());
        }