예제 #1
0
        private string APIDataExcute(APIModel modelObj)
        {
            switch (modelObj.APIAction)
            {
            case APIEnum.weather:
                return(new WeatherAPI().GetWeatherAlarm(modelObj.KeyTargetWords));

            case APIEnum.filesManage:
                var    bingApi = new BingAPI();
                string res     = string.Empty;
                if (modelObj.KeyActionWords.IndexOf("下载BING图片") != -1)
                {
                    res = bingApi.DownTodayBg();
                }
                if (modelObj.KeyActionWords.IndexOf("BING背景") != -1)
                {
                    res = bingApi.GetTodayBg();
                }

                return(res);

            default:
                break;
            }
            return("");
        }
예제 #2
0
 public InreachIPCException(string message, APIModel model, Services services)
     : base($"{{Message=\"{message}\"," +
            $"{(model.Response != null ? $"Code={Enum.GetName(typeof(HttpStatusCode), model.Response.StatusCode)}, Response={model.Response.Content.ReadAsStringAsync().Result}, " : string.Empty)}" +
            $"Model={model}, " +
            $"ServicesEndpoint={Enum.GetName(typeof(Config.RegionalEndpoints), services._config.APIEndpoint)}}}")
 {
 }
예제 #3
0
        public void TestExportClassWithFirstClassAttribute()
        {
            EAMetaModel meta = new EAMetaModel();

            APIModel.createAPI_AttributesFirstClass(meta);
            meta.setupSchemaPackage();

            //Test
            JSchema jschema = SchemaManager.schemaToJsonSchema(EARepository.Repository, EARepository.currentDiagram).Value;

            {
                JSchema child = jschema.Properties["propClass"];
                Assert.AreEqual(JSchemaType.String, child.Type);
            }
            {
                JSchema child = jschema.Properties["propertyClass2"];
                Assert.AreEqual(JSchemaType.String, child.Type);
            }


            EA.Package package = SchemaManager.generateSample(EARepository.Repository);
            object     o       = package.Diagrams.GetAt(0);

            EA.Diagram diaObj = (EA.Diagram)o;

            IList <EA.Element> objects = MetaDataManager.diagramSamples(EARepository.Repository, diaObj);

            Assert.AreEqual(1 + 1, objects.Count);
        }
        public async Task <IActionResult> AddAPI([FromBody] APIAddRequest request)
        {
            APIModel apiModel = new APIModel()
            {
                name       = request.name,
                url        = request.url,
                sampleCall = request.sampleCall,
                desc       = request.desc,
                price      = request.price,
            };

            try
            {
                await _dbContext.ApiModels.AddAsync(apiModel);

                await _dbContext.SaveChangesAsync();

                return(Ok(new ResponseDTO()
                {
                    Success = true
                }));
            }
            catch (DbUpdateException e)
            {
                Console.Write(e.Message);
                return(BadRequest(new ResponseDTO()
                {
                    Success = false,
                    Errors = new List <string> {
                        "Cannot Add API to Database",
                        e.Message
                    }
                }));
            }
        }
예제 #5
0
        public void TestInvalidSchema()
        {
            EAMetaModel meta = new EAMetaModel();

            APIModel.createInvalidAPI(meta);
            meta.setupSchemaPackage();

            FileManager fileManager = new FileManager(null);

            SchemaManager.setFileManager(fileManager);

            string theexception = "An exception should be thrown";

            try
            {
                JSchema jschema = SchemaManager.schemaToJsonSchema(EARepository.Repository, EARepository.currentDiagram).Value;
                Assert.Fail(theexception);
            }
            catch (ModelValidationException e)
            {
                string r = "";
                foreach (string s in e.errors.messages)
                {
                    r += s;
                }
                Assert.AreNotEqual("Assert.Fail failed. " + theexception, r);

                Assert.IsTrue(r.Contains("Class Name needs to start with an uppercase character"));

                Assert.IsTrue(r.Contains("Connector with empty SupplierEnd.Role is not allowed"));

                Assert.IsTrue(r.Contains("Connector with no SupplierEnd.Role cardinality is not allowed"));
            }
        }
