Example #1
0
        /// <summary>
        /// 获取文件夹相关信息
        /// </summary>
        /// <param name="dir">文件夹info</param>
        /// <param name="plies">层数</param>
        /// <returns></returns>
        public static RecordBean GetDirBean(DirectoryInfo dir, uint plies)
        {
            string       owner;
            RecordExCode errorCode;

            try
            {
                DirectorySecurity security = dir.GetAccessControl();
                IdentityReference identity = security.GetOwner(typeof(NTAccount));
                owner     = identity.ToString();
                errorCode = RecordExCode.Normal;
            }
            catch (IdentityNotMappedException e)
            {
                owner     = "IdentityNotMappedException";
                errorCode = RecordExCode.IdentityNotMappedException;
                Log.Warn(string.Format("获取文件夹所有者失败。{0} {1}, [error code: {2}]",
                                       dir.FullName, e.Message, errorCode));
            }
            catch (ArgumentException e)
            {
                owner     = "ArgumentException";
                errorCode = RecordExCode.ArgumentException;
                Log.Warn(string.Format("获取文件夹有者失败。{0} {1}, [error code: {2}]",
                                       dir.FullName, e.Message.Replace("\r\n", ""), errorCode));
            }
            catch (UnauthorizedAccessException e)
            {
                owner     = "UnauthorizedAccessException";
                errorCode = RecordExCode.ArgumentException;
                Log.Warn(string.Format("获取文件夹所有者失败。{0} {1}, [error code: {2}]",
                                       dir.FullName, e.Message, errorCode));
            }
            catch (InvalidOperationException e)
            {
                owner     = "InvalidOperationException";
                errorCode = RecordExCode.InvalidOperationException;
                Log.Warn(string.Format("获取文件夹所有者失败。{0} {1}, [error code: {2}]",
                                       dir.FullName, e.Message, errorCode));
            }
            catch (FileNotFoundException e)
            {
                errorCode = RecordExCode.NotFound;
                Log.Warn(string.Format("文件夹不存在。{0}, [error code: {1}]", e.Message, errorCode));
                return(new RecordBean()
                {
                    Path = dir.FullName,
                    ExceptionCode = (int)errorCode,
                });
            }
            return(new RecordBean()
            {
                Path = dir.FullName,
                Plies = plies,
                CerateTime = dir.CreationTime,
                Owner = owner,
                ExceptionCode = (int)errorCode,
                DirCount = 0,
                IsFile = false,
                IsChange = false,
            });
        }
Example #2
0
        protected override void ProcessRecord()
        {
            if (Directory.Exists(DirectoryPath))
            {
                DirectorySecurity security = null;

                //  Account, Rights, AccessControlから追加
                if (!string.IsNullOrEmpty(Account))
                {
                    if (security == null)
                    {
                        security = Directory.GetAccessControl(DirectoryPath);
                    }
                    string accessString = string.Format("{0};{1};{2};{3};{4}",
                                                        Account,
                                                        _Rights,
                                                        Recursive ? Item.CONTAINERINHERIT + ", " + Item.OBJECTINHERIT : Item.NONE,
                                                        Item.NONE,
                                                        AccessControl);

                    //  テスト自動生成
                    _generator.DirectoryAccess(DirectoryPath, accessString, true);

                    foreach (FileSystemAccessRule addRule in DirectoryControl.StringToAccessRules(accessString))
                    {
                        security.AddAccessRule(addRule);
                    }
                }

                //  Access文字列で追加
                if (!string.IsNullOrEmpty(Access))
                {
                    if (security == null)
                    {
                        security = Directory.GetAccessControl(DirectoryPath);
                    }

                    //  テスト自動生成
                    _generator.DirectoryAccess(DirectoryPath, Access, true);

                    foreach (FileSystemAccessRule addRule in DirectoryControl.StringToAccessRules(Access))
                    {
                        security.AddAccessRule(addRule);
                    }
                }

                //  Inherited設定
                if (Inherited != Item.NONE)
                {
                    if (security == null)
                    {
                        security = Directory.GetAccessControl(DirectoryPath);
                    }

                    //  テスト自動生成
                    _generator.DirectoryInherited(DirectoryPath, Inherited == Item.ENABLE);

                    switch (Inherited)
                    {
                    case Item.ENABLE:
                        security.SetAccessRuleProtection(false, false);
                        break;

                    case Item.DISABLE:
                        security.SetAccessRuleProtection(true, true);
                        break;

                    case Item.REMOVE:
                        security.SetAccessRuleProtection(true, false);
                        break;
                    }
                }

                if (security != null)
                {
                    Directory.SetAccessControl(DirectoryPath, security);
                }

                //  フォルダー属性を追加
                if (!string.IsNullOrEmpty(_Attributes))
                {
                    //  テスト自動生成
                    _generator.DirectoryAttributes(DirectoryPath, _Attributes, true);

                    FileAttributes nowAttr = File.GetAttributes(DirectoryPath);
                    FileAttributes addAttr = (FileAttributes)Enum.Parse(typeof(FileAttributes), _Attributes);
                    File.SetAttributes(DirectoryPath, nowAttr | addAttr);
                }

                WriteObject(new DirectorySummary(DirectoryPath, true));
            }
        }
        static void Main(string[] args)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                try
                {
                    if (serverManager != null)
                    {
                        Console.WriteLine("Set Application pool identity folderpermissions (Modify) to all websites? Y/N");
                        if (Console.ReadLine().ToUpper() == "Y")
                        {
                            using (StreamWriter sw = File.AppendText(logFile))
                            {
                                sw.WriteLine("Setting permissions for directories at " + DateTime.Now);
                                sw.WriteLine();
                            }

                            foreach (Site site in serverManager.Sites)
                            {
                                foreach (var application in site.Applications)
                                {
                                    string directoryPath = application.VirtualDirectories["/"].PhysicalPath;

                                    if (Directory.Exists(directoryPath))
                                    {
                                        using (StreamWriter sw = File.AppendText(logFile))
                                        {
                                            sw.WriteLine(application.ApplicationPoolName + ": " + directoryPath);
                                        }

                                        Console.WriteLine(application.ApplicationPoolName + ": " + directoryPath);

                                        DirectoryInfo     info = new DirectoryInfo(directoryPath);
                                        DirectorySecurity ds   = info.GetAccessControl();

                                        // Sets ACE to folder, sub-folders and files
                                        FileSystemAccessRule appIdentityRule = new FileSystemAccessRule(
                                            @"IIS APPPOOL\" + application.ApplicationPoolName,
                                            FileSystemRights.Modify,
                                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                            PropagationFlags.None,
                                            AccessControlType.Allow
                                            );

                                        ds.AddAccessRule(appIdentityRule);
                                        info.SetAccessControl(ds);
                                    }
                                    else
                                    {
                                        using (StreamWriter sw = File.AppendText(logFile))
                                        {
                                            sw.WriteLine("DIRECTORY MISSING FOR " + application.ApplicationPoolName + ": " + directoryPath);
                                        }

                                        Console.WriteLine("DIRECTORY MISSING FOR " +
                                                          application.ApplicationPoolName + ": " + directoryPath);
                                    }
                                }
                            }
                            using (StreamWriter sw = File.AppendText(logFile))
                            {
                                sw.WriteLine();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    using (StreamWriter sw = File.AppendText(logFile))
                    {
                        sw.WriteLine(e.Message);
                    }
                }
            }
        }
 /// <inheritdoc cref="System.IO.Directory.CreateDirectory(string)"/>
 /// <param name="path">The directory to create.</param>
 /// <param name="directorySecurity">The permissions that should be applied to created directory.</param>
 /// <include file="../Documentation/XmlDoc/TxFileSystem.XmlDoc.Extensions.xml" path='TxFileSystem.BaseDocs/Extensions/Operations/Operation[@kind="DirectoryOperation" and @type="create"]/*' />
 public IDirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     return(new CreateDirectoryOperation(this, path, directorySecurity).Execute());
 }
Example #5
0
 public static DirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     return(CreateDirectory(path));
 }
Example #6
0
 public void SetAccessControl(DirectorySecurity directorySecurity)
 {
     Directory.SetAccessControl(FullPath, directorySecurity);
 }
