public async Task <IActionResult> OnPostUp()
        {
            HttpRequests req = new HttpRequests();

            if (await req.UpdatePlaceType(new { name = placetypeName }, Convert.ToInt32(RouteData.Values["id"]), BaseController.GetToken()) == HttpStatusCode.NoContent)
            {
                return(RedirectToPage("/PlaceTypeSite"));
            }
            else
            {
                return(null);
            }
        }
 public async Task <string> GetAsync(string keyword)
 {
     try
     {
         var exampleRequester = new HttpRequests();
         var url = "https://culinarycompaniongrocerlink.azurewebsites.net/grocerlink?keyword=";
         url += keyword;
         return(await exampleRequester.GetAsync(url));
     }
     catch (Exception e)
     {
         return(e.ToString());
     }
 }
示例#3
0
 public async Task <string> GetTechniqueAsync(string keyword)
 {
     try
     {
         var exampleRequester = new HttpRequests();
         var url = "https://culinarycompaniontechniques20200427203903.azurewebsites.net/Techniques?search=";
         url += keyword;
         return(await exampleRequester.GetAsync(url));
     }
     catch
     {
         return("Nope");
     }
 }
示例#4
0
        public async Task <IActionResult> OnPost()
        {
            HttpRequests req       = new HttpRequests();
            PlaceType    placetype = new PlaceType()
            {
                Name = PlacetypeName
            };

            if (await req.CreatePlaceTypeAsync(placetype, BaseController.GetToken()) != HttpStatusCode.OK)
            {
                // Zeig Fehler an
            }
            return(RedirectToPage("/PlacetypeSite"));
        }
示例#5
0
        public async Task <IActionResult> OnPost()
        {
            HttpRequests   req = new HttpRequests();
            Object         r   = new { rating = Rating, text = reviewContent };
            HttpStatusCode c   = await req.UpdateReview(r, Convert.ToInt32(RouteData.Values["id"]), BaseController.GetreviewID(), BaseController.GetToken());

            if (c == HttpStatusCode.NoContent)
            {
                return(RedirectToPage("/PlaceSite", new { id = RouteData.Values["id"] }));
            }
            else
            {
                return(null);
            }
        }
示例#6
0
        private void ResponseFromSubmitForm(string xregion)
        {
            m_log.DebugFormat("[Controller]: ResponseFromSubmitForm {0}", xregion);

            try
            {
                // Check the xregion for info about the sim URL
                // string.Format("{0}={1}", region, HttpUtility.UrlEncode(gregion.ServerURI)

                string[] parts = xregion.Split('=');
                if (parts.Length <= 1)
                {
                    return;
                }

                string name   = parts[0];
                string simUrl = HttpUtility.UrlDecode(parts[1]);
                if (!simUrl.EndsWith("/"))
                {
                    simUrl += "/";
                }
                m_log.InfoFormat("[Controller]: Simulator url is {0}, region name is {1}", simUrl, name);

                // Tell the engine we're a-go
                PotamOSController.Engine.NewPage(UIPages.DynamicScene, string.Empty);

                // Finally get the scene
                string url = simUrl + "hppo/scene" + (xregion == "DEFAULT" ? "" : "/" + name);
                try
                {
                    HttpRequests.GetStream(url, SceneManager.Instance.LoadSceneFromXml);
                    m_log.DebugFormat("[Controller]: YIPPIE! Got the scene!");
                }
                catch (Exception e)
                {
                    m_log.WarnFormat("[Controller]: Problem with GetStream request to {0}, {1}", url, e);
                    PotamOSController.Engine.NewPage(UIPages.Splash, string.Empty);
                }
                //Hppo hppo = new Hppo(m_HppoInfo);
                //  ...
                //return hppo;
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[Controller]: Problem with response from post form {0}", e);
                PotamOSController.Engine.NewPage(UIPages.Splash, "");
            }
        }
示例#7
0
        public async Task <IActionResult> OnPost()
        {
            HttpRequests req   = new HttpRequests();
            Object       place = new
            {
                name        = Name,
                zipCode     = ZipCode,
                city        = City,
                street      = Street,
                country     = Country,
                placeTypeID = Placetype
            };
            Place p = await req.CreatePlaceAsync(place, BaseController.GetToken());

            return(RedirectToPage("/PlaceSite", new { id = Convert.ToInt32(p.ID) }));
        }
示例#8
0
文件: Docker.cs 项目: jayd2446/wsld
        public static int DownloadImage( )
        {
            var layers = HttpRequests.AskForLayers();

            Console.WriteLine("Image with " + layers.Count() + " layers");
            Console.WriteLine("Downloading...");

            for (int i = 0; i < layers.Count(); ++i)
            {
                var layer = layers.ElementAt(i);
                Fops.WriteToFileAppend(HttpRequests.DownloadLayer(layer["digest"].ToString()), UserConfig.w_tmp_rootfs_path);
                Console.WriteLine("Downloaded " + (i + 1) + " of " + layers.Count());
            }

            Console.WriteLine("Finished! All layers downloaded.");
            return(layers.Count());
        }
