static void test() { try { string ipaddress = "192.168.67.215"; string hostServer = @"\\" + ipaddress + @"\monitor\"; // NetworkShare.ConnectToShare(hostServer, "atladmin", "7mmT@XAy"); //Connect with the new credentials NetworkShare.ConnectToShare(@"\\192.168.67.215\monitor", "atladmin", "7mmT@XAy"); string filepath = ("C:\\webs\\atl_pbx_web\\recordings\\"); DirectoryInfo diSource = new DirectoryInfo(hostServer); DirectoryInfo diTarget = new DirectoryInfo(filepath); foreach (FileInfo wav_file in diSource.GetFiles()) { if (wav_file.CreationTime < DateTime.Now.AddMinutes(-13)) { if (File.Exists(Path.Combine(diTarget.FullName, wav_file.Name))) { File.Delete(Path.Combine(diTarget.FullName, wav_file.Name)); } wav_file.MoveTo(Path.Combine(diTarget.FullName, wav_file.Name)); WriteToFile("Successfully moved file... " + wav_file.Name); } } NetworkShare.DisconnectFromShare(hostServer, false); //Disconnect from the server. } catch (Exception ex) { WriteToFile(ex.Message.ToString()); } }
private void deleteShareBtn_Click(object sender, EventArgs e) { NetworkShare[] shareBuffer = new NetworkShare[sharesListBox.SelectedItems.Count]; StringBuilder sb = new StringBuilder(); sb.AppendLine("Do you want to delete these entries?\n"); int i = 0; foreach (Object item in sharesListBox.SelectedItems) { NetworkShare share = (NetworkShare)item; sb.AppendLine("(" + share.ShareLetter + ":) " + share.SharePath); shareBuffer[i] = share; i++; } DialogResult result = MessageBox.Show(sb.ToString(), "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { foreach (NetworkShare share in shareBuffer) { NetworkShares.Instance.Shares.Remove(share); DatabaseConnection connection = DatabaseConnection.Instance; var database = connection.Client.GetDatabase(Properties.Settings.Default.mongodb_database); var collection = database.GetCollection <BsonDocument>(Properties.Settings.Default.mongodb_collection_shares); collection.DeleteOne(Builders <BsonDocument> .Filter.Eq("share_letter", share.ShareLetter)); } } }
public FormMain() { InitializeComponent(); AppConfig.Instance.LoadAppSetting( System.Configuration.ConfigurationManager.AppSettings["db"]); AppConfig.Instance.LoadGateSetting( int.Parse(System.Configuration.ConfigurationManager.AppSettings["gateid"])); useNetworkStorage = int.Parse(ConfigurationManager.AppSettings["use_remote_file"]) > 0 ? true : false; if (useNetworkStorage) { //open network share share_server = ConfigurationManager.AppSettings["remote_server"]; share_folder = ConfigurationManager.AppSettings["remote_share"]; share_user = ConfigurationManager.AppSettings["remote_user"]; share_password = ConfigurationManager.AppSettings["remote_password"]; share_path = ConfigurationManager.AppSettings["remote_folder"]; networkShare = new NetworkShare(); networkShare.LoginToShare(share_server, share_folder, share_user, share_password); if (share_path.Length > 0) { imagePath = string.Format(@"\\{0}\{1}\{2}\", share_server, share_folder, share_path); } else { imagePath = string.Format(@"\\{0}\{1}\", share_server, share_folder); } } else { imagePath = ConfigurationManager.AppSettings["local_image_dir"]; } }
public ShareForm(NetworkShare share) { InitializeComponent(); this.LoadDriveLetters(); this.editShare = share; this.newShareBtn.Text = this.Text = "Edit Share"; this.pathTbx.Text = share.SharePath; this.driveLettersCbx.SelectedIndex = this.driveLettersCbx.FindString(share.ShareLetter); }
public frmJournalLoad1C() { InitializeComponent(); if (Config.hCntMain == null) { Config.hCntMain = new Procedures(ConnectionSettings.GetServer(), ConnectionSettings.GetDatabase(), ConnectionSettings.GetUsername(), ConnectionSettings.GetPassword(), ConnectionSettings.ProgramName); } dgvData.AutoGenerateColumns = false; net = new NetworkShare(true, false); }
public FormMain() { InitializeComponent(); timer.Start(); RFID_START_DELIM = Properties.Settings.Default.SerialStartChar; RFID_END_DELIM = Properties.Settings.Default.SerialEndChar; AppConfig.Instance.LoadAppSetting( ConfigurationManager.AppSettings["db"]); AppConfig.Instance.LoadGateSetting( int.Parse(ConfigurationManager.AppSettings["gateid"])); //check if using network share to store image string share = ConfigurationManager.AppSettings["use_network_share"]; useNetworkShare = int.Parse(share) > 0 ? true : false; if (useNetworkShare) { //open network share share_server = ConfigurationManager.AppSettings["remote_server"]; share_folder = ConfigurationManager.AppSettings["remote_share"]; share_user = ConfigurationManager.AppSettings["remote_user"]; share_password = ConfigurationManager.AppSettings["remote_password"]; share_path = ConfigurationManager.AppSettings["remote_folder"]; networkShare = new NetworkShare(); networkShare.LoginToShare(share_server, share_folder, share_user, share_password); if (share_path.Length > 0) { imagePath = string.Format(@"\\{0}\{1}\{2}\", share_server, share_folder, share_path); } else { imagePath = string.Format(@"\\{0}\{1}\", share_server, share_folder); } } else { imagePath = System.IO.Path.Combine(Application.StartupPath, "images"); if (!System.IO.Directory.Exists(imagePath)) { System.IO.Directory.CreateDirectory(imagePath); } } }
private void frmLoaderFile1C_Load(object sender, EventArgs e) { DataTable conf = Config.hCntMain.EditGetConf(ConnectionSettings.GetIdProgram(), "", ""); EnumerableRowCollection <DataRow> rowCollect = conf.AsEnumerable().Where(r => r.Field <string>("id_value").Equals("psss")); if (rowCollect.Count() > 0) { net = new NetworkShare(true, false); net.ConnectToShare(); pathSign = rowCollect.First()["value"].ToString() + "\\sign"; if (!Directory.Exists(pathSign)) { MessageBox.Show(Config.centralText("Программа не обнаружила\nкаталога с подписями\nарендодателей.\nЗагрузка счетов 1С невозможна.\n"), "Загрузка счетов", MessageBoxButtons.OK, MessageBoxIcon.Warning); Close(); return; } } }
private void unmountBtn_Click(object sender, EventArgs e) { foreach (Object item in sharesListBox.SelectedItems) { NetworkShare share = (NetworkShare)item; if (NetworkDrives.IsDriveMapped(share.ShareLetter)) { NetworkDrives.DisconnectNetworkDrive(share.ShareLetter, false); share.IsMounted = false; } else { MessageBox.Show("You can not unmount an unmounted drive.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } } NetworkShares.Instance.Sync(); }
private void addShareBtn_Click(object sender, EventArgs e) { foreach (Object item in sharesListBox.SelectedItems) { NetworkShare share = (NetworkShare)item; if (NetworkDrives.IsDriveMapped(share.ShareLetter)) { MessageBox.Show("Letter Drive (" + share.ShareLetter + ":) is already mounted!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { NetworkDrives.MapNetworkDrive(share.ShareLetter, share.SharePath); share.IsMounted = true; } } NetworkShares.Instance.Sync(); }
private void editShareBtn_Click(object sender, EventArgs e) { NetworkShare[] shareBuffer = new NetworkShare[sharesListBox.SelectedItems.Count]; int i = 0; foreach (Object item in sharesListBox.SelectedItems) { NetworkShare share = (NetworkShare)item; shareBuffer[i] = share; i++; } foreach (NetworkShare share in shareBuffer) { ShareForm sf = new ShareForm(share); sf.ShowDialog(); } }
public override void Connect_To_Database(StorageConfig config) { myConfig = config as CSVConfig; if (myConfig == null) { throw new Exception("Database Config is NULL"); } if (!string.IsNullOrEmpty(myConfig.NetworkUserName)) { try { networkShare = new NetworkShare(Path.GetDirectoryName(myConfig.Textfile), myConfig.NetworkUserName, myConfig.NetworkPassword); } catch (Exception ex) { if (!RaiseThreadExceptionOccured(this, ex)) { Logging.LogText("Exception: ", ex, Logging.LogLevel.Error); } } } }
private async void btSave_Click(object sender, EventArgs e) { blockers.SaveControlsEnabledState(this); blockers.SetControlsEnabled(this, false); progressBar1.Visible = true; var result = await Task <bool> .Factory.StartNew(() => { lStringError.Clear(); net = new NetworkShare(true, false); pathSignTmpPDF = tbPath.Text + "\\tmpPdfSign\\"; pathEndParse = tbPath.Text + "\\EndParse\\"; if (!Directory.Exists(pathSignTmpPDF)) { Directory.CreateDirectory(pathSignTmpPDF); } if (!Directory.Exists(pathEndParse)) { Directory.CreateDirectory(pathEndParse); } lFileData.Clear(); var listFileExcel = Directory.GetFiles(tbPath.Text).Where(s => s.EndsWith(".xls") || s.EndsWith(".xlsx")); var listFileWord = Directory.GetFiles(tbPath.Text).Where(s => s.EndsWith(".doc") || s.EndsWith(".docx")); var listFilePDF = Directory.GetFiles(tbPath.Text).Where(s => s.EndsWith(".pdf")); Logging.StartFirstLevel((int)LogEvents.Добавление_связи_договора_в_БД); if (listFileExcel.Count() > 0) { Logging.Comment("Обработка файлов Excel"); } foreach (string filePath in listFileExcel) { ParseExcelFile(filePath); } if (listFileWord.Count() > 0) { Logging.Comment("Обработка файлов Word"); } foreach (string filePath in listFileWord) { ParseWordFile(filePath); } Logging.StopFirstLevel(); if (lStringError.Count > 0) { Logging.StartFirstLevel((int)LogEvents.Нет_Подписей); string msg = "У следующих арендодателей\nотсутствуют файлы подписи для\nсчетов 1С.\n"; Logging.Comment("Отсутствуют подписи для создания pdf файлов у арендодателей"); foreach (string s in lStringError) { Logging.Comment(s); msg += $"- {s}\n"; } Logging.StopFirstLevel(); msg += $"Их файлы не будут обработаны."; MessageBox.Show(Config.centralText(msg + "\n"), "У арендодателей отсутствуют подписи", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (lFileData.Count > 0) { if (DialogResult.Yes == MessageBox.Show(Config.centralText("В процессе загрузки счетов 1С найдены счета\nбез связи с договором. Установить связь\n вручную и обработать счета заново?\n"), "Обнаружены не связанные договора", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) { lStringError.Clear(); if (DialogResult.OK == new frmLinkAgreementVs1C() { lFileData = lFileData.ToList() }.ShowDialog()) { var ListToParse = lFileData.AsEnumerable <FileData>().Where(r => r.idAgreement != 0); if (ListToParse.Count() > 0) { Logging.StartFirstLevel((int)LogEvents.учное_добавление_связи_договора_в_БД); foreach (FileData fData in ListToParse) { if (!AddSignAndConvertToPDF(fData.tFile, fData)) { } } Logging.StopFirstLevel(); if (lStringError.Count > 0) { Logging.StartFirstLevel((int)LogEvents.Нет_Подписей); Logging.Comment("Отсутствуют подписи для создания pdf файлов у арендодателей"); string msg = "У следующих арендодателей\nотсутствуют файлы подписи для\nсчетов 1С.\n"; foreach (string s in lStringError) { Logging.Comment(s); msg += $"- {s}\n"; } Logging.StopFirstLevel(); msg += $"Их файлы не будут обработаны."; MessageBox.Show(Config.centralText(msg + "\n"), "У арендодателей отсутствуют подписи", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } } Config.DoOnUIThread(() => { blockers.RestoreControlEnabledState(this); progressBar1.Visible = false; }, this); MessageBox.Show(Config.centralText("Загрузка счетов 1С\nзавершена.\n"), "Загрузка счетов 1С", MessageBoxButtons.OK, MessageBoxIcon.Information); return(true); }); }
private void frmDocument_Load(object sender, EventArgs e) { net = new NetworkShare(true, isLandLoard); getData(); dgvScan_CurrentCellChanged(null, null); }
private void newShareBtn_Click(object sender, EventArgs e) { string driveLetter = this.driveLettersCbx.SelectedItem.ToString(); string path = this.pathTbx.Text; if (string.IsNullOrEmpty(path)) { MessageBox.Show("Path is not set!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { // New Share if (editShare == null) { bool wentWrong = false; NetworkShare share = new NetworkShare(driveLetter, path); var document = new BsonDocument { { "share_letter", new BsonString(driveLetter) }, { "share_path", new BsonString(path) } }; DatabaseConnection connection = DatabaseConnection.Instance; var database = connection.Client.GetDatabase(Properties.Settings.Default.mongodb_database); var collection = database.GetCollection <BsonDocument>(Properties.Settings.Default.mongodb_collection_shares); try { collection.InsertOne(document); } catch (MongoServerException mse) { wentWrong = true; MessageBox.Show(mse.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (!wentWrong) { NetworkShares.Instance.Shares.Add(share); } else { wentWrong = false; } } this.Close(); } else // Edit Share { NetworkShares shares = NetworkShares.Instance; int index = shares.Shares.IndexOf(editShare); string editLetter = editShare.ShareLetter; editShare.ShareLetter = driveLetter; editShare.SharePath = path; shares.Shares[index] = editShare; DatabaseConnection connection = DatabaseConnection.Instance; var database = connection.Client.GetDatabase(Properties.Settings.Default.mongodb_database); var collection = database.GetCollection <BsonDocument>(Properties.Settings.Default.mongodb_collection_shares); var filter = Builders <BsonDocument> .Filter.Eq("share_letter", editLetter); var update = Builders <BsonDocument> .Update .Set("share_letter", driveLetter) .Set("share_path", path); var result = collection.UpdateOne(filter, update); this.Close(); } } }
protected void Page_Load(object sender, EventArgs e) { try { if (Session[Constants.NameSessionUser] == null) { Utilities.logout(Page.Session, Page.Response); } else { _user = (Users)Session[Constants.NameSessionUser]; } if (!IsPostBack) { Session[_nombreSession] = null; } if (Request.Params["numero"] != null && Request.Params["rutapdf"] != null) { _nodoc = Request.Params["numero"].ToString(); _rutapdf = Request.Params["rutapdf"].ToString(); NetworkShare.ConnectToShare(@"\\10.10.10.30\FileRepositorySS", "Administrator", "adminBata."); //System.IO.FileInfo file = new System.IO.FileInfo(@_rutapdf); //if ((file.Exists)) //{ Response.Clear(); //Response.AddHeader("Content-Disposition", "attachment; filename=" + _nodoc + ".pdf"); ////Response.AddHeader("Content-Length", file.Length.ToString()); //Response.ContentType = "Application/pdf"; ////Response.TransmitFile(Server.MapPath(_rutapdf)); //Response.WriteFile(_rutapdf); string pdfPath = _rutapdf; WebClient client = new WebClient(); Byte[] buffer = client.DownloadData(@pdfPath); Response.AddHeader("Content-Disposition", "attachment; filename=" + _nodoc + ".pdf"); Response.ContentType = "application/pdf"; Response.AddHeader("content-length", buffer.Length.ToString()); Response.BinaryWrite(buffer); Response.End(); Response.Close(); //file = null; //} //Set the appropriate ContentType. //Response.ContentType = "Application/pdf"; ////Get the physical path to the file. //string FilePath = MapPath(_rutapdf + ".pdf"); ////Write the file directly to the HTTP content output stream. //Response.WriteFile(FilePath); //Response.End(); //HttpContext.Current.Response.Clear(); //HttpContext.Current.Response.ContentType = "application/pdf"; ////Response.Clear(); ////Response.ContentType = "application/pdf"; //HttpContext.Current.Response.AddHeader( // "content-disposition", string.Format("attachment; filename={0}", _nodoc + ".pdf")); //HttpContext.Current.Response.End(); //Response.AppendHeader("Content-Disposition", "attachment; filename=" + _nodoc + ".pdf"); //Response.TransmitFile(_rutapdf); //Response.End(); } } catch (Exception ex) { this.msnMessage.LoadMessage(ex.Message, ucMessage.MessageType.Error); //throw new Exception(msgErr.Message, msgErr.InnerException); //Response.Redirect("panelReturns.aspx"); } }
static void Main(string[] args) { System.Threading.Thread.Sleep(10000); try { // FOR TEST ONLY: if (false) { args = new string[6]; args[0] = "Database=LinkManager"; args[1] = "ClientName=LinkManager"; args[2] = "DatabaseProvider=System.Data.SqlClient"; args[3] = "ConnectionString=Data%20Source%3D.%5CStandard%3BInitial%20Catalog%3DLinkManager%3BIntegrated%20Security%3DTrue"; args[4] = "FileName=C%3A%5CProjects%5CBlueocean%5CLink%5CLinkLibraries%5CLinkManager%5CClients%5CLinkOnline%5CLinkOnline%5CFileadmin%5CClientBackups%5Clinkmanager.xml"; args[5] = "BackupEntryPath=ClientBackups%2FClientBackup%5B%40Id%3D%227c384b95-8d92-4147-bd3c-4949bcceb4c7%22%5D"; } // Run through all command line arguments. foreach (string arg in args) { // Get the name of the argument. string name = arg.Split('=')[0]; // Get the value of the argument. string value = HttpUtility.UrlDecode(arg.Split('=')[1]); switch (name) { case "FileName": fileNameClientBackups = value; break; case "BackupEntryPath": clientBackupEntryPath = value; break; case "Database": databaseName = value; break; case "ClientName": clientName = value; break; case "DatabaseProvider": databaseProvider = HttpUtility.UrlDecode(value); break; case "ConnectionString": connectionString = HttpUtility.UrlDecode(value); break; } } clientUsers = new List <Guid>(); GetClientUsers(); // Build the full path to the backup directory name. string directoryName = Path.Combine( ConfigurationManager.AppSettings["BackupRoot"], DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MMM"), clientName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") ); if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Username"])) { if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // Backup the client's definition files. BackupFileSystem(directoryName); // Backup the client's database. BackupDatabase(Path.Combine( directoryName, clientName + ".bak" )); } else { string error = NetworkShare.ConnectToShare( ConfigurationManager.AppSettings["BackupRoot"], ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"] ); /*using (new NetworkConnection(ConfigurationManager.AppSettings["BackupRoot"], new System.Net.NetworkCredential( * ConfigurationManager.AppSettings["Username"], * ConfigurationManager.AppSettings["Password"] * )))*/ { if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // Backup the client's definition files. BackupFileSystem(directoryName); string tempFile = Path.GetTempFileName() + ".bak"; // Backup the client's database. BackupDatabase(tempFile); File.Move(tempFile, Path.Combine( directoryName, clientName + ".bak" )); } NetworkShare.DisconnectFromShare( ConfigurationManager.AppSettings["BackupRoot"], false ); } XmlDocument document = new XmlDocument(); document.Load(fileNameClientBackups); XmlNode xmlNode = document.SelectSingleNode(clientBackupEntryPath); xmlNode.Attributes["Status"].Value = "Finished"; xmlNode.Attributes["FinishDate"].Value = DateTime.Now.ToString(); xmlNode.Attributes["BackupPath"].Value = directoryName; document.Save(fileNameClientBackups); string zipPath = Path.Combine( ConfigurationManager.AppSettings["BackupRoot"], "Archives", DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MMM") ); string zipArchiveName = Path.Combine( zipPath, clientName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip" ); if (!Directory.Exists(zipPath)) { Directory.CreateDirectory(zipPath); } StreamWriter writer = new StreamWriter(zipArchiveName); ZipArchive zipArchive = new ZipArchive(writer.BaseStream, ZipArchiveMode.Create); CreateEntryFromDirectory(zipArchive, directoryName, false); zipArchive.Dispose(); } catch (Exception ex) { XmlDocument document = new XmlDocument(); document.Load(fileNameClientBackups); XmlNode xmlNode = document.SelectSingleNode(clientBackupEntryPath); xmlNode.Attributes["Status"].Value = "Failed"; xmlNode.Attributes["FinishDate"].Value = DateTime.Now.ToString(); xmlNode.Attributes["BackupPath"].Value = ""; xmlNode.InnerXml = ex.ToString(); document.Save(fileNameClientBackups); } }