public ApiResponse <Solicitud_de_Pago_de_FacturasPagingModel> ListaSelAll(int startRowIndex, int maximumRows, string Where, string Order)
        {
            try
            {
                var varRecords = RestApiHelper.InvokeApi <Spartane.Core.Domain.Solicitud_de_Pago_de_Facturas.Solicitud_de_Pago_de_FacturasPagingModel>(baseApi, ApiControllerUrl + "/ListaSelAll?startRowIndex=" + startRowIndex +
                                                                                                                                                       "&maximumRows=" + maximumRows +
                                                                                                                                                       (string.IsNullOrEmpty(Where) ? "" : "&Where=" + Where) +
                                                                                                                                                       (string.IsNullOrEmpty(Order) ? "" : "&Order=" + Order),
                                                                                                                                                       Method.GET, ApiHeader);

                return(new ApiResponse <Core.Domain.Solicitud_de_Pago_de_Facturas.Solicitud_de_Pago_de_FacturasPagingModel>(true, varRecords));
            }
            catch (Exception ex)
            {
                return(new ApiResponse <Core.Domain.Solicitud_de_Pago_de_Facturas.Solicitud_de_Pago_de_FacturasPagingModel>(false, new Solicitud_de_Pago_de_FacturasPagingModel()
                {
                    Solicitud_de_Pago_de_Facturass = null, RowCount = 0
                }));
            }
        }
