Example #1
0
        public static void SkipMonths(string path, bool clearErrors = false)
        {
            var loop = new LoopManager <Location_CodeOnly>(
                path,
                PATH_LOGGING + "SetupSkipMonthsFinished.txt",
                PATH_LOGGING + "SetupSkipMonthsErrored.txt",
                l => l.Location.ToString(),
                clearErrors
                );
            var skipFields = Enumerable.Range(1, 12).Select(m => "Skip" + m.ToString()).ToArray();

            loop.EndLoop(
                Parallel.ForEach(
                    loop.Updates,
                    PARALLEL_OPTS,
                    location =>
            {
                try
                {
                    int locID   = Postman.GetLocationIDFromCode(location.Location);
                    var setupID = Postman.GetLocationServiceSetup(locID, s => s.ServiceCode == "MONTHLY MOSQ").SetupID.Value.ToString();
                    PPWebLib.PestPac.EditServiceSetup(setupID, null, skipFields);
                    loop.LogUpdate(location.Location.ToString(), setupID);
                }
                catch (Exception e)
                {
                    loop.LogUpdate(location.Location, e.Message, UpdateType.Error);
                }
            }
                    ),
                false
                );
        }
        private IEnumerator PopulateRecipesRoutine()
        {
            ClearExistingRecipes();

            loadingText.text = "Loading...";

            UnityWebRequest request = Postman.CreateGetRequest(Endpoints.instance.RECIPES());

            yield return(request.SendWebRequest());

            string response = request.downloadHandler.text;

            JSONNode json = JSON.Parse(response);

            foreach (JSONNode recipe in json)
            {
                RecipeEntry entry = Instantiate(recipeEntryPrefab.gameObject, scrollViewContent).GetComponent <RecipeEntry>();
                entry.SetIngredients(recipe["ingredients"].AsArray);
                entry.SetParentDialog(this);
                entry.SetRecipeText(recipe["name"]);
                entry.SetSteps(recipe["steps"].AsArray);
            }

            loadingText.text = "";
        }
Example #3
0
        public object Any(Postman request)
        {
            var feature = HostContext.GetPlugin <PostmanFeature>();

            if (request.ExportSession)
            {
                if (feature.EnableSessionExport != true)
                {
                    throw new ArgumentException("PostmanFeature.EnableSessionExport is not enabled");
                }

                var url = Request.GetBaseUrl()
                          .CombineWith(Request.PathInfo)
                          .AddQueryParam("ssopt", Request.GetItemOrCookie(SessionFeature.SessionOptionsKey))
                          .AddQueryParam("sspid", Request.GetPermanentSessionId())
                          .AddQueryParam("ssid", Request.GetTemporarySessionId());

                return(HttpResult.Redirect(url));
            }

            var id  = SessionExtensions.CreateRandomSessionId();
            var ret = new PostmanCollection
            {
                info = new PostmanCollectionInfo()
                {
                    version = "1",
                    name    = HostContext.AppHost.ServiceName,
                    schema  = "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
                },
                item = GetRequests(request, id, HostContext.Metadata.OperationsMap.Values),
            };

            return(ret);
        }
Example #4
0
        private void Receive()
        {
            try
            {
                NetworkStream netStream = new NetworkStream(this.ReceiveSocket);
                while (true)
                {
                    Postman postman = Postman.GetPackage(netStream);
                    RenderForm();
                    switch (postman.Type)
                    {
                    case Postman.PostmanType.SEND_KEY:
                        this.OtherMysterio.PubKey = Mysterio.ConvertBytesToKey(postman.Payload);
                        break;

                    case Postman.PostmanType.SEND_MESSAGE:
                        string plainText = Mysterio.Decrypt(this.MyMysterio.PriKey, postman.Payload);
                        ThreadHelper.AppendMessages(this, txtMessages, DateTime.Now.ToString("MM/dd/yyyy h:mm:ss tt\t") + plainText, false);
                        break;
                    }
                    AddEvent(postman.Type.ToString(), Encoding.Unicode.GetString(postman.Payload));
                }
            }catch (Exception e)
            {
                //MessageBox.Show(e.Message);
                Stop();
            }
        }
        private IEnumerator RemoveRoutine()
        {
            ConfirmDialog dialog = FindObjectOfType <ConfirmDialog>();

            dialog.ApplyColours();
            dialog.Show();
            dialog.SetInfoMessage("Remove '<b>" + nameText.text + "</b>'?");
            dialog.SetNone();

            while (dialog.IsNone())
            {
                yield return(null);
            }

            if (dialog.IsNo() || dialog.IsCancel())
            {
                dialog.Hide();
                yield break;
            }

            if (dialog.IsYes())
            {
                dialog.Hide();

                string          url     = string.Format("{0}/{1}/close", Endpoints.instance.TODOIST_TASKS(), taskId);
                UnityWebRequest request = Postman.CreatePostRequest(url, new JSONObject());
                request.SetRequestHeader("Authorization", "Bearer " + apiKey);
                yield return(request.SendWebRequest());

                Destroy(this.gameObject);
            }
        }