예제 #6
0
        public async void Start()
        {
            APIModel reqModel = new APIModel
            {
                User                 = patientModel.User,
                Forename             = patientModel.Forename,
                Surname              = patientModel.Surname,
                DateOfBirth          = patientModel.DateOfBirth,
                PrimaryContactNumber = patientModel.Phone,
                PrimaryAddressLine1  = patientModel.AddrLine1,
                PrimaryAddressLine2  = patientModel.AddrLine2,
                PrimaryAddressLine3  = patientModel.AddrLine3,
                PostCode             = patientModel.Postcode
            };

            var requestJSON = JsonConvert.SerializeObject(reqModel, Formatting.Indented);
            var start       = DateTime.Now;
            var response    = await httpClient.PostAsync(clientUrl, new StringContent(requestJSON, Encoding.UTF8, "application/json"));

            //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, clientUrl);
            //var response = await httpClient.SendAsync(request);
            string responseBody = await response.Content.ReadAsStringAsync();

            TimeSpan timeDiff = DateTime.Now - start;

            Response = string.Format("Elapsed={0}mS Status = {1} - {2}", timeDiff.TotalMilliseconds, response.StatusCode, responseBody);
        }
예제 #7
0
        public void MultipleLevelsOfResources()
        {
            EAMetaModel meta = new EAMetaModel();

            meta.setupAPIPackage();
            EAFactory api = APIModel.createMOM(meta);

            YamlMappingNode map = new YamlMappingNode();

            //Test
            APIManager.reifyAPI(EARepository.Repository, api.clientElement, map);

            YamlScalarNode mom = new YamlScalarNode();
            YamlNode       momValue;

            mom.Value = "/mom";
            Assert.IsTrue(map.Children.TryGetValue(mom, out momValue));


            YamlMappingNode resourceProps = (YamlMappingNode)momValue;
            YamlScalarNode  ev            = new YamlScalarNode();
            YamlNode        eventValue;

            ev.Value = "/event";
            Assert.IsTrue(resourceProps.Children.TryGetValue(ev, out eventValue));
        }