Esempio n. 2
0
        public void ThenICompaareUserInformationToChelseyDietrich(int id, string name, string username, string email, string street,
                                                                  string suite, string city, int zipcode, double lat, double lng, string phone, string website, string cname, string catchPhrase, string bs)
        {
            User.UserInfo userInfo = new User.UserInfo()
                                     .SetId(id)
                                     .SetName(name)
                                     .SetUsername(username)
                                     .SetEmail(email)
                                     .SetAddress(new User.Address(street, suite, city, zipcode, new User.Geo(lat, lng)))
                                     .SetPhone(phone)
                                     .SetWebsite(website)
                                     .SetCompany(new User.Company(cname, catchPhrase, bs));
            var    response = RestApiHelper.GetResponse();
            string expected = JsonConvert.SerializeObject(userInfo);

            User.UserInfo info   = JsonConvert.DeserializeObject <User.UserInfo>(response.Content);
            string        actual = JsonConvert.SerializeObject(info);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 3
0
        public void BadRequestNotAddRecordTest(string firstName, string secondName, int gender, string dateOfBirth, string middleName = null)
        {
            // Проверить, что некооректный запрос не создает запись в БД

            // Сначала получим ID последней имеющейся записи
            int lastUserId = System.Convert.ToInt32(RestApiHelper.GetLastUserId(RequestUrl));

            // теперь отправим некорректный запрос на создание
            try
            {
                AddRequest req = new AddRequest(RequestUrl, firstName, secondName, gender, dateOfBirth, middleName);
                req.Run();
            }
            catch { }

            // Снова получим ID последней имеющейся записи
            int newLastUserId = System.Convert.ToInt32(RestApiHelper.GetLastUserId(RequestUrl));

            //ID записи в БД не должен был измениться
            Assert.AreEqual(lastUserId, newLastUserId);
        }
Esempio n. 4
0
        public static async Task DownloadAllUserDocumentsAsync()
        {
            foreach (var userDocument in await RepositoryManager.UserDocumentRepositoryInstance.GetAsync(x => x.AssignedUserId == ApplicationContext.LoggedInUserId && x.IsDownloaded == false && x.IsCompleted == false))
            {
                var document = (await RepositoryManager.DocumentRepositoryInstance.GetAsync(x => x.DocumentId == userDocument.DocumentId))?.FirstOrDefault();
                if (document == null)
                {
                    continue;
                }
                var stream = await RestApiHelper.DownloadFileAsync(document.DocumentUrl);

                if (stream == null)
                {
                    continue;
                }
                await SaveFileAsync($"{document.DocumentId}.pdf", stream);

                userDocument.IsDownloaded = true;
                await RepositoryManager.UserDocumentRepositoryInstance.SaveAsync(userDocument);
            }
        }
Esempio n. 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="searchTerm"></param>
        /// <returns></returns>
        public async Task <TriviaPlayer[]> SearchPlayerAsync(string searchTerm)
        {
            TriviaPlayer[] triviaPlayers = null;

            string requestUri = string.Format(TriviaSearchUri, searchTerm);
            string response   = null;

            try
            {
                response = await RestApiHelper.ExecuteHttpGetAsync(requestUri, RestApiHelper.ContentTypeJson);

                System.Diagnostics.Debug.WriteLine($"Received response: {response}");
                triviaPlayers = JsonConvert.DeserializeObject <TriviaPlayer[]>(response);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine($"Search failed: {e.Message}");
            }

            return(triviaPlayers);
        }
Esempio n. 6
0
        // 接口层有十分钟左右的缓存误差
        private static async Task <ListResp <GetRoleItemResp> > GetAuthUserFuncListFromApi()
        {
            var memIdentity = UserContext.Identity;

            if (memIdentity.auth_type != PortalAuthorizeType.SuperAdmin)
            {
                return(await RestApiHelper.GetApi <ListResp <GetRoleItemResp> >("/b/permit/GetAuthUserFuncList"));
            }

            // 如果是超级管理员直接返回所有
            var sysFunItemsRes = await GetAllFuncItems();

            if (!sysFunItemsRes.IsSuccess())
            {
                return(new ListResp <GetRoleItemResp>().WithResp(sysFunItemsRes));
            }

            var roleItems = sysFunItemsRes.data.Select(item => item.ToRoleItemResp()).ToList();

            return(new ListResp <GetRoleItemResp>(roleItems));
        }
Esempio n. 7
0
        private async Task <UserRegLoginResp> AdminLogin(LoginNameReq req, string apiUrl)
        {
            var stateRes = CheckLoginModelState(req);

            if (!stateRes.IsSuccess())
            {
                return(new UserRegLoginResp().WithResp(stateRes));
            }

            var loginRes = await RestApiHelper.PostApi <UserRegLoginResp>(apiUrl, req);

            if (!loginRes.IsSuccess())
            {
                return(loginRes);
            }

            AdminHelper.SetCookie(Response, loginRes.token);

            loginRes.token = string.Empty;// 写入cookie后不再明文传递到js
            return(loginRes);
        }
Esempio n. 8
0
        private async void getPdfFile()
        {
            using (var Dialog = UserDialogs.Instance.Loading("Exibindo...", null, null, true, MaskType.Clear))
            {
                if (File.Exists(_paciente.nome_arquivo))

                {
                    var retorno = await RestApiHelper.DownloadFileAsync(_paciente.nome_arquivo);

                    Xamarin.Forms.DependencyService.Get <IFileService>().Savefile(_paciente.nome_arquivo, retorno, "Download");
                }

                /* if (await FileManager.ExistsAsync(_paciente.nome_arquivo) == false)
                 * {
                 *   await FileManager.DownloadDocumentsAsync(_paciente);
                 * }
                 */
                //NomeArquivo = FileManager.GetFilePathFromRoot(_paciente.nome_arquivo);
                NomeArquivo    = Xamarin.Forms.DependencyService.Get <IFileStore>().GetFilePath(_paciente.nome_arquivo);
                NomeArquivoSem = Path.GetFileName(_paciente.nome_arquivo);
            }
        }
Esempio n. 9
0
        public async Task <IRestResponse <CourseSearchResponse> > SearchWithKeyword(string keyword)
        {
            var restClientFactory  = new RestClientFactory(_context.GetFindACourseApiConfig <FindACourseApiConfig>().BaseUrl);
            var restRequestFactory = new RestRequestFactory(_resource, Method.POST);

            restRequestFactory.SetHeaders(new Dictionary <string, string>()
            {
                { "Content-Type", "application/json-patch+json" },
                { "Ocp-Apim-Subscription-Key", _context.GetFindACourseApiConfig <FindACourseApiConfig>().OcpApimSubscriptionKey }
            });

            var requestBody = new CourseSearchBody()
            {
                subjectKeyword = keyword,
                limit          = 20
            };

            restRequestFactory.AddBody(requestBody);
            var restApiHelper = new RestApiHelper(restClientFactory, restRequestFactory);

            return(await restApiHelper.ExecuteAsync <CourseSearchResponse>());
        }
Esempio n. 10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseSwagger();
            // Swagger.io
            app.UseSwaggerUI(c =>
            {
                string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
                c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "My API V1");
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseCors("_myAllowSpecificOrigins");


            app.UseHangfireServer();
            var notifSett = applicationSettings.NotificationSettings;

            // Recurring job to blast notification
            // Call notification endpoint periodically
            // Notification URL & interval are configured in appsettings
            RecurringJob.AddOrUpdate(() => RestApiHelper.GetAsync(string.Format(notifSett.NotificationApiPath)), $"*/{notifSett.RefreshIntervalMins} * * * *");

            _logger.Info("[TicketBOT] Ticket Bot Service (Started)");
        }
Esempio n. 11
0
        public void BeforeScenario()
        {
            RestApiHelper <Parameters> restApi = new RestApiHelper <Parameters>("3.0");
            string operationName = "stations";
            string id            = "5d3afec76c634e000131c036";
            NameValueCollection paramCollection = new NameValueCollection();

            paramCollection.Add("APPID", appid);

            string jsonRequest = @"{
                                    ""external_id"": ""SF_TEST001"",
                                    ""name"": ""San Francisco Test Station"",
                                    ""longitude"": -122.43,
                                    ""latitude"": 37.76,
                                    ""altitude"": 150
                                  }";

            var restUrl     = restApi.SetUrl(restApi.QueryBuilder(operationName, id, paramCollection));
            var restRequest = restApi.CreatePutRequest(jsonRequest);

            restApi.GetResponse(restUrl, restRequest);
        }