Example #6
0
        public string GetName(PostmanFeature feature, Postman request, Type requestType, string virtualPath)
        {
            var fragments = request.Label ?? feature.DefaultLabelFmt;
            var sb        = StringBuilderCache.Allocate();

            foreach (var fragment in fragments)
            {
                var parts     = fragment.ToLower().Split(':');
                var asEnglish = parts.Length > 1 && parts[1] == "english";

                if (parts[0] == "type")
                {
                    sb.Append(asEnglish ? requestType.Name.ToEnglish() : requestType.Name);
                }
                else if (parts[0] == "route")
                {
                    sb.Append(virtualPath);
                }
                else
                {
                    sb.Append(parts[0]);
                }
            }
            return(StringBuilderCache.ReturnAndFree(sb));
        }
        void Send()
        {
            NetworkStream networkStream = new NetworkStream(this.ReceiveSocket);

            while (true)
            {
                string  str     = Console.ReadLine();
                Postman postMan = new Postman();

                switch (str.ToUpper())
                {
                case "SEND_KEY":
                    postMan.Type    = Postman.PostmanType.SEND_KEY;
                    postMan.Payload = Mysterio.ConvertKeyToBytes(this.ServerMysterio.PubKey);
                    break;

                default:
                    postMan.Type    = Postman.PostmanType.SEND_MESSAGE;
                    postMan.Payload = Mysterio.Encrypt(this.ClientMysterio.PubKey, str);
                    break;
                }

                Postman.SendPackage(networkStream, postMan);
                if (str.ToUpper().Equals("QUIT"))
                {
                    break;
                }
            }

            networkStream.Close();
        }
Example #8
0
        public void Setup()
        {
            inputQueueFormatName   = Queues.TryCreate(inputQueuePath, QueueTransactional.None);
            adminQueueFormatName   = Queues.TryCreate(adminQueuePath, QueueTransactional.None);
            outputQueueFormatName1 = Queues.TryCreate(outputQueuePath1, QueueTransactional.None);
            outputQueueFormatName2 = Queues.TryCreate(outputQueuePath2, QueueTransactional.None);
            deadQueueFormatName    = $"{inputQueueFormatName };Poison";

            Queues.Purge(inputQueueFormatName);
            Queues.Purge(adminQueueFormatName);

            input = new QueueWriter(inputQueueFormatName);

            dead = new QueueReader(deadQueueFormatName);
            dead.Purge();

            outRead1 = new QueueReader(outputQueueFormatName1);
            outRead1.Purge();

            outRead2 = new QueueReader(outputQueueFormatName2);
            outRead2.Purge();

            outSend1 = new QueueWriter(outputQueueFormatName1);
            outSend2 = new QueueWriter(outputQueueFormatName2);

            sender = new Postman(adminQueueFormatName);
        }
