private void EnumerateFiles() { TryAgain :; try { label2.Text = Resources.FileCount; if (RootPath != null) { foreach (string file in RootPath) { while (PauseOperation) { Thread.Sleep(500); } FilesCount++; } } CountingFilesOperation = false; } catch (Exception ex) { EasyLogger.Error(ex); goto TryAgain; } }
internal static void Create() { try { WshShell lib = new WshShell(); IWshShortcut _startMenuShortcut; string _programs = Environment.GetFolderPath(Environment.SpecialFolder.Programs); string _startup = Environment.GetFolderPath(Environment.SpecialFolder.Programs) + "\\Startup"; Directory.CreateDirectory(_programs + "\\" + Assembly.GetExecutingAssembly().GetName().Name); _startMenuShortcut = (IWshShortcut)lib.CreateShortcut(_programs + "\\" + Assembly.GetExecutingAssembly().GetName().Name + "\\" + Assembly.GetExecutingAssembly().GetName().Name + ".lnk"); _startMenuShortcut.TargetPath = Assembly.GetEntryAssembly().Location; _startMenuShortcut.WorkingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); _startMenuShortcut.Description = Assembly.GetExecutingAssembly().GetName().Name; _startMenuShortcut.Save(); _startMenuShortcut = (IWshShortcut)lib.CreateShortcut(_startup + "\\" + Assembly.GetExecutingAssembly().GetName().Name + ".lnk"); _startMenuShortcut.TargetPath = Assembly.GetEntryAssembly().Location; _startMenuShortcut.WorkingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); _startMenuShortcut.Description = Assembly.GetExecutingAssembly().GetName().Name; _startMenuShortcut.Save(); } catch (Exception ex) { EasyLogger.Error("CreateShortcut - @Create(1): " + ex); } }
public static void DeleteSetFiles() { // Delete Files foreach (string file in Default.FilesToDelete) { bool deleted = false; if (File.Exists(file)) { try { File.Delete(file); deleted = true; } catch (Exception ex) { deleted = false; EasyLogger.Error(file + " : " + ex); continue; } if (deleted) { EasyLogger.Info("Deleting file: " + file); } } } }
private static void Proc_DataReceived(object sender, DataReceivedEventArgs e) { if (e.Data != null) { if (e.Data.StartsWith("Program:")) { string file = e.Data.Replace("Program:", "").TrimStart(); if (Path.IsPathRooted(file) && !Path.GetDirectoryName(file).StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows))) { if (!FileExistance.FileExists(file)) { try { if (!BackedUp) { string datetime = DateTime.Now.ToString("Mdhms"); RunCommand("netsh", "advfirewall export " + "\"" + AppDomain.CurrentDomain.BaseDirectory + "\\Backup\\" + datetime + "_FirwallPolicy.wfw" + "\""); BackedUp = true; } EasyLogger.Info("Removing (inbound/outbound) " + file + " from Windows Firewall..."); RunCommand("netsh", "advfirewall firewall delete rule name=all program= " + "\"" + file + "\""); } catch (Exception ex) { EasyLogger.Error(ex.Message); } } } } } }
internal static async Task <string> PostAsync(string PAGE_ID, string NEW_PAGE_TOKEN, string MESSAGE_STRING, string LINK_URL) { try { Dictionary <string, string> values = new Dictionary <string, string> { { "message", MESSAGE_STRING }, { "link", LINK_URL }, { "access_token", NEW_PAGE_TOKEN } }; FormUrlEncodedContent content = new FormUrlEncodedContent(values); HttpResponseMessage response = await client.PostAsync("https://graph.facebook.com/" + PAGE_ID + "/feed?", content); _ = await response.Content.ReadAsStringAsync(); return("OK"); } catch (Exception ex) { EasyLogger.Error("FacebookText - @Post(2): " + ex); return("Error: " + ex.Message); } }
private static void StartApp() { AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException; Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); try { if (Properties.Settings.Default.UpgradeRequired) { Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.DBBackupTime = Properties.Settings.Default.DBBackupTime; Properties.Settings.Default.Save(); Properties.Settings.Default.Upgrade(); } Properties.Settings.Default.Save(); Properties.Settings.Default.Reload(); } catch (Exception ex) { EasyLogger.Error("Program - @StartApp(1): " + ex); } try { Application.Run(new Scheduler()); } catch (Exception ex) { EasyLogger.Error("Program - @StartApp(2): " + ex); MessageBox.Show(ex.Message, "social Post Scheduler", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void DeleteSetPaths() { // Delete Files foreach (string dir in Default.DirectoriesToDelete) { bool deleted = false; if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); deleted = true; } catch (Exception ex) { try { using (Process proc = new Process()) { proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.Arguments = "/C takeown /a /r /d Y /f" + dir; proc.Start(); proc.WaitForExit(); } var file = new FileInfo(dir.ToString()) { Attributes = FileAttributes.Normal }; foreach (var subDirectoryPath in Directory.GetDirectories(dir)) { var directoryInfo = new DirectoryInfo(subDirectoryPath); foreach (var filePath in directoryInfo.GetFiles()) { file = new FileInfo(filePath.ToString()) { Attributes = FileAttributes.Normal }; } } Directory.Delete(dir, true); } catch (Exception) { deleted = false; EasyLogger.Error(dir + " : " + ex); continue; } } if (deleted) { EasyLogger.Info("Deleting directory: " + dir); } } } }
internal static bool FileExists(string filename) { try { StringBuilder longPath = new StringBuilder(255); GetLongPathName(Path.GetFullPath(filename), longPath, longPath.Capacity); if (File.Exists(longPath.ToString())) { return(true); } if (Directory.Exists(longPath.ToString())) { return(true); } else { return(false); } } catch (Exception ex) { #if DEBUG EasyLogger.Error(ex); MessageBox.Show(ex.Message); #endif return(true); } }
// Process StartInfo Method internal static void StartInfo(string process, string arguments = null, bool hidden = false, bool runas = false, bool wait = false) { try { using (Process proc = new Process()) { if (arguments != null) { proc.StartInfo.Arguments = arguments; } proc.StartInfo.FileName = process; if (hidden) { proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; } if (runas) { proc.StartInfo.Verb = "runas"; } proc.StartInfo.UseShellExecute = true; proc.Start(); if (wait) { proc.WaitForExit(); } } } catch (System.ComponentModel.Win32Exception ex) { EasyLogger.Error(ex.Message); } }
public static void SetAsHidden() { // Hide Files foreach (var hideFile in Default.FilesToHide) { try { var filePath = Environment.ExpandEnvironmentVariables(hideFile); if (File.Exists(filePath)) { if ((File.GetAttributes(filePath) & FileAttributes.Hidden) != FileAttributes.Hidden) { FileAttributes attributes = File.GetAttributes(filePath); if (attributes != FileAttributes.Hidden || attributes != FileAttributes.System) { EasyLogger.Info("Hiding file: " + filePath); File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden); File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.System); } } } } catch (Exception ex) { EasyLogger.Error(hideFile + " : " + ex); continue; } } // Hide Directories foreach (var hideFile in Default.DirectoriesToHide) { try { var filePath = Environment.ExpandEnvironmentVariables(hideFile); if (Directory.Exists(filePath)) { if ((File.GetAttributes(filePath) & FileAttributes.Hidden) != FileAttributes.Hidden) { EasyLogger.Info("Hiding directory: " + filePath); FileAttributes attributes = File.GetAttributes(filePath); if (attributes != FileAttributes.Hidden || attributes != FileAttributes.System) { File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden); File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.System); } } } } catch (Exception ex) { EasyLogger.Error(hideFile + " : " + ex); continue; } } }
private void AddTexValuesComboBox(ComboBox comboBox, StringCollection collection, bool isService = false) { string selected = comboBox.Text; bool ItemExists = false; if (selected != string.Empty) { foreach (string item in comboBox.Items) { if (item == selected) { ItemExists = true; break; } } if (!ItemExists) { if (!isService) { comboBox.Items.Add(selected); collection.Add(selected); } else { try { ServiceController sc = new ServiceController(selected); var displayName = sc.DisplayName; foreach (string item in comboBox.Items) { if (item == selected + ';' + displayName) { ItemExists = true; break; } } if (!ItemExists) { comboBox.Items.Add(selected + ';' + displayName); collection.Add(selected + ';' + displayName); } } catch (Exception ex) { EasyLogger.Error(selected + " : " + ex + Environment.NewLine); BeginInvoke(new MethodInvoker(() => Console(selected + " : " + ex.Message))); } } } comboBox.Text = string.Empty; } Default.Save(); }
internal async Task <string> FollowAsync(string _SCREEN_NAME) { try { string success = "No actions were taken..."; string USER_ID = string.Empty; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("authorization", "Bearer " + _BEARER_TOKEN); string response = await client.GetStringAsync("https://api.twitter.com/1.1/followers/ids.json?screen_name=" + _SCREEN_NAME); JObject jdata = JObject.Parse(response); JToken array = jdata["ids"]; foreach (JToken id in array) { USER_ID = id.ToString(); using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.FollowersConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) from Follow where TwitterId = @TwitterId", connection)) { connection.Open(); sqlCommand.Parameters.AddWithValue("@TwitterId", USER_ID); int userCount = (int)sqlCommand.ExecuteScalar(); if (userCount == 0) { success = await SendFollowRequest(USER_ID); if (success == "OK") { string values = "INSERT into Follow (TwitterId) VALUES (@TwitterId)"; using (SqlCommand command = new SqlCommand(values)) { command.Connection = connection; command.Parameters.AddWithValue("@TwitterId", USER_ID); command.ExecuteNonQuery(); } } } } } } } return(success); } catch (Exception ex) { EasyLogger.Error("GetToken - @RenewAccessToken(1): " + ex); return("ERROR: " + ex.Message); } }
private static void DeleteEmptySubdirectories(string parentDirectory) { foreach (string directory in Directory.GetDirectories(parentDirectory)) { if (directory != Environment.GetFolderPath(Environment.SpecialFolder.Startup) && directory != Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup) && directory != programs + "\\Administrative Tools" && directory != commonPrograms + "\\Administrative Tools" && directory != programs + "\\Windows Administrative Tools" && directory != commonPrograms + "\\Windows Administrative Tools" && directory != programs + "\\Windows System" && directory != commonPrograms + "\\Windows System" && directory != programs + "\\Windows Accessories" && directory != commonPrograms + "\\Windows Accessories" && directory != programs + "\\Windows Ease of Access" && directory != commonPrograms + "\\Windows Ease of Access" && directory != programs + "\\Games" && directory != commonPrograms + "\\Games") { try { DeleteEmptySubdirectories(directory); } catch { continue; } try { int totalDirectories = 0; foreach (string dir in Directory.GetDirectories(directory)) { totalDirectories++; } if (totalDirectories == 0) { int totalFiles = 0; foreach (string file in Directory.GetFiles(directory)) { if (Path.GetFileName(file.ToLower()) != "desktop.ini" && Path.GetFileName(file.ToLower()) != "thumbs.db") { totalFiles++; } } if (totalFiles == 0) { foreach (string file in Directory.GetFiles(directory)) { if (Path.GetFileName(file.ToLower()) == "desktop.ini" || Path.GetFileName(file.ToLower()) == "thumbs.db") { File.Delete(file); } } EasyLogger.Info("Removing empty directory: " + directory); try { Directory.Delete(directory); } catch (Exception ex) { EasyLogger.Error(ex); } } } } catch { continue; } } } }
private void Log_Click(object sender, EventArgs e) { // Used to isolate errors EasyLogger.Error("The log file path is: " + EasyLogger.LogFile); // Used to isolate warnings EasyLogger.Warning("The log file path is: " + EasyLogger.LogFile); // Used to isolate information EasyLogger.Info("The log file path is: " + EasyLogger.LogFile); }
private void CopyPathURLMethod() { Clipboard.Clear(); string[] array = SelectedItemPaths.Cast <string>().ToArray(); try { Clipboard.SetText(new Uri(array.ToStringArray(false)).AbsoluteUri); } catch (Exception ex) { EasyLogger.Error(ex); } }
internal static void ExecuteBackup() { try { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "BACKUPS"); EasyLogger.Info("Creating a new backup of the database..."); ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "sqllocaldb", Arguments = "stop MSSQLLocalDB", CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; Process process = new Process { StartInfo = startInfo }; process.Start(); process.WaitForExit(); } catch (Exception ex) { ErrorsHaveOccurred = true; EasyLogger.Error("BackupDatabase - @ExecuteBackup(1): " + ex); MessageBox.Show(ex.Message, "Followers", MessageBoxButtons.OK, MessageBoxIcon.Error); } try { if (File.Exists(databaseBackup)) { File.Copy(databaseBackup, databaseOLDBackup, true); } if (File.Exists(sourceBackup)) { File.Copy(sourceBackup, databaseBackup, true); } if (File.Exists(databaseBackup)) { File.SetLastWriteTime(databaseBackup, DateTime.Now); } } catch (Exception ex) { ErrorsHaveOccurred = true; EasyLogger.Error("BackupDatabase - @ExecuteBackup(2): " + ex); MessageBox.Show(ex.Message, "Followers", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static void Main() { int tries = 60; TryAgain :; try { if (!SQLConnection.IsServerConnected(Properties.Settings.Default.FollowersConnectionString)) { tries--; if (tries > 0) { EasyLogger.Warning("SQL Server is not responding. I'll try again " + tries + " more times until I require user input..."); Thread.Sleep(2000); goto TryAgain; } else { DialogResult result = MessageBox.Show("SQL Server is not responding. Would you like to try again?", "Social Post Scheduler", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { goto TryAgain; } else { Environment.Exit(0); } } } } catch (Exception ex) { EasyLogger.Error(ex); } try { System.Reflection.Assembly assembly = typeof(Program).Assembly; GuidAttribute attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0]; string id = attribute.Value; StartApp(); } catch (Exception ex) { EasyLogger.Error("Program - @Main(1): " + ex); MessageBox.Show(ex.Message, "TwitterFollower", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
internal static async Task <string> PostAsync(string IMAGE_URL, string MESSAGE_STRING) { try { Dictionary <string, string> values = new Dictionary <string, string> { { "image_url", IMAGE_URL }, { "caption", MESSAGE_STRING }, { "access_token", Properties.Settings.Default.InstagramToken } }; FormUrlEncodedContent content = new FormUrlEncodedContent(values); HttpResponseMessage response = null; string responseString = string.Empty; try { response = await client.PostAsync("https://graph.facebook.com/" + Properties.Settings.Default.InstagramPageID + "/media?", content); responseString = await response.Content.ReadAsStringAsync(); JObject json = JObject.Parse(responseString); string creation_id = json["id"].ToString(); values = new Dictionary <string, string> { { "creation_id", creation_id }, { "access_token", Properties.Settings.Default.InstagramToken } }; content = new FormUrlEncodedContent(values); response = await client.PostAsync("https://graph.facebook.com/" + Properties.Settings.Default.InstagramPageID + "/media_publish?", content); responseString = await response.Content.ReadAsStringAsync(); } catch { return("Instagram error for post " + MESSAGE_STRING + Environment.NewLine + responseString.ToString()); } return("Instagram results for post " + MESSAGE_STRING + Environment.NewLine + responseString.ToString()); } catch (Exception ex) { EasyLogger.Error("Instagram - @Post(2): " + ex); return("Error: " + ex.Message); } }
public static void SetStatus() { // Services To Manual foreach (string service in Default.ServicesToManual) { string serv = service.Split(';')[0]; try { var status = ServiceStatus(serv); if (status != "NA" && ServiceStatus(serv) != "Manual") { SetService(serv, "Manual"); StopServices(serv); } } catch (Exception ex) { EasyLogger.Error(service + " : " + ex); continue; } } // Services To Disable foreach (string service in Default.ServicesToDisable) { string serv = service.Split(';')[0]; try { var status = ServiceStatus(serv); if (status != "NA" && ServiceStatus(serv) != "Disabled") { SetService(serv, "Disabled"); StopServices(serv); } } catch (Exception ex) { EasyLogger.Error(service + " : " + ex); continue; } } }
private static void StartApp() { AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException; Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } catch (Exception ex) { EasyLogger.Error("Program - @StartApp(2): " + ex); MessageBox.Show(ex.Message, "TwitterFollower", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static DialogResult MessageForm(string text, string title = null, MessageBoxButtons buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Information, MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button2) { try { // Log this message for debugging if (icon == MessageBoxIcon.Error) { EasyLogger.Error(text); } else if (icon == MessageBoxIcon.Warning) { EasyLogger.Info(text); } else { EasyLogger.Info(text); } using (Form form = new Form()) { form.Opacity = 0; form.Show(); form.WindowState = FormWindowState.Minimized; form.WindowState = FormWindowState.Normal; DialogResult dialogResult = MessageBox.Show(form, text, title, buttons, icon, defaultButton); if (dialogResult == DialogResult.Yes) { form.Close(); } return(dialogResult); } } catch (Exception ex) { EasyLogger.Error(ex); return(DialogResult.None); } }
private void Proc_ErrorReceived(object sender, DataReceivedEventArgs e) { try { if (e.Data != null) { if (e.Data != string.Empty) { string Output = Regex.Replace(e.Data, "\x00", ""); EasyLogger.Info(Output); BeginInvoke(new MethodInvoker(() => Console(Output))); } } } catch (Exception ex) { EasyLogger.Error(ex + Environment.NewLine); BeginInvoke(new MethodInvoker(() => Console(ex.Message))); } }
internal static string RenewAccessToken(string USER_TOKEN, string APP_SECRET, string APP_ID) { try { using (WebClient wb = new WebClient()) { string responseInString = wb.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&client_secret=" + APP_SECRET + "&grant_type=fb_exchange_token&fb_exchange_token=" + USER_TOKEN); JObject json = JObject.Parse(responseInString); return(json["access_token"].ToString()); } } catch (Exception ex) { EasyLogger.Error("GetToken - @RenewAccessToken(1): " + ex); return("ERROR: " + ex.Message); } }
private void ServicesManualButton_Click(object sender, EventArgs e) { bool ItemExists = false; var selected = ServicesTextBox.Text; if (selected != string.Empty) { try { ServiceController sc = new ServiceController(selected); var displayName = sc.DisplayName; foreach (string item in ServicesManualBox.Items) { if (item == selected + ';' + displayName) { ItemExists = true; break; } } if (!ItemExists) { ServicesManualBox.Items.Add(selected + ';' + displayName); Default.ServicesToManual.Add(selected + ';' + displayName); } } catch (Exception ex) { EasyLogger.Error(selected + " : " + ex + Environment.NewLine); BeginInvoke(new MethodInvoker(() => Console(selected + " : " + ex.Message))); } ServicesTextBox.Text = string.Empty; } Default.Save(); }
public static void MessageLogging(string text, string title = null, MessageBoxButtons buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Information, MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button2) { try { // Log this message for debugging if (icon == MessageBoxIcon.Error) { EasyLogger.Error(text); } else if (icon == MessageBoxIcon.Warning) { EasyLogger.Info(text); } else { EasyLogger.Info(text); } } catch (Exception ex) { EasyLogger.Error(ex); } }
/// <summary> /// Publish a post with image /// </summary> /// <returns>result</returns> /// <param name="message">message to publish</param> /// <param name="pathToImage">image to attach</param> internal string PublishTweet(string message) { try { Task <string> rezText = Task.Run(async() => { string response = await Tweet(TweetLimit.CutTweetToLimit(message)); return(response); }); if (rezText.Result != "OK") { EasyLogger.Warning(rezText.Result); } return("OK"); } catch (Exception ex) { EasyLogger.Error("TweetMessage - @PublishTweet(1): " + ex); return(ex.Message); } }
public static void DeleteSetFiles() { // Delete Files and Folders in a Directory foreach (string paths in Default.PathFilesToDelete) { try { if (Directory.Exists(paths)) { var filesPath = Environment.ExpandEnvironmentVariables(paths); // Files foreach (string file in Directory.GetFiles(filesPath)) { bool deleted = false; try { File.Delete(file); deleted = true; } catch (Exception ex) { deleted = false; EasyLogger.Error(file + " : " + ex); continue; } if (deleted) { EasyLogger.Info("Deleting file: " + file); } } // Directories foreach (string directory in Directory.GetDirectories(filesPath)) { bool deleted = false; try { Directory.Delete(directory, true); deleted = true; } catch (Exception ex) { deleted = false; EasyLogger.Error(directory + " : " + ex); continue; } if (deleted) { EasyLogger.Info("Deleting directory: " + directory); } } } } catch (Exception ex) { EasyLogger.Error(paths + " : " + ex); continue; } } }
// Add Menu Items private void AddMenuItems(string[] array) { try { // Disabler bool isShortcut = false; bool isExeDllFile = false; foreach (string path in array) { try { if (Path.GetExtension(path) == ".lnk") { isShortcut = true; } if (Path.GetExtension(path) != ".exe" && Path.GetExtension(path) != ".dll") { isExeDllFile = false; } if (Path.GetExtension(path) == ".exe" || Path.GetExtension(path) == ".dll") { isExeDllFile = true; } if (Directory.Exists(ShortcutHandler.GetShortcutTarget(path))) { } } catch (Exception ex) { EasyLogger.Error(ex.Message + " Error at ShortcutHandler.GetShortcutTarget(path)"); continue; } } object OpenNotepadFiles = xMenuToolsSettings.GetValue("OpenNotepadFiles"); if (OpenNotepadFiles != null) { if (OpenNotepadFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(OpenNotepad); } } object BlockWithFirewallFiles = xMenuToolsSettings.GetValue("BlockWithFirewallFiles"); if (BlockWithFirewallFiles != null) { if (BlockWithFirewallFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(BlockFirewall); } } object CopyPathFiles = xMenuToolsSettings.GetValue("CopyPathFiles"); if (CopyPathFiles != null && !isShortcut) { if (CopyPathFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(CopyPath); } } object CopyNameFiles = xMenuToolsSettings.GetValue("CopyNameFiles"); if (CopyNameFiles != null && !isShortcut) { if (CopyNameFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(CopyName); } } object AttributesFiles = xMenuToolsSettings.GetValue("AttributesFiles"); if (AttributesFiles != null) { if (AttributesFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(Attributes); Attributes.DropDownItems.Add(AttributesMenu); Attributes.DropDownItems.Add(new ToolStripSeparator()); Attributes.DropDownItems.Add(HiddenAttributes); Attributes.DropDownItems.Add(SystemAttributes); Attributes.DropDownItems.Add(ReadOnlyAttributes); } } object SymlinkFiles = xMenuToolsSettings.GetValue("SymlinkFiles"); if (SymlinkFiles != null) { if (SymlinkFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(SymLink); } } object TakeOwnershipFiles = xMenuToolsSettings.GetValue("TakeOwnershipFiles"); if (TakeOwnershipFiles != null) { if (TakeOwnershipFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(TakeOwnership); } } object AttributesShortcuts = xMenuToolsSettings.GetValue("AttributesShortcuts"); if (AttributesShortcuts != null && isShortcut) { if (AttributesShortcuts.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(Attributes); } else { Attributes.Dispose(); } } object OpenNotepadShort = xMenuToolsSettings.GetValue("OpenNotepadShort"); if (OpenNotepadShort != null && isShortcut) { if (OpenNotepadShort.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(OpenNotepad); } else { OpenNotepad.Dispose(); } } object CopyPathShortFiles = xMenuToolsSettings.GetValue("CopyPathShortFiles"); if (CopyPathShortFiles != null && isShortcut) { if (CopyPathShortFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(CopyPath); } } object CopyNameShortFiles = xMenuToolsSettings.GetValue("CopyNameShortFiles"); if (CopyNameShortFiles != null && isShortcut) { if (CopyNameShortFiles.ToString() == "1") { xMenuToolsMenu.DropDownItems.Add(CopyName); } } MenuItemDisabler(isShortcut, isExeDllFile); } catch (System.ComponentModel.Win32Exception ex) { StartProcess.StartInfo(AttributesInfo.GetAssembly.AssemblyInformation("directory") + @"\xMenuTools.exe", "\"" + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source + Environment.NewLine + ex.GetBaseException() + Environment.NewLine + ex.TargetSite + "\"" + " -catchhandler"); } }
// Delete Files and Folders in a Directory older than x days public static void DeleteSetFiles() { foreach (string path in Default.PathFilesToDeleteOlder) { try { int days = Convert.ToInt32(path.Split(',')[0]); var filesPath = Environment.ExpandEnvironmentVariables(path.Split(',')[1].Trim()); // Files foreach (string f in Directory.GetFiles(filesPath, "*", SearchOption.AllDirectories)) { bool deleted = false; try { FileInfo fi = new FileInfo(f); if (fi.LastWriteTime < DateTime.Now.AddDays(-days)) { File.Delete(f); deleted = true; } } catch (Exception ex) { deleted = false; EasyLogger.Error(f + " : " + ex); continue; } if (deleted) { EasyLogger.Info("Deleting file: " + f); } } // Directories string[] dirs = Directory.GetDirectories(filesPath, "*", SearchOption.AllDirectories); foreach (string d in dirs) { bool deleted = false; try { DirectoryInfo fi = new DirectoryInfo(d); if (fi.LastWriteTime < DateTime.Now.AddDays(-days)) { try { Directory.Delete(d, false); deleted = true; } catch { continue; } } } catch (Exception ex) { deleted = false; EasyLogger.Error(d + " : " + ex); continue; } if (deleted) { EasyLogger.Info("Deleting file: " + d); } } } catch (Exception ex) { EasyLogger.Error(path + " : " + ex); continue; } } }
/// <summary> /// {instagram_id}/media?image_url={image_url}&access_token={access_token} /// {instagram_id}/media_publish?creation_id={creation-id}&access_token={access_token} /// </summary> internal static void PostToInstagram() { try { string USER_TOKEN = GetToken.RenewAccessToken(Properties.Settings.Default.InstagramToken, Properties.Settings.Default.InstagramAppSecret, Properties.Settings.Default.InstagramAppID); if (USER_TOKEN.Contains("ERROR:")) { EasyLogger.Error(USER_TOKEN); } else { if (USER_TOKEN != "The remote server returned an error: (400) Bad Request.") { EasyLogger.Info("Your Instagram user token has been renewed successfully!"); Properties.Settings.Default.InstagramToken = USER_TOKEN; Properties.Settings.Default.Save(); Properties.Settings.Default.Reload(); } else { EasyLogger.Warning("Error: The remote server returned an error: (400) Bad Request."); return; } HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.WebsiteFeed); hwr.Accept = "text/xml, */*"; hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us"); hwr.UserAgent = "Mozilla"; hwr.KeepAlive = true; hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; using (var resp = (HttpWebResponse)hwr.GetResponse()) { using (Stream s = resp.GetResponseStream()) { string cs = String.IsNullOrEmpty(resp.CharacterSet) ? "UTF-8" : resp.CharacterSet; Encoding e = Encoding.GetEncoding(cs); using (StreamReader sr = new StreamReader(s, e)) { var allXml = sr.ReadToEnd(); allXml = Regex.Replace(allXml, "(.*)<script type='text/javascript'>.+?</script>(.*)", "$1$2", RegexOptions.Singleline); using (XmlReader xmlr = XmlReader.Create(new StringReader(allXml))) { SyndicationFeed feedContent = SyndicationFeed.Load(xmlr); List <SyndicationItem> feedItems = new List <SyndicationItem>(); foreach (SyndicationItem item in feedContent.Items) { feedItems.Add(item); } feedItems.Reverse(); feedContent.Items = feedItems; if (null == feedContent) { return; } foreach (SyndicationItem item in feedContent.Items) { string quota_total = string.Empty; string quota_usage = string.Empty; try { using (WebClient wb = new WebClient()) { string responseInString = wb.DownloadString("https://graph.facebook.com/" + Properties.Settings.Default.InstagramPageID + "/content_publishing_limit?fields=config&access_token=" + Properties.Settings.Default.InstagramToken); JObject jdata = JObject.Parse(responseInString); JToken array = jdata["data"]; foreach (JToken info in array) { quota_total = info["config"]["quota_total"].ToString(); } } using (WebClient wb = new WebClient()) { string responseInString = wb.DownloadString("https://graph.facebook.com/" + Properties.Settings.Default.InstagramPageID + "/content_publishing_limit?fields=quota_usage&access_token=" + Properties.Settings.Default.InstagramToken); JObject jdata = JObject.Parse(responseInString); JToken array = jdata["data"]; foreach (JToken info in array) { quota_usage = info["quota_usage"].ToString(); } } } catch { } int usage = Convert.ToInt32(quota_usage); int total = Convert.ToInt32(quota_total); if (usage >= total) { EasyLogger.Info("Instagram post quota reached!"); break; } try { System.Collections.ObjectModel.Collection <SyndicationLink> links = item.Links; string title = item.Title.Text + " - " + links[0].Uri.ToString(); string image = ExtensionMethods.GetEnclosureUri(item); DateTimeOffset date = item.PublishDate; if (StringToDTOffset(Properties.Settings.Default.PublishDate) < date) { Task <string> success = PostAsync(image, title); int posts_used = Convert.ToInt32(quota_usage); posts_used++; EasyLogger.Info(success.Result + Environment.NewLine + "Instagram Post usage for the day: " + posts_used + " of " + quota_total); Properties.Settings.Default.PublishDate = date.ToString(); Properties.Settings.Default.Save(); Properties.Settings.Default.Reload(); } } catch (Exception ex) { EasyLogger.Error(ex); continue; } } } } } } } } catch (Exception ex) { EasyLogger.Error(ex); } }