Esempio n. 12
0
        public void CleanCompaniesTestData()
        {
            //Authorize to API
            RestApiHelper           helper      = new RestApiHelper();
            AutomationEngineerSteps stepsObject = new AutomationEngineerSteps();

            Dictionary <string, string> parameters = new Dictionary <string, string>
            {
                { "username", "test" },
                { "password", "password1" },
                { "grant_type", "password" }
            };

            helper.Authorize("/token", parameters);

            //Clean all companies
            stepsObject.WhenIGetAll("company");
            if (RestApiHelper.companyResponse != null)
            {
                foreach (Company company in RestApiHelper.companyResponse)
                {
                    stepsObject.WhenISendDeleteByIdRequestForWithName("company", company.Name);
                }
            }

            //Clean all employees
            stepsObject.WhenIGetAll("employee");
            if (RestApiHelper.employeeResponse != null)
            {
                foreach (Employee employee in RestApiHelper.employeeResponse)
                {
                    stepsObject.WhenISendDeleteByIdRequestForWithName("employee", employee.Name);
                }
            }

            helper.CleanAllRespones();
        }
Esempio n. 13
0
    public override void invokeCallback(WWW www)
    {
        apiCallCount--;

        if (callback != null)
        {
            int    responcecode = 0;
            string error        = null;

            if (isRequestCanceled)            //cancel
            {
                if ((extentionType & ExtentionType.AutoCancelIfRequired) == ExtentionType.AutoCancelIfRequired)
                {
                    error        = "RestApiExtention:AutoCancel";
                    responcecode = (int)ErrorCodes.AutoCanceled;
                    callback(null, error, error, responcecode, customData);
                    callback          = null;
                    customData        = null;
                    isRequestCanceled = false;
                    return;
                }
                else if ((extentionType & ExtentionType.CancelAndRestartIfRequired) == ExtentionType.CancelAndRestartIfRequired)
                {
                    //Ignore the cancel request
                    Debug.Log("Suspended");
                    isRequestCanceled = false;
                    return;
                }
                else
                {
                    error        = "RestApiExtention:Canceled";
                    responcecode = (int)ErrorCodes.Canceled;
                    callback(null, error, error, responcecode, customData);
                    callback          = null;
                    customData        = null;
                    isRequestCanceled = false;
                    return;
                }
            }
            else
            {
                error = www.error;              //Actual server error
                //GameStateManager.Instance.checkNetworkConnection = true;
            }


            string      resultText;
            IDictionary resultDict;

            if (error != null)           //Network related error
            {
                Debug.LogError("***Network error!!  Call Admin Guy!! ==>" + error + "***APICALL** " + www.url);
                resultDict = null;
                resultText = error;
                ExtentionType temp = extentionType;

                if ((temp & ExtentionType.RetryAfterNetworkError) == ExtentionType.RetryAfterNetworkError && currentRetryAttempts < retryAttempts)
                {
                    currentRetryAttempts++;
                    RestApiHelper.GetInstance().StartHandleWWWAfterDelay(retryDely, www, this);
                    return;
                }
                else
                {
                    Debug.LogError("***Network error!!  Call Admin Guy!! ==>" + error + "***APICALL** " + www.url);
                    responcecode = (int)ErrorCodes.ExeededRetries;
                }

                //GameStateManager.Instance.checkNetworkConnection = true;
            }
            else
            {
                //Handling API related error in advancd
                Debug.Log("***APICALL**  TimeStamp:" + System.DateTime.Now.ToLongTimeString() + " " + www.url + "\n=>" + www.text);
                resultDict = (IDictionary)Json.Deserialize(www.text);
                resultText = www.text;
                if (resultDict != null)
                {
                    responcecode = int.Parse(string.Format("{0}", resultDict["responseCode"]));
                }

                else
                {
                    Debug.LogError("***Server error!! Call server ppl !! ==>" + www.text + "***APICALL** " + www.url);
                }
                //GameStateManager.Instance.checkNetworkConnection = true;
            }

            callback(resultDict, resultText, error, responcecode, customData);
            callback   = null;
            customData = null;
        }
    }
