コード例 #1
0
        /// <summary>
        /// Initializes the class. This includes loading application settings from the configuration file. The application name should be scoped within the system.
        /// For non web applications, this method must be called directly from the main executable assembly and not from a supporting library.
        ///
        /// To debug this method, create a folder called C:\AnyoneFullControl and give Everyone full control. A file will appear in that folder explaining how far
        /// it got in init.
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="isClientSideProgram"></param>
        /// <param name="systemLogic"></param>
        /// <param name="mainDataAccessStateGetter">A method that returns the current main data-access state whenever it is requested, including during this
        /// AppTools.Init call. Do not allow multiple threads to use the same state at the same time. If you pass null, the data-access subsystem will not be
        /// available in the application.</param>
        public static void Init(string appName, bool isClientSideProgram, SystemLogic systemLogic, Func <DataAccessState> mainDataAccessStateGetter = null)
        {
            var initializationLog = "Starting init";

            try {
                if (initialized)
                {
                    throw new ApplicationException("This class can only be initialized once.");
                }

                if (systemLogic == null)
                {
                    throw new ApplicationException("The system must have a global logic class and you must pass an instance of it to AppTools.Init.");
                }

                // Initialize ConfigurationStatics, including the general provider, before the exception handling block below because it's reasonable for the exception
                // handling to depend on this.
                ConfigurationStatics.Init(systemLogic.GetType(), appName, isClientSideProgram, ref initializationLog);

                // Setting the initialized flag to true must be done before executing the secondary init block below so that exception handling works.
                initialized        = true;
                initializationLog += Environment.NewLine + "Succeeded in primary init.";
            }
            catch (Exception e) {
                initializationLog += Environment.NewLine + e;
                StandardLibraryMethods.EmergencyLog("Initialization log", initializationLog);
                throw;
            }

            try {
                var asposeLicense = ConfigurationStatics.SystemGeneralProvider.AsposeLicenseName;
                if (asposeLicense.Any())
                {
                    new Aspose.Pdf.License().SetLicense(asposeLicense);
                    new Aspose.Words.License().SetLicense(asposeLicense);
                }

                // This initialization could be performed using reflection. There is no need for AppTools to have a dependency on these classes.
                AppMemoryCache.Init();
                BlobFileOps.Init();
                DataAccessStatics.Init();
                DataAccessState.Init(mainDataAccessStateGetter);
                EncryptionOps.Init();
                HtmlBlockStatics.Init();
                InstallationSupportUtility.ConfigurationLogic.Init1();
                UserManagementStatics.Init();

                systemLogic.InitSystem();
            }
            catch (Exception e) {
                secondaryInitFailed = true;

                // Suppress all exceptions since they would prevent apps from knowing that primary initialization succeeded. EWF apps need to know this in order to
                // automatically restart themselves. Other apps could find this knowledge useful as well.
                try {
                    EmailAndLogError("An exception occurred during application initialization:", e);
                }
                catch {}
            }
        }
