Exemple #1
0
        /// <summary>
        /// Program's asynchronous startup.
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync()
        {
            IConfiguration configuration = ConfigureAppSettings();

            ConfigureLogger();

            ApiCalls            api      = new ApiCalls(configuration, logger);
            DiscordSocketClient client   = new DiscordSocketClient();
            CommandService      commands = new CommandService();

            IServiceProvider services = new ServiceCollection().AddSingleton(client)
                                        .AddSingleton(commands)
                                        .AddSingleton(configuration)
                                        .AddSingleton <InteractiveService>()
                                        .AddSingleton(api)
                                        .BuildServiceProvider();
            string commandPrefix = configuration["commandPrefix"];
            string token         = GetToken(configuration);

            client.Log += LogClientEvent;

            PrintCurrentVersion();
            await RegisterCommandsAsync(client, commands, services, configuration).ConfigureAwait(false);

            await client.LoginAsync(TokenType.Bot, token).ConfigureAwait(false);

            await client.StartAsync().ConfigureAwait(false);

            await client.SetGameAsync(GlobalConfiguration.GetStatusText(commandPrefix), type : ActivityType.Listening).ConfigureAwait(false);

            await Task.Delay(-1).ConfigureAwait(false);
        }
Exemple #2
0
        private async Task GetPrixTypes()
        {
            try
            {
                AppHelper.ALoadingShow("Chargement...");
                var RequestResult = await ApiCalls.GetPrixTypes();

                if (RequestResult.success)
                {
                    PrixTypes = RequestResult.data;
                }
                else
                {
                    AppHelper.ASnack(message: RequestResult.message, type: SnackType.Error);
                    await Application.Current.MainPage.Navigation.PopAsync();
                }
            }
            catch (Exception)
            {
                AppHelper.ASnack(message: Assets.Strings.ErreurMessage, type: SnackType.Error);
            }
            finally
            {
                AppHelper.ALoadingHide();
            }
        }
Exemple #3
0
        private async Task GetStationDetails()
        {
            try
            {
                AppHelper.ALoadingShow("Chargement...");
                var RequestResult = await ApiCalls.GetStationDetails();

                if (RequestResult.success)
                {
                    StationDetails    = RequestResult.data;
                    ContentVisible    = true;
                    RefreshBtnVisible = false;
                }
                else
                {
                    ContentVisible    = false;
                    RefreshBtnVisible = true;
                    AppHelper.ASnack(message: RequestResult.message, type: SnackType.Error);
                }
            }
            catch (Exception ex)
            {
                AppHelper.ASnack(message: Assets.Strings.ErreurMessage, type: SnackType.Error);
            }
            finally
            {
                AppHelper.ALoadingHide();
            }
        }
 public IActionResult Index()
 {
     ViewBag.table1 = ApiCalls.GetManufacturers200();
     ViewBag.table2 = ApiCalls.GetManufacturersFlights();
     ViewBag.table3 = ApiCalls.GetAirbuses();
     return(View());
 }