Example #9
0
        public static LocationModel SendPOST(Lead customer)
        {
            LocationInputModel location = new LocationInputModel();

            location.Branch = customer.location.name.Substring(8);

            string[] names = Postman.ExtractMatches(PPRGX.NAMES.Match(customer.name));
            location.FirstName = names[0];
            location.LastName  = names[1];

            string[] locinfo = Postman.ExtractMatches(Regex.Match(customer.address, ModifiedLocInfoPat));
            location.State   = stateAbbrvs[locinfo[2]];
            location.Address = locinfo[0];
            location.City    = locinfo[1];
            location.Zip     = locinfo[3];
            location.TaxCode = PestPacGeoCoding.GetTaxCode(new Params(locinfo[0], locinfo[1], location.State, locinfo[3]));

            location.Phone       = customer.phone;
            location.EMail       = customer.email;
            location.EnteredDate = customer.created_at;

            location.UserDefinedFields = new List <UserDefinedField>()
            {
                new UserDefinedField("# Services", customer.services.ToString())
            };

            names   = null;
            locinfo = null;

            return(client.CreateLocation(location));
        }
        void Receive()
        {
            NetworkStream networkStream = new NetworkStream(ReceiveSocket);

            while (true)
            {
                Postman postMan = Postman.GetPackage(networkStream);
                Console.WriteLine(postMan);
                switch (postMan.Type)
                {
                case Postman.PostmanType.SEND_KEY:
                    this.ClientMysterio.PubKey = Mysterio.ConvertBytesToKey(postMan.Payload);
                    break;

                case Postman.PostmanType.SEND_MESSAGE:
                    string plainText = Mysterio.Decrypt(this.ServerMysterio.PriKey, postMan.Payload);
                    Console.WriteLine(plainText);
                    break;
                }
                if (postMan.Type == Postman.PostmanType.DISCONNECT)
                {
                    break;
                }
            }
            networkStream.Close();
        }
Example #11
0
        } // AddNewSubscription

        // добавить почтальона
        public async Task AddNewPostman(string surname, string name, string patronymic, string[] plots)
        {
            using (var ctx = new PostOfficeDbContext())
            {
                Person person = new Person
                {
                    Surname    = surname,
                    Name       = name,
                    Patronymic = patronymic
                };
                await Task.Run(() => ctx.People.Add(person));

                Postman postman = new Postman
                {
                    PersonId = person.Id
                };

                await Task.Run(() => ctx.Postmen.Add(postman));

                foreach (var plot in plots)
                {
                    await Task.Run(() => ctx.Plots
                                   .Where(p => p.PlotNumber == plot)
                                   .ForEachAsync(p => p.PostmanId = postman.Id));
                }

                ctx.SaveChanges();
            } // using

            ShowAllPostmen();
        } // AddNewPostman
Example #12
0
        private IEnumerator RequestRecipeRoutine()
        {
            configKey = FindObjectOfType <FoodPlanner>().GetWidgetConfigKey();
            config    = Config.instance.GetWidgetConfig();
            plannerId = config[configKey]["plannerId"];

            string label = "";

            foreach (char c in day.ToString().Substring(0, 3).ToUpper())
            {
                label += c + "\n";
            }

            dayText.text = label;
            recipe.text  = "Loading...";

            UnityWebRequest request = Postman.CreateGetRequest(Endpoints.instance.PLANNER(day.ToString()));

            yield return(request.SendWebRequest());

            bool ok = request.error == null ? true : false;

            if (!ok)
            {
                WidgetLogger.instance.Log("Error: " + (string)JSON.Parse(request.downloadHandler.text)["message"]);
                yield break;
            }

            recipe.text = (string)JSON.Parse(request.downloadHandler.text)["recipe"];
        }