Example #7
0
 public override void SetAccessControl(string path, DirectorySecurity directorySecurity)
 {
     new DirectoryInfo(path).SetAccessControl(directorySecurity);
 }
 /// <summary>
 ///     Creates all the directories in the specified @this, applying the specified Windows security.
 /// </summary>
 /// <param name="this">The directory to create.</param>
 /// <param name="directorySecurity">The access control to apply to the directory.</param>
 /// <returns>An object that represents the directory for the specified @this.</returns>
 /// ###
 /// <exception cref="T:System.IO.IOException">
 ///     The directory specified by <paramref name="this" /> is a file.-or-The
 ///     network name is not known.
 /// </exception>
 /// ###
 /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
 /// ###
 /// <exception cref="T:System.ArgumentException">
 ///     <paramref name="this" /> is a zero-length string, contains only
 ///     white space, or contains one or more invalid characters as defined by
 ///     <see
 ///         cref="F:System.IO.Path.InvalidPathChars" />
 ///     . -or-<paramref name="this" /> is prefixed with, or contains only a colon character (:).
 /// </exception>
 /// ###
 /// <exception cref="T:System.ArgumentNullException">
 ///     <paramref name="this" /> is null.
 /// </exception>
 /// ###
 /// <exception cref="T:System.IO.PathTooLongException">
 ///     The specified @this, file name, or both exceed the system-
 ///     defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file
 ///     names must be less than 260 characters.
 /// </exception>
 /// ###
 /// <exception cref="T:System.IO.DirectoryNotFoundException">
 ///     The specified @this is invalid (for example, it is on
 ///     an unmapped drive).
 /// </exception>
 /// ###
 /// <exception cref="T:System.NotSupportedException">
 ///     <paramref name="this" /> contains a colon character (:) that
 ///     is not part of a drive label ("C:\").
 /// </exception>
 public static DirectoryInfo CreateDirectory(this FileInfo @this, DirectorySecurity directorySecurity)
 {
     return Directory.CreateDirectory(@this.Directory.FullName, directorySecurity);
 }
Example #9
0
        public void Init()
        {
            Processos     process       = new Processos();
            DirectoryInfo dir           = new DirectoryInfo(@"C:\\vch");
            FileInfo      fil           = new FileInfo(@"C:\\vch\\dados.db");
            int           ctrlFirstExec = 0;

            if (dir.Exists != true)
            {
                ctrlFirstExec = 1;
                string user = System.Windows.Forms.SystemInformation.UserName;
                System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo("C:\\");

                DirectorySecurity ds = new DirectorySecurity();
                ds.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Modify, AccessControlType.Allow));
                ds.SetAccessRuleProtection(false, false);
                folderInfo.Create(ds);
                folderInfo.CreateSubdirectory("vch");

                OrganizaTelaEvent(1);
            }

            if (fil.Exists != true)
            {
                try
                {
                    AuxiliarNhibernate.AbrirSessao();
                    //fil.Create();
                }
                catch (Exception e)
                {
                    //System.Windows.Forms.MessageBox.Show(e.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (process.ReadPermissionFolder() == false || process.ReadPermissionFile() == false)
            {
                OrganizaTelaEvent(1);
                return;
            }

            var sessao = AuxiliarNhibernate.AbrirSessao();

            Thread t = new Thread(process.VerificaParaAtualizar);

            t.Name = "UpdaterWorker";
            t.Start();

            if (ctrlFirstExec == 0)
            {
                var parametroDAO = new ParametroDAO(sessao);
                var param        = parametroDAO.BuscarPorID(1);//Armazenamento.GetParametros();

                int ctrl      = 0;
                int ctrlVazio = 0;
                try
                {
                    StaticParametros.SetGeraLogs(param.GeraLog);

                    if (param.CaminhoToke.Contains(".ives") && param.CaminhoToke != "" && File.Exists(param.CaminhoToke))
                    {
                        StaticParametros.SetDirToke(param.CaminhoToke);
                        txtFolderToken.Text = param.CaminhoToke;
                        DefineToken(param.CaminhoToke);
                        ctrl++;
                    }

                    if (param.CaminhoDir != "")
                    {
                        if (Directory.Exists(param.CaminhoDir))
                        {
                            txtFolderIni.Text = param.CaminhoDir;
                            StaticParametros.SetDirOrigem(param.CaminhoDir);
                            ctrl++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //OrganizaTelaEvent(1);
                    ctrlVazio = 1;
                }

                var parametroDBDAO = new ParametroDB_DAO(sessao);
                var paramDB        = parametroDBDAO.BuscarTodos();//parametroDBDAO.BuscarPorID(1);
                //var paramDB = Armazenamento.GetParametrosDB();

                try
                {
                    if (paramDB.Count == 1)
                    {
                        StaticParametersDB.SetListBanco(paramDB[0]);

                        if (paramDB[0].Grupo == 0 || paramDB[0].Token == null || paramDB[0].Token == "")
                        {
                            throw new Exception();
                        }
                        else
                        {
                            StaticParametersDB.Setcurrent(paramDB[0].Id);
                        }
                    }
                    else if (paramDB.Count > 1)
                    {
                        foreach (var p in paramDB)
                        {
                            StaticParametersDB.SetListBanco(p);
                        }

                        foreach (var p in paramDB)
                        {
                            if (p.Grupo == 0 || p.Token == null || p.Token == "")
                            {
                                throw new Exception();
                            }
                        }

                        StaticParametersDB.Setcurrent(paramDB[0].Id);
                    }
                    else
                    {
                        throw new Exception();
                    }
                    StaticParametros.SetIntegraBanco(true);
                    TxtStatusBanco.Text = "Conectado";
                    ctrl++;
                }
                catch (Exception ex)
                {
                    StaticParametros.SetIntegraBanco(false);
                    TxtStatusBanco.Text = "Desconectado";
                    if (ctrlVazio == 0)
                    {
                        var paramn = new Parametro {
                            Id = 1, CaminhoDir = StaticParametros.GetDirOrigem(), CaminhoToke = StaticParametros.GetDirToke(), IntegraBanco = StaticParametros.GetIntegraBanco(), GeraLog = StaticParametros.GetGeraLogs()
                        };
                        parametroDAO.Salvar(param);

                        //Armazenamento.UpdateParametros(new Parametro { Id = 1, CaminhoDir = param.CaminhoDir, CaminhoToke = param.CaminhoToke, IntegraBanco = false });
                    }
                }

                if (ctrl >= 2)
                {
                    try
                    {
                        if (txtFolderToken.Text == "")
                        {
                            OrganizaTelaEvent(1);
                        }
                        else
                        {
                            OrganizaTelaEvent(2);
                        }
                        //Job();
                        if (StaticParametros.GetDirOrigem() != null && StaticParametros.GetDirOrigem() != "")
                        {
                            process.CriarPastas();
                        }
                    }
                    catch (Exception ex)
                    {
                        OrganizaTelaEvent(1);
                    }
                }
                else
                {
                    Thread Tproc = new Thread(process.LimpaLog);
                    Tproc.Start();

                    OrganizaTelaEvent(1);
                }
            }

            sessao.Close();

            if (process.WritePermissionFolder() == false || process.WritePermissionFile() == false)
            {
                OrganizaTelaEvent(1);
            }
        }
Example #10
0
        private void GenerateReport()
        {
            //string z nazwą pomieszczenia
            string fileName = "";

            fileName = "Historia";
            //ścieżka z nazwą pliku do tworzenia
            string path = Application.StartupPath + "/Historia/" + fileName + ".pdf";
            //ścieżka do utworzenia katalogu na wydruki
            string path2 = Application.StartupPath + "/Historia/";
            //ustawienie zabezpieczenia do zapisu i tworzenie katalogu
            DirectorySecurity securityRules = new DirectorySecurity();
            string            dirPath       = Path.GetDirectoryName(path2);

            securityRules.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Modify, AccessControlType.Allow));
            if (dirPath == null)
            {
                throw new InvalidOperationException("Nie udało się zapisać ze względu na lokalne ustawienia bezpieczeństwa!");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath, securityRules);
            }

            //rozmiar dokumentu i marginesów
            Document document = new Document(PageSize.A4.Rotate(), 25, 25, 50, 50);
            //ustawienia czcionek
            var bigFont    = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 18);
            var normalFont = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 10);
            var smallFont  = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 4);
            //utworzenie dokumentu
            PdfWriter writer = null;
            bool      bOpen  = false;

            try
            {
                writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
                //ewent do numeracji stron
                writer.PageEvent = new ITextEvent();
            }
            catch (IOException e)
            {
                MessageBox.Show(e.Message, "OSTRZEŻENIE!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                bOpen = true;
            }


            if (bOpen == false)
            {
                document.Open();

                //treść wydruku

                //tutuł
                Paragraph p = new Paragraph("Usunięty sprzęt Informatyki i Łączności:" + Environment.NewLine, bigFont);
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);
                p           = new Paragraph(Environment.NewLine, bigFont);
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);

                PdfPTable pdfTable = new PdfPTable(dataGridView1.Columns.Count);
                //rozmiar szerokosc kolumn
                float[] widths = new float[] { 50f, 125f, 125f, 150f, 150f, 125f, 125f, 125f, 125f, 125f, 125f,
                                               125f, 125f, 125f, 125f, 400f };
                //zmienna do zapisu szerokosci kolumn wybranych kolumn


                pdfTable.SetWidths(widths);
                pdfTable.DefaultCell.Padding = 5;
                pdfTable.WidthPercentage     = 100;

                pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
                //tworzenie header column
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, smallFont));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    pdfTable.AddCell(cell);
                }
                //wypełnianie komorek danymi
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        PdfPCell cell2 = new PdfPCell(new Phrase(cell.Value.ToString(), smallFont));
                        cell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                        pdfTable.AddCell(cell2);
                    }
                }
                document.Add(pdfTable);

                //dolne wpisy
                ColumnText.ShowTextAligned(writer.DirectContent,
                                           Element.ALIGN_CENTER, new Phrase("Wykaz usuniętego sprzętu wygenerowany z EwiInf dla Aresztu Śledczego w Łodzi " + DateTime.Now.ToString(), normalFont), 250, 60, 0);
                //koniec wydruku

                document.Close();

                //otwarcie pliku w pdf readerze
                Process.Start(path);
            }
        }
 public override IDirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     return(FileSystem.DirectoryInfo.GetFromDirectoryInfo(base.CreateDirectory(FileSystem.Path.GetEncryptedPath(path, false), directorySecurity)));
 }
 public override void SetAccessControl(string path, DirectorySecurity directorySecurity)
 {
     base.SetAccessControl(FileSystem.Path.GetEncryptedPath(path, true), directorySecurity);
 }