コード例 #2
0
        public static void Main()
        {
            GlobalInitializationOps.InitStatics(new GlobalInitializer(), "Tester", false);

            EwlStatics.RunStandardLibraryTests();

            Console.WriteLine(new TimeSpan(0, 0, 0, 0, 4861000).ToHourMinuteSecondString());
            Console.WriteLine(new TimeSpan(0, 0, 0, 0, 4861000).ToHourMinuteString());
            Console.WriteLine(new TimeSpan(0, 0, 0, 0, 104861000).ToHourMinuteSecondString());
            Console.WriteLine(new TimeSpan(0, 0, 0, 0, 104861000).ToHourMinuteString());
            Console.WriteLine(new TimeSpan(1, 2, 3, 4, 0).ToHourMinuteSecondString());
            Console.WriteLine(new TimeSpan(1, 2, 3, 4, 0).ToHourMinuteString());
            Console.WriteLine(new TimeSpan(0, 1, 32).ToHourMinuteSecondString());

            Console.WriteLine(FormattingMethods.GetFormattedBytes(64));
            Console.WriteLine(FormattingMethods.GetFormattedBytes(64000));
            Console.WriteLine(FormattingMethods.GetFormattedBytes(64000000));
            Console.WriteLine(FormattingMethods.GetFormattedBytes(64500000000));

            Console.WriteLine("fred".CapitalizeString());
            Console.WriteLine("".CapitalizeString());
            Console.WriteLine("\n".CapitalizeString());
            Console.WriteLine("f".CapitalizeString());
            Console.WriteLine("1234f".CapitalizeString());
            Console.WriteLine("1234".CapitalizeString());
            Console.WriteLine("       f".CapitalizeString());
            Console.WriteLine("       ".CapitalizeString());
            Console.WriteLine(" fred".CapitalizeString());
            Console.WriteLine(" fred died.".CapitalizeString());
            Console.WriteLine(".".CapitalizeString());
            Console.WriteLine(" .".CapitalizeString());
            Console.WriteLine(" .fred died.".CapitalizeString());
            Console.WriteLine(" . fred died.".CapitalizeString());
            Console.WriteLine("\nfred".CapitalizeString());
            Console.WriteLine(" \n fred".CapitalizeString());
            Console.WriteLine("\n------\nfred".CapitalizeString());

            Console.WriteLine("one two three.csv".ToSafeFileName());

            Console.WriteLine("One {one one } two {two}".RemoveTextBetweenStrings("{", "}"));
            Console.WriteLine("This 'quoted text'.".RemoveTextBetweenStrings("'", "'"));
            Console.WriteLine("A comments looks like /*A comment.*/.".RemoveTextBetweenStrings("/*", "*/"));
            Console.WriteLine("body.ewf div.ewfIeWarningBanner table a { font-size:1.5em; }".RemoveTextBetweenStrings("{", "}"));

            Console.WriteLine("one".ConcatenateWithSpace("two"));
            Console.WriteLine(EnterpriseWebLibrary.StringTools.ConcatenateWithDelimiter(", ", "one", "two", "three"));
            Console.WriteLine(EnterpriseWebLibrary.StringTools.ConcatenateWithDelimiter("|", "", "one", "", "", "two", "", "three ", "   "));

            Console.WriteLine("abcde".Truncate(4));
            Console.WriteLine("abcde".TruncateStart(4));
            Console.WriteLine(NetTools.CombineUrls(@"http://www.redstapler.biz", "/Files", "Carriers", "Hancock/", "blabla.pdf"));
            Console.WriteLine(NetTools.CombineUrls(@"http://www.redstapler.biz", "//Files", "Carriers", "Hancock//", "blabla.pdf//"));
            Console.WriteLine(NetTools.CombineUrls(@"///http://www.redstapler.biz//", "/Files/", "Carriers/", "Hancock/", "/blabla.pdf/"));
            Console.WriteLine(NetTools.CombineUrls(@"http://localhost/ToddPublicWebSite/", "Carriers", "UP", "ComparisonLogo.jpg"));

            Console.WriteLine(EwlStatics.CombinePaths(@"C:\Inetpub\", "Files", "orgs", "box.txt"));
            Console.WriteLine(EwlStatics.CombinePaths(@"C:\Inetpub\", "Files", "orgs", "anotherFolder", "box.txt"));
            Console.WriteLine(EwlStatics.CombinePaths(@"C:\Inetpub\", "Files", @"orgs\"));
            Console.WriteLine(EwlStatics.CombinePaths(@"C:\Inetpub", @"\Files\", @"\orgs", "box.txt"));
            Console.WriteLine(EwlStatics.CombinePaths(@"Inetpub", @"Files"));
            Console.WriteLine(EwlStatics.CombinePaths(@"D:\Source Control Repository\Charette", @"", @"\Aspose.Words.lic"));

            Console.WriteLine(EnterpriseWebLibrary.StringTools.CamelToEnglish(null));
            Console.WriteLine("".CamelToEnglish());
            Console.WriteLine("L".CamelToEnglish());
            Console.WriteLine("l".CamelToEnglish());
            Console.WriteLine("LeftLeg".CamelToEnglish());
            Console.WriteLine("hits you in the Head and the LeftLeg!  That hurts.".CamelToEnglish());

            var mySet = new HashSet <string> {
                "a", "c", "", "b", "fred"
            };

            var list = new List <string>(mySet);

            foreach (var item in mySet)
            {
                list.Add(item);
            }

            //	mySet = new Set( list );

            var ls = new ListSet <string> {
                "one", "two", "one", "two"
            };

            foreach (var item in ls)
            {
                Console.WriteLine(item);
            }

            var validator = new Validator();
            var vp        = new ValidationErrorHandler(errorWriter);

            Console.WriteLine(validator.GetUrl(vp, "hTTp://RedStapler.biZ/fRed", false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(validator.GetUrl(vp, "fred", true));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.Write(validator.GetNullableSqlSmallDateTimeExact(vp, "fred", "MM/dd/yyy", false));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(validator.GetInt(vp, "fred"));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);               // "myGoodInt" );
            Console.WriteLine(validator.GetInt(vp, "-342"));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);               // "myBadDate" );
            Console.WriteLine(validator.GetSqlSmallDateTimeFromParts(vp, "3", "", ""));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);               // "myBadDate" );
            Console.WriteLine(validator.GetSqlSmallDateTimeFromParts(vp, "", "", ""));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);               // "zip" );
            Console.WriteLine(validator.GetZipCode(vp, "14580", true).FullZipCode);
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);               // "zip" );
            Console.WriteLine(validator.GetZipCode(vp, "14580-1234", true).FullZipCode);
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);               // "badZip" );
            Console.WriteLine(validator.GetZipCode(vp, "123", false).FullZipCode);
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            Console.WriteLine("---------------------------------\nPhone Numbers:\n------------------------------------\n");
            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(validator.GetPhoneNumber(vp, "5854556476", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);


            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(validator.GetPhoneNumber(vp, "585 4556476", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(validator.GetPhoneNumber(vp, "( 585 )455-6476", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(validator.GetPhoneNumber(vp, "(585)455-6476", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(validator.GetPhoneNumber(vp, "585-455-6476", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("With lots of spaces: " + validator.GetPhoneNumber(vp, "585   872   0291  ", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("With x: " + validator.GetPhoneNumber(vp, "5854556476   x   12345", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("With space ext. allowed: " + validator.GetPhoneNumber(vp, "5854556476 12345", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("Toni example 1: " + validator.GetPhoneNumber(vp, "321-663-4810", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("Toni example 2: " + validator.GetPhoneNumber(vp, "585-336-7600 ext 65361", true, true, false));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("Gibberish, should fail^ " + validator.GetPhoneNumber(vp, "sodifuoisafdoiu", true, true, true));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("With space no ext. allowed, should fail^ " + validator.GetPhoneNumber(vp, "5854556476 12345", false, false, true));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("With extension and no delimeters, should fail^ " + validator.GetPhoneNumber(vp, "585455647612345", true, true, false));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine(
                "With extension and no delimeters, should succeed since allowGarbage is on. " + validator.GetPhoneNumber(vp, "585455647612345", true, true, true));
            Assert.IsFalse(vp.LastResult != ErrorCondition.NoError);

            vp = new ValidationErrorHandler(errorWriter);
            Console.WriteLine("Should fail^ " + validator.GetPhoneNumber(vp, "02934", true, true, false));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            Console.WriteLine("------------------------\nEnd phone numbers.\n-------------------------------\n");

            vp = new ValidationErrorHandler(errorWriter);               // "badByte" );
            Console.WriteLine(validator.GetByte(vp, "234987234"));
            Assert.IsFalse(vp.LastResult == ErrorCondition.NoError);

            var key = Rijndael.Create().Key;

            Console.Write("Encryption Key: { ");
            foreach (var b in key)
            {
                Console.Write(b + ", ");
            }
            Console.WriteLine();

            Console.WriteLine("SSN length: " + EncryptionOps.EncryptString(EncryptionOps.GenerateInitVector(), "987654321").Length);
        }
コード例 #3
0
        /// <summary>
        /// Initializes the system. This includes loading application settings from the configuration file. The application name should be scoped within the system.
        /// For non web applications, this method must be called directly from the main executable assembly and not from a supporting library.
        ///
        /// To debug this method, create a folder called C:\AnyoneFullControl and give Everyone full control. A file will appear in that folder explaining how far
        /// it got in init.
        /// </summary>
        /// <param name="globalInitializer">The system's global initializer. Do not pass null.</param>
        /// <param name="appName"></param>
        /// <param name="isClientSideApp"></param>
        /// <param name="assemblyFolderPath">Pass a nonempty string to override the assembly folder path, which is used to locate the installation folder. Use with
        /// caution.</param>
        /// <param name="mainDataAccessStateGetter">A method that returns the current main data-access state whenever it is requested, including during this
        /// InitStatics call. Do not allow multiple threads to use the same state at the same time. If you pass null, the data-access subsystem will not be
        /// available in the application.</param>
        /// <param name="useLongDatabaseTimeouts">Pass true if the application is a background process that can tolerate slow database access.</param>
        public static void InitStatics(
            SystemInitializer globalInitializer, string appName, bool isClientSideApp, string assemblyFolderPath = "",
            Func <DataAccessState> mainDataAccessStateGetter = null, bool useLongDatabaseTimeouts = false)
        {
            var initializationLog = "Starting init";

            try {
                if (initialized)
                {
                    throw new ApplicationException("This class can only be initialized once.");
                }

                if (globalInitializer == null)
                {
                    throw new ApplicationException("The system must have a global initializer.");
                }

                // Initialize these before the exception handling block below because it's reasonable for the exception handling to depend on them.
                ConfigurationStatics.Init(assemblyFolderPath, globalInitializer.GetType(), appName, isClientSideApp, ref initializationLog);
                EmailStatics.Init();
                TelemetryStatics.Init();

                // Setting the initialized flag to true must be done before executing the secondary init block below so that exception handling works.
                initialized        = true;
                initializationLog += Environment.NewLine + "Succeeded in primary init.";
            }
            catch (Exception e) {
                initializationLog += Environment.NewLine + e;
                EwlStatics.EmergencyLog("Initialization log", initializationLog);
                throw;
            }

            try {
                CultureInfo.DefaultThreadCurrentCulture = Cultures.EnglishUnitedStates;

                var asposePdfLicensePath = EwlStatics.CombinePaths(ConfigurationStatics.InstallationConfiguration.AsposeLicenseFolderPath, "Aspose.PDF.lic");
                if (File.Exists(asposePdfLicensePath))
                {
                    new Aspose.Pdf.License().SetLicense(asposePdfLicensePath);
                }
                var asposeWordsLicensePath = EwlStatics.CombinePaths(ConfigurationStatics.InstallationConfiguration.AsposeLicenseFolderPath, "Aspose.Words.lic");
                if (File.Exists(asposeWordsLicensePath))
                {
                    new Aspose.Words.License().SetLicense(asposeWordsLicensePath);
                }

                AppMemoryCache.Init();
                BlobStorageStatics.Init();
                DataAccessStatics.Init();
                DataAccessState.Init(mainDataAccessStateGetter, useLongDatabaseTimeouts);
                EncryptionOps.Init();
                HtmlBlockStatics.Init();
                UserManagementStatics.Init();

                GlobalInitializationOps.globalInitializer = globalInitializer;
                globalInitializer.InitStatics();
            }
            catch (Exception e) {
                secondaryInitFailed = true;

                // Suppress all exceptions since they would prevent apps from knowing that primary initialization succeeded. EWF apps need to know this in order to
                // automatically restart themselves. Other apps could find this knowledge useful as well.
                try {
                    TelemetryStatics.ReportError("An exception occurred during application initialization:", e);
                }
                catch {}
            }
        }
コード例 #4
0
        void ControlTreeDataLoader.LoadData()
        {
            Attributes.Add(uniqueIdentifierAttribute, UniqueUdentifier);
            Attributes.Add(parmetersAttribute, Parameters);
            // This gives us some ability to be slightly more strongly typed, allowing us to change the actual attribute names here while not breaking script.
            EwfPage.Instance.ClientScript.RegisterClientScriptBlock(GetType(),
                                                                    uniqueIdentifierAttribute,
                                                                    @"uniqueIdentifierAttribute = '{0}';".FormatWith(uniqueIdentifierAttribute),
                                                                    true);

            EwfPage.Instance.ClientScript.RegisterClientScriptBlock(GetType(), parmetersAttribute, @"parameters = '{0}';".FormatWith(parmetersAttribute), true);
            // Provides a handle to the upload service for the script.
            EwfPage.Instance.ClientScript.RegisterClientScriptBlock(GetType(),
                                                                    "uploadServicePath",
                                                                    @"uploadServicePath = '{0}';".FormatWith(ResolveClientUrl("~/Ewf/FileUploader/Upload.aspx")),
                                                                    true);
            // Handle to the path of the progress image. jquery.progressbar needs to know where the images are to be used.
            // Just because this appears above the definition of jquery.progressbar doesn't mean it appears before
            // it in the resulting document, which causes the progressbar file to consider it undefined. To fix this,
            // I wrapped the jquery.progressbar file in a $(document).ready() call so that it is not defined until the
            // entire document loads, where imagesPath will be already defined, no matter its position.
            EwfPage.Instance.ClientScript.RegisterClientScriptBlock(GetType(),
                                                                    "imagesPath",
                                                                    @"imagesPath = '{0}';".FormatWith(ResolveClientUrl("~/Ewf/FileUploader/")),
                                                                    true);

            // NOTE: So this won't work if this control is used in a user control...
            var encryptedFullyQualifiedName = EncryptionOps.GetEncryptedString(EncryptionOps.GenerateInitVector(), EwfPage.Instance.GetType().BaseType.FullName);

            EwfPage.Instance.ClientScript.RegisterClientScriptBlock(GetType(), "pageHandle", @"pageHandle = '{0}';".FormatWith(encryptedFullyQualifiedName), true);

            EwfPage.Instance.ClientScript.RegisterClientScriptInclude(GetType(), "ClientSide", this.GetClientUrl("~/Ewf/FileUploader/ClientSide.js"));
            EwfPage.Instance.ClientScript.RegisterClientScriptInclude(GetType(),
                                                                      "jquery.progressbar",
                                                                      this.GetClientUrl("~/Ewf/FileUploader/jquery.progressbar.min.js"));

            // Choose between dropping files onto the page or browse for them.
            var chooseUploadMethod = SelectList.CreateRadioList(SelectList.GetTrueFalseItems("Drag and drop files", "Browse for files"),
                                                                true,
                                                                useHorizontalLayout: true);

            var dragFilesHerePanel = new Panel {
                CssClass = "dropZone"
            }.AddControlsReturnThis(new Paragraph("Drop files here")
            {
                CssClass = "dropFilesHereMessage"
            });

            // Not using an ASP.NET control because I want full control without any magic.
            var browseForFiles = new WebControl(HtmlTextWriterTag.Input);

            browseForFiles.Attributes.Add("type", "file");
            browseForFiles.Attributes.Add("multiple", "multiple");
            browseForFiles.Attributes.Add("onchange", @"inputChanged(this);");

            chooseUploadMethod.AddDisplayLink((true as bool?).ToSingleElementArray(), true, dragFilesHerePanel.ToSingleElementArray());
            chooseUploadMethod.AddDisplayLink((false as bool?).ToSingleElementArray(), true, browseForFiles.ToSingleElementArray());

            var uploadPending = new Box("Files to be uploaded",
                                        new Control[]
            {
                new Panel {
                    CssClass = "queuedFilesContentArea"
                }.AddControlsReturnThis(new Paragraph("No files are currently in the queue."))
                , new Heading {
                    CssClass = "upload-count"
                }
            })
            {
                CssClass = "queuedFiles"
            };

            Controls.Add(
                new Box(new Control[]
            {
                new Panel {
                    CssClass = "ewfErrorMessageListBlock"
                }, chooseUploadMethod,
                new Panel {
                    CssClass = "dropWrapper"
                }.AddControlsReturnThis(dragFilesHerePanel), browseForFiles, uploadPending,
                new CustomButton(() => @"uploadButtonClicked(this);")
                {
                    ActionControlStyle = new ButtonActionControlStyle("Begin upload"),
                    CssClass           = "beginUploadButton"
                }
            })
            {
                CssClass = "upload-box"
            });
        }