Esempio n. 14
0
 public void GivenIHaveAEndpointEndpoint(string endpoint)
 {
     RestApiHelper.SetUrl(endpoint);
 }
Esempio n. 15
0
 public void ThenIWillGetUserInformation()
 {
     var response = RestApiHelper.GetResponse();
 }
Esempio n. 16
0
 public void WhenICallGetMethodOfGetUserInformationUsingUserAnd(string userId, long accountNumber)
 {
     RestApiHelper.CreateRequest(userId, accountNumber);
 }
Esempio n. 17
0
 public void WhenICallGetMethodOfGetUserInformationUsingUser(string userId)
 {
     RestApiHelper.CreateRequest(userId);
 }
Esempio n. 18
0
 public void WhenICallGetMethodOfApi()
 {
     RestApiHelper.CreateRequest();
 }
        public async Task WhenTheApiIsQueriedToReturnAllActiveQuestionnairesAsync()
        {
            var listOfActiveQuestionnaires = await RestApiHelper.GetInstance().GetAllActiveQuestionnaires();

            _scenarioContext.Set(listOfActiveQuestionnaires, ApiResponse);
        }
Esempio n. 20
0
 public void WriteTo(StringBuilder sb)
 {
     sb.Append('/');
     sb.Append(RestApiHelper.FormatDefinitionSinglePath(_propertyName));
 }