Example #13
0
        public void Compare_Repos_July_vs_Today(string owner)
        {
            NotificationBuilder         nbuilder        = new NotificationBuilder();
            NotificationChannelsBuilder channelsBuilder = new NotificationChannelsBuilder().UseSmtpPickupDirectory(@"c:\work").UseSmtpPickupDirectory(@"c:\work2\send");

            List <RepositoryEvent> Events = new List <RepositoryEvent>();
            ITableSnapshotBuilder  builder;

            builder = RepositoryListSnapshotBuilder.CreateInMemorySnapshotFromRequest(Resources.GetRepositoryResponse(owner, RepositoryResponseGeneration.July));
            ITableSnapshot microsoftSnapshotJuly = builder.Build();

            builder = RepositoryListSnapshotBuilder.CreateInMemorySnapshotFromRequest(this.Extractor.GetMetadataAsynch(this.Token, owner).Result);
            ITableSnapshot microsoftSnapshotToday = builder.Build();

            TableDiffByLookup differ = new TableDiffByLookup(microsoftSnapshotJuly, microsoftSnapshotToday);


            differ.DifferencesDelegate = (deletedRecord, inserted) =>
            {
                EventType   et       = EventType.Created;
                IDataRecord template = inserted;
                if ((deletedRecord != null) && (inserted != null))
                {
                    et       = EventType.Modified;
                    template = inserted;
                }

                if ((deletedRecord != null) && (inserted == null))
                {
                    et       = EventType.Deleted;
                    template = deletedRecord;
                    //RepositoryTableSnapshot.CreatedAtFieldName
                }

                RepositoryEvent ev = EventFactory.CreateRepositoryEvent(template, et);
                nbuilder.AddEvent(ev);
            };
            differ.Execute();
            //Assert.Equal(1312, differ.OldSnapshotRecordCount);

            //create Notification
            //Deliver Notification

            nbuilder.AddChannels(channelsBuilder);

            List <Notification> toSend = new List <Notification>();

            for (int i = 0; i < 5; i++)
            {
                Notification noti = nbuilder.Build();
                noti.From = new NotificationAddress()
                {
                    Identifier = "*****@*****.**"
                };
                noti.To = new NotificationAddress[] { noti.From };
                toSend.Add(noti);
            }

            Postman.DeliverNotification(toSend);
        }
Example #14
0
        } // AddNewPostman

        // увольнение почтальона
        public async Task LayOffPostman(string surname, string name, string patronymic)
        {
            using (var ctx = new PostOfficeDbContext())
            {
                Postman postman = ctx.Postmen
                                  .First(p => p.Person.Surname == surname &&
                                         p.Person.Name == name &&
                                         p.Person.Patronymic == patronymic);
                List <Postman> postmen = ctx.Postmen
                                         .Where(p => p.Id != postman.Id)
                                         .ToList();
                await Task.Run(() => ctx.Plots
                               .Where(p => p.PostmanId == postman.Id)
                               .ForEachAsync(p => p.PostmanId = postmen[Utils.GetRand(0, postmen.Count - 1)].Id));

                await Task.Run(() => ctx.Postmen
                               .Remove(postman));

                Person person = ctx.People.First(p => p.Surname == surname &&
                                                 p.Name == name &&
                                                 p.Patronymic == patronymic);
                await Task.Run(() => ctx.People.Remove(person));

                ctx.SaveChanges();
            } // using

            ListPostmen();
            ShowAllPostmen();
        } // LayOffPostman
Example #15
0
        public IEnumerator AddItemRoutine(string item)
        {
            string uuid = System.Guid.NewGuid().ToString();
            string body = JsonBody.TodoistTask(item, projectId);

            UnityWebRequest request = Postman.CreatePostRequest(Endpoints.instance.TODOIST_TASKS(), body);

            request.SetRequestHeader("Authorization", "Bearer " + apiKey);
            request.SetRequestHeader("X-Request-Id", uuid);
            yield return(request.SendWebRequest());

            bool ok = request.error == null ? true : false;

            if (!ok)
            {
                WidgetLogger.instance.Log("<b>" + listType.ToString() + " List</b>: Could not add item (" + item + "): " + request.downloadHandler.text);
                itemsNotUploaded.Add(item);

                // Todoist is flaky, and to avoid messing up category order, try again immediately
                if (request.responseCode == 500)
                {
                    yield return(AddItemRoutine(item));
                }
            }
            else if (itemsNotUploaded.Contains(item))
            {
                itemsNotUploaded.Remove(item);
            }

            addDialog.SetStatusText(string.Format("'{0}' uploaded!", item));
        }
