private static uint?FindMaxTravelID(INode myNode, PlanRequest request) { // Entries in active plan that are also in the new plan List <ConstellationPlanEntry> activeEntries = new List <ConstellationPlanEntry>(); // Entries in new plan List <ConstellationPlanEntry> newEntries = request.Plan.Entries; // IDs of entries in the new plan IEnumerable <uint?> newEntryIDs = request.Plan.Entries.Select(entry => entry.NodeID); // Fill out activeEntries foreach (ConstellationPlanEntry entry in myNode.ActivePlan.Entries) { if (newEntryIDs.Contains(entry.NodeID)) { activeEntries.Add(entry); } } // Order by ID pre-zip activeEntries = activeEntries.OrderBy(entry => entry.NodeID).ToList(); newEntries = newEntries.OrderBy(entry => entry.NodeID).ToList(); // Zip active and new entries together on NodeID including Position of them both IEnumerable <Tuple <uint?, Vector3, Vector3> > entriesZipped = Enumerable.Zip(activeEntries, newEntries, (ae, ne) => new Tuple <uint?, Vector3, Vector3>(ae.NodeID, ae.Position, ne.Position)); // Distance nodes have to travel based on active and new plan IEnumerable <Tuple <uint?, float> > travelDistanceByID = entriesZipped.Select(entry => new Tuple <uint?, float>(entry.Item1, Vector3.Distance(entry.Item2, entry.Item3))); // Find max travel distance and ID of node that has to travel that uint?maxTravelID = travelDistanceByID.OrderByDescending(x => x.Item2).First().Item1; return(maxTravelID); }
public PlanResponse Create(PlanRequest plan) { IRestRequest request = this.CreateRequest(this.Resource, Method.POST); request.AddBody(plan); return(this.ExecuteRequest <PlanResponse>(request).Data); }
public PlanResponse Update(string sPlanCode, PlanRequest plan) { IRestRequest request = this.CreateRequest(this.Resource + "/{PlanCode}", Method.PUT); request.AddUrlSegment("PlanCode", sPlanCode); request.AddBody(plan); return this.ExecuteRequest<PlanResponse>(request).Data; }
public async Task <ActionResult <PlanRequest> > PostWeightingPlan(PlanRequest weightingPlan) { _context.WeightingPlans.Add(weightingPlan); await _context.SaveChangesAsync(); return(CreatedAtAction("GetWeightingPlan", new { id = weightingPlan.Id }, weightingPlan)); }
private static void Transmit(PlanRequest request, INode myNode) { // If last location is filled, execute the plan if (request.Plan.Entries.All(x => x.NodeID != null)) { request.Command = Request.Commands.EXECUTE; request.SourceID = myNode.Id; PlanExecuter.ExecutePlan(myNode, request); } else { uint?nextSeq = myNode.Router.NextSequential(myNode, request.Dir); if (nextSeq == null) { Router.CommDir newDir = request.Dir == Router.CommDir.CW ? Router.CommDir.CCW : Router.CommDir.CW; request.Dir = newDir; nextSeq = myNode.Router.NextSequential(myNode, newDir); } request.DestinationID = nextSeq; if (myNode.Router.NetworkMap.GetEntryByID(myNode.Id).Neighbours.Contains(nextSeq)) { myNode.CommsModule.SendAsync(nextSeq, request, Constants.COMMS_TIMEOUT, Constants.COMMS_ATTEMPTS); } else { uint?nextHop = myNode.Router.NextHop(myNode.Id, nextSeq); myNode.CommsModule.SendAsync(nextHop, request, Constants.COMMS_TIMEOUT, Constants.COMMS_ATTEMPTS); } } }
public async Task TesteCriarPlano() { var body = new PlanRequest { Code = "plan103", Name = "Plano Especial", Description = "Descrição do Plano Especial", Amount = 990, Setup_Fee = 500, Max_Qty = 1, Interval = new Interval { Length = 1, Unit = "MONTH" }, Billing_Cycles = 12, Trial = new Trial { Days = 30, Enabled = true, Hold_Setup_Fee = true } }; var result = await WC.Signature.CreatePlan(body); }
/// <summary>Performs work in order to find optimum location in new constellation for given node /// <para>Recieves planrequest, finds best free location, or trades locations with other node in order to optimize net cost</para> /// </summary> public static void GeneratePlan(INode myNode, PlanRequest request) { // Remove failure detection requests in queue as we are planning to make changes to network structure anyway, which might solve the failure myNode.CommsModule.RequestList.RemoveAll(x => x.Command == Request.Commands.DETECTFAILURE); if (request.DestinationID != myNode.Id) { return; } else { myNode.ExecutingPlan = false; myNode.State = Node.NodeState.PLANNING; myNode.GeneratingPlan = request.Plan; PlanRequest newRequest = request.DeepCopy(); newRequest.AckExpected = true; if (newRequest.Plan.Entries.Any(entry => entry.NodeID == myNode.Id == false)) { List <NodeLocationMatch> matches = CalculatePositions(myNode, newRequest); ConstellationPlan newPlan = ProcessPlan(matches, newRequest, myNode); newRequest.Plan = newPlan; } Transmit(newRequest, myNode); } }
private static List <NodeLocationMatch> CalculatePositions(INode myNode, PlanRequest Request) { List <NodeLocationMatch> matches = new List <NodeLocationMatch>(); List <NetworkMapEntry> ReachableSats = myNode.Router.NetworkMap.Entries .Where(entry => myNode.Router.ReachableSats(myNode).Contains(entry.ID)).ToList(); foreach (NetworkMapEntry node in ReachableSats) { if (node.ID == myNode.Id || Request.Plan.Entries.Any(entry => entry.NodeID == node.ID)) { continue; } //Find all locations List <Vector3> OrderedPositions = Request.Plan.Entries .Where(entry => entry.NodeID == null) .Select(entry => entry.Position).ToList(); //Find closest location for given node OrderedPositions = OrderedPositions.OrderBy(position => Vector3.Distance(node.Position, position)).ToList(); //Save node-location match matches.Add(new NodeLocationMatch(node.ID, OrderedPositions.First(), Vector3.Distance(node.Position, OrderedPositions.First()))); } return(matches); }
public static void ExcludeNode(INode myNode, DetectFailureRequest request) { ConstellationPlan RecoveryPlan = GenerateConstellation.GenerateTargetConstellation(myNode.Router.ReachableSats(myNode).Count, 7.152f); PlanRequest recoveryRequest = new PlanRequest { SourceID = myNode.Id, DestinationID = myNode.Id, Command = Request.Commands.GENERATE, Plan = RecoveryPlan, Dir = Router.CommDir.CW }; NetworkUpdateRequest updateRequest = new NetworkUpdateRequest(new List <uint?>() { request.NodeToCheck }); recoveryRequest.DependencyRequests.Add(updateRequest); if (myNode.Router.NextSequential(myNode, Router.CommDir.CW) == null) { recoveryRequest.Dir = Router.CommDir.CCW; } PlanGenerator.GeneratePlan(myNode, recoveryRequest); }
public async Task <IActionResult> PutWeightingPlan(int id, PlanRequest weightingPlan) { if (id != weightingPlan.Id) { return(BadRequest()); } _context.Entry(weightingPlan).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WeightingPlanExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public PlanResponse Update(string sPlanCode, PlanRequest plan) { IRestRequest request = this.CreateRequest(this.Resource + "/{PlanCode}", Method.PUT); request.AddUrlSegment("PlanCode", sPlanCode); request.AddBody(plan); return(this.ExecuteRequest <PlanResponse>(request).Data); }
public async Task <string> CreateProductAsync(PlanRequest plan) { HttpResponseMessage response = await client.PostAsJsonAsync("api/plans", plan); response.EnsureSuccessStatusCode(); // return URI of the created resource. return(response.StatusCode.ToString()); }
// PlanController Operations public async Task <JsonResponse> AddPlan() { var user = await GetUser(); var request = new PlanRequest { userId = user.user.UserId, date = DateTime.Today.AddDays(1), meal = "Breakfast", recipe = TestKeys.RamenNoodle, servingsYield = 4 }; return(await _planCtrl.Post(request)); }
/// <summary> /// Alterar Plano - Change Plan /// </summary> /// <param name="body"></param> /// <param name="code"> Código do plano </param> /// <returns></returns> public async Task <HttpStatusCode> ChangePlan(PlanRequest body, string code) { StringContent stringContent = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"); HttpResponseMessage response = await Http_Client.HttpClient.PutAsync($"assinaturas/v1/plans/{code}", stringContent); if (!response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); WirecardException.WirecardError wirecardException = WirecardException.DeserializeObject(content); throw new WirecardException(wirecardException, "HTTP Response Not Success", content, (int)response.StatusCode); } return(response.StatusCode); }
public static void ExecutePlan(INode myNode, PlanRequest request) { if (request.DestinationID != myNode.Id) { return; } else { myNode.State = Node.NodeState.EXECUTING; if (myNode.ExecutingPlan) { myNode.State = Node.NodeState.PASSIVE; return; // Ignore Execute command if already executing which stops the execute communication loop } else { myNode.ExecutingPlan = true; } if (request.SourceID != myNode.Router.NextSequential(myNode, request.Dir)) { ForwardRequest(myNode, request); } Thread.Sleep(Constants.COMMS_TIMEOUT / Constants.TimeScale); //Set my targetposition to the position i was assigned in the plan myNode.TargetPosition = request.Plan.Entries.Find(entry => entry.NodeID == myNode.Id).Position; uint?maxTravelID = FindMaxTravelID(myNode, request); // If the found ID is this node's, then discovery should be started when the node is at its new location. if (maxTravelID == myNode.Id) { DiscoveryIfNewNeighboursAfterExecuting(myNode); } myNode.ActivePlan = request.Plan; myNode.Router.ClearNetworkMap(); myNode.Router.UpdateNetworkMap(request.Plan); Thread.Sleep(Constants.ONE_SECOND_IN_MILLISECONDS / Constants.TimeScale); myNode.State = Node.NodeState.PASSIVE; } }
public async Task <IActionResult> CreateEmployee([FromBody] PlanRequest request) { if (request == null) { return(NotFound()); } var plan = _mapper.Map <Plan>(request); var result = await _planService.Create(plan); if (result == null) { return(NotFound()); } return(Ok(plan)); }
public static void Recovery(INode myNode, uint?secondFailedNode) { //Remove edge from router, ensuring it won't try to route through the failed node myNode.Router.DeleteEdge(myNode.Id, secondFailedNode); // Find positions of nodes this node can reach List <Vector3> positions = new List <Vector3> { myNode.Position }; List <uint?> nodesToVisit = new List <uint?> { myNode.Id }; while (nodesToVisit.Count > 0) { uint?nodeToVisit = nodesToVisit[0]; nodesToVisit.RemoveAt(0); List <NetworkMapEntry> neighbourEntries = myNode.Router.NetworkMap.GetEntryByID(nodeToVisit).Neighbours.Select(x => myNode.Router.NetworkMap.GetEntryByID(x)).ToList(); nodesToVisit.AddRange(neighbourEntries.Where(x => positions.Contains(x.Position) == false).Select(x => x.ID)); positions.AddRange(neighbourEntries.Where(x => positions.Contains(x.Position) == false).Select(x => x.Position)); } // Calculate midpoint Vector3 midpoint = positions.Aggregate(Vector3.Zero, (x, y) => x + y); Vector3 midpointOnRightAltitude = Vector3.Normalize(midpoint) * Vector3.Distance(Vector3.Zero, myNode.Position); // Generate recovery plan and start planning ConstellationPlan recoveryPlan = GenerateConstellation.GenerateRecoveryConstellation(midpointOnRightAltitude, positions.Count); PlanRequest recoveryRequest = new PlanRequest { SourceID = myNode.Id, DestinationID = myNode.Id, Command = Request.Commands.GENERATE, Plan = recoveryPlan, }; NetworkUpdateRequest updateRequest = new NetworkUpdateRequest(new NetworkUpdateRequest(new List <uint?>() { secondFailedNode })); recoveryRequest.DependencyRequests.Add(updateRequest); myNode.Router.NetworkMap.Entries.RemoveAll(entry => entry.ID == secondFailedNode); myNode.CommsModule.Send(myNode.Id, recoveryRequest); }
/// <summary> /// Post plan to DB /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task <PlanSingleResponse> PostPlanAsync(PlanRequest model) { var formKeyValuesList = new List <FormKeyValue>() { new StringFormKeyValue("Title", model.Title), new StringFormKeyValue("Description", model.Description), }; if (model.CoverFile != null) { formKeyValuesList.Add(new FileFormKeyValue("CoverFile", model.CoverFile, model.FileName)); } var response = await base._client.SendFormProtectedAsync <PlanSingleResponse>($"{base._baseURL}/api/plans", ActionType.POST, formKeyValuesList.ToArray()); return(response.Result); }
private Safe2Pay_Request(Config config) { this.config = config; client = new Client(config); Account = new AccountRequest(this.config); Carnet = new CarnetRequest(this.config); Invoice = new InvoiceRequest(this.config); Marketplace = new MarketplaceRequest(this.config); Payment = new CheckoutRequest(this.config); Plan = new PlanRequest(this.config); Subscription = new SubscriptionRequest(this.config); Token = new TokenRequest(this.config); Transfer = new TransferRequest(this.config); Transaction = new TransactionRequest(this.config); AdvancePayment = new AdvancePaymentRequest(this.config); }
private static void ForwardRequest(INode myNode, PlanRequest request) { PlanRequest newRequest = request.DeepCopy(); uint? nextSeq = myNode.Router.NextSequential(myNode, newRequest.Dir); if (nextSeq == null) { newRequest.Dir = newRequest.Dir == Router.CommDir.CW ? Router.CommDir.CCW : Router.CommDir.CW; nextSeq = myNode.Router.NextSequential(myNode, newRequest.Dir); } if (nextSeq != null) { newRequest.SenderID = myNode.Id; newRequest.DestinationID = nextSeq; uint?nextHop = myNode.Router.NextHop(myNode.Id, nextSeq); myNode.CommsModule.SendAsync(nextHop, newRequest, Constants.COMMS_TIMEOUT, Constants.COMMS_ATTEMPTS); } }
private static void Recover(INode myNode) { ConstellationPlan recoveryPlan = GenerateConstellation.GenerateTargetConstellation(myNode.Router.ReachableSats(myNode).Count, 7.152f); PlanRequest recoveryRequest = new PlanRequest { SourceID = myNode.Id, DestinationID = myNode.Id, Command = Request.Commands.GENERATE, Plan = recoveryPlan }; if (myNode.Router.NextSequential(myNode, Router.CommDir.CW) == null) { recoveryRequest.Dir = Router.CommDir.CCW; } myNode.CommsModule.Send(myNode.Id, recoveryRequest); }
public async Task <PlanResponse> criarPlano(string code, string name, string description, int amount) { Wirecard.WirecardClient WC = null; WC = await SetAmbiente(WC); try { var newPlan = new PlanRequest() { Code = code, Name = name, Description = description, Amount = amount, Interval = new Interval() { Unit = (code.Contains("year") ? "YEAR":"MONTH"), Length = 1 }, Payment_Method = "CREDIT_CARD" }; var plan = await WC.Signature.CreatePlan(newPlan); var planNew = new PlanResponse() { Code = code, Name = name, Description = description, Amount = amount, Payment_Method = "CREDIT_CARD" }; var repMongo = new Repository.MongoRep("", _settings, ""); await repMongo.GravarOne <PlanResponse>(planNew); return(plan); } catch (Exception ex) { return(null); } }
/// <summary> /// Criar plano - Create plan /// </summary> /// <returns></returns> public async Task <PlanResponse> CreatePlan(PlanRequest body) { StringContent stringContent = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"); HttpResponseMessage response = await Http_Client.HttpClient.PostAsync($"assinaturas/v1/plans", stringContent); if (!response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); WirecardException.WirecardError wirecardException = WirecardException.DeserializeObject(content); throw new WirecardException(wirecardException, "HTTP Response Not Success", content, (int)response.StatusCode); } try { return(JsonConvert.DeserializeObject <PlanResponse>(await response.Content.ReadAsStringAsync())); } catch (System.Exception ex) { throw ex; } }
public async Task <PlanSingleResponse> PostPlanAsync(PlanRequest planRequest) { httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken); var multiForm = new MultipartFormDataContent() { { new StringContent(planRequest.Title), "Title" }, { new StringContent(planRequest.Description), "Description" }, }; if (planRequest.CoverFile != null) { multiForm.Add(new StreamContent(planRequest.CoverFile), "CoverFile", planRequest.FileName); } var response = await httpClient.PostAsync(_baseUrl + "/api/plans", multiForm); var responseAsString = await response.Content.ReadAsStringAsync(); PlanSingleResponse planSingleResponse = JsonSerializer.Deserialize <PlanSingleResponse>(responseAsString, serializerOptions); return(planSingleResponse); }
private void SaveModal(string plan_name) { GetAllObjectOnArea(); Plan planToSave = PlanManager.instance.currentPlan; planToSave.user_id = UserManager.instance.user.id; planToSave.plan_name = plan_name; //GameObject[] tmp = GameObject.Find("Area").GetComponentsInParent<GameObject>(); PlanRequest plan = new PlanRequest { plan_details = new ItemData[planToSave.details.Count], name = plan_name //testing = ("yes im saving") }; Debug.Log("Plan name? = " + plan.name + " plan_details.count = " + plan.plan_details.Count()); int i = 0; foreach (Application.Models.PlanDetails det in planToSave.details) { plan.plan_details[i] = det.ToItemData(); Debug.Log("Processing the " + plan.plan_details[i].ItemMisc); i++; } //planToSave.testing = Application.Models.PlanDetails.ToItemData(); StartCoroutine(HttpManager.instance.plans.Save(HttpManager.instance.token, (string json) => { UnityEngine.Debug.Log(json); CancelOnClick(); }, (string error) => { Debug.Log("Save Error = " + error); CancelOnClick(); }, plan)); }
private static ConstellationPlan ProcessPlan(List <NodeLocationMatch> matches, PlanRequest request, INode myNode) { //Find entries not taken by other nodes List <ConstellationPlanEntry> FreeEntries = request.Plan.Entries .Where(entry => entry.NodeID == null && matches.Select(match => match.Position) //Select positions from matches .Contains(entry.Position) == false).ToList(); //Order by distance to my node FreeEntries.OrderBy(entry => Vector3.Distance(myNode.Position, entry.Position)); //Lowest distance is my best entry. ConstellationPlanEntry bestEntry = FreeEntries.First(); bestEntry = request.Plan.Entries.Find(entry => entry.Position == bestEntry.Position); //Take the location in the plan bestEntry.NodeID = myNode.Id; bestEntry.Fields["DeltaV"].Value = Vector3.Distance(bestEntry.Position, myNode.Position); myNode.GeneratingPlan = request.Plan; //Return the plan return(request.Plan); }
public PlanRequest(PlanRequest other) : base(other) { Plan = other.Plan.DeepCopy(); }
public PlanResponse Create(PlanRequest plan) { IRestRequest request = this.CreateRequest(this.Resource, Method.POST); request.AddBody(plan); return this.ExecuteRequest<PlanResponse>(request).Data; }
public async Task <IActionResult> Put([FromForm] PlanRequest model) { string userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; string url = $"{_configuration["AppUrl"]}Images/default.jpg"; string fullPath = null; // Check the file if (model.CoverFile != null) { string extension = Path.GetExtension(model.CoverFile.FileName); if (!allowedExtensions.Contains(extension)) { return(BadRequest(new OperationResponse <Plan> { Message = "Plan image is not a valid image file", IsSuccess = false, })); } if (model.CoverFile.Length > 500000) { return(BadRequest(new OperationResponse <Plan> { Message = "Image file cannot be more than 5mb", IsSuccess = false, })); } string newFileName = $"Images/{Guid.NewGuid()}{extension}"; fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", newFileName); url = $"{_configuration["AppUrl"]}{newFileName}"; } var oldPlan = await _plansService.GetPlanById(model.Id, userId); if (fullPath == null) { url = oldPlan.CoverPath; } var editedPlan = await _plansService.EditPlanAsync(model.Id, model.Title, model.Description, url, userId); if (editedPlan != null) { if (fullPath != null) { using (var fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) { await model.CoverFile.CopyToAsync(fs); } } return(Ok(new OperationResponse <Plan> { IsSuccess = true, Message = $"{editedPlan.Title} has been edited successfully!", Record = editedPlan })); } return(BadRequest(new OperationResponse <Plan> { Message = "Something went wrong", IsSuccess = false })); }
public async Task <Plan> CreatePlan(PlanRequest createPlanRequest) { return(await SendRequest <Plan>(HttpMethod.Post, PLANS_PATH, createPlanRequest)); }
public IEnumerator Save(String token, OnRequestComplete complete, OnRequestError error, PlanRequest plan) { string url = routes.Single(u => u.Key == "plans").Value; Debug.Log("plan name in kHttp = " + plan.name); Debug.Log("Plan ToJson = " + JsonUtility.ToJson(plan)); Debug.Log("URL is = " + url); UnityWebRequest request = UnityWebRequest.Put(url, JsonUtility.ToJson(plan)); request.SetRequestHeader("Accept", "application/json"); request.SetRequestHeader("Content-Type", "application/json"); request.SetRequestHeader("Authorization", "Bearer " + token); request.method = UnityWebRequest.kHttpVerbPOST; yield return(request.SendWebRequest()); if (request.isNetworkError || request.isHttpError) { Debug.Log("GOT A HTTP isHttpError = " + request.isHttpError); Debug.Log("GOT A HTTP isNetworkError = " + request.isNetworkError); error(request.error); } else { String json = request.downloadHandler.text; complete(json); } }
public async Task <IActionResult> Put([FromForm] PlanRequest plan) { string userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; string url = $"{_configuration["AppUrl"]}Images/DefaultPlan.jpg"; string fullPath = null; if (plan.CoverFile != null) { string extension = Path.GetExtension(plan.CoverFile.FileName); if (!allowedExtensions.Contains(extension)) { return(BadRequest(new OperationResponse <string> { IsSuccess = false, Message = "Image type not supported", })); } if (plan.CoverFile.Length > 500000) { return(BadRequest(new OperationResponse <string> { IsSuccess = false, Message = "Image size cannot be bigger than 5MB", })); } string newFileName = $"Images/{Guid.NewGuid()}{extension}"; fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", newFileName); url = $"{_configuration["AppUrl"]}{newFileName}"; } var oldPlan = await _planService.GetPlanByIdAsync(plan.Id, userId); if (fullPath == null) { url = oldPlan.CoverPath; } var editedPlan = await _planService.EditPlanAsync(plan.Id, plan.Title, plan.Description, url, userId); if (editedPlan != null) { if (fullPath != null) { using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) { await plan.CoverFile.CopyToAsync(fileStream); } } return(Ok(new OperationResponse <Plan> { IsSuccess = true, Message = $"{editedPlan.Title} has been added successfully", OperationDate = DateTime.UtcNow, Record = editedPlan, })); } return(BadRequest(new OperationResponse <string> { IsSuccess = false, Message = "Adding plan failed", })); }