Esempio n. 21
0
        /// <summary>
        /// Used to read the client companies like clientCompanyName
        /// </summary>
        /// <param name="company"></param>
        /// <param name="clientCompanyName"></param>
        /// <returns></returns>
        public async Task <List <ClientCompany> > GetClientCompanies(Company company, string clientCompanyName)
        {
            HttpResponseMessage resp = null;

            try
            {
                List <ClientCompany> companies = new List <ClientCompany>();

                if (string.IsNullOrWhiteSpace(clientCompanyName))
                {
                    throw new ArgumentException($"Please enter correct cilent company name", "clientCompanyName");
                }

                if (company == null)
                {
                    throw new ArgumentException($"Please provide company data", "company");
                }

                // get companies page by page to find the matching client company name.
                int start = 0;
                int limit = 100;



                //Looks like jira doesnt have an option to find the service desk using name. So we have to loop through all service desk and find matching names
                //This loop will find all matching records and breaks once it search through all companies.
                while (true)
                {
                    //New req need to create else client throws error [The request message was already sent.]
                    var JIRAReq = getJIRARequestObj(company.TicketSysId, Utility.ParseDInfo(company.TicketSysPassword, _appSettings.General.SysInfo));
                    JIRAReq.Method     = HttpMethod.Get;
                    JIRAReq.RequestUri = new Uri(string.Format(_appSettings.JIRAApiEndpoint.GetServiceDesk, company.TicketSysUrl, start, limit));
                    resp = await RestApiHelper.SendAsync(JIRAReq);

                    resp.EnsureSuccessStatusCode();

                    //FilterCollection to get matching names
                    var servicedeskDetails = JsonConvert.DeserializeObject <ServicedeskDetails>(await resp.Content.ReadAsStringAsync());
                    if (servicedeskDetails.size > 0)
                    {
                        servicedeskDetails
                        .values
                        .Where(x => (
                                   (x?.projectName?.Contains(clientCompanyName, StringComparison.InvariantCultureIgnoreCase)) ?? false
                                   )
                               )?.ToList()
                        ?.ForEach(srvDsk =>
                                  companies.Add(
                                      new ClientCompany()
                        {
                            ClientCompanyName    = srvDsk.projectName,
                            TicketSysCompanyCode = srvDsk.id,
                            Active            = true,
                            CreatedOn         = DateTime.Now,
                            VerificationEmail = company.contactEmail                                     //currently using conpanys contact. user should call and get OTP from company
                        }
                                      ));
                    }
                    else
                    {
                        break;
                    }
                    start += (limit + 1);
                }

                //need to get the email info of the customer
                //as there is no such api available, we are designing to send the OTP  to the Company email.

                return(companies);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                string APIError = "<EMPTY>";
                if (resp != null)
                {
                    var error = JsonConvert.DeserializeObject <Error>(await resp.Content.ReadAsStringAsync());
                    if (error != null)
                    {
                        APIError = error.errorMessage;
                    }
                }

                throw new Exception($"Error: {ex.Message}. API Error:{APIError}");
            }
        }
Esempio n. 22
0
 public void WhenIGonnaGet(string p0)
 {
     restApi         = new RestApiHelper <Parameters>();
     paramCollection = new NameValueCollection();
     operationName   = p0;
 }
Esempio n. 23
0
 public void WhenICallDELETEMethodUsing(string id)
 {
     RestApiHelper.CreateDeleteRequest(id);
 }
Esempio n. 24
0
 public void WhenIMakeAGETRequestOnResourceId(int userId)
 {
     _restHelper = new RestApiHelper();
     _restHelper.CreateGetRequestForSingleUser(userId);
 }