Example #16
0
        public static void PostServiceOrders(string path)
        {
            Console.Write("Enter the number of the batch you want to post to: ");
            int batchNum = Convert.ToInt32(Console.ReadLine().Trim());
            var loop     = new LoopManager <PostedOrder>(
                path,
                "FinishedPostedOrders.txt",
                "ErroredPostedOrders.txt",
                o => o.OrderID
                );

            loop.EndLoop(
                Parallel.ForEach(
                    loop.Updates, LoopManager.PARALLEL_OPTS, postedOrder =>
            {
                try
                {
                    var responseCode = Postman.PostServiceOrder(postedOrder.OrderID, postedOrder.Tech, batchNum);
                    if (responseCode.IsOK())
                    {
                        loop.LogUpdate(postedOrder.OrderID, "OK", UpdateType.Finished);
                    }
                    else
                    {
                        loop.LogUpdate(postedOrder.OrderID, responseCode.ToString(), UpdateType.Error);
                    }
                }
                catch (Exception e)
                {
                    loop.LogUpdate(postedOrder.OrderID, e.Message, UpdateType.Error);
                }
            }
                    )
                );
        }
Example #17
0
        public Control(dbBind db, string username, string host, string password, string popAdress, string port, string smtpAdress, string smtpPort)
        {
            this.db = db;
            analyzer = new Analyzer(db, 60, 1); //антипаттерн
            analyzer.log += Program.MainForm.log;

            this.postman = new Postman("Вопрос_", db, username, host, password, popAdress, Convert.ToInt32(port), smtpAdress, Convert.ToInt32(smtpPort), messageControl, Program.MainForm.log, mailTimer);
        }
Example #18
0
        public ActionResult SendEmail(Hashtable Params, Hashtable FormData)
        {
            Postman.Send("*****@*****.**", Params["receiver"].ToString(), Params["subject"].ToString(), Params["message"].ToString(), null);

            //"Orçamento solicitado no site " + company.LegalEntityProfile.Website,
            //mailBody, new[] { addressFileToAttach });
            return(View());
        }
Example #19
0
        public void fred()
        {
            QueueWriter q   = null;
            Message     msg = null;
            Postman     pm  = null;

            q.Deliver(msg, pm);
        }
Example #20
0
 static void Main(string[] args)
 {
     Postman.EmailFrom("*****@*****.**")
     .To("*****@*****.**", "*****@*****.**")
     .CC("*****@*****.**")
     .WithSubject("Testing postman on facade")
     .WithBody("<h1>HELLO MUNDO!</h1>")
     .Attachments("C:\\somefile.txt")
     .Deliver();
 }
Example #21
0
 /// <summary>
 /// This method sends an email to customer, case the status of Service Order
 /// was changed to success
 /// </summary>
 /// <param name="originalServiceOrder"></param>
 private void SendEmailToCustomer(ServiceOrder originalServiceOrder)
 {
     if (originalServiceOrder.Customer.UserId.HasValue)
     {
         Postman.Send("*****@*****.**", originalServiceOrder.Customer.User.UserName, "Ordem de serviço atendida",
                      String.Format(@"Ordem de serviço de número: {0} criada no dia {1}, foi atendida e concluída !!
                                 <br/><br/> <a href='{2}'>Clique aqui para gerar sua nota fiscal!</a>", originalServiceOrder.ServiceOrderNumber,
                                    originalServiceOrder.OpenedDate, originalServiceOrder.Company.LegalEntityProfile.Website), null);
     }
 }
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            await Postman.DisposeAsync().ConfigureAwait(false);

            await base.StopAsync(cancellationToken).ConfigureAwait(false);

            await ConfigWatcher.StopAsync(cancellationToken).ConfigureAwait(false);

            await Warden.StopAsync(cancellationToken).ConfigureAwait(false);
        }
Example #23
0
        public ActionResult SendMail(string email, string password)
        {
            Postman mailer = new Postman();

            mailer.ToEmail = email;
            mailer.Subject = "Parola öğrenme talebi";
            mailer.Body    = password;
            mailer.IsHtml  = true;
            mailer.Send();
            return(View());
        }