예제 #8
0
        public static async Task <APIModel> LoadData(int DataNumber = 0)
        {
            string url = "";

            if (DataNumber > 0)
            {
                url = $"https://xkcd.com/{DataNumber}/info.0.json";
            }
            else
            {
                url = $"https://xkcd.com/info.0.json";
            }

            using (HttpResponseMessage response = await APIHelper.ApiClient.GetAsync(url))
            {
                if (response.IsSuccessStatusCode)
                {
                    APIModel comic = await response.Content.ReadAsAsync <APIModel>();

                    return(comic);
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }
예제 #9
0
        public bool Farmacia(farmaciasAPI farmaciass, string tipo)
        {
            switch (tipo)
            {
            case "insert":
                api = new APIModel();

                farmaciasAPI far;
                far = (farmaciasAPI)farmaciass;

                bool     v              = false;
                string[] listado        = new string[1000];
                string[] insert         = new string[10000];
                int      incrementable  = 0;
                int      incrementable1 = 0;

                for (int i = 0; i < far.result.records.Count(); i++)
                {
                    bool f = api.farmacia_get(far.result.records[i]._id);    // Valida si existe el registro anteriormente

                    if (!f)
                    {
                        v = api.farmacia_insert(far.result.records[i]._id, far.result.records[i].local_nombre, far.result.records[i].local_lat, far.result.records[i].local_lng, far.result.records[i].fk_localidad);
                        if (!v)
                        {
                            listado[incrementable] = far.result.records[i]._id.ToString();    //Registeo de las farmacias no creadas.
                            incrementable++;
                        }
                        else
                        {
                            insert[incrementable1] = far.result.records[i]._id.ToString();    //Registeo de las farmacias creadas.
                            incrementable1++;
                        }
                    }
                }

                if (incrementable1 > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }

                //return v;

                break;

            default:
                string[] listado1 = new string[1000];

                return(false);

                break;
            }
        }
예제 #10
0
파일: TaxJar.cs 프로젝트: SwiftDerek/imc_di
        public async Task <double> GetRate(APIModel aPIModel)
        {
            // TODO: Use generic parameter i.e. ReqRates not APIModel

            string endpoint = "rates";

            ResRates response = await URL.AppendPathSegment(endpoint).SetQueryParams(aPIModel).WithOAuthBearerToken(ApiKey).GetJsonAsync <ResRates>();

            return(response.Rate.CombinedRate);
        }
        public APIResultModel Post([FromBody] APIModel apiModel)
        {
            var result = new APIResultModel();

            apiModel.Id = _apiModel.Count() == 0 ? 1 : _apiModel.Max(c => c.Id) + 1;
            _apiModel.Add(apiModel);
            result.Data      = apiModel.Id;
            result.IsSuccess = true;
            return(result);
        }
예제 #12
0
파일: TaxJar.cs 프로젝트: SwiftDerek/imc_di
        public async Task <double> GetTaxableAmount(APIModel aPIModel)
        {
            // TODO: Use generic parameter i.e. ReqTaxes not APIModel

            string endpoint = "taxes";

            ResTaxes response = await URL.AppendPathSegment(endpoint).WithOAuthBearerToken(ApiKey).PostJsonAsync(aPIModel).ReceiveJson <ResTaxes>();

            return(response.Tax.AmountToCollect);
        }
예제 #13
0
        public IActionResult API()
        {
            var jake = new APIModel {
                Name          = "Jake",
                FavoriteColor = "Black",
                FavoriteFood  = "Pizza"
            };

            return(Json(jake));
        }
예제 #14
0
        /// <summary>
        /// Lưu thông tin API
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public void SaveInfoAPI(APIModel model)
        {
            bool IsUpdate = model.IsUpdate;

            try
            {
                using (SqliteConnection db = new SqliteConnection(Constants.PathDatabase))
                {
                    db.Open();
                    using (SqliteCommand sqlCommand = new SqliteCommand())
                    {
                        sqlCommand.Connection = db;
                        if (IsUpdate)
                        {
                            sqlCommand.CommandText = "UPDATE ConfigServer SET ServiceBase=@ServiceBase,TotalFrame=@TotalFrame,QueueURL=@QueueURL,AccessKeyName=@AccessKeyName,AccessKeyValue=@AccessKeyValue,BusTopicName=@BusTopicName,BusKeySend=@BusKeySend,AzureName=@AzureName,AzureKey=@AzureKey,AzureContainer=@AzureContainer,AzureUrlHost=@AzureUrlHost where ServerId=@ServerId;";
                            sqlCommand.Parameters.AddWithValue("@ServiceBase", model.ServiceBase);
                            sqlCommand.Parameters.AddWithValue("@TotalFrame", model.TotalFrame);
                            sqlCommand.Parameters.AddWithValue("@QueueURL", model.QueueURL);
                            sqlCommand.Parameters.AddWithValue("@AccessKeyName", model.AccessKeyName);
                            sqlCommand.Parameters.AddWithValue("@AccessKeyValue", model.AccessKeyValue);
                            sqlCommand.Parameters.AddWithValue("@BusTopicName", model.BusTopicName);
                            sqlCommand.Parameters.AddWithValue("@BusKeySend", model.BusKeySend);
                            sqlCommand.Parameters.AddWithValue("@AzureName", model.AzureName);
                            sqlCommand.Parameters.AddWithValue("@AzureKey", model.AzureKey);
                            sqlCommand.Parameters.AddWithValue("@AzureContainer", model.AzureContainer);
                            sqlCommand.Parameters.AddWithValue("@AzureUrlHost", model.AzureUrlHost);
                            sqlCommand.Parameters.AddWithValue("@ServerId", model.ServerId);
                            sqlCommand.ExecuteNonQuery();
                        }
                        //Thêm mới nếu chưa có
                        else
                        {
                            sqlCommand.CommandText = "INSERT INTO ConfigServer VALUES (NULL, @ServiceBase, @TotalFrame, @QueueURL, @AccessKeyName, @AccessKeyValue, @BusTopicName, @BusKeySend, @AzureName, @AzureKey, @AzureContainer, @AzureUrlHost);";
                            sqlCommand.Parameters.AddWithValue("@ServiceBase", model.ServiceBase);
                            sqlCommand.Parameters.AddWithValue("@TotalFrame", model.TotalFrame);
                            sqlCommand.Parameters.AddWithValue("@QueueURL", model.QueueURL);
                            sqlCommand.Parameters.AddWithValue("@AccessKeyName", model.AccessKeyName);
                            sqlCommand.Parameters.AddWithValue("@AccessKeyValue", model.AccessKeyValue);
                            sqlCommand.Parameters.AddWithValue("@BusTopicName", model.BusTopicName);
                            sqlCommand.Parameters.AddWithValue("@BusKeySend", model.BusKeySend);
                            sqlCommand.Parameters.AddWithValue("@AzureName", model.AzureName);
                            sqlCommand.Parameters.AddWithValue("@AzureKey", model.AzureKey);
                            sqlCommand.Parameters.AddWithValue("@AzureContainer", model.AzureContainer);
                            sqlCommand.Parameters.AddWithValue("@AzureUrlHost", model.AzureUrlHost);
                            sqlCommand.ExecuteNonQuery();
                        }
                    }
                }
                InfoSettingFix.InfoSetting = this.GetCameraAPI();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static async Task ExecuteAPI(HttpContext context, System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 20];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string strRequest = Encoding.UTF8.GetString(buffer);
                string str        = strRequest.Replace("\0", string.Empty);
                string jsonStr    = string.Empty;

                try
                {
                    //Method
                    APIModel    apiModel = JsonSerializer.Deserialize <APIModel>(str);
                    string      apiName  = apiModel.Method;
                    BaseCommand command  = Activator.CreateInstance(CommandsDict[apiName]) as BaseCommand;
                    command.WebSocket = webSocket;
                    jsonStr           = command.Execute(str);
                    buffer            = Encoding.UTF8.GetBytes(jsonStr);
                    BaseRequestModel requestModel = JsonSerializer.Deserialize <BaseRequestModel>(str);
                    if (!string.IsNullOrEmpty(requestModel.Token))
                    {
                        if (command is UserLogoutCommand)
                        {
                            //do nothing
                        }
                        else
                        {
                            UserInfo userInfo = UserInfoDict[requestModel.Token];
                            userInfo.ActionTime = DateTime.Now;
                        }
                    }
                    else if (command is UserLoginCommand)
                    {
                        //do nothing
                    }
                }
                catch (Exception ex)
                {
                    ErrorResponseModel responseModel = new ErrorResponseModel();
                    responseModel.StatusCode = 0;
                    responseModel.ErrorCode  = "500";
                    responseModel.Message    = ex.Message;
                    jsonStr = JsonSerializer.Serialize(responseModel);
                    buffer  = Encoding.UTF8.GetBytes(jsonStr);
                }

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, jsonStr.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);

                buffer = new byte[1024 * 20];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
        public APIResultModel Put(int id, [FromBody] APIModel apiModel)
        {
            var result = new APIResultModel();
            int index;

            if ((index = _apiModel.FindIndex(c => c.Id == id)) != -1)
            {
                _apiModel[index] = apiModel;
                result.IsSuccess = true;
            }
            return(result);
        }
예제 #17
0
        public ActionResult API()
        {
            var model = new APIModel();

            model.AvailableMethods.Add(new SelectListItem {
                Value = "1", Text = "Add Role", Selected = model.APIMethodId == 1
            });
            model.AvailableMethods.Add(new SelectListItem {
                Value = "2", Text = "Add Table/View/SP", Selected = model.APIMethodId == 2
            });
            return(View(model));
        }
예제 #18
0
 public DBSelectSpecs(APIModel model, int max = 0,
                      int limit = 0)
 {
     _model = model;
     if (max != 0)
     {
         _max = max;
     }
     if (limit != 0)
     {
         _limit = limit;
     }
 }
예제 #19
0
        /// <summary>
        /// Lưu thông tin api
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveAPI_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(ServiceBase.Text) || string.IsNullOrEmpty(TotalFrame.Text) || string.IsNullOrEmpty(QueueURL.Text) ||
                    string.IsNullOrEmpty(AccessKeyName.Text) || string.IsNullOrEmpty(AccessKeyValue.Text) || string.IsNullOrEmpty(ASAccountName.Text) || string.IsNullOrEmpty(ASAccountKey.Text) ||
                    string.IsNullOrEmpty(ASContainer.Text) || string.IsNullOrEmpty(ASUrlHost.Text))
                {
                    var dialogValidate = new MessageDialog("Điền đầy đủ các thông tin bắt buộc (*)");
                    dialogValidate.ShowAsync();
                    return;
                }

                int totalFrame = int.Parse(TotalFrame.Text);

                if (totalFrame <= 0)
                {
                    var dialogValidate = new MessageDialog("Số mẫu phân tích/1ms phải lớn hơn hoặc bằng 1");
                    dialogValidate.ShowAsync();
                    return;
                }

                APIModel apiModel = new APIModel()
                {
                    ServiceBase    = ServiceBase.Text,
                    TotalFrame     = totalFrame,
                    ServerId       = ServerId,
                    IsUpdate       = IsUpdateApi,
                    QueueURL       = QueueURL.Text,
                    AccessKeyName  = AccessKeyName.Text,
                    AccessKeyValue = AccessKeyValue.Text,
                    BusTopicName   = SBTopicName.Text,
                    BusKeySend     = SBKeySend.Text,
                    AzureName      = ASAccountName.Text,
                    AzureKey       = ASAccountKey.Text,
                    AzureContainer = ASContainer.Text,
                    AzureUrlHost   = ASUrlHost.Text
                };
                serviceUtil.SaveInfoAPI(apiModel);
                IsUpdateApi = true;
                var dialog = new MessageDialog("Lưu thông tin thành công");
                dialog.ShowAsync();
            }
            catch (Exception ex)
            {
                var dialogErro = new MessageDialog("Phát sinh lỗi: " + ex.Message);
                dialogErro.ShowAsync();
            }
        }