Example #13
0
        private void btnSQLiteSqlServer_Click(object sender, EventArgs e)
        {
            string tempFilePath  = string.Empty;
            string SqlServerPath = string.Empty;
            string sqlConnString;
            string dbname;

            string tempDirPath = Path.GetTempPath() + @"\SqlConverter";

            if (Directory.Exists(tempDirPath))
            {
                Directory.Delete(tempDirPath, true);
            }
            System.IO.Directory.CreateDirectory(tempDirPath);
            DirectoryInfo     tempDirInfo     = new DirectoryInfo(tempDirPath);
            DirectorySecurity tempDirSecurity = tempDirInfo.GetAccessControl();

            tempDirSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            tempDirInfo.SetAccessControl(tempDirSecurity);

            string SQLitePath = Path.GetFullPath(txtSQLitePath.Text);

            if (!File.Exists(SQLitePath))
            {
                MessageBox.Show("Input file " + SQLitePath + " not found.", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (txtSqlServerPath.Text != string.Empty)
            {
                tempFilePath = Path.GetFullPath(tempDirPath + @"\" + Path.GetFileName(txtSqlServerPath.Text));

                SqlServerPath = Path.GetFullPath(txtSqlServerPath.Text);
                if (cboWhatToCopy.SelectedIndex == 2)       //  ie if we are copying into an existing database
                {
                    if (!File.Exists(SqlServerPath))
                    {
                        MessageBox.Show("Output file '" + SqlServerPath + "' not found.", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    System.IO.File.Copy(SqlServerPath, tempFilePath);
                }
                else
                {
                    if (File.Exists(SqlServerPath))
                    {
                        DialogResult result = MessageBox.Show("Replace existing file '" + SqlServerPath + "'?", "Confirm replace file", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                        if (result != DialogResult.OK)
                        {
                            return;
                        }
                    }
                }

                string constr;
                if (cbxIntegrated.Checked)
                {
                    constr = GetSqlServerConnectionString(txtSqlAddress.Text, "master");
                }
                else
                {
                    constr = GetSqlServerConnectionString(txtSqlAddress.Text, "master", txtUserDB.Text, txtPassDB.Text);
                }

                using (SqlConnection conn = new SqlConnection(constr))
                {
                    conn.Open();
                    string queryString = "CREATE DATABASE SqlConverter on (NAME=N'" + Path.GetFileNameWithoutExtension(txtSqlServerPath.Text) + "',FILENAME=N'" + tempFilePath + "')";
                    if (cboWhatToCopy.SelectedIndex == 2)       //  ie if we are copying into an existing database
                    {
                        queryString += " FOR ATTACH";
                    }

                    SqlCommand query = new SqlCommand(queryString, conn);
                    query.ExecuteNonQuery();
                    dbname = "SqlConverter";
                }
            }
            else
            {
                dbname = (string)cboDatabases.SelectedItem;
            }

            if (cbxIntegrated.Checked)
            {
                sqlConnString = GetSqlServerConnectionString(txtSqlAddress.Text, dbname);
            }
            else
            {
                sqlConnString = GetSqlServerConnectionString(txtSqlAddress.Text, dbname, txtUserDB.Text, txtPassDB.Text);
            }

            this.Cursor = Cursors.WaitCursor;
            SqlConversionHandler handler = new SqlConversionHandler(delegate(bool done,
                                                                             bool success, int percent, string msg)
            {
                Invoke(new MethodInvoker(delegate()
                {
                    UpdateSensitivity();
                    lblMessage.Text   = msg;
                    pbrProgress.Value = percent;

                    if (done)
                    {
                        if (txtSqlServerPath.Text != string.Empty)
                        {
                            dropSqlConverterDatabase();
                            if (success)
                            {
                                System.IO.File.Copy(tempFilePath, SqlServerPath, true);
                            }
                            Directory.Delete(tempDirPath, true);
                        }
                        if (success)
                        {
                            MessageBox.Show(this,
                                            msg,
                                            "Conversion Finished",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                            pbrProgress.Value = 0;
                            lblMessage.Text   = string.Empty;
                        }
                        else
                        {
                            if (!_shouldExit)
                            {
                                MessageBox.Show(this,
                                                msg,
                                                "Conversion Failed",
                                                MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                                pbrProgress.Value = 0;
                                lblMessage.Text   = string.Empty;
                            }
                            else
                            {
                                Application.Exit();
                            }
                        }
                        btnSQLiteSqlServer.Enabled = true;
                        this.Cursor = Cursors.Default;
                        UpdateSensitivity();
                    }
                }));
            });
            SqlTableSelectionHandler selectionHandler = new SqlTableSelectionHandler(delegate(List <TableSchema> schema)
            {
                List <TableSchema> updated = null;
                Invoke(new MethodInvoker(delegate
                {
                    // Allow the user to select which tables to include by showing him the
                    // table selection dialog.
                    TableSelectionDialog dlg = new TableSelectionDialog();
                    DialogResult res         = dlg.ShowTables(schema, this);
                    if (res == DialogResult.OK)
                    {
                        updated = dlg.IncludedTables;
                    }
                }));
                return(updated);
            });

            FailedViewDefinitionHandler viewFailureHandler = new FailedViewDefinitionHandler(delegate(ViewSchema vs)
            {
                string updated = null;
                Invoke(new MethodInvoker(delegate
                {
                    ViewFailureDialog dlg = new ViewFailureDialog();
                    dlg.View         = vs;
                    DialogResult res = dlg.ShowDialog(this);
                    if (res == DialogResult.OK)
                    {
                        updated = dlg.ViewSQL;
                    }
                    else
                    {
                        updated = null;
                    }
                }));

                return(updated);
            });

            string password = txtPassword.Text.Trim();

            if (!cbxEncrypt.Checked)
            {
                password = null;
            }

            bool copyStructure = (cboWhatToCopy.SelectedIndex != 2);
            bool copyData      = (cboWhatToCopy.SelectedIndex != 1);

            SQLiteToSqlServer.ConvertSQLiteToSqlServerDatabase(sqlConnString, SQLitePath, password, handler,
                                                               selectionHandler, viewFailureHandler, copyStructure, copyData);
        }
Example #14
0
        public object WriteToFile(string scenario, string folderPath)
        {
            string filename = "";

            try
            {
                if (Directory.Exists(folderPath))
                {
                    filename = Path.Combine(folderPath, scenario + "_" + ".txt");
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                    using (FileStream fs = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite))
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            if (scenario == "Scenario1")
                            {
                                sw.WriteLine("The second should show the addresses sorted alphabetically by street name\n\n");

                                string colAddress = "Address".PadRight(20);
                                sw.WriteLine("{0}", colAddress);
                                foreach (Objects.AddressEntries address in GetAddresses())
                                {
                                    sw.WriteLine("{0} {1}", address.StreetNumber, address.StreetName);
                                }
                            }
                            else if (scenario == "Scenario2")
                            {
                                sw.WriteLine("frequency of the first and last names ordered\n");
                                sw.WriteLine("\tfrequency of the first ordered by frequency\n");
                                string colName  = "Name".PadRight(20);
                                string colCount = "Count".PadRight(20);
                                sw.WriteLine("{0}{1}", colName, colCount);
                                foreach (KeyValuePair <string, int> kpv in FirstNameFreq())
                                {
                                    sw.WriteLine("{0}{1}", kpv.Key.ToString().PadRight(20), kpv.Value.ToString().PadRight(20));
                                }

                                sw.WriteLine("\n\n\n");
                                sw.WriteLine("\tfrequency of the first ordered by frequency and Name and lastname\n");
                                string colName2  = "Name".PadRight(20);
                                string colCount2 = "Count".PadRight(20);
                                sw.WriteLine("{0}{1}", colName2, colCount2);
                                foreach (KeyValuePair <string, int> kpv in FirstNameSurFreq())
                                {
                                    sw.WriteLine("{0}{1}", kpv.Key.ToString().PadRight(20), kpv.Value.ToString().PadRight(20));
                                }
                            }
                        }
                }
                else
                {
                    DirectoryInfo     dInfo     = new DirectoryInfo(folderPath);
                    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                    dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                    dInfo.SetAccessControl(dSecurity);

                    //	System.Security.AccessControl.DirectorySecurity directorySecurity = new System.Security.AccessControl.DirectorySecurity(folderPath, System.Security.AccessControl.AccessControlSections.All);
                    Directory.CreateDirectory(folderPath + "/Export", dSecurity);
                    WriteToFile(scenario, folderPath);
                }
                return(new { Success = true, Message = string.Format("Your file is saved in this location: {0}", filename) });
            }
            catch (Exception ex)
            {
                return(new
                {
                    Success = false,
                    Error = ex.Message
                });
            }
        }
Example #15
0
 public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     return(new DirectoryInfoWrapper(FileSystem, Directory.CreateDirectory(path, directorySecurity)));
 }
 /// <summary>
 ///     Creates all directories and subdirectories in the specified @this if the directory doesn't already exists.
 ///     This methods is the same as FileInfo.CreateDirectory however it's less ambigues about what happen if the
 ///     directory already exists.
 /// </summary>
 /// <param name="this">The directory to create.</param>
 /// <param name="directorySecurity">The access control to apply to the directory.</param>
 /// <returns>An object that represents the directory for the specified @this.</returns>
 /// ###
 /// <exception cref="T:System.IO.IOException">
 ///     The directory specified by <paramref name="this" /> is a file.-or-The
 ///     network name is not known.
 /// </exception>
 /// ###
 /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
 /// ###
 /// <exception cref="T:System.ArgumentException">
 ///     <paramref name="this" /> is a zero-length string, contains only
 ///     white space, or contains one or more invalid characters as defined by
 ///     <see
 ///         cref="F:System.IO.Path.InvalidPathChars" />
 ///     . -or-<paramref name="this" /> is prefixed with, or contains only a colon character (:).
 /// </exception>
 /// ###
 /// <exception cref="T:System.ArgumentNullException">
 ///     <paramref name="this" /> is null.
 /// </exception>
 /// ###
 /// <exception cref="T:System.IO.PathTooLongException">
 ///     The specified @this, file name, or both exceed the system-
 ///     defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file
 ///     names must be less than 260 characters.
 /// </exception>
 /// ###
 /// <exception cref="T:System.IO.DirectoryNotFoundException">
 ///     The specified @this is invalid (for example, it is on
 ///     an unmapped drive).
 /// </exception>
 /// ###
 /// <exception cref="T:System.NotSupportedException">
 ///     <paramref name="this" /> contains a colon character (:) that
 ///     is not part of a drive label ("C:\").
 /// </exception>
 public static DirectoryInfo EnsureDirectoryExists(this DirectoryInfo @this, DirectorySecurity directorySecurity)
 {
     return Directory.CreateDirectory(@this.FullName, directorySecurity);
 }
Example #17
0
 public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     return((DirectoryInfoBase) new DirectoryInfoAdapter(Directory.CreateDirectory(path, directorySecurity)));
 }
 public override IDirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     return(CreateDirectoryInternal(path, directorySecurity));
 }
Example #19
0
 public override void SetAccessControl(string path, DirectorySecurity directorySecurity)
 {
     Directory.SetAccessControl(path, directorySecurity);
 }
Example #20
0
        private static async Task <ApplicationManager> CreateApplicationInternal(int siteIndex)
        {
            string applicationName = _sitePrefix + siteIndex;

            string operationName = "SitePool.CreateApplicationInternal " + applicationName;

            var context     = new KuduTestContext();
            var siteManager = GetSiteManager(context);

            Site site = siteManager.GetSite(applicationName);

            if (site != null)
            {
                TestTracer.Trace("{0} Site already exists at {1}. Reusing site", operationName, site.SiteUrl);
                var appManager = new ApplicationManager(siteManager, site, applicationName)
                {
                    SitePoolIndex = siteIndex
                };

                // In site reuse mode, clean out the existing site so we start clean
                // Enumrate all w3wp processes and make sure to kill any process with an open handle to klr.host.dll
                foreach (var process in (await appManager.ProcessManager.GetProcessesAsync()).Where(p => p.Name.Equals("w3wp", StringComparison.OrdinalIgnoreCase)))
                {
                    var extendedProcess = await appManager.ProcessManager.GetProcessAsync(process.Id);

                    if (extendedProcess.OpenFileHandles.Any(h => h.IndexOf("dnx.host.dll", StringComparison.OrdinalIgnoreCase) != -1))
                    {
                        await appManager.ProcessManager.KillProcessAsync(extendedProcess.Id, throwOnError : false);
                    }
                }

                await appManager.RepositoryManager.Delete(deleteWebRoot : true, ignoreErrors : true);

                // Make sure we start with the correct default file as some tests expect it
                WriteIndexHtml(appManager);

                TestTracer.Trace("{0} completed", operationName);
                return(appManager);
            }
            else
            {
                TestTracer.Trace("{0} Creating new site", operationName);
                lock (_createSiteLock)
                {
                    if (ConfigurationManager.AppSettings["UseNetworkServiceIdentity"] == "true")
                    {
                        var applicationsPath = context.Configuration.ApplicationsPath;
                        if (!Directory.Exists(applicationsPath))
                        {
                            Directory.CreateDirectory(applicationsPath);

                            var accessRule = new FileSystemAccessRule("NETWORK SERVICE",
                                                                      fileSystemRights: FileSystemRights.Modify | FileSystemRights.Write | FileSystemRights.ReadAndExecute | FileSystemRights.Read | FileSystemRights.ListDirectory,
                                                                      inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                      propagationFlags: PropagationFlags.None,
                                                                      type: AccessControlType.Allow);

                            var directoryInfo = new DirectoryInfo(applicationsPath);
                            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
                            directorySecurity.AddAccessRule(accessRule);
                            directoryInfo.SetAccessControl(directorySecurity);
                        }
                    }

                    site = siteManager.CreateSiteAsync(applicationName).Result;
                }

                TestTracer.Trace("{0} Created new site at {1}", operationName, site.SiteUrl);
                return(new ApplicationManager(siteManager, site, applicationName)
                {
                    SitePoolIndex = siteIndex
                });
            }
        }
Example #21
0
 private void SetAccessControlDir(string path, DirectorySecurity rules)
 {
     System.IO.Directory.SetAccessControl(AddExtendedDevicePathPrefix(path), rules);
 }
Example #22
0
        protected override void ProcessRecord()
        {
            if (Directory.Exists(DirectoryPath))
            {
                DirectorySecurity security = null;

                //  Access設定
                //  ""で全アクセス権設定を削除
                if (Access != null)
                {
                    if (security == null)
                    {
                        security = Directory.GetAccessControl(DirectoryPath);
                    }

                    //  テスト自動生成
                    _generator.DirectoryAccess(DirectoryPath, Access, false);

                    foreach (FileSystemAccessRule removeRule in security.GetAccessRules(true, false, typeof(NTAccount)))
                    {
                        security.RemoveAccessRule(removeRule);
                    }
                    if (Access != string.Empty)     //  このif文分岐が無くても同じ挙動するけれど、一応記述
                    {
                        foreach (FileSystemAccessRule addRule in DirectoryControl.StringToAccessRules(Access))
                        {
                            security.AddAccessRule(addRule);
                        }
                    }
                }

                //  Owner設定
                if (!string.IsNullOrEmpty(Owner))
                {
                    //  埋め込みのsubinacl.exeを展開
                    string subinacl = EmbeddedResource.GetSubinacl(Item.APPLICATION_NAME);

                    //  管理者実行確認
                    Functions.CheckAdmin();

                    //  テスト自動生成
                    _generator.DirectoryOwner(DirectoryPath, Owner);

                    using (Process proc = new Process())
                    {
                        proc.StartInfo.FileName    = subinacl;
                        proc.StartInfo.Arguments   = $"/subdirectories \"{DirectoryPath}\" /setowner=\"{Owner}\"";
                        proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        proc.Start();
                        proc.WaitForExit();
                    }
                }

                //  Inherited設定
                if (Inherited != Item.NONE)
                {
                    if (security == null)
                    {
                        security = Directory.GetAccessControl(DirectoryPath);
                    }

                    //  テスト自動生成
                    _generator.DirectoryInherited(DirectoryPath, Inherited == Item.ENABLE);

                    switch (Inherited)
                    {
                    case Item.ENABLE:
                        security.SetAccessRuleProtection(false, false);
                        break;

                    case Item.DISABLE:
                        security.SetAccessRuleProtection(true, true);
                        break;

                    case Item.REMOVE:
                        security.SetAccessRuleProtection(true, false);
                        break;
                    }
                }

                if (security != null)
                {
                    Directory.SetAccessControl(DirectoryPath, security);
                }

                //  作成日時
                if (CreationTime != null)
                {
                    //  テスト自動生成
                    _generator.DirectoryCreationTime(DirectoryPath, (DateTime)CreationTime);

                    Directory.SetCreationTime(DirectoryPath, (DateTime)CreationTime);
                }

                //  更新一時
                if (LastWriteTime != null)
                {
                    //  テスト自動生成
                    _generator.DirectoryLastWriteTime(DirectoryPath, (DateTime)LastWriteTime);

                    Directory.SetLastWriteTime(DirectoryPath, (DateTime)LastWriteTime);
                }

                //  フォルダー属性
                if (!string.IsNullOrEmpty(_Attributes))
                {
                    //  テスト自動生成
                    _generator.DirectoryAttributes(DirectoryPath, _Attributes, false);

                    if (!_Attributes.Contains(Item.DIRECTORY))
                    {
                        _Attributes += ", " + Item.DIRECTORY;
                    }
                    File.SetAttributes(DirectoryPath, (FileAttributes)Enum.Parse(typeof(FileAttributes), _Attributes));
                }

                //  セキュリティブロックの解除
                if (RemoveSecurityBlock)
                {
                    foreach (string fileName in Directory.GetFiles(DirectoryPath, "*", SearchOption.AllDirectories))
                    {
                        //  テスト自動生成
                        _generator.FileSecurityBlock(fileName, false);

                        FileControl.RemoveSecurityBlock(fileName);
                    }
                }

                /*  実行していて結構うっとおしいので、出力しないことにします。
                 * WriteObject(new DirectorySummary(Path, true));
                 */
            }
        }
Example #23
0
        private void doOpen(OpenFileDialog ofd)
        {
            Console.WriteLine("Attempting to open: " + ofd.FileName);

            if (ofd.FileName != "")
            {
                try
                {
                    if (ofd.FileName.EndsWith(".gif"))
                    {
                        using (System.IO.Stream sr = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            GifBitmapDecoder gbd   = new GifBitmapDecoder(sr, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                            List <Bitmap>    bmps  = new List <Bitmap>();
                            List <string>    names = new List <string>();
                            for (int i = 0; i < gbd.Frames.Count; i++)
                            {
                                bmps.Add(BitmapFromSource(gbd.Frames[i]));
                                names.Add(i.ToString());
                            }
                            SharedSettings.iCanvasWidth      = ((int)gbd.Frames[0].Width);
                            SharedSettings.iCanvasHeight     = ((int)gbd.Frames[0].Height);
                            SharedSettings.Layers            = (bmps.ToArray());
                            SharedSettings.LayerNames        = (names.ToArray());
                            SharedSettings.bLoadFromSettings = (true);
                            bmps.Clear();
                            names.Clear();
                        }
                    }
                    else if (ofd.FileName.EndsWith(".lep"))
                    {
                        Console.WriteLine(ofd.FileName);
                        string baseDir = System.IO.Directory.GetCurrentDirectory();

                        try
                        {
                            DeleteDirectory(baseDir + @"\load");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Couldn't delete 'load' Directory!" + e.InnerException);
                        }

                        List <String> layerNames   = new List <String>();
                        List <Bitmap> layerBitmaps = new List <Bitmap>();

                        DirectorySecurity securityRules = new DirectorySecurity();
                        securityRules.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
                        DirectoryInfo di = Directory.CreateDirectory("load", securityRules);

                        System.IO.Compression.ZipFile.ExtractToDirectory(ofd.FileName, baseDir + @"\load");

                        using (System.IO.StreamReader sr = new System.IO.StreamReader(baseDir + @"\load\names.txt", Encoding.Default))
                        {
                            string line;
                            // Read the stream to a string, and write the string to the console.
                            while ((line = sr.ReadLine()) != null)
                            {
                                layerNames.Add(line);
                            }

                            sr.Close();
                            sr.Dispose();
                        }

                        int w = 0;
                        int h = 0;

                        for (int n = 0; n < layerNames.Count; n++)
                        {
                            Bitmap temp = (Bitmap)Image.FromFile(baseDir + @"\load\" + layerNames[n] + ".png");

                            w = (temp.Width > w) ? temp.Width : w;
                            h = (temp.Height > h) ? temp.Height : h;
                            layerBitmaps.Add((Bitmap)temp.Clone());
                        }

                        try
                        {
                            if (Directory.Exists(baseDir + @"\load\watermark"))
                            {
                                //Console.WriteLine("Watermark Found");
                                SharedSettings.bitmapWatermark = (Bitmap)Bitmap.FromFile(baseDir + @"\load\watermark\watermark.png").Clone();
                                SharedSettings.watermarkPath   = baseDir + @"\load\watermark\watermark.png";
                                List <string> watermarkdata = new List <string>();
                                using (System.IO.StreamReader sr = new System.IO.StreamReader(baseDir + @"\load\watermark\watermarkdata.txt", Encoding.Default))
                                {
                                    string line;

                                    // Read the stream to a string, and write the string to the console.
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        Console.WriteLine(line);
                                        watermarkdata.Add(line);
                                    }
                                    sr.Close();
                                    sr.Dispose();
                                }

                                bool show;
                                Boolean.TryParse(watermarkdata[0], out show);
                                SharedSettings.bRenderWatermark = show;
                                SharedSettings.watermarkStyle   = watermarkdata[1];
                            }
                        }
                        catch (Exception err)
                        {
                            SharedSettings.bitmapWatermark = null;
                            Console.WriteLine("Exception Thrown in Watermark Loading" + err.InnerException);
                        }

                        SharedSettings.iCanvasWidth      = w;
                        SharedSettings.iCanvasHeight     = h;
                        SharedSettings.Layers            = layerBitmaps.ToArray();
                        SharedSettings.LayerNames        = layerNames.ToArray();
                        SharedSettings.bLoadFromSettings = true;

                        Console.WriteLine(SharedSettings.Layers.Count());

                        layerBitmaps.Clear(); //Clears all Bitmap File References
                        layerNames.Clear();   //Clears Layer Name File Reference
                        Console.WriteLine(SharedSettings.Layers.Count());
                    }
                    else
                    {
                        BackgroundWorker bw = new BackgroundWorker();
                        bw.DoWork += (send, args) =>
                        {
                            Console.WriteLine("Wrong File Type");
                            string message = SharedSettings.getGlobalString("projectopen_error");
                            MessageBox.Show(new Form()
                            {
                                WindowState = FormWindowState.Maximized, TopMost = true
                            }, message);
                        };

                        bw.RunWorkerAsync();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    Result = SharedSettings.getGlobalString("projectopen_error");
                    //MessageBox.Show(Result);
                }
            }
        }
 public void SetAccessControl(string path, DirectorySecurity directorySecurity)
 {
     new SetAccessControlOperation(this, path, directorySecurity).Execute();
 }
 public override void Create(DirectorySecurity directorySecurity)
 {
     mockFileDataAccessor.Directory.CreateDirectory(FullName, directorySecurity);
 }
Example #26
0
        public void CreatePrison()
        {
            if (this.Container.IsLocked)
            {
                return;
            }

            this.Lock.EnterWriteLock();

            var containerRules = new HP.WindowsPrison.PrisonConfiguration();

            containerRules.PrisonHomeRootPath = this.Properties.Directory;

            containerRules.Rules |= HP.WindowsPrison.RuleTypes.WindowStation;
            containerRules.Rules |= HP.WindowsPrison.RuleTypes.IISGroup;


            containerRules.TotalPrivateMemoryLimitBytes = this.Properties.MemoryQuotaBytes;
            containerRules.PriorityClass        = ProcessPriorityClass.BelowNormal;
            containerRules.ActiveProcessesLimit = 10;

            if (this.Properties.UploadThrottleBitsps > 0)
            {
                containerRules.Rules |= HP.WindowsPrison.RuleTypes.Network;
                containerRules.NetworkOutboundRateLimitBitsPerSecond = this.Properties.UploadThrottleBitsps;
                containerRules.AppPortOutboundRateLimitBitsPerSecond = this.Properties.UploadThrottleBitsps;
            }

            if (this.Properties.UseDiskQuota)
            {
                containerRules.Rules         |= HP.WindowsPrison.RuleTypes.Disk;
                containerRules.DiskQuotaBytes = this.Properties.DiskQuotaBytes;
            }

            Logger.Info("Creating Process Prison: {0}", this.Container.Id.ToString());
            this.Container.Tag = "dea";
            this.Container.Lockdown(containerRules);

            this.Properties.WindowsUserName = this.Container.User.UserName;
            this.Properties.WindowsPassword = this.Container.User.Password;

            this.Properties.InstanceId = this.Container.Id.ToString();

            this.Lock.ExitWriteLock();

            // Explode the app into its directory and optionally bind its local runtime.
            Directory.CreateDirectory(this.Properties.Directory);

            DirectoryInfo     deploymentDirInfo     = new DirectoryInfo(this.Properties.Directory);
            DirectorySecurity deploymentDirSecurity = deploymentDirInfo.GetAccessControl();

            // Owner is important to account for disk quota
            deploymentDirSecurity.SetOwner(new NTAccount(this.Properties.WindowsUserName));
            deploymentDirSecurity.SetAccessRule(
                new FileSystemAccessRule(
                    this.Properties.WindowsUserName,
                    FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify | FileSystemRights.FullControl,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None | PropagationFlags.InheritOnly,
                    AccessControlType.Allow));

            using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), ProcessPrivileges.Privilege.Restore))
            {
                deploymentDirInfo.SetAccessControl(deploymentDirSecurity);
            }
        }
 public override DirectoryInfoBase CreateSubdirectory(string path, DirectorySecurity directorySecurity)
 {
     return(mockFileDataAccessor.Directory.CreateDirectory(Path.Combine(FullName, path), directorySecurity));
 }
        // ====================
        // Send Journal Voucher
        // ====================
        public async void SendJournalVoucher(Forms.TrnIntegrationForm trnIntegrationForm, String userCode, String file, String domain)
        {
            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nOpening File: " + file + " \r\n\n");

            List <Entities.FolderMonitoringTrnJournalVoucher> newJournalVouchers = new List <Entities.FolderMonitoringTrnJournalVoucher>();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            String jsonData = "";

            // ========
            // Cleaning
            // ========
            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nCleaning Journal Voucher... (0%) \r\n\n");
            while (true)
            {
                try
                {
                    String deleteTemporaryJournalVoucherTask = await DeleteTemporaryJournalVoucher(domain);

                    if (!deleteTemporaryJournalVoucherTask.Equals("Clean Successful..."))
                    {
                        trnIntegrationForm.folderMonitoringLogMessages(deleteTemporaryJournalVoucherTask);
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                    else
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("JVIntegrationLogOnce");

                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\nCleaning Journal Voucher... (100%) \r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Clean Successful!" + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        break;
                    }
                }
                catch (Exception e)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                    Thread.Sleep(5000);
                }
            }

            // ================
            // Reading CSV Data
            // ================
            trnIntegrationForm.folderMonitoringLogMessages("Reading CSV Data... (0%) \r\n\n");
            while (true)
            {
                newJournalVouchers = new List <Entities.FolderMonitoringTrnJournalVoucher>();

                try
                {
                    if (SysFileControl.IsCurrentFileClosed(file))
                    {
                        Int32 count = 0;

                        using (StreamReader dataStreamReader = new StreamReader(file))
                        {
                            dataStreamReader.ReadLine();
                            while (dataStreamReader.Peek() >= 0)
                            {
                                count += 1;

                                List <String> data = dataStreamReader.ReadLine().Split(',').ToList();
                                newJournalVouchers.Add(new Entities.FolderMonitoringTrnJournalVoucher
                                {
                                    BranchCode       = data[0],
                                    JVDate           = data[1],
                                    Remarks          = data[2],
                                    ManualJVNumber   = data[3],
                                    UserCode         = userCode,
                                    CreatedDateTime  = data[4],
                                    EntryBranchCode  = data[5],
                                    AccountCode      = data[6],
                                    ArticleCode      = data[7],
                                    Particulars      = data[8],
                                    DebitAmount      = Convert.ToDecimal(data[9]),
                                    CreditAmount     = Convert.ToDecimal(data[10]),
                                    APRRNumber       = data[11],
                                    APManualRRNumber = data[12],
                                    ARSINumber       = data[13],
                                    ARManualSINumber = data[14],
                                    IsClear          = Convert.ToBoolean(data[15]),
                                    No = count
                                });

                                journalDate = Convert.ToDateTime(data[1]);
                            }
                        }

                        trnIntegrationForm.folderMonitoringLogMessages("JVIntegrationLogOnce");

                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\nReading CSV Data... (100%) \r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Read Successful!" + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        break;
                    }
                    else
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("Error: File: " + file + " is currently open. \r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                }
                catch (Exception e)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                    Thread.Sleep(5000);
                }
            }

            if (newJournalVouchers.Any())
            {
                // =========================
                // Checking Muliple JV Dates
                // =========================
                trnIntegrationForm.folderMonitoringLogMessages("Checking Multiple JV Dates... (0%) \r\n\n");
                while (true)
                {
                    try
                    {
                        var groupedJVDates = from d in newJournalVouchers group d by d.JVDate into g select g.Key;

                        var JVDates = from d in groupedJVDates.ToList() select d;
                        if (JVDates.Count() > 1)
                        {
                            trnIntegrationForm.folderMonitoringLogMessages("Checking Error: Cannot integrate multiple JV Dates. \r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                            Thread.Sleep(5000);
                        }
                        else
                        {
                            trnIntegrationForm.folderMonitoringLogMessages("JVIntegrationLogOnce");

                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nChecking Multiple JV Dates... (100%) \r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Check Successful!" + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                }

                Boolean post = false;

                // =======
                // Sending
                // =======
                trnIntegrationForm.folderMonitoringLogMessages("Sending Journal Voucher... (0%) \r\n\n");
                while (true)
                {
                    try
                    {
                        Decimal percentage = 0;

                        Boolean send = false;
                        Int32   skip = 0;

                        for (Int32 i = 1; i <= newJournalVouchers.Count(); i++)
                        {
                            if (i % 100 == 0)
                            {
                                jsonData = serializer.Serialize(newJournalVouchers.Skip(skip).Take(100));
                                skip     = i;

                                send       = true;
                                percentage = Convert.ToDecimal((Convert.ToDecimal(skip) / Convert.ToDecimal(newJournalVouchers.Count())) * 100);
                            }
                            else
                            {
                                if (i == newJournalVouchers.Count())
                                {
                                    if (newJournalVouchers.Count() <= 100)
                                    {
                                        jsonData = serializer.Serialize(newJournalVouchers);
                                    }
                                    else
                                    {
                                        jsonData = serializer.Serialize(newJournalVouchers.Skip(skip).Take(i - skip));
                                    }

                                    send       = true;
                                    percentage = Convert.ToDecimal((Convert.ToDecimal(i) / Convert.ToDecimal(newJournalVouchers.Count())) * 100);
                                }
                            }

                            if (send)
                            {
                                while (true)
                                {
                                    try
                                    {
                                        String insertTemporaryJournalVoucherTask = await InsertTemporaryJournalVoucher(domain, jsonData);

                                        if (!insertTemporaryJournalVoucherTask.Equals("Send Successful..."))
                                        {
                                            trnIntegrationForm.folderMonitoringLogMessages(insertTemporaryJournalVoucherTask);
                                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                            Thread.Sleep(5000);
                                        }
                                        else
                                        {
                                            trnIntegrationForm.folderMonitoringLogMessages("JVIntegrationLogOnce");
                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nSending Journal Voucher... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                            if (i == newJournalVouchers.Count())
                                            {
                                                trnIntegrationForm.folderMonitoringLogMessages("Send Successful!" + "\r\n\n");
                                                trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");
                                            }

                                            break;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        trnIntegrationForm.folderMonitoringLogMessages("Sending Error: " + e.Message + "\r\n\n");
                                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                        Thread.Sleep(5000);
                                    }
                                }

                                send = false;
                            }
                        }

                        post = true;
                        break;
                    }
                    catch (Exception e)
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                }

                // =======
                // Posting
                // =======
                if (post)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Posting Journal Voucher... (0%) \r\n\n");
                    while (true)
                    {
                        try
                        {
                            var groupedJournalVouchers = from d in newJournalVouchers
                                                         group d by new
                            {
                                d.BranchCode,
                                d.ManualJVNumber
                            } into g
                            select g.Key;

                            var journalVouchers = from d in groupedJournalVouchers.ToList() select d;
                            if (journalVouchers.Any())
                            {
                                Decimal percentage = 0;
                                Int32   count      = 0;

                                foreach (var journalVoucher in journalVouchers.ToList())
                                {
                                    count     += 1;
                                    percentage = Convert.ToDecimal((Convert.ToDecimal(count) / Convert.ToDecimal(journalVouchers.Count())) * 100);

                                    while (true)
                                    {
                                        try
                                        {
                                            String postJournalVoucherTask = await PostJournalVoucher(domain, journalVoucher.BranchCode, journalVoucher.ManualJVNumber);

                                            if (!postJournalVoucherTask.Equals("Post Successful..."))
                                            {
                                                trnIntegrationForm.folderMonitoringLogMessages(postJournalVoucherTask);
                                                trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                                trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                                Thread.Sleep(5000);
                                            }
                                            else
                                            {
                                                trnIntegrationForm.folderMonitoringLogMessages("JVIntegrationLogOnce");
                                                trnIntegrationForm.folderMonitoringLogMessages("\r\n\nPosting Journal Voucher... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                                if (count == journalVouchers.Count())
                                                {
                                                    trnIntegrationForm.folderMonitoringLogMessages("Post Successful!" + "\r\n\n");
                                                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                                    String jDate  = journalDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);
                                                    String apiURL = "http://" + domain + "/api/folderMonitoring/journal/" + jDate + "/JV";

                                                    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL);
                                                    httpWebRequest.Method = "GET";
                                                    httpWebRequest.Accept = "application/json";

                                                    HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                                    using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
                                                    {
                                                        var result = streamReader.ReadToEnd();
                                                        JavaScriptSerializer js = new JavaScriptSerializer();
                                                        Entities.FolderMonitoringTrnJournal sumUpJournal = (Entities.FolderMonitoringTrnJournal)js.Deserialize(result, typeof(Entities.FolderMonitoringTrnJournal));

                                                        if (sumUpJournal != null)
                                                        {
                                                            trnIntegrationForm.folderMonitoringLogMessages("Date: " + sumUpJournal.JournalDate + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Total Debit: " + sumUpJournal.TotalDebitAmount + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Total Credit: " + sumUpJournal.TotalCreditAmount + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Balance: " + sumUpJournal.TotalBalance + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");
                                                        }
                                                    }
                                                }

                                                break;
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            trnIntegrationForm.folderMonitoringLogMessages("Posting Error: " + e.Message + "\r\n\n");
                                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                            Thread.Sleep(5000);
                                        }
                                    }
                                }
                            }

                            break;
                        }
                        catch (Exception e)
                        {
                            trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                            Thread.Sleep(5000);
                        }
                    }
                }
            }
            else
            {
                trnIntegrationForm.folderMonitoringLogMessages("Erorr: Data Source Empty \r\n\n");
                trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");
            }

            // =============
            // Move CSV File
            // =============
            trnIntegrationForm.folderMonitoringLogMessages("Moving Journal Voucher File... (0%) \r\n\n");
            while (true)
            {
                try
                {
                    String settingsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Settings.json");
                    using (StreamReader trmRead = new StreamReader(settingsPath))
                    {
                        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                        Entities.SysSettings sysSettings          = javaScriptSerializer.Deserialize <Entities.SysSettings>(trmRead.ReadToEnd());

                        String executingUser = WindowsIdentity.GetCurrent().Name;

                        DirectorySecurity securityRules = new DirectorySecurity();
                        securityRules.AddAccessRule(new FileSystemAccessRule(executingUser, FileSystemRights.Read, AccessControlType.Allow));
                        securityRules.AddAccessRule(new FileSystemAccessRule(executingUser, FileSystemRights.FullControl, AccessControlType.Allow));

                        if (!Directory.Exists(sysSettings.FolderForSentFiles + "\\JV_" + DateTime.Now.ToString("yyyyMMdd") + "\\"))
                        {
                            DirectoryInfo createDirectoryJVCSV = Directory.CreateDirectory(sysSettings.FolderForSentFiles + "\\JV_" + DateTime.Now.ToString("yyyyMMdd") + "\\", securityRules);
                        }

                        String folderForSentFiles = sysSettings.FolderForSentFiles + "\\JV_" + DateTime.Now.ToString("yyyyMMdd") + "\\";
                        File.Move(file, folderForSentFiles + "JV_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".csv");
                    }

                    trnIntegrationForm.folderMonitoringLogMessages("JVIntegrationLogOnce");

                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\nMoving JournalVoucher File... (100%) \r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Move Successful!" + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    break;
                }
                catch (Exception e)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Moving File Error: " + e.Message + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                    Thread.Sleep(5000);
                }
            }
        }
 public override void SetAccessControl(DirectorySecurity directorySecurity)
 {
     mockFileDataAccessor.Directory.SetAccessControl(directoryPath, directorySecurity);
 }
Example #30
0
        private void ConfigureService()
        {
            SetConfigureStatus(0, "Updating configuration files...");

            string output;

            string args = "";

            if (rdoNewMaster.Checked)
            {
                args += " --master";
            }

            Invoke((MethodInvoker) delegate
            {
                string master_host, master_port;
                GetMasterHostPort(out master_host, out master_port);

                args += " --master_host " + master_host + "," + master_port;

                foreach (ListViewItem lvi in lvwEndpoints.Items)
                {
                    args += " --endpoint " + lvi.SubItems[0].Text;

                    if (lvi.SubItems.Count > 1)
                    {
                        args += "," + lvi.SubItems[1].Text + "," + lvi.SubItems[2].Text;
                    }
                }
            });

            if (rdoListener.Checked)
            {
                args += " --listen ::," + txtListenerPort.Text;
            }

            if (chkAcceptConfig.Checked)
            {
                args += " --accept-config";
            }

            if (chkAcceptCommands.Checked)
            {
                args += " --accept-commands";
            }

            args += " --ticket \"" + txtTicket.Text + "\"";
            args += " --trustedcert \"" + _TrustedFile + "\"";
            args += " --cn \"" + txtInstanceName.Text + "\"";
            args += " --zone \"" + txtInstanceName.Text + "\"";

            if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                            "node setup" + args,
                            out output))
            {
                ShowErrorText("Running command 'icinga2.exe " + "node setup" + args + "' produced the following output:\n" + output);
                return;
            }

            SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");
            DirectoryInfo        di   = new DirectoryInfo(Program.Icinga2InstallDir);
            DirectorySecurity    ds   = di.GetAccessControl();
            FileSystemAccessRule rule = new FileSystemAccessRule(txtUser.Text,
                                                                 FileSystemRights.Modify,
                                                                 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

            try {
                ds.AddAccessRule(rule);
                di.SetAccessControl(ds);
            } catch (System.Security.Principal.IdentityNotMappedException) {
                ShowErrorText("Could not set ACLs for \"" + txtUser.Text + "\". Identitiy is not mapped.\n");
                return;
            }

            SetConfigureStatus(75, "Installing the Icinga 2 service...");

            RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                       "--scm-uninstall",
                       out output);

            if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                            "daemon --validate",
                            out output))
            {
                ShowErrorText("Running command 'icinga2.exe daemon --validate' produced the following output:\n" + output);
                return;
            }

            if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                            "--scm-install --scm-user \"" + txtUser.Text + "\" daemon",
                            out output))
            {
                ShowErrorText("\nRunning command 'icinga2.exe --scm-install --scm-user \"" +
                              txtUser.Text + "\" daemon' produced the following output:\n" + output);
                return;
            }

            if (chkInstallNSCP.Checked)
            {
                SetConfigureStatus(85, "Waiting for NSClient++ installation to complete...");

                Process proc = new Process();
                proc.StartInfo.FileName  = "msiexec.exe";
                proc.StartInfo.Arguments = "/i \"" + Program.Icinga2InstallDir + "\\sbin\\NSCP.msi\"";
                proc.Start();
                proc.WaitForExit();
            }

            SetConfigureStatus(100, "Finished.");

            FinishConfigure();
        }
        private void butOK_Click(object sender, System.EventArgs e)
        {
            if (!Directory.Exists(textLocation.Text))
            {
                MsgBox.Show(this, "Location does not exist.");
                return;
            }
            if (Directory.Exists(ODFileUtils.CombinePaths(textLocation.Text, textName.Text)))
            {
                MsgBox.Show(this, "Folder already exists.");
                return;
            }
            try {
                FileSystemAccessRule fsar = new FileSystemAccessRule("everyone", FileSystemRights.FullControl, AccessControlType.Allow);
                DirectorySecurity    ds   = new DirectorySecurity();
                ds.AddAccessRule(fsar);
                string requestDir     = textLocation.Text;
                string rootFolderName = textName.Text;
                string rootDir        = ODFileUtils.CombinePaths(requestDir, rootFolderName);
                //Enable file sharing for the A to Z folder.
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    //Process.Start("net","usershare add OpenDentImages \""+rootDir+"\"");//for future use.
                }
                else                  //Windows
                {
                    Process.Start("NET", "SHARE OpenDentImages=\"" + rootDir + "\"");
                }
                //All folder names to be created should be put in this list, so that each folder is created exactly
                //the same way.
                string[] aToZFolderNames = new string[] {
                    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
                    "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
                    "EmailAttachments", "Forms", "Reports", "Sounds",
                };
                //Create A to Z folders in root folder.
                for (int i = 0; i < aToZFolderNames.Length; i++)
                {
                    string pathToCreate = ODFileUtils.CombinePaths(rootDir, aToZFolderNames[i]);
                    if (!Directory.Exists(pathToCreate))
                    {
                        // Mono does support Directory.CreateDirectory(string, DirectorySecurity)
#if !LINUX
                        Directory.CreateDirectory(pathToCreate, ds);
#else
                        Directory.CreateDirectory(pathToCreate);
#endif
                    }
                }
                //Save new image path into the DocPath and
                //set "use A to Z folders" check-box to checked.
                Prefs.UpdateString(PrefName.DocPath, rootDir);
                Prefs.UpdateString(PrefName.AtoZfolderUsed, "1");
                Cache.Refresh(InvalidType.Prefs);
                //Prefs_client.RefreshClient();
            }
            catch (Exception ex) {
                Logger.openlog.LogMB("Failed to create A to Z folders: " + ex.ToString(), Logger.Severity.ERROR);
            }
            DialogResult = DialogResult.OK;
        }
 /// <summary>
 ///     Creates all the directories in the specified @this, applying the specified Windows security.
 /// </summary>
 /// <param name="this">The directory to create.</param>
 /// <param name="directorySecurity">The access control to apply to the directory.</param>
 /// <returns>An object that represents the directory for the specified @this.</returns>
 /// ###
 /// <exception cref="T:System.IO.IOException">
 ///     The directory specified by <paramref name="this" /> is a file.-or-The
 ///     network name is not known.
 /// </exception>
 /// ###
 /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
 /// ###
 /// <exception cref="T:System.ArgumentException">
 ///     <paramref name="this" /> is a zero-length string, contains only
 ///     white space, or contains one or more invalid characters as defined by
 ///     <see
 ///         cref="F:System.IO.Path.InvalidPathChars" />
 ///     . -or-<paramref name="this" /> is prefixed with, or contains only a colon character (:).
 /// </exception>
 /// ###
 /// <exception cref="T:System.ArgumentNullException">
 ///     <paramref name="this" /> is null.
 /// </exception>
 /// ###
 /// <exception cref="T:System.IO.PathTooLongException">
 ///     The specified @this, file name, or both exceed the system-
 ///     defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file
 ///     names must be less than 260 characters.
 /// </exception>
 /// ###
 /// <exception cref="T:System.IO.DirectoryNotFoundException">
 ///     The specified @this is invalid (for example, it is on
 ///     an unmapped drive).
 /// </exception>
 /// ###
 /// <exception cref="T:System.NotSupportedException">
 ///     <paramref name="this" /> contains a colon character (:) that
 ///     is not part of a drive label ("C:\").
 /// </exception>
 public static DirectoryInfo CreateAllDirectories(this DirectoryInfo @this, DirectorySecurity directorySecurity)
 {
     return Directory.CreateDirectory(@this.FullName, directorySecurity);
 }