示例#9
0
        /// <summary>
        /// 获取微信粉丝信息
        /// </summary>
        /// <param name="wxopenid">微信OpenID</param>
        /// <param name="access_token">用户级access_token</param>
        /// <param name="wxfansinfo">粉丝信息</param>
        /// <param name="errmsg">出错时返回的错误提示信息</param>
        /// <returns>是否成功执行</returns>
        private bool GetWXFansInfo(string wxopenid, string access_token, ref WXFansInfo wxfansinfo, ref string errmsg)
        {
            bool   result = true;
            string url    = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + wxopenid + "&lang=zh_CN";

            //string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + wxopenid + "&lang=zh_CN";
            try
            {
                string json = HttpRequests.WXInterfaceHttpRequest(url, "", "GET");
                wxfansinfo = ObjectSeriallizeHelper.JsonToObject <WXFansInfo>(json);
            }
            catch (Exception ex)
            {
                errmsg = ex.Message.ToString();
                result = false;
                LogWriter.WriteLog(ex);
            }
            return(result);
        }
        private bool RefreshAndSave()
        {
            if (refreshAlternating)
            {
                System.Diagnostics.Debug.WriteLine("RefreshAndSave");

                Task.Run(async() => {
                    foreach (User u in App.Users)
                    {
                        await HttpRequests.PostUserEdit(u);
                        await HttpRequests.extaractUsers();
                    }
                }).ContinueWith((end) => {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (currentSearchBar.Text != "" && currentSearchBar.Text != null)
                        {
                            currentInfoList.ItemsSource = App.Users.AsEnumerable().Where(i => i.name.ToLower().Contains(currentSearchBar.Text.ToLower()));
                        }
                        else
                        {
                            currentInfoList.ItemsSource = App.Users;
                        }

                        currentInfoList.EndRefresh();
                    });
                });
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Save");

                Task.Run(async() => { foreach (User u in App.Users)
                                      {
                                          await HttpRequests.PostUserEdit(u);
                                      }
                         });
            }

            refreshAlternating = !refreshAlternating;
            return(App.Foreground);
        }
示例#11
0
 public static void UpdateHttpRequest(HttpRequests http)
 {
     using (RemindMeDbEntities db = new RemindMeDbEntities())
     {
         var count = db.HttpRequests.Where(o => o.Id >= 0).Count();
         if (count > 0)
         {
             db.HttpRequests.Attach(http);
             var entry = db.Entry(http);
             entry.State = System.Data.Entity.EntityState.Modified; //Mark it for update
             db.SaveChanges();                                      //push to database
             db.Dispose();
         }
         else
         {//The settings table is still empty
             db.HttpRequests.Add(http);
             db.SaveChanges();
             db.Dispose();
         }
     }
 }
        public async Task <string> PostAsync()
        {
            try
            {
                string bodyDummy = "toast";
                using (var reader = new StreamReader(Request.Body))
                {
                    var abody = reader.ReadToEndAsync().Result;
                    bodyDummy = abody;
                }

                var recipeRequester = new HttpRequests();
                var uri             = "https://u7bwesiqoc.execute-api.us-east-1.amazonaws.com/Prod/search/";
                var body            = bodyDummy;
                return(await recipeRequester.PostAsync(uri, body, "JSON"));
            }
            catch (Exception e)
            {
                return(e.ToString());
            }
        }
示例#13
0
        public async Task <IActionResult> OnPost()
        {
            HttpRequests req   = new HttpRequests();
            object       place = new
            {
                name        = Name,
                zipCode     = ZipCode,
                city        = City,
                street      = Street,
                country     = Country,
                placeTypeID = Placetype
            };
            HttpStatusCode c = await req.UpdatePlaceAsync(place, Convert.ToInt32(RouteData.Values["id"]), BaseController.GetToken());

            if (c == HttpStatusCode.NoContent)
            {
                int placeID             = Convert.ToInt32(RouteData.Values["id"]);
                List <openingTimes> ops = await req.GetOpenTimesAsync(placeID, BaseController.GetToken());

                openingTimes opti;
                for (int i = 0; i < 7; i++)
                {
                    if (ops.Where((o) => o.Day == i).ToList().Count != 0)
                    {
                        opti = new openingTimes {
                            Day = i, Open = Request.Form["Open" + i].ToString(), Close = Request.Form["Close" + i].ToString()
                        };
                        if (await req.UpdateOpeningTime(opti, placeID, ops.Where((o) => o.Day == i).ToList()[0].ID, BaseController.GetToken()) != HttpStatusCode.OK)
                        {
                            // Fehler mitteilen
                        }
                    }
                }
                return(RedirectToPage("/PlaceSite", new { id = RouteData.Values["id"] }));
            }
            else
            {
                return(null);
            }
        }
示例#14
0
        public static async Task <List <SongBundle> > GetSearchResults(string query)
        {
            string results = await HttpRequests.GetRequest(GeniusSearchUrl + Uri.EscapeUriString(query), GeniusAuthHeader);

            JObject parsed = JObject.Parse(results);

            IList <JToken> parsedList = parsed["response"]?["hits"]?.Children().ToList();

            List <SongBundle> resultsList = new List <SongBundle>();

            if (parsedList != null && parsedList.Count != 0)
            {
                foreach (JToken result in parsedList)
                {
                    Song song = new Song
                    {
                        Id      = (int)result["result"]?["id"],
                        Title   = (string)result["result"]?["title"],
                        Artist  = (string)result["result"]?["primary_artist"]?["name"],
                        Cover   = (string)result["result"]?["song_art_image_thumbnail_url"],
                        Header  = (string)result["result"]?["header_image_url"],
                        ApiPath = (string)result["result"]?["api_path"],
                        Path    = (string)result["result"]?["path"]
                    };

                    RomanizedSong rSong = new RomanizedSong();
                    if (Prefs.GetBoolean("romanize_search", false))
                    {
                        rSong = await JapaneseTools.RomanizeSong(song, false);
                    }

                    resultsList.Add(new SongBundle(song, rSong));
                }

                return(resultsList);
            }

            resultsList = new List <SongBundle>();
            return(resultsList);
        }