예제 #20
0
        protected bool InitAPIRequestModel()
        {
            if (_apiRequestModel != null)
            {
                return(true);
            }

            if (_orderInfo.id <= 0)
            {
                SaveOrder();
            }

            _apiRequestModel = APIModel.CopyFrom(_orderInfo);
            return(true);
        }
예제 #21
0
        public async Task <ActionResult> API(APIModel model)
        {
            bool isSuccess = true;

            try
            {
                //On UI, If we select 'Add Role' in the ddl
                if (model.APIMethodId == 1)
                {
                    isSuccess = await AddRole();
                }
                //On UI, If we select Add Table/View/SP
                else if (model.APIMethodId == 2)
                {
                    isSuccess = await AddTableViewSPFunction();
                }
            }
            catch (WebApiException ex)
            {
                logger.Error($"Error occurred when calling Izenda REST Api, url: {ex.RequestedUrl}, HttpStatusCode: {ex.StatusCode}", ex);
                isSuccess = false;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                isSuccess = false;
            }

            //buid model again for view
            model.AvailableMethods.Add(new SelectListItem {
                Value = "1", Text = "Add Role", Selected = model.APIMethodId == 1
            });
            model.AvailableMethods.Add(new SelectListItem {
                Value = "2", Text = "Add Table/View/SP", Selected = model.APIMethodId == 2
            });

            if (isSuccess == true)
            {
                model.Message = "DONE. Please see the log for information.";
            }
            else
            {
                model.Message = "ERROR. Please see the log for information.";
            }
            return(View(model));
        }
        //precisa acrescentar um código na pasta APP_START arquivo WebApiConfig.cs


        // GET: api/APIOS
        public IEnumerable Get()
        {
            var lista = new APIModel().ListaAPI().OrderBy(i => i.Numero);

            return(lista);

            //var clientes = new ClienteModel().ListarCliente();
            //return clientes;
            try
            {
                return(lista);
            }
            catch (Exception)
            {
                throw;
            }
        }
        APIModel.JsonCompanySerlization CallAPI()
        {
            string username = "******";
            string password = "******";

            APIModel.LoginTokenResult accessToken = APIModel.GetLoginToken(username, password);
            if (accessToken.AccessToken != null)
            {
                //Console.WriteLine(accessToken);
                APIModel.JsonCompanySerlization list = APIModel.GetPendingCompany(accessToken.AccessToken);
                return(list);
            }
            else
            {
                return(null);// "Error Occurred:{0}, {1}", accessToken.Error, accessToken.ErrorDescription;
                //Console.WriteLine("Error Occurred:{0}, {1}", accessToken.Error, accessToken.ErrorDescription);
            }
        }
