Пример #1
0
        private static int Main(string[] args)
        {
            GlobalInitializationOps.InitStatics(new GlobalInitializer(), "Development Utility", true);
            try {
                return(GlobalInitializationOps.ExecuteAppWithStandardExceptionHandling(
                           () => {
                    try {
                        if (args.Count() < 2)
                        {
                            throw new UserCorrectableException("You must specify the installation path as the first argument and the operation name as the second.");
                        }

                        // Get installation.
                        var installationPath = args[0];
                        DevelopmentInstallation installation;
                        try {
                            installation = getInstallation(installationPath);
                        }
                        catch (Exception e) {
                            throw new UserCorrectableException("The installation at \"" + installationPath + "\" is invalid.", e);
                        }

                        // Get operation.
                        var operations = AssemblyTools.BuildSingletonDictionary <Operation, string>(Assembly.GetExecutingAssembly(), i => i.GetType().Name);
                        var operationName = args[1];
                        if (!operations.ContainsKey(operationName))
                        {
                            throw new UserCorrectableException(operationName + " is not a known operation.");
                        }
                        var operation = operations[operationName];

                        if (!operation.IsValid(installation))
                        {
                            throw new UserCorrectableException("The " + operation.GetType().Name + " operation cannot be performed on this installation.");
                        }
                        operation.Execute(installation, new OperationResult());
                    }
                    catch (Exception e) {
                        Output.WriteTimeStampedError(e.ToString());
                        if (e is UserCorrectableException)
                        {
                            throw new DoNotEmailOrLogException();
                        }
                        throw;
                    }
                }));
            }
            finally {
                GlobalInitializationOps.CleanUpStatics();
            }
        }
        /// <summary>
        /// Call this from Application_Start in your Global.asax.cs file. Besides this call, there should be no other code in the method.
        /// </summary>
        /// <param name="globalInitializer">The system's global initializer. Do not pass null.</param>
        /// <param name="appInitializer">The application initializer, which performs web-site specific initialization and cleanup. If you have one of these you
        /// should name the class AppInitializer.</param>
        public static void InitStatics(SystemInitializer globalInitializer, SystemInitializer appInitializer = null)
        {
            // This is a hack to support data-access state in WCF services.
            var wcfDataAccessState = new ThreadLocal <DataAccessState>(() => new DataAccessState());

            // Initialize system.
            var initTimeDataAccessState = new ThreadLocal <DataAccessState>(() => new DataAccessState());

            try {
                GlobalInitializationOps.InitStatics(
                    globalInitializer,
                    Path.GetFileName(Path.GetDirectoryName(HttpRuntime.AppDomainAppPath)),
                    false,
                    mainDataAccessStateGetter: () => {
                    return(EwfApp.Instance != null ? EwfApp.Instance.RequestState != null ? EwfApp.Instance.RequestState.DataAccessState :
                           initTimeDataAccessState.Value :
                           System.ServiceModel.OperationContext.Current != null ? wcfDataAccessState.Value : null);
                });
            }
            catch {
                // Suppress all exceptions since there is no way to report them.
                return;
            }
            ewlInitialized = true;

            // Initialize web application.
            if (!GlobalInitializationOps.SecondaryInitFailed)
            {
                EwfApp.ExecuteWithBasicExceptionHandling(
                    () => {
                    EwfConfigurationStatics.Init();

                    GlobalConfiguration.Configure(WebApiStatics.ConfigureWebApi);

                    // Prevent MiniProfiler JSON exceptions caused by pages with hundreds of database queries.
                    MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue;

                    var globalType = BuildManager.GetGlobalAsaxType().BaseType;
                    if (!(globalType.Assembly.CreateInstance("EnterpriseWebLibrary.EnterpriseWebFramework." + globalType.Namespace + ".MetaLogicFactory") is
                          AppMetaLogicFactory metaLogicFactory))
                    {
                        throw new ApplicationException("Meta logic factory not found.");
                    }
                    EwfApp.Init(globalType, metaLogicFactory);

                    EwfPage.Init(
                        ModalBox.CreateBrowsingModalBox,
                        () => {
                        var cssInfos = new List <ResourceInfo>();
                        cssInfos.AddRange(EwfApp.MetaLogicFactory.CreateBasicCssInfos());
                        if (EwfUiStatics.AppMasterPage != null)
                        {
                            cssInfos.AddRange(EwfApp.MetaLogicFactory.CreateEwfUiCssInfos());
                        }
                        cssInfos.AddRange(EwfApp.Instance.GetStyleSheets());
                        if (EwfUiStatics.AppMasterPage != null)
                        {
                            cssInfos.AddRange(EwfUiStatics.AppProvider.GetStyleSheets());
                        }
                        return(cssInfos);
                    });
                    CssPreprocessingStatics.Init(globalInitializer.GetType().Assembly, globalType.Assembly);
                    HyperlinkBehaviorExtensionCreators.Init(ModalBox.GetBrowsingModalBoxOpenStatements);
                    EwfUiStatics.Init(globalType);

                    EwfInitializationOps.appInitializer = appInitializer;
                    appInitializer?.InitStatics();

                    initTimeDataAccessState     = null;
                    EwfApp.FrameworkInitialized = true;
                },
                    false,
                    false);
            }

            // If initialization failed, unload and restart the application after a reasonable delay.
            if (!EwfApp.FrameworkInitialized)
            {
                const int unloadDelay = 60000;                 // milliseconds
                initFailureUnloadTimer = new Timer(
                    state => EwfApp.ExecuteWithBasicExceptionHandling(
                        () => {
                    if (ConfigurationStatics.IsDevelopmentInstallation)
                    {
                        return;
                    }
                    HttpRuntime.UnloadAppDomain();

                    // Restart the application by making a request. Idea from Rick Strahl:
                    // http://weblog.west-wind.com/posts/2013/Oct/02/Use-IIS-Application-Initialization-for-keeping-ASPNET-Apps-alive.
                    //
                    // Disable server certificate validation so that this request gets through even for web sites that don't use a certificate that is trusted by
                    // default. There is no security risk since we're not sending any sensitive information and we're not using the response.
                    Tewl.Tools.NetTools.ExecuteWithResponse(
                        IisConfigurationStatics.GetFirstBaseUrlForCurrentSite(false),
                        response => {},
                        disableCertificateValidation: true);
                },
                        false,
                        false),
                    null,
                    unloadDelay,
                    Timeout.Infinite);
            }
        }
        /// <summary>
        /// Call this from Application_Start in your Global.asax.cs file. Besides this call, there should be no other code in the method.
        /// </summary>
        /// <param name="globalInitializer">The system's global initializer. Do not pass null.</param>
        /// <param name="appInitializer">The application initializer, which performs web-site specific initialization and cleanup. If you have one of these you
        /// should name the class AppInitializer.</param>
        public static void InitStatics(SystemInitializer globalInitializer, SystemInitializer appInitializer = null)
        {
            // This is a hack to support data-access state in WCF services.
            var wcfDataAccessState = new ThreadLocal <DataAccessState>(() => new DataAccessState());

            // Initialize system.
            var initTimeDataAccessState = new ThreadLocal <DataAccessState>(() => new DataAccessState());

            try {
                GlobalInitializationOps.InitStatics(
                    globalInitializer,
                    Path.GetFileName(Path.GetDirectoryName(HttpRuntime.AppDomainAppPath)),
                    false,
                    mainDataAccessStateGetter: () => {
                    return(EwfApp.Instance != null ? EwfApp.Instance.RequestState != null ? EwfApp.Instance.RequestState.DataAccessState :
                           initTimeDataAccessState.Value :
                           System.ServiceModel.OperationContext.Current != null ? wcfDataAccessState.Value : null);
                });
            }
            catch {
                // Suppress all exceptions since there is no way to report them.
                return;
            }
            ewlInitialized = true;

            // Initialize web application.
            if (!GlobalInitializationOps.SecondaryInitFailed)
            {
                EwfApp.ExecuteWithBasicExceptionHandling(
                    () => {
                    EwfConfigurationStatics.Init();

                    GlobalConfiguration.Configure(WebApiStatics.ConfigureWebApi);

                    var miniProfilerOptions = new MiniProfilerOptions();
                    miniProfilerOptions.IgnoredPaths.Clear();
                    MiniProfiler.Configure(miniProfilerOptions);

                    var globalType     = BuildManager.GetGlobalAsaxType().BaseType;
                    var providerGetter = new SystemProviderGetter(
                        globalType.Assembly,
                        globalType.Namespace + ".Providers",
                        providerName =>
                        @"{0} provider not found in application. To implement, create a class named {0} in ""Your Web Site\Providers"" that derives from App{0}Provider."
                        .FormatWith(providerName));

                    if (ExternalFunctionalityStatics.SamlFunctionalityEnabled)
                    {
                        ExternalFunctionalityStatics.ExternalSamlProvider.InitAppStatics(
                            providerGetter,
                            () => AuthenticationStatics.SamlIdentityProviders.Select(
                                identityProvider => {
                            using (var client = new HttpClient()) {
                                client.Timeout = new TimeSpan(0, 0, 10);
                                var metadata   = Task.Run(
                                    async() => {
                                    using (var response = await client.GetAsync(identityProvider.MetadataUrl, HttpCompletionOption.ResponseHeadersRead)) {
                                        response.EnsureSuccessStatusCode();
                                        var document = new XmlDocument();
                                        using (var stream = await response.Content.ReadAsStreamAsync())
                                            using (var reader = XmlReader.Create(stream))
                                                document.Load(reader);
                                        return(document.DocumentElement);
                                    }
                                })
                                                 .Result;
                                return(metadata, identityProvider.EntityId);
                            }
                        })
                            .Materialize());
                    }

                    UrlHandlingStatics.Init(
                        (baseUrlString, appRelativeUrl) =>
                        AppRequestState.ExecuteWithUrlHandlerStateDisabled(() => UrlHandlingStatics.ResolveUrl(baseUrlString, appRelativeUrl)?.Last()));
                    CssPreprocessingStatics.Init(globalInitializer.GetType().Assembly, globalType.Assembly);
                    ResourceBase.Init(
                        (requestTransferred, resource) => {
                        if (requestTransferred)
                        {
                            var urlHandlers       = new List <BasicUrlHandler>();
                            UrlHandler urlHandler = resource;
                            do
                            {
                                urlHandlers.Add(urlHandler);
                            }while((urlHandler = urlHandler.GetParent()) != null);
                            AppRequestState.Instance.SetUrlHandlers(urlHandlers);

                            AppRequestState.Instance.SetNewUrlParameterValuesEffective(false);
                            AppRequestState.Instance.SetResource(resource);
                        }
                        else
                        {
                            AppRequestState.Instance.SetResource(resource);
                        }
                    },
                        () => AppRequestState.Instance.Resource);
                    PageBase.Init(
                        (() => BasePageStatics.AppProvider.GetPageViewDataModificationMethod(), () => BasePageStatics.AppProvider.JavaScriptDocumentReadyFunctionCall),
                        BasicPageContent.GetContent);
                    HyperlinkBehaviorExtensionCreators.Init(ModalBox.GetBrowsingModalBoxOpenStatements);
                    FileUpload.Init(() => ((BasicPageContent)PageBase.Current.BasicContent).FormUsesMultipartEncoding = true);
                    ModalBox.Init(() => ((BasicPageContent)PageBase.Current.BasicContent).BrowsingModalBoxId);
                    CreditCardCollector.Init(() => ((BasicPageContent)PageBase.Current.BasicContent).IncludesStripeCheckout = true);
                    BasePageStatics.Init(providerGetter.GetProvider <AppStandardPageLogicProvider>("StandardPageLogic"));
                    BasicPageContent.Init(
                        contentObjects => {
                        var contentUsesUi = contentObjects.Any(i => i is UiPageContent);

                        var cssInfos = new List <ResourceInfo>();
                        cssInfos.Add(
                            new ExternalResource(
                                "//fonts.googleapis.com/css2?family=Libre+Franklin:wght@500;600;700&family=Open+Sans:ital,wght@0,400;0,600;0,700;1,400&display=fallback"));
                        cssInfos.Add(new ExternalResource("//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"));
                        cssInfos.Add(new StaticFiles.Versioned.Third_party.Jquery_ui.Jquery_ui_1114custom_v2.Jquery_uiminCss());
                        cssInfos.Add(new StaticFiles.Third_party.Select_cssCss());
                        cssInfos.Add(new StaticFiles.Versioned.Third_party.Chosen.Chosen_v187.ChosenminCss());
                        cssInfos.Add(new StaticFiles.Third_party.Time_picker.StylesCss());
                        cssInfos.Add(new ExternalResource("//cdn.jsdelivr.net/qtip2/2.2.1/jquery.qtip.min.css"));
                        cssInfos.Add(new ExternalResource("//cdnjs.cloudflare.com/ajax/libs/dialog-polyfill/0.4.9/dialog-polyfill.min.css"));
                        cssInfos.Add(new StaticFiles.Styles.BasicCss());
                        if (contentUsesUi)
                        {
                            cssInfos.AddRange(
                                new ResourceInfo[]
                            {
                                new StaticFiles.Styles.Ui.ColorsCss(), new StaticFiles.Styles.Ui.FontsCss(), new StaticFiles.Styles.Ui.LayoutCss(),
                                new StaticFiles.Styles.Ui.TransitionsCss()
                            });
                        }
                        foreach (var resource in BasePageStatics.AppProvider.GetStyleSheets())
                        {
                            assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource);
                            cssInfos.Add(resource);
                        }
                        if (contentUsesUi)
                        {
                            foreach (var resource in EwfUiStatics.AppProvider.GetStyleSheets())
                            {
                                assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource);
                                cssInfos.Add(resource);
                            }
                        }
                        else
                        {
                            foreach (var resource in BasePageStatics.AppProvider.GetCustomUiStyleSheets())
                            {
                                assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource);
                                cssInfos.Add(resource);
                            }
                        }
                        return(cssInfos);
                    },
                        (markup, includeStripeCheckout) => {
                        string getElement(ResourceInfo resource) => "<script src=\"{0}\" defer></script>".FormatWith(resource.GetUrl());

                        var infos = new List <ResourceInfo>();
                        infos.Add(new ExternalResource("//code.jquery.com/jquery-1.12.3.min.js"));
                        infos.Add(new StaticFiles.Versioned.Third_party.Jquery_ui.Jquery_ui_1114custom_v2.Jquery_uiminJs());
                        infos.Add(new StaticFiles.Versioned.Third_party.Chosen.Chosen_v187.ChosenjqueryminJs());
                        infos.Add(new StaticFiles.Third_party.Time_picker.CodeJs());
                        infos.Add(new ExternalResource("//cdn.jsdelivr.net/qtip2/2.2.1/jquery.qtip.min.js"));
                        infos.Add(new ExternalResource("//cdnjs.cloudflare.com/ajax/libs/dialog-polyfill/0.4.9/dialog-polyfill.min.js"));
                        infos.Add(new StaticFiles.Third_party.Spin_js.SpinminJs());
                        infos.Add(new ExternalResource("//cdn.ckeditor.com/4.5.8/full/ckeditor.js"));
                        infos.Add(new ExternalResource("https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"));
                        infos.Add(new ExternalResource("https://instant.page/5.1.0"));
                        if (includeStripeCheckout)
                        {
                            infos.Add(new ExternalResource("https://checkout.stripe.com/checkout.js"));
                        }
                        infos.Add(new StaticFiles.CodeJs());
                        foreach (var i in infos.Select(getElement))
                        {
                            markup.Append(i);
                        }
                        markup.Append(MiniProfiler.Current.RenderIncludes().ToHtmlString());
                        foreach (var resource in BasePageStatics.AppProvider.GetJavaScriptFiles())
                        {
                            assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(resource);
                            markup.Append(getElement(resource));
                        }
                    },
                        () => {
                        var icons = new List <(ResourceInfo, string, string)>();

                        var faviconPng48X48 = BasePageStatics.AppProvider.FaviconPng48X48;
                        if (faviconPng48X48 != null)
                        {
                            assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(faviconPng48X48);
                            icons.Add((faviconPng48X48, "icon", "48x48"));
                        }

                        var favicon = BasePageStatics.AppProvider.Favicon;
                        if (favicon != null)
                        {
                            assertResourceIsIntermediateInstallationPublicResourceWhenNecessary(favicon);
                            icons.Add((favicon, "icon", ""));
                        }

                        return(icons);
                    },
                        hideWarnings => {
                        var url = AppRequestState.Instance.Url;
                        if (AppRequestState.Instance.UserAccessible && AppRequestState.Instance.ImpersonatorExists)
                        {
                            url = new UserManagement.Pages.Impersonate(
                                url,
                                optionalParameterSetter: (specifier, parameters) =>
                                specifier.User = AppTools.User != null ? AppTools.User.Email : UserManagement.Pages.Impersonate.AnonymousUser).GetUrl();
                        }
                        return(new NonLiveLogIn(
                                   url,
                                   optionalParameterSetter: (specifier, parameters) => {
                            specifier.Password = ConfigurationStatics.SystemGeneralProvider.IntermediateLogInPassword;
                            specifier.HideWarnings = hideWarnings;
                        }).GetUrl());
                    },
                        () => {
                        if (!AppRequestState.Instance.UserAccessible || !AppRequestState.Instance.ImpersonatorExists ||
                            (ConfigurationStatics.IsIntermediateInstallation && !AppRequestState.Instance.IntermediateUserExists))
                        {
                            return(null);
                        }
                        return("User impersonation is in effect.",
                               new HyperlinkSetup(new UserManagement.Pages.Impersonate(AppRequestState.Instance.Url), "Change user").Append <ActionComponentSetup>(
                                   new ButtonSetup(
                                       "End impersonation",
                                       behavior: new PostBackBehavior(
                                           postBack: PostBack.CreateFull(
                                               id: "ewfEndImpersonation",
                                               modificationMethod: UserImpersonationStatics.EndImpersonation,
                                               actionGetter: () => new PostBackAction(
                                                   new ExternalResource(
                                                       EwfConfigurationStatics.AppConfiguration.DefaultBaseUrl.GetUrlString(
                                                           EwfConfigurationStatics.AppSupportsSecureConnections)))))))
                               .Materialize());
                    });
                    EwfUiStatics.Init(providerGetter.GetProvider <AppEwfUiProvider>("EwfUi"));
                    AuthenticationStatics.Init(
                        providerGetter.GetProvider <AppAuthenticationProvider>("Authentication"),
                        (user, code) => new UserManagement.Pages.LogIn(
                            "",
                            optionalParameterSetter: (specifier, parameters) => {
                        specifier.User = user;
                        specifier.Code = code;
                    }).GetUrl(),
                        destinationUrl => new UserManagement.Pages.ChangePassword(destinationUrl).GetUrl(disableAuthorizationCheck: true));
                    Admin.EntitySetup.Init(() => RequestDispatchingStatics.AppProvider.GetFrameworkUrlParent());
                    RequestDispatchingStatics.Init(providerGetter.GetProvider <AppRequestDispatchingProvider>("RequestDispatching"));

                    EwfInitializationOps.appInitializer = appInitializer;
                    appInitializer?.InitStatics();

                    executeWithAutomaticDatabaseConnections(AuthenticationStatics.InitAppSpecificLogicDependencies);
                    if (AuthenticationStatics.SamlIdentityProviders.Any() || ExternalFunctionalityStatics.SamlFunctionalityEnabled)
                    {
                        executeWithAutomaticDatabaseConnections(ExternalFunctionalityStatics.ExternalSamlProvider.InitAppSpecificLogicDependencies);
                    }

                    initTimeDataAccessState     = null;
                    EwfApp.FrameworkInitialized = true;
                },
        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);
        }