示例#15
0
        private void UpsertEmployee(GetEmployeeResponse request)
        {
            var upsertEmployeeRequest = new UpsertEmployeeRequest
            {
                FirstName = request.FirstName,
                LastName  = request.LastName
            };

            if (request.Id > 0)
            {
                var updateEmployee = Task.Run(() => HttpRequests.UpdateEmployee(request.Id, upsertEmployeeRequest));

                updateEmployee.Wait();
            }

            else
            {
                var createEmployee = Task.Run(() => HttpRequests.CreateEmployee(upsertEmployeeRequest));

                createEmployee.Wait();
            }
        }
示例#16
0
        public BindingList <GetEmployeeResponse> GetDataSource()
        {
            var getEmployeeList = Task.Run(() => HttpRequests.GetEmployees());

            try
            {
                getEmployeeList.Wait();
            }
            catch
            {
                MessageBox.Show(string.Format("Connection to Server Status: {0}", getEmployeeList.Status.ToString()));
                return(null);
            }

            var result = new BindingList <GetEmployeeResponse>();

            foreach (var employee in getEmployeeList.Result)
            {
                result.Add(employee);
            }

            return(result);
        }
示例#17
0
        /// <summary>
        /// 检测用户级access_token是否有效
        /// </summary>
        /// <param name="wxopenid">微信Openid</param>
        /// <param name="access_token">用户级access_token</param>
        /// <param name="errmsg">出错时返回的错误提示信息</param>
        /// <returns>是否成功执行</returns>
        private bool CheckUserAccessToken(string wxopenid, string access_token, ref string errmsg)
        {
            bool   result = true;
            string url    = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + wxopenid;

            try
            {
                string   json     = HttpRequests.WXInterfaceHttpRequest(url, "", "GET");
                ApiBasic apibasic = ObjectSeriallizeHelper.JsonToObject <ApiBasic>(json);
                if (apibasic.errcode != 0)
                {
                    result = false;
                    errmsg = "access_token已失效";
                }
            }
            catch (Exception ex)
            {
                errmsg = ex.Message.ToString();
                result = false;
                LogWriter.WriteLog(ex);
            }
            return(result);
        }