예제 #24
0
        public void TestSchemaExport()
        {
            EAMetaModel meta = new EAMetaModel();

            APIModel.createAPI1(meta);
            meta.setupSchemaPackage();

            FileManager fileManager = new FileManager(null);

            SchemaManager.setFileManager(fileManager);

            //Test
            JSchema jschema = SchemaManager.schemaToJsonSchema(EARepository.Repository, EARepository.currentDiagram).Value;


            Assert.IsTrue(jschema.Properties.ContainsKey("booleanAttr"));
            Assert.AreEqual(JSchemaType.Boolean, jschema.Properties["booleanAttr"].Type);
        }
예제 #25
0
        public void TestRAML1()
        {
            EAMetaModel meta = new EAMetaModel();

            meta.setupAPIPackage();
            EAFactory api = APIModel.createAPI1(meta);

            YamlMappingNode map = new YamlMappingNode();

            RAMLManager.REIFY_VERSION = APIAddinClass.RAML_1_0;

            //Test
            RAMLManager.reifyAPI(EARepository.Repository, api.clientElement, map);

            YamlDocument d = new YamlDocument(map);

            YamlStream stream = new YamlStream();

            stream.Documents.Add(d);

            StringWriter writer = new StringWriter();

            stream.Save(writer, false);

            string yaml = writer.ToString();

            Assert.IsTrue(yaml.Contains("is: [notcacheable]"));

            Assert.IsTrue(yaml.Contains("dev-environment"));
            Assert.IsTrue(yaml.Contains("prod-environment"));

            Assert.IsTrue(yaml.Contains("someuriparameter"));

            Assert.IsTrue(yaml.Contains("data_item_description"));

            FileManager fileManager = new FileManager(null);

            fileManager.setBasePath(".");
            fileManager.initializeAPI(EARepository.currentPackage.Name);
            fileManager.setup(APIAddinClass.RAML_0_8);
            fileManager.exportAPI(EARepository.currentPackage.Name, APIAddinClass.RAML_0_8, yaml.ToString(), "");
        }