Esempio n. 25
0
        private SwaggerObjectBase LoadCore(JToken token, string swaggerPath, bool isExample = false)
        {
            // Fetch from cache first
            var location         = JsonLocationHelper.GetLocation(token);
            var jsonLocationInfo = new JsonLocationInfo(swaggerPath, location);

            if (_documentObjectCache.TryGetValue(jsonLocationInfo, out SwaggerObjectBase existingObject))
            {
                return(existingObject);
            }

            if (token is JObject jObject)
            {
                // Only one $ref is allowed inside a swagger JObject
                if (jObject.TryGetValue(ReferenceKey, out JToken referenceToken) && !isExample)
                {
                    if (referenceToken.Type != JTokenType.String && referenceToken.Type != JTokenType.Null)
                    {
                        throw new JsonException($"JSON reference $ref property must have a string or null value, instead of {referenceToken.Type}, location: {referenceToken.Path}.");
                    }

                    var swaggerReference = RestApiHelper.FormatReferenceFullPath((string)referenceToken);
                    switch (swaggerReference.Type)
                    {
                    case SwaggerFormattedReferenceType.InternalReference:
                        var deferredObject = new SwaggerReferenceObject
                        {
                            DeferredReference = swaggerReference.Path,
                            ReferenceName     = swaggerReference.Name,
                            Location          = location
                        };

                        // For swagger, other properties are still allowed besides $ref, e.g.
                        // "schema": {
                        //   "$ref": "#/definitions/foo"
                        //   "example": { }
                        // }
                        // Use Token property to keep other properties
                        // These properties cannot be referenced
                        jObject.Remove("$ref");
                        deferredObject.Token = jObject;
                        _documentObjectCache.Add(jsonLocationInfo, deferredObject);
                        return(deferredObject);

                    case SwaggerFormattedReferenceType.ExternalReference:
                        jObject.Remove("$ref");

                        var externalJObject = LoadExternalReference(Path.Combine(Path.GetDirectoryName(swaggerPath), swaggerReference.ExternalFilePath));
                        RestApiHelper.CheckSpecificKey(externalJObject, ReferenceKey, () =>
                        {
                            throw new DocfxException($"{ReferenceKey} in {swaggerReference.ExternalFilePath} is not supported in external reference currently.");
                        });
                        foreach (var item in externalJObject)
                        {
                            if (jObject.TryGetValue(item.Key, out JToken value))
                            {
                                Logger.LogWarning($"{item.Key} inside {jObject.Path} would be overwritten by the value of same key inside {swaggerReference.ExternalFilePath} with path {externalJObject.Path}.");
                            }
                            jObject[item.Key] = item.Value;
                        }

                        var resolved = new SwaggerValue
                        {
                            Location = location,
                            Token    = jObject
                        };
                        _documentObjectCache.Add(jsonLocationInfo, resolved);
                        return(resolved);

                    case SwaggerFormattedReferenceType.ExternalEmbeddedReference:
                        // Defer resolving external reference to resolve step, to prevent loop reference.
                        var externalDeferredObject = new SwaggerReferenceObject
                        {
                            ExternalFilePath  = Path.Combine(Path.GetDirectoryName(swaggerPath), swaggerReference.ExternalFilePath),
                            DeferredReference = swaggerReference.Path,
                            ReferenceName     = swaggerReference.Name,
                            Location          = location
                        };
                        jObject.Remove("$ref");
                        externalDeferredObject.Token = jObject;
                        _documentObjectCache.Add(jsonLocationInfo, externalDeferredObject);
                        return(externalDeferredObject);

                    default:
                        throw new DocfxException($"{referenceToken} does not support type {swaggerReference.Type}.");
                    }
                }

                var swaggerObject = new SwaggerObject {
                    Location = location
                };
                foreach (KeyValuePair <string, JToken> property in jObject)
                {
                    swaggerObject.Dictionary.Add(property.Key, LoadCore(property.Value, swaggerPath, isExample || IsExampleProperty(property.Key, jObject?.Parent?.Parent?.Path)));
                }

                _documentObjectCache.Add(jsonLocationInfo, swaggerObject);
                return(swaggerObject);
            }

            if (token is JArray jArray)
            {
                var swaggerArray = new SwaggerArray {
                    Location = location
                };
                foreach (var property in jArray)
                {
                    swaggerArray.Array.Add(LoadCore(property, swaggerPath, isExample));
                }

                return(swaggerArray);
            }

            return(new SwaggerValue
            {
                Location = location,
                Token = token
            });
        }
Esempio n. 26
0
 public void WhenIGonnaGetStationRequest(string p0)
 {
     restApi         = new RestApiHelper <Parameters>(p0);
     operationName   = "stations";
     paramCollection = new NameValueCollection();
 }