示例#18
0
        /// <summary>
        /// API调用方法
        /// </summary>
        /// <param name="url">调用地址</param>
        /// <param name="postData">参数</param>
        /// <param name="requestmethod">请求方式:POST或者GET</param>
        /// <returns>返回请求结果</returns>
        public static string PalmCoreIIS3676API(string url, Dictionary <string, string> postData, string requestmethod)
        {
            string str           = "";
            string iis_host      = System.Configuration.ConfigurationManager.AppSettings["CoreApiHostIIS3676"];                       //核心程序IIS的API接口链接
            string api_code      = System.Configuration.ConfigurationManager.AppSettings["Call_CoreApiCode"];                         //调用接口所需的Code
            string api_key       = System.Configuration.ConfigurationManager.AppSettings["Call_CoreApiKey"];                          //调用接口所需的Key
            string api_timestamp = GetTimeStamp();                                                                                    //调用接口所需的时间戳
            string api_sign      = TextEncrypt.MD5Encrypt32(api_code + api_key + api_timestamp, System.Text.Encoding.UTF8).ToLower(); //调用接口所需的签名

            url = iis_host + url;
            try
            {
                postData.Add("api_code", api_code);
                postData.Add("api_timestamp", api_timestamp);
                postData.Add("api_sign", api_sign);
                str = HttpRequests.HttpRequestString(url, postData, requestmethod);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(str);
        }
示例#19
0
 public async Task <IActionResult> OnPost()
 {
     if (Request.Form["username"] != "" && Request.Form["pwd"] != "")
     {
         Object u = new
         {
             username    = Username,
             firstName   = Firstname,
             lastName    = Lastname,
             password    = Password,
             description = Description,
             street      = Street,
             zipCode     = ZipCode,
             city        = City,
             country     = Country
         };
         HttpRequests r = new HttpRequests();
         if (await r.CreateUserAsync(u) != HttpStatusCode.OK)
         {
             // Zeige Fehler an
         }
     }
     return(RedirectToPage("/Index"));
 }
示例#20
0
 public ActionFacade(HttpRequests _httpRequests, TftpRequests _tftpRequests, TcpRequests _tcpRequests)
 {
     HttpRequests = _httpRequests;
     TftpRequests = _tftpRequests;
     TcpRequests  = _tcpRequests;
 }
示例#21
0
 public MedicineTenderOfferService(MyDbContext context)
 {
     MedicineTenderOfferRepository = new MedicineTenderOfferRepository(context);
     PharmacyTenderOfferRepository = new PharmacyTenderOfferRepository(context);
     HttpRequests = new HttpRequests();
 }
示例#22
0
文件: Docker.cs 项目: jglete/wsld
        private static byte[] DownloadLayer(string digest, string repository)
        {
            string url = docker_register_url + repository + "/blobs/" + digest;

            return(HttpRequests.GetResponseBytes(url).Result);
        }
示例#23
0
        public static async Task <SongBundle> GetSongDetails(SongBundle song)
        {
            Log(Logging.Type.Info, "Starting GetSongDetails operation");
            string results = await HttpRequests.GetRequest(GeniusApiUrl + song.Normal.ApiPath, GeniusAuthHeader);

            JObject parsed = JObject.Parse(results);

            parsed = (JObject)parsed["response"]?["song"]; //Change root to song

            Song fromJson = new Song
            {
                Title   = (string)parsed?.SelectToken("title") ?? "",
                Artist  = (string)parsed?.SelectToken("primary_artist.name") ?? "",
                Album   = (string)parsed?.SelectToken("album.name") ?? "",
                Header  = (string)parsed?.SelectToken("header_image_url") ?? "",
                Cover   = (string)parsed?.SelectToken("song_art_image_url") ?? "",
                ApiPath = (string)parsed?.SelectToken("api_path") ?? "",
                Path    = (string)parsed?.SelectToken("path") ?? ""
            };

            song.Normal = fromJson;

            if (parsed != null && parsed["featured_artists"].HasValues)
            {
                IList <JToken> parsedList = parsed["featured_artists"].Children().ToList();

                song.Normal.FeaturedArtist = "feat. ";
                foreach (JToken artist in parsedList)
                {
                    if (song.Normal.FeaturedArtist == "feat. ")
                    {
                        song.Normal.FeaturedArtist += artist["name"]?.ToString();
                    }
                    else
                    {
                        song.Normal.FeaturedArtist += ", " + artist["name"];
                    }
                }

                Log(Logging.Type.Processing, "Added featured artists to song");
            }
            else
            {
                song.Normal.FeaturedArtist = "";
            }

            //Execute all Japanese transliteration tasks at once
            if (Prefs.GetBoolean("auto_romanize_details", true) && song.Normal.Title.ContainsJapanese() || song.Normal.Artist.ContainsJapanese() || song.Normal.Album.ContainsJapanese())
            {
                Task <string> awaitTitle  = song.Normal.Title.StripJapanese();
                Task <string> awaitArtist = song.Normal.Artist.StripJapanese();
                Task <string> awaitAlbum  = song.Normal.Album.StripJapanese();

                await Task.WhenAll(awaitTitle, awaitArtist, awaitAlbum);

                RomanizedSong romanized = new RomanizedSong();
                // This snippet is the same in GetAndShowLyrics
                song.Romanized ??= romanized;

                romanized.Title  = await awaitTitle;
                romanized.Artist = await awaitArtist;
                romanized.Album  = await awaitAlbum;

                romanized.Id          = song.Normal.Id;
                song.Romanized        = romanized;
                song.Normal.Romanized = true;

                Log(Logging.Type.Event, "Romanized song info with ID " + song.Normal.Id);
                Analytics.TrackEvent("Romanized song info", new Dictionary <string, string> {
                    { "SongID", song.Normal.Id.ToString() }
                });
            }
            else
            {
                song.Romanized = null;
            }

            return(song);
        }
示例#24
0
        private async Task GetDetails(string apiPath)
        {
            callsMade++;

            Log(Type.Info, "Starting getDetails operation");
            string results = await HttpRequests.GetRequest(GeniusApiUrl + apiPath, GeniusAuthHeader);

            if (results == null)
            {
                Log(Type.Processing, "Returned null, calling API again...");
                results = await HttpRequests.GetRequest(GeniusApiUrl + apiPath, GeniusAuthHeader);
            }
            JObject parsed = JObject.Parse(results);

            Song song = new Song()
            {
                Title   = (string)parsed["response"]["song"]["title"],
                Artist  = (string)parsed["response"]["song"]["primary_artist"]["name"],
                Album   = (string)parsed.SelectToken("response.song.album.name"),
                Header  = (string)parsed["response"]["song"]["header_image_url"],
                Cover   = (string)parsed["response"]["song"]["song_art_image_url"],
                ApiPath = (string)parsed["response"]["song"]["api_path"],
                Path    = (string)parsed["response"]["song"]["path"]
            };

            Log(Type.Processing, "Created new Song variable");

            if (parsed["response"]["song"]["featured_artists"].HasValues)
            {
                Log(Type.Info, "Track has featured artists");
                IList <JToken> parsedList = parsed["response"]["song"]["featured_artists"].Children().ToList();
                song.FeaturedArtist = "feat. ";
                foreach (JToken artist in parsedList)
                {
                    if (song.FeaturedArtist == "feat. ")
                    {
                        song.FeaturedArtist += artist["name"].ToString();
                    }
                    else
                    {
                        song.FeaturedArtist += ", " + artist["name"];
                    }
                }
            }
            else
            {
                Log(Type.Info, "Track does not have featured artists");
                song.FeaturedArtist = "";
            }

            string downloadedLyrics;

            HtmlWeb web = new HtmlWeb();

            Log(Type.Processing, "Trying to load page");
            HtmlDocument doc = await web.LoadFromWebAsync("https://genius.com" + song.Path);

            Log(Type.Info, "Loaded Genius page");
            HtmlNode lyricsBody = doc.DocumentNode.SelectSingleNode("//div[@class='lyrics']");

            downloadedLyrics = Regex.Replace(lyricsBody.InnerText, @"^\s*", "");
            downloadedLyrics = Regex.Replace(downloadedLyrics, @"[\s]+$", "");
            song.Lyrics      = downloadedLyrics;

            await SaveSongLyrics(song);

            Log(Type.Info, "Finished saving!");

            completedTasks++;
            Log(Type.Info, "Completed getDetails task for " + song.ApiPath);
        }
示例#25
0
 /// <summary> This method is getting list of filtered malicious<c>PatientUser</c>.</summary>
 /// <returns> List of filtered malicious patients. </returns>
 public List <PatientUser> GetMaliciousPatients()
 {
     return(GetValidPatientsInLastMonth(GetCanceledAppointmentsInLastMonth(HttpRequests.GetAllAppointments().Result)));
 }
示例#26
0
        private async void ExecuteHttpRequest(object sender, EventArgs e, HttpRequests http, Reminder rem)
        {
            try
            {
                if (!BLIO.HasInternetAccess())
                {
                    BLIO.Log("Cancelling ExecuteHttpRequest(). No internet access");
                    return;
                }

                BLIO.Log("ExecuteHttpRequest timer tick! [ " + http.URL + " ]");
                if (httpTimers.Where(t => t.Key.Id == rem.Id) == null)
                {
                    BLIO.Log("Attempted to ExecuteHttpRequest() from a timer that no longer exists. Cancelling.");
                    return;
                }

                JObject response = await BLIO.HttpRequest(http.Type, http.URL, http.OtherHeaders, http.AcceptHeader, http.ContentTypeHeader, http.Body);



                List <HttpCondition> conditions = new List <HttpCondition>();
                foreach (HttpRequestCondition cond in BLLocalDatabase.HttpRequestConditions.GetConditions(http.Id))
                {
                    conditions.Add(new HttpCondition(cond, response));
                }

                bool conditionMet = conditions.Count > 0;
                foreach (HttpCondition con in conditions) //Check for ALL conditions and see if all of them return true
                {
                    if (!con.Evaluate())
                    {
                        conditionMet = false;
                    }
                }

                if (conditionMet)
                {
                    //All conditions returned true!

                    MakeReminderPopup(rem);

                    if (http.AfterPopup == "Stop")
                    {
                        var timer = GetTimer(rem);
                        if (timer != null)
                        {
                            timer.Stop();

                            //remove from dictionary
                            httpTimers.Remove(rem);
                        }
                    }
                }
                else
                {
                    BLIO.Log("ExecuteHttpRequest returned FALSE");
                }
            }
            catch (Exception ex)
            {
                BLIO.Log("ExecuteHttpRequest() Failed. " + ex.GetType().ToString());
            }
        }
示例#27
0
        /// <summary>
        /// Display changes on the current page. (For example a deleted or enabled/disabled reminder)
        /// </summary>
        /// <param name="editedReminder">If a reminder has been edited, this object will contain that reminder</param>
        public void UpdateCurrentPage(Reminder editedReminder = null)
        {
            MaterialSkin.MaterialSkinManager.Themes theme = MaterialSkin.MaterialSkinManager.Instance.Theme;

            BLIO.Log("Starting UpdateCurrentPage()...");

            //Reminder list containing normal reminders and conditional reminders, enabled and disabled
            List <Reminder> reminders = BLReminder.GetOrderedReminders();

            //^ All reminders in one list with the disabled ones at the end of the list
            BLIO.Log(reminders.Count + " reminders loaded");

startMethod:
            if ((pageNumber * 7) + 1 > reminders.Count)
            {
                if (theme == MaterialSkin.MaterialSkinManager.Themes.DARK)
                {
                    btnNextPage.Icon = Properties.Resources.nextDisabledDark;
                }
                else
                {
                    btnNextPage.Icon = Properties.Resources.nextDisabledDark;
                }
            }
            else
            {
                if (theme == MaterialSkin.MaterialSkinManager.Themes.DARK)
                {
                    btnNextPage.Icon = Properties.Resources.NextWhite;
                }
                else
                {
                    btnNextPage.Icon = Properties.Resources.nextDark;
                }
            }

            int reminderItemCounter = 0;

            for (int i = (pageNumber - 1) * 7; i < ((pageNumber) * 7); i++)
            {
                if (reminders.Count - 1 >= i) //Safely within index numbers
                {
                    if (reminderItemCounter >= pnlReminders.Controls.Count)
                    {
                        return;
                    }

                    //Get the user control item from the panel. There's 7 user controls in the panel, so we have another counter for those
                    MUCReminderItem itm = (MUCReminderItem)pnlReminders.Controls[reminderItemCounter];
                    //Update the reminder object inside the user control, that's waay faster than removing and re-drawing a new control.
                    itm.Reminder = reminders[i];
                    itm.RefreshLabelFont();
                }
                else
                {
                    //User deleted a reminder, which was the last one out of the list from that page. Navigate to the previous page.
                    if (i % 7 == 0 && pageNumber > 1)
                    {
                        BLIO.Log("navigating to the previous page after deletion of an reminder...");
                        pageNumber--;
                        goto startMethod;
                    }

                    for (int ii = i; ii < 7; ii++)
                    {
                        if (ii >= pnlReminders.Controls.Count)
                        {
                            break;
                        }

                        MUCReminderItem itm = (MUCReminderItem)pnlReminders.Controls[ii];
                        itm.Reminder = null;
                    }

                    //This happens when an reminder has been deleted, and there are less than 7 reminders on that page. Empty out the remaining reminder items.
                    while (reminderItemCounter <= 6)
                    {
                        BLIO.Log("Detected the deletion of an reminder on the current page.");
                        //Get the user control item from the panel. There's 7 user controls in the panel, so we have another counter for those
                        try
                        {
                            MUCReminderItem itm = (MUCReminderItem)pnlReminders.Controls[reminderItemCounter];

                            if (itm.Reminder != null)
                            {
                                BLIO.Log("Emptying ReminderItem with ID " + itm.Reminder.Id);
                            }
                            //Update the reminder object inside the user control, that's waay faster than removing and re-drawing a new control.
                            itm.Reminder = null;

                            reminderItemCounter++;
                        }
                        catch (Exception ex)
                        {
                            BLIO.Log("Setting new Reminder value failed. -> " + ex.GetType().ToString());
                        }
                    }

                    break;
                }

                reminderItemCounter++;

                if (reminderItemCounter == 7)
                {
                    break;
                }
            }



            if (reminders.Count <= 7)
            {
                MaterialForm1.Instance.UpdatePageNumber(-1);
            }
            else
            {
                MaterialForm1.Instance.UpdatePageNumber(pageNumber);
            }

            if (Instance != null)
            {
                Instance.tmrCheckReminder.Start();
            }


            if (editedReminder != null && editedReminder.HttpId != null)
            {
                //This object has been altered. Deleted, Perma-deleted, edited OR disabled
                if (BLReminder.GetReminderById(editedReminder.Id) == null || editedReminder.Deleted > 0 || editedReminder.Enabled == 0)
                {
                    //perma-deleted, soft-deleted or turned off
                    if (GetTimer(editedReminder) != null)
                    {
                        GetTimer(editedReminder).Stop();
                    }
                    RemoveTimer(editedReminder);
                }
                else //Reminder is still active, so it probably has been edited
                {
                    HttpRequests httpObj = BLLocalDatabase.HttpRequest.GetHttpRequestById((long)editedReminder.Id);
                    var          kvp     = httpTimers.Where(r => r.Key.Id == editedReminder.Id).FirstOrDefault();
                    if (kvp.Key != null)
                    {
                        //Already exist, stop timer, change & restart
                        RemoveTimer(editedReminder);
                        var timer = new System.Windows.Forms.Timer();
                        timer.Interval = Convert.ToInt32(httpObj.Interval * 60000);
                        timer.Tick    += (object s, EventArgs a) => ExecuteHttpRequest(s, a, httpObj, editedReminder);
                        timer.Start();
                        httpTimers.Add(editedReminder, timer);
                    }
                    else if (editedReminder.Enabled == 1) //Reminder has been re-enabled
                    {
                        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                        httpTimers.Add(editedReminder, timer);
                        timer.Interval = Convert.ToInt32(httpObj.Interval * 60000);
                        timer.Tick    += (object s, EventArgs a) => ExecuteHttpRequest(s, a, httpObj, editedReminder);
                        timer.Start();
                    }
                }
            }
            else
            {
                //Http requests
                foreach (Reminder rem in BLReminder.GetReminders(true).Where(r => r.HttpId != null).Where(r => r.Enabled == 1))
                {
                    HttpRequests httpObj = BLLocalDatabase.HttpRequest.GetHttpRequestById((long)rem.Id);

                    if (GetTimer(rem) == null)
                    {
                        //Don't add duplicates
                        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                        httpTimers.Add(rem, timer);
                        timer.Interval = Convert.ToInt32(httpObj.Interval * 60000);
                        timer.Tick    += (object s, EventArgs a) => ExecuteHttpRequest(s, a, httpObj, rem);
                        timer.Start();
                    }
                }
            }



            BLIO.Log("UpdateCurrentPage() completed.");
        }
示例#28
0
        public void Initialize()
        {
            try
            {
                MaterialSkin.MaterialSkinManager.Themes theme = MaterialSkin.MaterialSkinManager.Instance.Theme;

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                List <Reminder> corruptedReminders = BLReminder.CheckForCorruptedReminders();

                if (corruptedReminders != null)
                {
                    string message = "RemindMe has detected";
                    if (corruptedReminders.Count > 1)
                    {
                        message += " problems with the following reminders: \r\n";

                        foreach (Reminder rem in corruptedReminders)
                        {
                            message += "- " + rem.Name + "\r\n";
                        }

                        message += "\r\nThey have been removed from your list of reminders.";
                    }
                    else
                    {
                        message += " a problem with the reminder:\r\n\"" + corruptedReminders[0].Name + "\". \r\nIt has been removed from your list of reminders.";
                    }

                    MaterialMessageFormManager.MakeMessagePopup(message, 0);
                }

                BLIO.Log("Loading reminders from database");
                //Give initial value to newReminderUc
                newReminderUc           = new MUCNewReminder(this);
                newReminderUc.Visible   = false;
                newReminderUc.saveState = false;
                this.Parent.Controls.Add(newReminderUc);


                //MaterialForm1.Instance.ucNewReminder = newReminderUc;
                //BLFormLogic.AddRemindersToListview(lvReminders, BLReminder.GetReminders().Where(r => r.Hide == 0).ToList()); //Get all "active" reminders);

                BLIO.Log("Starting the reminder timer");
                tmrCheckReminder.Start();

                pnlReminders.Visible = true;

                pnlReminders.DragDrop  += MUCReminders_DragDrop;
                pnlReminders.DragEnter += MUCReminders_DragEnter;


                int counter = 0;
                //List<Reminder> reminders = BLReminder.GetOrderedReminders();
                List <Reminder> conditionalReminders = BLReminder.GetReminders(true).Where(r => r.HttpId != null).Where(r => r.Hide == 0).Where(r => r.Enabled == 1).ToList();
                List <Reminder> activeReminders      = BLReminder.GetReminders().Where(r => r.Hide == 0).OrderBy(r => Convert.ToDateTime(r.Date.Split(',')[0])).Where(r => r.Enabled == 1).ToList();
                List <Reminder> disabledReminders    = BLReminder.GetReminders().Where(r => r.Hide == 0).OrderBy(r => Convert.ToDateTime(r.Date.Split(',')[0])).Where(r => r.Enabled == 0).ToList();

                //we've got postponed reminders, now do this
                if (BLReminder.GetReminders().Where(r => !string.IsNullOrWhiteSpace(r.PostponeDate)).ToList().Count > 0)
                {
                    activeReminders = OrderPostponedReminders();
                }

                foreach (Reminder rem in activeReminders)
                {
                    if (pnlReminders.Controls.Count >= 7)
                    {
                        break;                                   //Only 7 reminders on 1 page
                    }
                    pnlReminders.Controls.Add(new MUCReminderItem(rem));

                    if (counter > 0)
                    {
                        pnlReminders.Controls[counter].Location = new Point(0, pnlReminders.Controls[counter - 1].Location.Y + pnlReminders.Controls[counter - 1].Size.Height);
                    }

                    counter++;
                }
                foreach (Reminder rem in conditionalReminders)
                {
                    if (pnlReminders.Controls.Count >= 7)
                    {
                        break;                                   //Only 7 reminders on 1 page
                    }
                    pnlReminders.Controls.Add(new MUCReminderItem(rem));

                    if (counter > 0)
                    {
                        pnlReminders.Controls[counter].Location = new Point(0, pnlReminders.Controls[counter - 1].Location.Y + pnlReminders.Controls[counter - 1].Size.Height);
                    }

                    counter++;
                }
                foreach (Reminder rem in disabledReminders)
                {
                    if (pnlReminders.Controls.Count >= 7)
                    {
                        break;
                    }

                    pnlReminders.Controls.Add(new MUCReminderItem(rem));

                    if (counter > 0)
                    {
                        pnlReminders.Controls[counter].Location = new Point(0, pnlReminders.Controls[counter - 1].Location.Y + pnlReminders.Controls[counter - 1].Size.Height);
                    }

                    counter++;
                }

                if (activeReminders.Count + disabledReminders.Count < 7) //Less than 7 reminders, let's fit in some empty MUCReminderItem 's
                {
                    for (int i = (activeReminders.Count + disabledReminders.Count); i < 7; i++)
                    {
                        pnlReminders.Controls.Add(new MUCReminderItem(null));

                        if (counter > 0)
                        {
                            pnlReminders.Controls[counter].Location = new Point(0, pnlReminders.Controls[counter - 1].Location.Y + pnlReminders.Controls[counter - 1].Size.Height);
                        }

                        counter++;
                    }
                }

                if (BLReminder.GetReminders().Where(r => r.Hide == 0).ToList().Count <= 7)
                {
                    MaterialForm1.Instance.UpdatePageNumber(-1); //Tell MaterialForm1 that there are not more than 1 pages
                }
                else
                {
                    if (theme == MaterialSkin.MaterialSkinManager.Themes.DARK)
                    {
                        btnNextPage.Icon = Properties.Resources.NextWhite;
                    }
                    else
                    {
                        btnNextPage.Icon = Properties.Resources.nextDark;
                    }

                    MaterialForm1.Instance.UpdatePageNumber(pageNumber);
                }

                //Just design, no logic here. Drags the color panel a bit down and shrink it so it doesnt overlap over the shadow
                MUCReminderItem itm = (MUCReminderItem)pnlReminders.Controls[0];
                itm.pnlSideColor.Size     = new Size(itm.pnlSideColor.Width, itm.pnlSideColor.Height - 4);
                itm.pnlSideColor.Location = new Point(itm.pnlSideColor.Location.X, itm.pnlSideColor.Location.Y + 4);


                //Http requests
                foreach (Reminder rem in conditionalReminders)
                {
                    HttpRequests httpObj = BLLocalDatabase.HttpRequest.GetHttpRequestById((long)rem.Id);

                    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                    timer.Interval = Convert.ToInt32(httpObj.Interval * 60000);
                    timer.Tick    += (object s, EventArgs a) => ExecuteHttpRequest(s, a, httpObj, rem);

                    httpTimers.Add(rem, timer);
                    timer.Start();
                }

                stopwatch.Stop();
                BLIO.Log("MUCReminders Initialize took " + stopwatch.ElapsedMilliseconds + " ms");
            }
            catch (Exception ex)
            {
                BLIO.Log("MUCReminders.Initialize() FAILED. Type -> " + ex.GetType().ToString());
                BLIO.Log("Message -> " + ex.Message);
            }
        }
示例#29
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (xClose)
            {
                xClose = false;
            }

            if (rem != null)
            {
                rem = BLReminder.GetReminderById(rem.Id);
            }

            if (rem == null)
            {
                goto close;
            }

            if (rem.HttpId != null)
            {
                //Conditional reminder
                HttpRequests req = BLLocalDatabase.HttpRequest.GetHttpRequestById(rem.Id);
                if (req.AfterPopup == "Stop")
                {
                    rem.Deleted = 1;
                    BLReminder.EditReminder(rem);
                    goto close;
                }
                else if (req.AfterPopup == "Repeat")
                {
                    goto close;
                }
                //else .... ?
            }

            if (rem.Id != -1 && rem.Deleted == 0) //Don't do stuff if the id is -1, invalid. the id is set to -1 when the user previews an reminder
            {
                if (BLReminder.GetReminderById(rem.Id) == null)
                {
                    //The reminder popped up, it existed, but when pressing OK it doesn't exist anymore (maybe the user deleted it or tempered with the .db file)
                    BLIO.Log("DETECTED NONEXISTING REMINDER WITH ID " + rem.Id + ", Attempted to press OK on a reminder that somehow doesn't exist");
                    goto close;
                }

                if (cbPostpone.Checked)
                {
                    BLIO.Log("Postponing reminder with id " + rem.Id);
                    if (BLFormLogic.GetTextboxMinutes(tbPostpone) <= 0)
                    {
                        return;
                    }

                    DateTime newReminderTime = new DateTime();

                    if (!string.IsNullOrWhiteSpace(tbPostpone.Text)) //postpone option is x minutes
                    {
                        newReminderTime  = DateTime.Now.AddMinutes(BLFormLogic.GetTextboxMinutes(tbPostpone));
                        rem.PostponeDate = newReminderTime.ToString();
                    }
                    else
                    {
                        rem.PostponeDate = null;
                        BLReminder.UpdateReminder(rem);
                    }



                    BLIO.Log("Postpone date assigned to reminder");
                    rem.Enabled = 1;
                    BLReminder.EditReminder(rem);
                    new Thread(() =>
                    {
                        //Log an entry to the database, for data!
                        try
                        {
                            BLOnlineDatabase.PostponeCount++;
                        }
                        catch (ArgumentException ex)
                        {
                            BLIO.Log("Exception at BLOnlineDatabase.PostponeCount++. -> " + ex.Message);
                            BLIO.WriteError(ex, ex.Message, true);
                        }
                    }).Start();
                    BLIO.Log("Reminder postponed!");
                }
                else
                {
                    rem.PostponeDate = null;
                    BLReminder.UpdateReminder(rem);
                }
            }

close:
            MUCReminders.Instance.UpdateCurrentPage(rem);
            BLIO.Log("Stopping media player & Closing popup");

            if (BLLocalDatabase.Setting.Settings.PopupType != "SoundOnly")
            {
                myPlayer.controls.stop();
            }

            this.Close();

            GC.Collect();
        }