예제 #26
0
        public async Task <APIModel> Process(APIModel model)
        {
            model.Response    = new HttpResponseMessage();
            model.ModelStatus = APIModel.ModelStatuses.SENDING;
            using (var httpClient = new HttpClient(new HttpClientHandler()
            {
                Credentials = new NetworkCredential(_config.Username, _config.Password)
            }))
            {
                var modelAttribute = (APIModel.ServicePath)model.GetType().GetCustomAttributes(typeof(APIModel.ServicePath), true).Single();
                switch (modelAttribute.method)
                {
                case APIModel.ServicePath.HttpMethods.POST:
                    var payload = JsonConvert.SerializeObject(model,
                                                              new JsonSerializerSettings()
                    {
                        NullValueHandling  = NullValueHandling.Ignore,
                        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
                    });
                    var postContent = new StringContent(payload, Encoding.UTF8, "application/json");
                    model.Response = await httpClient.PostAsync($"{_config.GetEndpointUri}/{model.BuildUri()}", postContent);

                    break;

                case APIModel.ServicePath.HttpMethods.GET:
                    model.Response = await httpClient.GetAsync($"{_config.GetEndpointUri}/{model.BuildUri()}");

                    break;
                }
            }

            if (model.Response.StatusCode != HttpStatusCode.OK)
            {
                model.ModelStatus = APIModel.ModelStatuses.ERROR;
                throw new InreachIPCException($"API request failed", model, this);
            }

            JsonConvert.PopulateObject(await model.Response.Content.ReadAsStringAsync(), model);
            model.ModelStatus = APIModel.ModelStatuses.PROCESSED;
            return(model);
        }
        public ActionResult GetPendingCRM(int?user, int?OrgId, int?CompanyId)
        {
            //if (Request.UrlReferrer == null || Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1] == "")
            //    return RedirectToAction("Login", "Login");
            string username = "******";
            string password = "******";

            APIModel.LoginTokenResult accessToken = APIModel.GetLoginToken(username, password);
            if (accessToken.AccessToken != null)
            {
                //Console.WriteLine(accessToken);
                APIModel.JsonCompanySerlization list = APIModel.GetPendingCompany(accessToken.AccessToken);
                return(Json(new { success = true, Company = list.data }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                Console.WriteLine("Error Occurred:{0}, {1}", accessToken.Error, accessToken.ErrorDescription);
            }

            return(View());
        }
예제 #28
0
		/// <summary>
		/// Checks if model to add to the DB already exists.
		/// </summary>
        private bool exists<T>(T am) where T : new()
		{
            try
            {
                var table = Select<T>();

                foreach (var r in table)
                {
                    APIModel ex = (APIModel)Convert.ChangeType(r, typeof(T));
                    APIModel ne = (APIModel)Convert.ChangeType(am, typeof(T));

                    if (ex.id== ne.id) return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return false;
		}
예제 #29
0
        public bool Sectores(farmaciasAPI farmaciass, string tipo)
        {
            switch (tipo)
            {
            case "insert":
                api = new APIModel();

                //farmaciass esto = new farmaciass();
                farmaciasAPI far;
                far = (farmaciasAPI)farmaciass;

                bool v = false;

                for (int i = 0; i < far.result.records.Count(); i++)
                {
                    bool e = api.sector_get(far.result.records[i].fk_localidad);
                    if (!e)
                    {
                        v = api.sector_insert(far.result.records[i].localidad_nombre, far.result.records[i].fk_localidad, far.result.records[i].fk_region);
                    }
                }

                return(v);

                break;

            case "update":
                Console.WriteLine("Case 2");
                return(false);

                break;

            default:
                Console.WriteLine("Default case");
                return(false);

                break;
            }
        }
예제 #30
0
        //add comstructor
        //add base url as property

        public APIModel GetRequest(string APIEndPoint, ExtentTest CurrentTest)
        {
            Dictionary <string, string> Headers = new Dictionary <string, string>();

            Headers.Add("Cookie", "__cfduid=de02f8e5eac0368cd2f92235381eb69621593899937");

            //Creates Http Client
            var client = new RestClient(url + APIEndPoint);

            client.Timeout = -1;

            var request = new RestRequest(Method.GET);

            if (Headers != null)
            {
                foreach (KeyValuePair <string, string> header in Headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }

            var           TimeStarted  = DateTime.Now;
            IRestResponse response     = client.Execute(request);
            var           TimeFinished = DateTime.Now;

            Reporting.StepPassed("Status Description: " + response.StatusCode, CurrentTest);
            Reporting.StepInfoAPI(response.Content, CodeLanguage.Xml, CurrentTest);

            //Serializtion
            APIModel Model = new APIModel()
            {
                Response   = response,
                EndPoint   = url + APIEndPoint,
                Duration   = TimeFinished - TimeStarted,
                StatusCode = response.StatusCode,
            };

            return(Model);
        }