Example #24
0
        private void Send()
        {
            NetworkStream netStream = new NetworkStream(this.ReceiveSocket);
            Postman       postman   = new Postman()
            {
                Type    = Postman.PostmanType.SEND_KEY,
                Payload = Mysterio.ConvertKeyToBytes(this.MyMysterio.PubKey)
            };

            Postman.SendPackage(netStream, postman);
            AddEvent(postman.Type.ToString(), Encoding.Unicode.GetString(postman.Payload));
        }
Example #25
0
        private void Send(string mess)
        {
            NetworkStream netStream = new NetworkStream(this.ReceiveSocket);
            Postman       postman   = new Postman()
            {
                Type    = Postman.PostmanType.SEND_MESSAGE,
                Payload = Mysterio.Encrypt(this.OtherMysterio.PubKey, mess)
            };

            Postman.SendPackage(netStream, postman);
            AddEvent(postman.Type.ToString(), Encoding.Unicode.GetString(postman.Payload));
        }
Example #26
0
        public async Task send_completes_when_delivered_to_queue()
        {
            using (var sender = new Postman(adminFormatName))
            {
                await sender.StartAsync();

                var msg = new Message {
                    Label = "send1"
                };
                await dest.DeliverAsync(msg, sender, QueueTransaction.Single);
            }
        }
        public void Setup()
        {
            requestQueueFormatName = Queues.TryCreate(requestQueuePath, QueueTransactional.None);
            replyQueueFormatName   = Queues.TryCreate(replyQueuePath, QueueTransactional.None);
            adminQueueFormatName   = Queues.TryCreate(adminQueuePath, QueueTransactional.None);

            Queues.Purge(requestQueueFormatName);;
            Queues.Purge(replyQueueFormatName);;
            Queues.Purge(adminQueueFormatName);;

            postman = new Postman(adminQueueFormatName);
            postman.StartAsync();
        }
Example #28
0
 /// <summary>
 /// Loading pages of result CoubAPI
 /// </summary>
 /// <param name="page">Page to load</param>
 /// <param name="per_page">Results per page (MAX 25)</param>
 /// <param name="section">Category load from</param>
 /// <returns></returns>
 public Welcome GetPage(int page, int per_page, string section = "hot")
 {
     Postman postman = new Postman();
     Console.WriteLine("Postman is here.");
     string uri = "https://coub.com/api/v2/timeline/" + section + "?page=" + page + "&per_page=" + per_page+ "&order_by=newest_popular";
     Console.WriteLine($"Get uri: {uri}");
     string resultGet = postman.Get(uri);
     Console.WriteLine($"Result is not empty: {string.IsNullOrEmpty(resultGet)}");
     Console.WriteLine("Parsing json.");
     Welcome coubResult = Welcome.FromJson(resultGet);
     Console.WriteLine("Json parsed successfully.");
     return coubResult;
 }