示例#30
0
        /// <summary>
        /// Checks if there is anything wrong with the reminder that might cause an exception
        /// </summary>
        /// <param name="rem">The reminder you want to check on</param>
        /// <returns>True if this reminder could cause an exception, false if not</returns>
        public static Exception IsValidReminder(Reminder rem)
        {
            try
            {
                DateTime date;

                if (rem.HttpId == null)
                {
                    //Check all possible dates
                    foreach (string stringDate in rem.Date.Split(','))
                    {
                        date = Convert.ToDateTime(stringDate);
                    }

                    if (rem.PostponeDate != null)
                    {
                        date = Convert.ToDateTime(rem.PostponeDate.Split(',')[0]);
                    }
                }


                if (rem.Enabled > 1 || rem.Enabled < 0)
                {
                    throw new Exception("Enabled is not 0 or 1");
                }

                if (rem.Deleted > 2 || rem.Deleted < 0)
                {
                    throw new Exception("Deleted is not between 0 and 2");
                }

                if (rem.Hide > 1 || rem.Hide < 0)
                {
                    throw new Exception("Hide is not 0 or 1");
                }

                if (rem.Corrupted > 1 || rem.Corrupted < 0)
                {
                    throw new Exception("Corrupted is not 0 or 1");
                }

                if (rem.EnableAdvancedReminder > 1 || rem.EnableAdvancedReminder < 0)
                {
                    throw new Exception("EnableAdvancedReminder is not 0 or 1");
                }

                if (rem.UpdateTime > 1 || rem.UpdateTime < 0)
                {
                    throw new Exception("UpdateTime is not 0 or 1");
                }

                //If the reminder is weekdays, check if there are more than 0 days
                if (rem.RepeatType == ReminderRepeatType.MULTIPLE_DAYS.ToString())
                {
                    string[] days = rem.RepeatDays.Split(',');

                    if (days.Length <= 0)
                    {
                        throw new Exception("RepeatType is MULTIPLE_DAYS and there are are no RepeatDays");
                    }
                }

                if (rem.RepeatType == ReminderRepeatType.CUSTOM.ToString())
                {
                    if (rem.EveryXCustom <= 0)
                    {
                        throw new Exception("RepeatType is CUSTOM and EveryXCustom is not set");
                    }
                }


                string test = GetRepeatTypeText(rem);

                AdvancedReminderProperties          avrProps = DLLocalDatabase.AVRProperty.GetAVRProperties(rem.Id);
                List <AdvancedReminderFilesFolders> avrFF    = DLLocalDatabase.AVRProperty.GetAVRFilesFolders(rem.Id);

                if (rem.HttpId != null)
                {
                    HttpRequests req = DLLocalDatabase.HttpRequest.GetHttpRequest(rem.Id);
                }
            }
            catch (Exception ex)
            {
                return(ex);
            }

            return(null);
        }