Example #33
0
        protected internal static string GetFilePermissions(FileSystemInfo fileInfo)
        {
            FileSystemSecurity fileSecurity = null;
            var filename = fileInfo.FullName;

            if (filename.Length >= 260 && !filename.StartsWith(@"\\?\"))
            {
                filename = string.Format(@"\\?\{0}", filename);
            }

            if (fileInfo is FileInfo)
            {
                try
                {
                    fileSecurity = new FileSecurity(filename, AccessControlSections.All);
                }
                catch (UnauthorizedAccessException)
                {
                    Log.Verbose(Strings.Get("Err_AccessControl"), fileInfo.FullName);
                }
                catch (InvalidOperationException)
                {
                    Log.Verbose("Invalid operation exception {0}.", fileInfo.FullName);
                }
                catch (FileNotFoundException)
                {
                    Log.Verbose("File not found to get permissions {0}.", fileInfo.FullName);
                }
                catch (ArgumentException)
                {
                    Log.Debug("Filename not valid for getting permissions {0}", fileInfo.FullName);
                }
                catch (Exception e)
                {
                    Logger.DebugException(e);
                }
            }
            else if (fileInfo is DirectoryInfo)
            {
                try
                {
                    fileSecurity = new DirectorySecurity(filename, AccessControlSections.All);
                }
                catch (UnauthorizedAccessException)
                {
                    Log.Verbose(Strings.Get("Err_AccessControl"), fileInfo.FullName);
                }
                catch (InvalidOperationException)
                {
                    Log.Verbose("Invalid operation exception {0}.", fileInfo.FullName);
                }
                catch (Exception e)
                {
                    Logger.DebugException(e);
                }
            }
            else
            {
                return(null);
            }
            if (fileSecurity != null)
            {
                return(fileSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All));
            }
            else
            {
                return("");
            }
        }
 public static void SetAccessControl(DirectoryInfo directoryInfo, DirectorySecurity directorySecurity);
Example #35
0
 /// <summary>
 /// Creates all the directories in the specified path, applying the specified Windows security.
 /// </summary>
 /// <param name="path">The directory to create.</param>
 /// <param name="directorySecurity">The access control to apply to the directory.</param>
 public static void CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     Directory.CreateDirectory(GetFullPath(path), directorySecurity);
     Logger.Log("Directory {0} has been created", path);
 }