Example #29
0
        private IEnumerator RunRoutine()
        {
            UnityWebRequest request = Postman.CreateGetRequest(Endpoints.instance.WEATHER());

            yield return(request.SendWebRequest());

            bool ok = request.error == null ? true : false;

            if (!ok)
            {
                WidgetLogger.instance.Log(this, "Error: " + request.error);
                yield break;
            }

            JSONNode        json = JSON.Parse(request.downloadHandler.text);
            List <JSONNode> hourlyWeatherData = GetHourlyWeatherData(json);
            List <JSONNode> dailyWeatherData  = GetDailyWeatherData(json);

            for (int i = 0; i < hourlyWeatherData.Count; i++)
            {
                JSONNode data        = hourlyWeatherData[i];
                TimeSpan time        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(data["time"]).ToLocalTime().TimeOfDay;
                string   iconCode    = GetFontCodeFor(data["icon"]);
                string   temperature = string.Format("{0}°", Mathf.RoundToInt((float)data["temperature"]));

                WeatherEntry entry = hourlyWeatherEntries[i];
                entry.SetDayColour(GetTextColour());
                entry.SetDayText(string.Format("{0:D2}:{1:D2}", time.Hours, time.Minutes));
                entry.SetIcon(iconCode);
                entry.SetIconColour(spriteColour);
                entry.SetTemperatureText(temperature);
                entry.SetTemperatureTextColour(GetTextColour());
            }

            for (int i = 0; i < dailyWeatherData.Count; i++)
            {
                JSONNode data        = dailyWeatherData[i];
                DateTime date        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(data["time"]);
                string   day         = date.DayOfWeek.ToString().Substring(0, 3);
                string   iconCode    = GetFontCodeFor(data["icon"]);
                string   temperature = string.Format("{0}°", Mathf.RoundToInt((float)data["temperatureHigh"]));

                WeatherEntry entry = dailyWeatherEntries[i];
                entry.SetDayColour(GetTextColour());
                entry.SetDayText(day.ToLower());
                entry.SetIcon(iconCode);
                entry.SetIconColour(spriteColour);
                entry.SetTemperatureText(temperature);
                entry.SetTemperatureTextColour(GetTextColour());
            }
        }
        private IEnumerator RunRoutine()
        {
            // Clear out existing entries
            foreach (Transform child in scrollContent)
            {
                Destroy(child.gameObject);
            }

            foreach (JSONNode journey in journeys)
            {
                List <string> stops = new List <string>();
                if (journey["stops"] != null)
                {
                    foreach (JSONNode stop in journey["stops"])
                    {
                        stops.Add(stop);
                    }
                }

                UnityWebRequest request = Postman.CreateGetRequest(Endpoints.instance.JOURNEY_PLANNER(journey["startPoint"], stops, journey["endPoint"]));
                yield return(request.SendWebRequest());

                bool ok = request.error == null ? true : false;
                if (!ok)
                {
                    WidgetLogger.instance.Log(this, "Error: " + request.error);
                    yield break;
                }

                JSONNode json = JSON.Parse(request.downloadHandler.text);

                int duration            = json["resourceSets"][0]["resources"][0]["travelDuration"];
                int durationWithTraffic = json["resourceSets"][0]["resources"][0]["travelDurationTraffic"];
                int timeDifference      = (durationWithTraffic - duration) / 60;

                Color trafficColour = noTrafficColour;

                if (timeDifference > mediumTrafficMinutes && timeDifference < heavyTrafficMinutes)
                {
                    trafficColour = mediumTrafficColour;
                }
                else if (timeDifference > heavyTrafficMinutes)
                {
                    trafficColour = heavyTrafficColour;
                }

                GameObject prefab = journeys.Count == 1 ? singleEntry.gameObject : scrollEntry.gameObject;
                Transform  parent = journeys.Count == 1 ? this.transform : scrollContent;
                Instantiate(prefab, parent).GetComponent <JourneyPlannerEntry>().Initialise(journey["name"], ConvertToTimeString(durationWithTraffic), trafficColour);
            }
        }
Example #31
0
        private IEnumerator AddToShoppingListRoutine()
        {
            ConfirmDialog dialog = FindObjectOfType <ConfirmDialog>();

            dialog.ApplyColours();
            dialog.Show();
            dialog.SetNone();
            dialog.SetInfoMessage("Add all ingredients from each recipe to the shopping list?");

            while (dialog.IsNone())
            {
                yield return(null);
            }

            if (dialog.IsNo())
            {
                dialog.Hide();
                dialog.SetNone();
                yield break;
            }

            if (dialog.IsYes())
            {
                TMP_Text addButtonText = addButton.GetComponentInChildren <TMP_Text>();
                addButtonText.text     = "Please wait...";
                addButton.interactable = false;

                dialog.Hide();

                OnlineList      shoppingList = FindObjectsOfType <OnlineList>().Where(x => x.GetListType().Equals(TodoistList.shoppingList)).First();
                UnityWebRequest request      = Postman.CreateGetRequest(Endpoints.instance.SHOPPING_LIST());
                yield return(request.SendWebRequest());

                JSONArray json = JSON.Parse(request.downloadHandler.text).AsArray;
                foreach (KeyValuePair <string, JSONNode> obj in json)
                {
                    string item = obj.Value.Value;
                    yield return(StartCoroutine(shoppingList.AddItemRoutine(item)));
                }

                shoppingList.Refresh();
                dialog.SetNone();

                addButton.interactable = true;
                addButtonText.text     = "Add To Shopping List";

                yield break;
            }
        }