Esempio n. 27
0
        /// <summary>
        /// Used to create a new case in JIRA
        /// </summary>
        /// <param name="company"></param>
        /// <param name="clientCompany"></param>
        /// <param name="CaseSubject"></param>
        /// <param name="CaseDescription"></param>
        /// <returns></returns>
        public async Task <CaseDetail> CreateCaseAsync(Company company, ClientCompany clientCompany, string CaseSubject, string CaseDescription)
        {
            HttpResponseMessage resp = null;

            try
            {
                CaseDetail caseDetail = new CaseDetail();
                if (company == null)
                {
                    throw new ArgumentException($"Company details should not be empty", "Company");
                }
                if (string.IsNullOrWhiteSpace(CaseSubject))
                {
                    throw new ArgumentException($"Please enter correct Case subject", "CaseSubject");
                }

                var JIRAReq = getJIRARequestObj(company.TicketSysId, Utility.ParseDInfo(company.TicketSysPassword, _appSettings.General.SysInfo));
                JIRAReq.Method     = HttpMethod.Post;
                JIRAReq.RequestUri = new Uri(string.Format(_appSettings.JIRAApiEndpoint.CreateCase, company.TicketSysUrl));
                var caseDt = new ServiceDeskRequest()
                {
                    serviceDeskId      = clientCompany.TicketSysCompanyCode,
                    requestTypeId      = "1240",
                    requestFieldValues = new RequestFieldValues()
                    {
                        summary     = CaseSubject,
                        description = CaseDescription,
                        duedate     = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd")
                    },
                };

                JIRAReq.Content = new StringContent(
                    JsonConvert.SerializeObject(caseDt),
                    Encoding.UTF8,
                    "application/json");

                resp = await RestApiHelper.SendAsync(JIRAReq);

                resp.EnsureSuccessStatusCode();
                var caseInfo = JsonConvert.DeserializeObject <JIRACaseDetail>(await resp.Content.ReadAsStringAsync());

                caseDetail = new CaseDetail()
                {
                    CaseID    = caseInfo.issueId,
                    CaseKey   = caseInfo.issueKey,
                    CreatedOn = caseInfo.createdDate.jira,
                    Status    = caseInfo.currentStatus.status,
                    Subject   = caseInfo.requestFieldValues.Where(x => x.fieldId == "summary").FirstOrDefault()?.value.ToString(),
                    Detail    = caseInfo.requestFieldValues.Where(x => x.fieldId == "description").FirstOrDefault()?.value.ToString(),
                    WebURL    = caseInfo.Links.Web
                };

                return(caseDetail);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                string APIError = "<EMPTY>";
                if (resp != null)
                {
                    var error = JsonConvert.DeserializeObject <Error>(await resp.Content.ReadAsStringAsync());
                    if (error != null)
                    {
                        APIError = error.errorMessage;
                    }
                }

                throw new Exception($"Error: {ex.Message}. API Error:{APIError}");
            }
        }
Esempio n. 28
0
 public async Task PostMessageAsync(string pageToken, JObject json)
 {
     await RestApiHelper.PostAsync(string.Format(_appSettings.FacebookGraphApiEndpoint.PostMessage, pageToken), new StringContent(json.ToString(), Encoding.UTF8, "application/json"));
 }
Esempio n. 29
0
        private SwaggerObjectBase Build(JToken token)
        {
            var jObject = token as JObject;

            if (jObject != null)
            {
                JToken referenceToken;

                // Only one $ref is allowed inside a swagger JObject
                if (jObject.TryGetValue("$ref", out referenceToken))
                {
                    if (referenceToken.Type != JTokenType.String && referenceToken.Type != JTokenType.Null)
                    {
                        throw new JsonException($"JSON reference $ref property must have a string or null value, instead of {referenceToken.Type}, location: {referenceToken.Path}.");
                    }

                    SwaggerReferenceObject deferredObject = new SwaggerReferenceObject();
                    var formatted = RestApiHelper.FormatReferenceFullPath((string)referenceToken);
                    deferredObject.DeferredReference = formatted.Item1;
                    deferredObject.ReferenceName     = formatted.Item2;

                    // For swagger, other properties are still allowed besides $ref, e.g.
                    // "schema": {
                    //   "$ref": "#/defintions/foo"
                    //   "example": { }
                    // }
                    // Use Token property to keep other properties
                    // These properties cannot be referenced
                    jObject.Remove("$ref");
                    deferredObject.Token = jObject;
                    return(deferredObject);
                }
                else
                {
                    string location = GetLocation(token);

                    SwaggerObject existingObject;
                    if (_documentObjectCache.TryGetValue(location, out existingObject))
                    {
                        return(existingObject);
                    }

                    var swaggerObject = new SwaggerObject {
                        Location = location
                    };

                    foreach (KeyValuePair <string, JToken> property in jObject)
                    {
                        swaggerObject.Dictionary.Add(property.Key, Build(property.Value));
                    }

                    _documentObjectCache.Add(location, swaggerObject);
                    return(swaggerObject);
                }
            }

            var jArray = token as JArray;

            if (jArray != null)
            {
                var swaggerArray = new SwaggerArray();
                foreach (var property in jArray)
                {
                    swaggerArray.Array.Add(Build(property));
                }

                return(swaggerArray);
            }

            return(new SwaggerValue
            {
                Token = token
            });
        }
Esempio n. 30
0
 public Login(MainScreen mainScreen, RestApiHelper api)
 {
     this.mainScreen = mainScreen;
     this.api        = api;
     InitializeComponent();
 }