Ejemplo n.º 1
0
 public Form1()
 {
     InitializeComponent();
     log = new AppLog(false, AppConfigFile.GetValue("LOGPATH"));
     log.Clear();
     log.Write("SINEX Initialized");
 }
Ejemplo n.º 2
0
        // rules: (see FindAppConfigFileTest)
        // 1. Check PrimaryList, app.config in top dir
        // 2. Check SecondaryList, app.conf in top dir
        // 3. Check PrimaryList, app.config in subdir
        // 4. Check SecondaryList, app.conf in subdir
        public override bool Execute()
        {
            AppConfigFile = FindAppConfig();
            if (AppConfigFile != null)
            {
                AppConfigFile.SetMetadata("TargetPath", TargetPath);
            }

            return(true);
        }
        protected override void ExecuteCore()
        {
            OutputAppConfigFileWithMetadata = new TaskItem(GeneratedAppConfigFile);

            if (AppConfigFile != null)
            {
                AppConfigFile.CopyMetadataTo(OutputAppConfigFileWithMetadata);
            }
            else
            {
                OutputAppConfigFileWithMetadata.SetMetadata(MetadataKeys.TargetPath, TargetName);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Parses the Content of an app.config File
        /// </summary>
        /// <param name="content">File Content</param>
        /// <param name="path">Path or Filename</param>
        /// <returns>Parsed Output</returns>
        public static AppConfigFile ParseAppConfigFileContent(string content, string path)
        {
            Validators.AssertIsNotNullOrWhitespace(content, nameof(content));

            var output = new AppConfigFile();

            var document = XElement.Parse(content);

            output.ApplicationSettings = GetApplicationSettings(document);
            var environment = GetEnvironmentFromPath(path);

            SetDeployEnvironment(output.ApplicationSettings, environment);

            return(output);
        }
        static void Main(string[] args)
        {
            CountryDAOPGSQL country = new CountryDAOPGSQL();

            Console.WriteLine(ConnectionDataInfo.TestConnection(AppConfigFile.GetInstance().ConnectionString));
            //Tickets a = new Tickets();

            Administrators a = new Administrators()
            {
                FirstName = "Patreck", LastName = "Sky", Level = 1, UserID = 2
            };

            AdministratorsDAOPGSQL admin = new AdministratorsDAOPGSQL();

            admin.Add(a);
            //admin.Get(2);
            //admin.GetAll();
        }
        void InitilizeConfiguration()
        {
            try
            {
                var fileContent = File.ReadAllText(AppConfigFileFullPath);
                ConfigFile = JsonConvert.DeserializeObject <AppConfigFile>(fileContent);

                var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
                XmlConfigurator.Configure(logRepository, new FileInfo(Log4NetConfigFileFullPath));
            }
            catch (Exception ex)
            {
                LoggerHelper.GetLogger.Error(ex);

                Console.WriteLine("Initilize Config File Error:");
                Console.WriteLine("-----------------------------");
                Console.WriteLine(string.Empty);
                throw;
            }
        }
Ejemplo n.º 7
0
            public static ServerConnection GetGPConnection()
            {
                AppConfigFile    config     = new AppConfigFile();
                ServerConnection connection = new ServerConnection();

                connection.Server   = config.Item("GPSERVER");
                connection.Database = config.Item("GPDATABASE");
                connection.UserId   = config.Item("GPUSERNAME");
                connection.Password = config.Item("GPPASSWORD");
                int connectionTest = connection.Test();

                if (connectionTest == 0)
                {
                    return(connection);
                }
                else
                {
                    return(null);
                }
            }
Ejemplo n.º 8
0
            public static ServerConnection GetLogConnection()
            {
                AppConfigFile    config     = new AppConfigFile();
                ServerConnection connection = new ServerConnection();

                connection.Server   = config.Item("MODSERVER");
                connection.Database = config.Item("MODDATABASE");
                connection.UserId   = config.Item("MODUSERNAME");
                connection.Password = config.Item("MODPASSWORD");
                int connectionTest = connection.Test();

                if (connectionTest == 0)
                {
                    return(connection);
                }
                else
                {
                    logit($"ERROR: Connection Test Failed. Server={connection.Server}");
                    return(null);
                }
            }
Ejemplo n.º 9
0
        public override bool Execute()
        {
            if (SuggestedRedirects == null || SuggestedRedirects.Length == 0)
            {
                Log.LogMessageFromResources("GenerateBindingRedirects.NoSuggestedRedirects");
                OutputAppConfigFile = null;
                return(true);
            }

            var redirects = ParseSuggestedRedirects();

            var doc = LoadAppConfig(AppConfigFile);

            if (doc == null)
            {
                return(false);
            }

            XElement runtimeNode = doc.Root
                                   .Nodes()
                                   .OfType <XElement>()
                                   .FirstOrDefault(e => e.Name.LocalName == "runtime");

            if (runtimeNode == null)
            {
                runtimeNode = new XElement("runtime");
                doc.Root.Add(runtimeNode);
            }
            else
            {
                UpdateExistingBindingRedirects(runtimeNode, redirects);
            }

            var ns = XNamespace.Get("urn:schemas-microsoft-com:asm.v1");

            var redirectNodes = from redirect in redirects
                                select new XElement(
                ns + "assemblyBinding",
                new XElement(
                    ns + "dependentAssembly",
                    new XElement(
                        ns + "assemblyIdentity",
                        new XAttribute("name", redirect.Key.Name),
                        new XAttribute("publicKeyToken", ResolveAssemblyReference.ByteArrayToString(redirect.Key.GetPublicKeyToken())),
                        new XAttribute("culture", String.IsNullOrEmpty(redirect.Key.CultureName) ? "neutral" : redirect.Key.CultureName)),
                    new XElement(
                        ns + "bindingRedirect",
                        new XAttribute("oldVersion", "0.0.0.0-" + redirect.Value),
                        new XAttribute("newVersion", redirect.Value))));

            runtimeNode.Add(redirectNodes);

            var writeOutput = true;

            if (FileSystems.Default.FileExists(OutputAppConfigFile.ItemSpec))
            {
                try
                {
                    var outputDoc = LoadAppConfig(OutputAppConfigFile);
                    if (outputDoc.ToString() == doc.ToString())
                    {
                        writeOutput = false;
                    }
                }
                catch (System.Xml.XmlException)
                {
                    writeOutput = true;
                }
            }

            if (AppConfigFile != null)
            {
                AppConfigFile.CopyMetadataTo(OutputAppConfigFile);
            }
            else
            {
                OutputAppConfigFile.SetMetadata(ItemMetadataNames.targetPath, TargetName);
            }

            if (writeOutput)
            {
                using (var stream = FileUtilities.OpenWrite(OutputAppConfigFile.ItemSpec, false))
                {
                    doc.Save(stream);
                }
            }

            return(!Log.HasLoggedErrors);
        }
Ejemplo n.º 10
0
        ///<param name="db">L'applicazione che userà main.dll avrà la sua variabile db e non userà DBNs.db, poichè DBNs.db è di tipo base e avrei difficoltà con l'intellisense</param>
        public static bool Initialize(SharedCodeWithApp codiceApp, DBBase db, Type classeDb, string logTestoUteAvv = "", string logTestoUteErr = "")
        {
            //***********************************************************************************************************************************************************************************************************************
            //****************ATTENZIONE: Inserire il codice: <runtime><legacyUnhandledExceptionPolicy enabled = "1" /></runtime>  nell'App.config, vedere Eccezioni.vb per i dettagli**********************************************
            //***********************************************************************************************************************************************************************************************************************
            App.Config = new Apps.AppConfigFile();

            mainInizializzato            = false;
            proceduraChiusuraGiàEseguita = false;

            Thread thrCheckTimeInizial = new Thread(thrCheckInitializeTime); //Non ho usato avvio download per non aspettare

            thrCheckTimeInizial.IsBackground = true;
            thrCheckTimeInizial.Start();

            if (Log.main == null)
            {
                Log.Initializes(ref Log.main, warnUserText: logTestoUteAvv, errUserText: logTestoUteErr);
            }

            AppDomain.CurrentDomain.UnhandledException       += Excep.GestoreExNonGestiteDeiThreadSecondari; //Intercetta tutte le eccezioni non gestite dei thread secondari
            Application.Current.DispatcherUnhandledException += Excep.GestoreExNonGestiteDelMainThread;      //Intercetta tutte le eccezioni non gestite del main thread (UI thread)

            if (codiceApp == null)
            {
                Log.main.Add(new Mess(LogType.ERR, "", "ricevuto codiceApp a null"));
                return(false);
            }
            App.SharedCodeApp = codiceApp;

            //if (defaultSaveLoc == null)
            //{
            //    Log.main.Add(new Mess(Tipi.ERR, "", "ricevuto defaultSaveLoc a null"));
            //    return false;
            //}

            if (App.CheckAdminPermission() == false) //Placed after App.CodiceAppCond because use it.
            {
                MessageBox.Show("The application requires administrator privileges");
                App.SharedCodeApp.ExitProcedure(saveConfigurations: false);
            }

            if (Thread.CurrentThread.ManagedThreadId != 1)
            {
                Log.main.Add(new Mess(LogType.ERR, "", "l'id del thread non è 1 richiamare Inizializza con il thread dell'UI"));
                return(false);
            }

            if (dll.inizializza() == false)
            {
                return(false);
            }

            //App.config.dbPrincipale.completa = "Provider=SQL Server Native Client 10.0;Server=Desktop\SQL2008R2Exp;Database=TestMain;Trusted_Connection=Yes;" 'oppure ";User Id=myUsername;Password = myPassword;"
            //App.config.SalvaSuFile()

            //App.MostraWndConfigApp()

            //Serial.Inizializza() 'Non so per quale stranissimo motivo, se lo inizializzo all'interno di "Serial" restituisce l'errore "System.IO.FileNotFoundException" dicendo che non...
            Serialize.jsonSett = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Auto
            };                                                                                              //...trova il file "Newtonsoft.Json.dll",

            //while (AppConfigFile.LoadFromFile(ref App.config, out _) == false)
            App.config = (AppConfigFile)App.config.LoadFromFile(out bool inErr);
            //while (inErr == true)
            //{
            //    App.ShowWndConfigApp();
            //    App.config = (AppConfigFile)App.config.LoadFromFile(out inErr);
            //}

            if (classeDb != null)
            {
                bool esito; List <string> listaErr;

                db                = (DBBase)Activator.CreateInstance(classeDb); //La New del db dell'applicativo viene fatta qui perchè devo avere la variabile LogNs.log inizializzata
                App.Db            = db;
                App.Db.ConnString = App.Config.MainDbConnString;

                if (db.ControlloStrutturaDB(out esito, out listaErr) == false)
                {
                    //Log.main.Add(Tipi.ERR, Log.main.errUserText, listaErr);
                    MessageBox.Show("Controllo strutta DB fallito");
                    return(false);  //qui ci va il return false perchè significa che non sono riusciuto neanche a farla la comparazione
                }

                if (esito == false)
                {
                    Log.main.Add(LogType.ERR, "", listaErr);
                    //TODO -10 open errors list window with options: try recovery or close.
                }

                thrLockedQryKiller = new Thread(DBUtil.thrCycle_LockedQryKiller); //Non ho usato avvio download per non aspettare
                thrLockedQryKiller.IsBackground = true;
                thrLockedQryKiller.Start();
            }

            App.AcquireStartupParameter(); //Deve stare prima di log.CaricaConfigAvviaThr perchè CaricaConfigAvviaThr in debugModeOn cambia comportamento


            if (Log.main.LoadConfigAndStartThread(App.Config) == false)
            {
                return(false);                                                        //deve stare dopo l'inizializzazione del DB e del App.config poichè normalmente caricherà le impostazioni da li
            }
            Log.main.ShowMessageWindow();

            if (Zip.inizializza() == false)
            {
                return(false);
            }

            App.Download = new Www.DownLoad("main");
            App.Upload   = new Www.UpLoad("main");

            thrAccessoRoot = new Thread(Root.ThrMostraNotificaAccessoRoot); //Non ho usato avvio download per non aspettare
            thrAccessoRoot.IsBackground = true;
            thrAccessoRoot.Start();

            Application.Current.Exit += ApplicationExit;

            mainInizializzato = true;
            //TestUpload()
            return(true);
        }
Ejemplo n.º 11
0
        private void button1_Click(object sender, EventArgs e)
        {
            AppConfigFile.GetValue("LOGPATH");
            string      url          = "";
            string      result       = "";
            string      resultPrelim = "";
            SinexPoLine poLine       = new Sinex.Http.SinexPoLine();
            string      inputType    = "TextFile";

            switch (inputType)
            {
            case "Download":
                Http.Connection connection = new Http.Connection(url);
                result = connection.Test();
                break;

            case "TextFile":
                resultPrelim = LoadTextFile(@"C:\Temp\Sinex\SinexFile.txt");
                WriteTextFile(@"C:\Temp\Sinex\RawFile.txt", resultPrelim);
                result = GetPos(resultPrelim);
                WriteTextFile(@"C:\Temp\Sinex\Pos.txt", result);
                break;

            case "TextBox":
                result = textBox1.Text;
                break;
            }
            bool      continueLoop        = true;
            int       currentIndex        = 0;
            int       poStart             = 0;
            int       lineItemsArrayStart = result.IndexOf("[");
            int       lineItemsArrayEnd   = result.IndexOf("]");
            int       poArrayEnd          = result.LastIndexOf("]");
            int       poHeaderStart       = 0;
            int       poHeaderEnd         = result.IndexOf("lineItems") - 3;
            int       poEnd          = lineItemsArrayEnd + 1;
            string    poHeader       = "";
            string    poHeaderNumber = "";
            DataTable gridResults    = new DataTable();

            gridResults.Columns.Add(poHeaderNumber, typeof(string));
            while (continueLoop)
            {
                poHeaderStart       = currentIndex;
                lineItemsArrayStart = result.IndexOf("[", currentIndex);
                lineItemsArrayEnd   = result.IndexOf("]", currentIndex);
                poHeaderEnd         = lineItemsArrayEnd; //result.IndexOf("lineItems", currentIndex) - 3;
                poHeader            = result.SubFromTo(poHeaderStart, poHeaderEnd) + "}";
                WriteTextFile(@"C:\Temp\Sinex\poHeader-PO.txt", poHeader);
                SinexPo po = new SinexPo();
                po             = JsonConvert.DeserializeObject <SinexPo>(poHeader);
                poHeaderNumber = po.poNumber;
                WriteTextFile(@"C:\Temp\Sinex\" + poHeaderNumber + " - PO.txt", poHeader);

                currentIndex = poHeaderEnd + 3;
                if (currentIndex == poArrayEnd)
                {
                    continueLoop = false;
                }
                DataRow dr = gridResults.NewRow();
                dr[0] = poHeaderNumber;
                gridResults.Rows.Add(dr);
            }
            grid.DataSource = gridResults;

            //string poHeader = result.SubFromTo(poHeaderStart, poHeaderEnd) + "}";
            //WriteTextFile(@"C:\Temp\Sinex\PoHeader.txt", poHeader);
            //Po po = new Po();
            //po = JsonConvert.DeserializeObject<Po>(poHeader);

            string poLines = result.SubFromTo(lineItemsArrayStart, lineItemsArrayEnd);

            WriteTextFile(@"C:\Temp\Sinex\PoLines.txt", poLines);

            poLine = JsonConvert.DeserializeObject <SinexPoLine>(result);
            //MessageBox.Show(poLine.poNumber);
            log.Write(result);
            MessageBox.Show(result);
        }
Ejemplo n.º 12
0
        public static SwarmDb GetDatabaseAsAdmin()
        {
            string connectionString = string.Empty;

            try
            {
                if (Path.DirectorySeparatorChar == '/' && HttpContext.Current == null)
                {
                    // We are running under mono in a backend environment

                    using (StreamReader reader = new StreamReader(MonoConfigFile.Replace(".config", "-admin.config")))
                    {
                        connectionString = reader.ReadLine();

                        Logging.LogInformation(LogSource.PirateDb,
                                               "SwarmDb initialized for Linux Backend: [" + connectionString + "]");
                    }
                }
                else if (HttpContext.Current != null)
                {
                    // We are running a web application, under Mono (production) or Windows (development)
                    using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(WebConfigFile.Replace(".config", "-admin.config")))
                           )
                    {
                        connectionString = reader.ReadLine();

                        Logging.LogInformation(LogSource.PirateDb,
                                               "SwarmDb initialized for web: [" + connectionString + "]");
                    }
                }
                else
                {
                    // We are running an application, presumably directly from Visual Studio.
                    // If so, the current working directory is "PirateWeb/30/Console/bin".
                    using (StreamReader reader = new StreamReader(AppConfigFile.Replace(".config", "-admin.config")))
                    {
                        connectionString = reader.ReadLine();

                        Logging.LogInformation(LogSource.PirateDb,
                                               "SwarmDb initialized for application: [" + connectionString +
                                               "]");
                    }
                }
            }
            catch (Exception)
            {
                Logging.LogWarning(LogSource.PirateDb, "Unable to read Database.Config - defaulting");
                // Ignore if we can't read the Database.config
            }

            // To simplify future checks
            if (connectionString != null && connectionString.Length == 0)
            {
                connectionString = null;
            }

            // If we still have nothing, and we're running from web, then assume we have a dev environment and use the hostname as db, user, and pass.
            if (String.IsNullOrEmpty(connectionString))
            {
                if (HttpContext.Current != null) // dummy comment to force build, remove on sight
                {
                    string hostName = HttpContext.Current.Request.Url.Host;

                    connectionString = "server=peregrine;database=" + hostName + ";user="******"-admin;password="******"-admin";  // TODO: Replace "peregrine" with "localhost"
                }
                else
                {
                    throw new InvalidOperationException("No database-as-admin connection string found -- write a connect string into the \"ActivizrAdminConnect\" environment var, or on one line into a file named database-admin.config; see connectionstrings.com for examples");  // TODO: Replace with custom exception to present config screen
                }
            }

            // Now write the correct data to the cache, for faster lookup next time
            if (_cachedConnectionString == null)
            {
                _cachedConnectionString = connectionString;
            }

            return(new SwarmDb(DbProviderFactories.GetFactory(DefaultProviderName), connectionString));
        }