Exemple #5
0
        private void ddlDepartments_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlBranches.SelectedValue.ToString() != "0" && ddlDepartments.SelectedValue.ToString() != "0")
            {
                List <Branch>     branches    = ApiCalls.GetBranches();
                List <Department> departments = ApiCalls.GetDepartments();

                Int32 branchId     = branches.Where(x => x.Code == ddlBranches.SelectedValue.ToString()).FirstOrDefault().Id;
                Int32 departmentId = departments.Where(x => x.Code == ddlDepartments.SelectedValue.ToString()).FirstOrDefault().Id;

                StringBuilder filter = new StringBuilder();
                filter.Append(" 1=1");
                filter.Append(" and " + Converter.GetColumnNameByPropertyName <Batch>(nameof(Batch.BranchId)) + " = '" + branchId + "'");
                filter.Append(" and " + Converter.GetColumnNameByPropertyName <Batch>(nameof(Batch.DepartmentId)) + " = '" + departmentId + "'");

                List <Batch> batches = ApiCalls.GetBatches(filter.ToString());
                batches.Insert(0, new Batch {
                    BatchNo = "Select Batch", Id = 0
                });
                ddlBatches.DataSource    = batches;
                ddlBatches.DisplayMember = "BatchNo";
                ddlBatches.ValueMember   = "Id";
                ddlBatches.SelectedValue = 0;
            }
        }
        private static async Task Run()
        {
            // The following properties indicate which partner and customer context the calls are going to be made.
            string PartnerId  = "<Partner tenant id>";
            string CustomerId = "<Customer tenant id>";

            Console.WriteLine(" ===================== Partner center  API calls ============================", DateTime.Now);
            IAggregatePartner ops = await GetUserPartnerOperationsAsync(PartnerId);

            SeekBasedResourceCollection <CustomerUser> customerUsers = ops.Customers.ById(CustomerId).Users.Get();

            Console.WriteLine(JsonConvert.SerializeObject(customerUsers));

            Console.WriteLine(" ===================== Partner graph  API calls ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenResult = await LoginToGraph(PartnerId);

            Newtonsoft.Json.Linq.JObject mydetails = await ApiCalls.GetAsync(tokenResult.Item1, "https://graph.microsoft.com/v1.0/me");

            Console.WriteLine(JsonConvert.SerializeObject(mydetails));

            // CSP partner applications are pre-consented into customer tenant, so they do not need a custom consent from customer.
            // direct token acquire to a customer tenant should work.
            Console.WriteLine(" ===================== Customer graph  API calls ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenCustomerResult = await LoginToCustomerGraph(PartnerId, CustomerId);

            Newtonsoft.Json.Linq.JObject customerDomainsUsingGraph = await ApiCalls.GetAsync(tokenCustomerResult.Item1, "https://graph.windows.net/" + CustomerId + "/domains?api-version=1.6");

            Console.WriteLine(JsonConvert.SerializeObject(customerDomainsUsingGraph));

            Console.ReadLine();
        }
        public static ISofOperation PrepareRebootResults()
        {
            ISofOperation operation = new SofOperation();
            var           location  = Path.Combine(Settings.AgentDirectory, "rebootoperation.data");

            if (!File.Exists(location))
            {
                return(null);
            }

            var operationId = File.ReadAllText(location);

            Logger.Log("Found reboot operation, preparing to send back results for operation id {0}", LogLevel.Info, operationId);

            var rebooted = (IsBootUp().ToLower() == "yes") ? true.ToString().ToLower() : false.ToString().ToLower();

            var json = new JObject();

            json["operation"]    = "reboot";
            json["operation_id"] = operationId;
            json["success"]      = (String.IsNullOrEmpty(rebooted)) ? "no" : rebooted;

            operation.Id        = operationId;
            operation.Api       = ApiCalls.CoreRebootResults();
            operation.Type      = "reboot";
            operation.RawResult = json.ToString();

            File.Delete(location);
            Logger.Log("Deleted reboot operation file, sending back results.");

            return(operation);
        }
        private static async Task RunAsync()
        {
            // The following properties indicate which partner and customer context the calls are going to be made.
            string PartnerId  = "<Partner tenant id>";
            string CustomerId = "<Customer tenant id>";

            Console.WriteLine(" ===================== Partner Center operations ============================", DateTime.Now);
            IAggregatePartner ops = await GetUserPartnerOperationsAsync(PartnerId);

            SeekBasedResourceCollection <CustomerUser> customerUsers = ops.Customers.ById(CustomerId).Users.Get();

            Console.WriteLine(JsonConvert.SerializeObject(customerUsers));

            Console.WriteLine(" ===================== Partner graph operations ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenResult = await LoginToGraph(PartnerId);

            Newtonsoft.Json.Linq.JObject mydetails = await ApiCalls.GetAsync(tokenResult.Item1, "https://graph.microsoft.com/v1.0/me");

            Console.WriteLine(JsonConvert.SerializeObject(mydetails));

            /**
             * Cloud Solution Provider partners can configure application for pre-consent. This means they do not need a
             * custom consent from the customer. This is possible because the partner can consent on behalf of the customer.
             */

            Console.WriteLine(" ===================== Customer graph operations ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenCustomerResult = await LoginToCustomerGraph(PartnerId, CustomerId);

            Newtonsoft.Json.Linq.JObject customerDomainsUsingGraph = await ApiCalls.GetAsync(tokenCustomerResult.Item1, "https://graph.windows.net/" + CustomerId + "/domains?api-version=1.6");

            Console.WriteLine(JsonConvert.SerializeObject(customerDomainsUsingGraph));

            Console.ReadLine();
        }
Exemple #9
0
        private static void DeleteTestData()
        {
            var data    = new RunData();
            var apiCall = new ApiCalls(data);

            apiCall.DeleteTestRoles();
            apiCall.DeleteTestForms();
        }
Exemple #10
0
        /// <summary>
        /// This takes care of executing any operation received by the server.
        /// </summary>
        /// <param name="operation"></param>
        public void RunOperation(ISofOperation operation)
        {
            var rvOperation = new RvSofOperation(operation.RawOperation);

            switch (rvOperation.Type)
            {
            case OperationValue.InstallWindowsUpdate:
                rvOperation.Api  = ApiCalls.RvInstallWinUpdateResults();
                rvOperation.Type = OperationValue.InstallWindowsUpdate;
                InstallWindowsUpdate(rvOperation);
                break;

            case OperationValue.InstallSupportedApp:
                rvOperation.Api  = ApiCalls.RvInstallSupportedAppsResults();
                rvOperation.Type = OperationValue.InstallSupportedApp;
                InstallSupportedApplication(rvOperation);
                break;

            case OperationValue.InstallCustomApp:
                rvOperation.Api  = ApiCalls.RvInstallCustomAppsResults();
                rvOperation.Type = OperationValue.InstallCustomApp;
                InstallCustomApplication(rvOperation);
                break;

            case OperationValue.InstallAgentUpdate:
                rvOperation.Api  = ApiCalls.RvInstallAgentUpdateResults();
                rvOperation.Type = OperationValue.InstallAgentUpdate;
                InstallAgentUpdate(rvOperation);
                break;

            case OperationValue.Uninstall:
                rvOperation.Api  = ApiCalls.RvUninstallOperation();
                rvOperation.Type = OperationValue.Uninstall;
                UninstallOperation(rvOperation);
                break;

            case OperationValue.AgentUninstall:
                rvOperation.Type = OperationValue.AgentUninstall;
                UninstallRvAgentOperation();
                break;

            case RvOperationValue.UpdatesAndApplications:
                rvOperation.Type      = RvOperationValue.UpdatesAndApplications;
                rvOperation           = UpdatesApplicationsOperation(rvOperation);
                rvOperation.RawResult = RvFormatter.Applications(rvOperation);
                rvOperation.Api       = ApiCalls.RvUpdatesApplications();
                SendResults(rvOperation);
                break;

            case OperationValue.ResumeOp:
                ResumeOperations();
                break;

            default:
                Logger.Log("Received unrecognized operation. Ignoring.");
                break;
            }
        }
Exemple #11
0
        public static void UpdateBatchStatusDone(string batchKey)
        {
            new Services();
            StringBuilder filter = new StringBuilder();

            filter.Append(" 1=1");
            filter.Append(" and " + Converter.GetColumnNameByPropertyName <Batch>(nameof(Batch.BatchKey)) + " = '" + batchKey + "'");
            filter.Append(" and " + Converter.GetColumnNameByPropertyName <Batch>(nameof(Batch.StageId)) + " = '4'");
            filter.Append(" and " + Converter.GetColumnNameByPropertyName <Batch>(nameof(Batch.BatchStatus)) + " = '1'");
            filter.Append(" and " + Converter.GetColumnNameByPropertyName <Batch>(nameof(Batch.Status)) + " = '1'");

            logWriter = new LogWriter("ProcessSplitFromADCFiles WaitAll: " + filter.ToString());
            List <Batch> batches = ApiCalls.GetBatches(filter.ToString());

            if (batches.Count > 0)
            {
                Batch batch = batches.FirstOrDefault();
                if (batch != null)
                {
                    List <Branch>     branches    = ApiCalls.GetBranches();
                    List <Department> departments = ApiCalls.GetDepartments();

                    while (branches.Count == 0)
                    {
                        branches = ApiCalls.GetBranches();
                    }
                    while (departments.Count == 0)
                    {
                        departments = ApiCalls.GetDepartments();
                    }

                    Branch     branch     = branches.Where(x => x.Id == batch.BranchId).FirstOrDefault();
                    Department department = departments.Where(x => x.Id == batch.DepartmentId).FirstOrDefault();

                    XmlDocument doc     = new XmlDocument();
                    XmlNode     docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    doc.AppendChild(docNode);
                    XmlElement el                = (XmlElement)doc.AppendChild(doc.CreateElement("BatchStatusModel"));
                    DateTime   currentDate       = DateTime.Now;
                    string     currentDateString = currentDate.ToString("yyyy-MM-ddTHH:mm:ss");
                    el.AppendChild(doc.CreateElement("BranchId")).InnerText     = branch.Code;
                    el.AppendChild(doc.CreateElement("DepartmentId")).InnerText = department.Code;
                    el.AppendChild(doc.CreateElement("StageId")).InnerText      = "4";
                    el.AppendChild(doc.CreateElement("BatchKey")).InnerText     = batch.BatchKey;
                    el.AppendChild(doc.CreateElement("UserId")).InnerText       = "system";
                    el.AppendChild(doc.CreateElement("BatchNo")).InnerText      = batch.BatchNo;
                    el.AppendChild(doc.CreateElement("BatchCount")).InnerText   = batch.BatchCount.ToString();
                    el.AppendChild(doc.CreateElement("Status")).InnerText       = "0";
                    el.AppendChild(doc.CreateElement("CreatedDate")).InnerText  = batch.CreatedDate.ToString("yyyy-MM-ddTHH:mm:ss");
                    el.AppendChild(doc.CreateElement("UpdatedDate")).InnerText  = currentDateString;
                    //el.AppendChild(doc.CreateElement("CreatedBy")).InnerText = user.Id.ToString();
                    //el.AppendChild(doc.CreateElement("UpdatedBy")).InnerText = user.Id.ToString();
                    string statusFileName = ADCStatusPath + "Archive\\" + "rpt-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + batch.BatchKey + "_" + department.Code + "_" + branch.Code + ".xml";
                    doc.Save(statusFileName);
                    bool response = PostBatchStatusXMLFile(statusFileName);
                }
            }
        }
 /// <summary>
 /// Client handler constructor.
 /// </summary>
 /// <param name="client">The current <see cref="DiscordSocketClient"/>.</param>
 /// <param name="api">The API interface instance.</param>
 /// <param name="configuration">The <see cref="IConfiguration"/> object to access application settings.</param>
 /// <param name="logger">The log4net <see cref="ILog"/> instance.</param>
 public ClientHandler(DiscordSocketClient client, ApiCalls api, InteractionService interactionService, IConfiguration configuration, ILog logger = null)
 {
     Client             = client;
     Api                = api;
     InteractionService = interactionService;
     Configuration      = configuration;
     Logger             = logger;
     IsDebug            = Debugger.IsAttached;
 }
 public ChangePasswordController(bool test = false)
 {
     if (test == false)
     {
         Api = new ApiCalls();
     }
     else
     {
         Api = new ApiCallsMock();
     }
 }
Exemple #14
0
 public RegistrarUsuarioController(bool test = false)
 {
     if (test == false)
     {
         Api = new ApiCalls();
     }
     else
     {
         Api = new ApiCallsMock();
     }
 }
Exemple #15
0
        private async Task <ExportsViewModel> GetDefaultExportsViewModel()
        {
            ExportsViewModel result = new ExportsViewModel();
            await ApiCalls.PopulateFilterSection1(result);

            FilterInputs filters = new FilterInputs();
            var          schools = await ApiCalls.GetSchools();

            result.SelectedSchools = string.Join(",", schools.Select(p => p.SchoolId));
            return(result);
        }
Exemple #16
0
        private void SendNewUpdatesHandler(object sender, ElapsedEventArgs e)
        {
            var operation = new SofOperation
            {
                Plugin = "rv",
                Type   = RvOperationValue.UpdatesAndApplications,
                Api    = ApiCalls.RvUpdatesApplications()
            };

            RegisterOperation(operation);
            RunOperation(operation);
        }
        public void RemoveRoleUsingApi(string users)
        {
            if (users == "restricted_user")
            {
                users = RunData.RestrictedUserFullName;
            }

            var listOfUsers = users.ConvertStringIntoList();
            var apiCall     = new ApiCalls(RunData);

            apiCall.RemoveRolesAssignedToUsers(listOfUsers);
        }
Exemple #18
0
 public ProductoController(bool test = false)
 {
     if (test == false)
     {
         Api = new ApiCalls();
         ses = new Session();
     }
     else
     {
         Api = new ApiCallsMock();
         ses = new SessionMock();
     }
 }
        // GET: Map
        public ActionResult Index()
        {
            MapViewModel model    = new MapViewModel();
            string       userName = User.Identity.Name;

            model.results = ApiCalls.FarmersMarketApi(userName, context);

            var vendorId = context.Roles.First(r => r.Name == "Vendor").Id;
            var vendor   = context.Users.Where(u => u.Roles.Any(r => r.RoleId == vendorId)).ToList();

            model.Vendor = vendor;
            return(View(model));
        }
Exemple #20
0
 private void ddlBatches_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (ddlBatches.Items.Count > 1)
     {
         if (ddlBatches.SelectedValue.ToString() != "0")
         {
             StringBuilder filter = new StringBuilder();
             filter.Append(" 1=1");
             filter.Append(" and ID = '" + ddlBatches.SelectedValue + "'");
             List <Batch> batches = ApiCalls.GetBatches(filter.ToString());
             Batch        batch   = batches.FirstOrDefault();
             ddlStages.SelectedValue = batch.StageId;
         }
     }
 }
        public async Task <ActionResult> GetSectionsPartial(List <string> schoolIds,
                                                            //List<string> schoolYears,
                                                            //List<string> terms,
                                                            List <string> boxesAlreadyChecked,
                                                            bool getMore)
        {
            ViewData.TemplateInfo.HtmlFieldPrefix = "Sections";

            //var model = await ApiCalls.GetSections(schoolIds, schoolYears, terms, getMore);
            var model = await ApiCalls.GetSections(schoolIds, getMore);

            CheckSelectedBoxes(model.FilterCheckboxes, boxesAlreadyChecked);

            return(PartialView("_CriteriaSection", model));
        }
Exemple #22
0
        public static async Task <bool> AuthenticationCheck(this HttpRequest request)
        {
            if (!LoggingIsPaused)
            {
                ApiCalls.Add(1);
            }

            if (!request.Headers.ContainsKey(APIKEY) || !request.Headers.Values.Contains(APIVALUE))
            {
                Exception custErr = new Exception("Illegal API call attempted");
                await custErr.LogErrors("EXTENSIONS", "AuthenticationCheck");

                return(false);
            }
            return(true);
        }
        public ActionResult ShowMarkerVendor(string userId)
        {
            MapViewModel model    = new MapViewModel();
            string       userName = User.Identity.Name;

            model.results = ApiCalls.FarmersMarketApi(userName, context);
            var vendorRoleId = context.Roles.First(r => r.Name == "Vendor").Id;
            var vendorList   = context.Users.Where(u => u.Roles.Any(r => r.RoleId == vendorRoleId)).ToList();

            model.Vendor = vendorList;
            var vendor = vendorList.Where(a => a.Id == userId);

            //model.lat = lat;
            //model.lng = lng;
            return(View("Index", model));
        }
Exemple #24
0
        public MainForm()
        {
            InitializeComponent();

            List <Branch> branches = ApiCalls.GetBranches();

            branches.Insert(0, new Branch {
                Name = "Select Branch", Id = 0, Code = "0"
            });
            ddlBranches.DataSource    = branches;
            ddlBranches.DisplayMember = "Name";
            ddlBranches.ValueMember   = "Code";
            ddlBranches.SelectedValue = "0";

            List <Department> departments = ApiCalls.GetDepartments();

            departments.Insert(0, new Department {
                Name = "Select Department", Id = 0, Code = "0"
            });
            ddlDepartments.DataSource    = departments;
            ddlDepartments.DisplayMember = "Name";
            ddlDepartments.ValueMember   = "Code";
            ddlDepartments.SelectedValue = "0";

            List <Batch> batches = new List <Batch>();

            batches.Insert(0, new Batch {
                BatchNo = "Select Batch", Id = 0
            });
            ddlBatches.DataSource    = batches;
            ddlBatches.DisplayMember = "BatchNo";
            ddlBatches.ValueMember   = "Id";
            ddlBatches.SelectedValue = 0;

            List <Stage> stages = ApiCalls.GetStages();

            stages.Insert(0, new Stage {
                Name = "Select Stage", Id = 0
            });
            stages.Add(new Stage {
                Name = "Delete", Id = 9
            });
            ddlStages.DataSource    = stages;
            ddlStages.DisplayMember = "Name";
            ddlStages.ValueMember   = "Id";
            ddlStages.SelectedValue = 0;
        }
Exemple #25
0
        public bool Equals(ApiUsage input)
        {
            if (input == null)
            {
                return(false);
            }

            return
                ((
                     ApiCalls == input.ApiCalls ||
                     (ApiCalls != null && ApiCalls.SequenceEqual(input.ApiCalls))
                     ) &&
                 (
                     ThrottledRequests == input.ThrottledRequests ||
                     (ThrottledRequests != null && ThrottledRequests.SequenceEqual(input.ThrottledRequests))
                 ));
        }
Exemple #26
0
        public static async void PokemonCommand(string arg)
        {
            try
            {
                var pokemon = await ApiCalls.GetPokemon(arg);

                var species = await ApiCalls.GetSpecies(pokemon.id);

                var evolutionChain = await ApiCalls.GetEvolution(species.evolution_chain.url);

                pokemon.Afficher(species, evolutionChain);
            }
            catch
            {
                Console.WriteLine("Le pokemon " + arg + " n'existe pas.");
            }
        }
        /// <summary>
        /// Gets content as IHttpActionResult
        /// </summary>
        /// <returns>Returns IHttpActionResult task with Json string deserialized into object</returns>
        public async Task <IHttpActionResult> GetContent()
        {
            ApiCalls.InitClient();
            using (var request = new HttpRequestMessage(HttpMethod.Get, baseUri + "planetary/apod?api_key=" + ConfigurationManager.AppSettings["NasKey"]))
                using (var response = await ApiCalls._client.SendAsync(request))
                {
                    response.EnsureSuccessStatusCode();
                    var content = await response.Content.ReadAsStringAsync();

                    if (string.IsNullOrEmpty(content) || string.IsNullOrWhiteSpace(content))
                    {
                        return(NotFound());
                    }
                    var desrlzdContent = JsonConvert.DeserializeObject(content);
                    return(Ok(desrlzdContent));
                }
        }
Exemple #28
0
        public MockClientFixture()
        {
            var cannedJson       = File.ReadAllText($"{AppContext.BaseDirectory}/Data/BexarTX.json");
            var mockHttpResponse = new HttpResponseMessage
            {
                Content = new StringContent(cannedJson)
            };

            mockHttpResponse.Headers.CacheControl = new CacheControlHeaderValue {
                MaxAge = new TimeSpan(0, CacheMinutes, 0)
            };
            mockHttpResponse.Headers.Add("X-Forecast-API-Calls", ApiCalls.ToString());
            mockHttpResponse.Headers.Add("X-Response-Time", ResponseTime);

            MockClient = new Mock <IHttpClient>();
            MockClient.Setup(f => f.HttpRequest(It.IsAny <string>())).Returns(Task.FromResult(mockHttpResponse));
        }
Exemple #29
0
 public void Update(ApiUsage?other)
 {
     if (other is null)
     {
         return;
     }
     if (!ApiCalls.DeepEqualsList(other.ApiCalls))
     {
         ApiCalls = other.ApiCalls;
         OnPropertyChanged(nameof(ApiCalls));
     }
     if (!ThrottledRequests.DeepEqualsList(other.ThrottledRequests))
     {
         ThrottledRequests = other.ThrottledRequests;
         OnPropertyChanged(nameof(ThrottledRequests));
     }
 }
Exemple #30
0
        private void DeleteBtn_Click(object sender, EventArgs e)
        {
            switch (Alpha.MeetingTabSelection)
            {
            case 0:
                Delete(AgendaDgv);
                break;

            case 1:
                Delete(GoodDgv);
                break;

            case 2:
                Delete(SprintDgv);
                break;

            case 3:
                Delete(RocksDgv);
                break;

            case 4:
                Delete(HeadlinesDgv);
                break;

            case 5:
                Delete(ToDoDgv);
                break;

            case 6:
                Delete(IssuesDgv);
                break;

            case 7:
                Delete(ConclusionsDgv);
                break;

            case 8:
                Delete(ContactsDgv);
                break;

            default:
                break;
            }
            ApiCalls.Update(DgvDataCurrent(), TableNameTabselection());
        }
Exemple #31
0
        //////////////////////////////////////////
        //  Helper Methods
        //////////////////////////////////////////

        /// <summary>
        ///     Custom web request function
        /// </summary>
        /// <param name="call">Type of API Call</param>
        /// <param name="args">GET parameters</param>
        /// <returns></returns>
        public async Task<Dictionary<string, object>> MakeApiCall(ApiCalls call, Dictionary<String, String> args)
        {
            try
            {
                //Build URL
                var Params = new StringBuilder();
                foreach (var kvp in args)
                {
                    Params.AppendFormat("{0}={1}&", kvp.Key, kvp.Value);
                }

                var url = String.Format("{0}{1}{2}/?api_key={3}&{4}", Apiurl, ApiRoute, call, ApiKey, Params);
                if (url.EndsWith("&")) url = url.Remove(url.Length - 1);

                using (var client = new HttpClient())
                {
                    var resp = await client.GetAsync(url);
                    var responseText = await resp.Content.ReadAsStringAsync();
                    var responseDict = JsonConvert.DeserializeObject<Dictionary<String, Object>>(responseText);

                    if (!resp.IsSuccessStatusCode && responseDict == null) throw new Exception("Problem with response.");

                    var data = JsonConvert.DeserializeObject<Dictionary<String, Object>>(responseDict["data"].ToString());

                    if (data.ContainsKey("error_message")) throw DogeException.Generate("error from server", new Exception((String) data["error_message"]));
                    
                    return data;
                }
            }
            catch (DogeException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw DogeException.Generate("couldn't connect to server", e);
            }
        }