Пример #5
0
        private static int Main(string[] args)
        {
            GlobalInitializationOps.InitStatics(new GlobalInitializer(), "Development Utility", true);
            try {
                return(GlobalInitializationOps.ExecuteAppWithStandardExceptionHandling(
                           () => {
                    try {
                        AppStatics.Init();

                        if (args.Length < 2)
                        {
                            throw new UserCorrectableException("You must specify the installation path as the first argument and the operation name as the second.");
                        }

                        // Create installations folder from template if necessary.
                        var installationPath = args[0];
                        var templateFolderPath = getInstallationsFolderPath(installationPath, true);
                        var message = "";
                        if (!Directory.Exists(templateFolderPath))
                        {
                            message = "No installation-configuration template exists.";
                        }
                        else
                        {
                            var configurationFolderPath = getInstallationsFolderPath(installationPath, false);
                            if (IoMethods.GetFilePathsInFolder(configurationFolderPath, searchOption: SearchOption.AllDirectories).Any())
                            {
                                message = "Installation configuration already exists.";
                            }
                            else
                            {
                                IoMethods.CopyFolder(templateFolderPath, configurationFolderPath, false);
                                Console.WriteLine("Created installation configuration from template.");
                            }
                        }

                        if (args[1] == "CreateInstallationConfiguration")
                        {
                            if (message.Any())
                            {
                                throw new UserCorrectableException(message);
                            }
                            return;
                        }

                        // Get installation.
                        DevelopmentInstallation installation;
                        try {
                            installation = getInstallation(installationPath);
                        }
                        catch (Exception e) {
                            throw new UserCorrectableException("The installation at \"" + installationPath + "\" is invalid.", e);
                        }

                        // Get operation.
                        var operations = AssemblyTools.BuildSingletonDictionary <Operation, string>(Assembly.GetExecutingAssembly(), i => i.GetType().Name);
                        var operationName = args[1];
                        if (!operations.ContainsKey(operationName))
                        {
                            throw new UserCorrectableException(operationName + " is not a known operation.");
                        }
                        var operation = operations[operationName];

                        if (!operation.IsValid(installation))
                        {
                            throw new UserCorrectableException("The " + operation.GetType().Name + " operation cannot be performed on this installation.");
                        }
                        operation.Execute(installation, args.Skip(2).ToImmutableArray(), new OperationResult());
                    }
                    catch (Exception e) {
                        Output.WriteTimeStampedError(e.ToString());
                        if (e is UserCorrectableException)
                        {
                            throw new DoNotEmailOrLogException();
                        }
                        throw;
                    }
                }));
            }
            finally {
                GlobalInitializationOps.CleanUpStatics();
            }
        }