示例#1
0
 public RequireCultureValidator()
 {
     RuleFor(x => x.CultureName)
     .NotNull().WithMessage(ErrorDetailConstants.HeaderFieldRequired)
     .NotEmpty().WithMessage(ErrorDetailConstants.HeaderFieldEmpty)
     .Must(m => ContextResolver.GetContextByCultureName(m) != null).WithMessage(ErrorDetailConstants.HeaderFieldNotSupported);
 }
    /// <summary>
    /// Gets the label text
    /// </summary>
    /// <param name="value">Field value</param>
    private string GetLabelText(object value)
    {
        string txt;

        if (!String.IsNullOrEmpty(OutputFormat))
        {
            txt = OutputFormat;
        }
        else
        {
            // Try to find the transformation
            if (!string.IsNullOrEmpty(Transformation) && UniGridTransformations.Global.ExecuteTransformation(label, Transformation, ref value))
            {
                txt = ValidationHelper.GetString(value, "");
            }
            else if (FieldInfo != null)
            {
                txt = GetStringValue(value);
            }
            else
            {
                txt = ValidationHelper.GetString(value, "");
            }
        }

        // Resolve macros
        return(ContextResolver.ResolveMacros(txt));
    }
        private Task assertEmptyContext(HttpContext context)
        {
            var ctx = ContextResolver.GetRequestContext <CorrelationContext>();

            Assert.NotNull(ctx);
            return(Task.FromResult(1));
        }
示例#4
0
        public Task SendEventsAsync(IReadOnlyCollection <EventData> events, long transmissionSequenceNumber, CancellationToken cancellationToken)
        {
            if (this.telemetryClient == null || events == null || events.Count == 0)
            {
                return(CompletedTask);
            }

            try
            {
                foreach (var e in events)
                {
                    //restore event context so ApplicationInsights TelemetryInitializer could access it
                    object eventContext;
                    if (e.TryGetPropertyValue("EventContext", out eventContext))
                    {
                        ContextResolver.SetRequestContext(eventContext);
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(CompletedTask);
                    }

                    IReadOnlyCollection <EventMetadata> metadata;
                    bool handled = false;

                    if (e.TryGetMetadata(MetricData.MetricMetadataKind, out metadata))
                    {
                        TrackMetric(e, metadata);
                        handled = true;
                    }

                    if (e.TryGetMetadata(RequestData.RequestMetadataKind, out metadata))
                    {
                        TrackRequest(e, metadata);
                        handled = true;
                    }

                    if (!handled)
                    {
                        object message = null;
                        e.Payload.TryGetValue("Message", out message);
                        TraceTelemetry t = new TraceTelemetry(message as string ?? string.Empty);
                        AddProperties(t, e);

                        telemetryClient.TrackTrace(t);
                    }
                }

                telemetryClient.Flush();

                this.healthReporter.ReportHealthy();
            }
            catch (Exception e)
            {
                this.healthReporter.ReportProblem("Diagnostics data upload has failed." + Environment.NewLine + e.ToString());
            }

            return(CompletedTask);
        }
示例#5
0
        private static object OnBeginGetResponse <TContext>(object requestObj, Configuration <TContext, WebRequest, WebResponse> config) where TContext : ICorrelationContext <TContext>
        {
            var request = requestObj as HttpWebRequest;

            if (request != null)
            {
                if (config.EndpointFilter.Validate(request.RequestUri))
                {
                    var ctx = ContextResolver.GetContext <TContext>();
                    if (ctx != null)
                    {
                        foreach (var injector in config.ContextInjectors)
                        {
                            injector.UpdateRequest(ctx, request);
                        }

                        try
                        {
                            config.RequestNotifier?.OnBeforeRequest(ctx.GetChildRequestContext(request.GetChildRequestId()), request);
                        }
                        catch (Exception)
                        {
                            //ignored
                        }
                    }
                }
            }

            return(requestObj);
        }
示例#6
0
    /// <summary>
    /// Resolve custom macros for specified input value.
    /// </summary>
    /// <param name="value">Value to resolve</param>
    /// <param name="dr">Current data row</param>
    /// <param name="columnName">Column name</param>
    /// <param name="sum">Summary of all items</param>
    private string ResolveCustomMacros(string value, DataRow dr, string columnName, double sum)
    {
        // Ensure resolver
        if (itemResolver == null)
        {
            itemResolver = CMSContext.CurrentResolver.CreateContextChild();
        }

        // Get current item value
        double itemvalue = ValidationHelper.GetDouble(dr[columnName], 0.0);

        // Custom macros definition
        string[,] macros = new string[4, 2];
        macros[0, 0]     = "xval";
        macros[0, 1]     = Convert.ToString(dr[0]);
        macros[1, 0]     = "yval";
        macros[1, 1]     = Convert.ToString(itemvalue);
        macros[2, 0]     = "ser";
        macros[2, 1]     = columnName;
        macros[3, 0]     = "pval";
        macros[3, 1]     = Convert.ToString(itemvalue / sum * 100);

        // Set custom macros
        itemResolver.SourceParameters = macros;
        // Resolve macros
        return(itemResolver.ResolveMacros(value));
    }
    private void SendEmail()
    {
        EmailMessage      msg  = new CMS.EmailEngine.EmailMessage();
        EmailTemplateInfo eti  = EmailTemplateProvider.GetEmailTemplate("Membership.ChangedPassword", CMSContext.CurrentSiteID);
        string            pswd = passStrength.Text.Trim();

        ui = UserInfoProvider.GetUserInfo(CurrentUser.UserName);
        if (ui != null)
        {
            if (eti != null)
            {
                MacroResolver mcr = new MacroResolver();

                // Macros
                string[,] macros = new string[5, 2];
                macros[0, 0]     = "UserName";
                macros[0, 1]     = ui.UserName;
                macros[1, 0]     = "Password";
                macros[1, 1]     = pswd;

                ContextResolver resolver = MacroContext.CurrentResolver;
                resolver.SourceParameters     = macros;
                resolver.EncodeResolvedValues = true;

                msg.EmailFormat = EmailFormatEnum.Both;
                msg.From        = "*****@*****.**";
                msg.Recipients  = CurrentUser.Email;
                msg.Subject     = "Changement de mot de passe - Servranx";

                EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, msg, eti, resolver, true);
            }
        }
    }
        private Task assertEmptyContext(IDictionary <string, object> environment)
        {
            var ctx = ContextResolver.GetRequestContext <CorrelationContext>();

            Assert.NotNull(ctx);
            return(Task.FromResult(1));
        }
    /// <summary>
    /// Returns a resolver based on given name.
    /// </summary>
    /// <param name="name">Name of the resolver</param>
    public static ContextResolver GetResolver(string name)
    {
        if (string.IsNullOrEmpty(name))
        {
            return(GetDefaultResolver());
        }

        string key = name.ToLowerCSafe();

        ContextResolver resolver = GetStaticResolver(name);

        if (resolver == null)
        {
            if (key.StartsWithCSafe("form."))
            {
                resolver = GetFormResolver(key.Substring(5));
            }
            else if (key.StartsWithCSafe("formdefinition."))
            {
                resolver = GetFormDefinitionResolver(name.Substring(15));
            }
            else
            {
                resolver = GetDefaultResolver();
            }
        }
        return(resolver.CreateContextChild());
    }
        public async Task SuccessFlowWebRequest()
        {
            fixture.Notifier.BeforeWasCalled = false;
            fixture.Notifier.AfterWasCalled  = false;
            fixture.Injector.WasCalled       = false;

            var correlationId = Guid.NewGuid().ToString();

            ContextResolver.SetContext(new CorrelationContext(correlationId));

            var request = WebRequest.CreateHttp("http://bing.com");

            try
            {
                await request.GetResponseAsync();
            }
            catch
            {
                // ignored
            }

            Assert.True(fixture.Injector.WasCalled);
            Assert.True(fixture.Notifier.BeforeWasCalled);
            Assert.True(fixture.Notifier.AfterWasCalled);
        }
示例#11
0
    /// <summary>
    /// Page load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Set control style and css class
        if (!string.IsNullOrEmpty(this.ControlStyle))
        {
            txtMacro.Editor.Attributes.Add("style", this.ControlStyle);
        }
        if (!string.IsNullOrEmpty(this.CssClass))
        {
            txtMacro.Editor.CssClass = this.CssClass;
        }

        this.txtMacro.ShowAutoCompletionAbove = this.ShowAutoCompletionAbove;
        this.txtMacro.Editor.UseSmallFonts    = true;
        this.txtMacro.Editor.Height           = new Unit("50px");
        this.txtMacro.MixedMode              = false;
        this.txtMacro.Editor.ShowToolbar     = false;
        this.txtMacro.Editor.ShowLineNumbers = false;
        ContextResolver resolver = (ContextResolver)GetValue("Resolver");

        if (resolver != null)
        {
            txtMacro.Resolver = resolver;
        }

        ScriptHelper.RegisterClientScriptBlock(this.Page, typeof(string), "InsertMacroCondition", "function InsertMacroCondition(text) {" + this.txtMacro.Editor.EditorID + ".setValue(text);}", true);
        ScriptHelper.RegisterDialogScript(this.Page);

        btnEdit.ImageUrl      = GetImageUrl("Design/Controls/UniGrid/Actions/Edit.png");
        btnEdit.OnClientClick = "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSFormControls/Inputs/ConditionBuilder.aspx") + "?condition=' + encodeURIComponent(" + this.txtMacro.Editor.EditorID + ".getValue()) , 'editmacrocondition', 900, 700); return false;";
    }
示例#12
0
    /// <summary>
    /// Creates breadcrumbs array leading to specified node using given tree provider and starting at given starting path.
    /// </summary>
    /// <param name="node">Tree node to generate breadcrumbs for.</param>
    /// <param name="startingPath">Path where to start to generate.</param>
    protected virtual string[,] CreateBreadcrumbs(TreeNode node, string startingPath)
    {
        string[,] breadcrumbs = null;

        if (node != null)
        {
            const string columns = "NodeID, NodeAliasPath, NodeSiteID, NodeOwner, DocumentName, DocumentLastVersionName, DocumentMenuCaption, DocumentCulture, SiteName, ClassName, NodeACLID";

            // Prepare the where condition
            string where = SqlHelperClass.AddWhereCondition(null, TreeProvider.GetNodesOnPathWhereCondition(node.NodeAliasPath, true, true));
            DataSet ds = DocumentHelper.GetDocuments(CurrentSiteName, startingPath, TreeProvider.ALL_CULTURES, true, null, where, "NodeAliasPath ASC", -1, false, 0, columns, node.TreeProvider);

            ds = TreeSecurityProvider.FilterDataSetByPermissions(ds, NodePermissionsEnum.Read, CMSContext.CurrentUser);

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                // Initialize resolver
                ContextResolver currentResolver = CMSContext.CurrentResolver.CreateContextChild();
                currentResolver.EncodeResolvedValues = true;

                DataRow[] resolverData = new DataRow[1];
                DataTable table        = ds.Tables[0];

                // Prepare breadcrumbs
                breadcrumbs = new string[table.Rows.Count + 1, 4];

                int i = 0;

                foreach (DataRow dr in table.Rows)
                {
                    // Add current datarow to the resolver
                    resolverData[0]            = dr;
                    currentResolver.SourceData = resolverData;

                    // Prepare the item name. Disable encoding.
                    currentResolver.EncodeResolvedValues = false;
                    string linkName = currentResolver.ResolveMacros(TreePathUtils.GetMenuCaption(ValidationHelper.GetString(dr["DocumentMenuCaption"], String.Empty), ValidationHelper.GetString(dr["DocumentName"], String.Empty)));
                    currentResolver.EncodeResolvedValues = true;

                    // Use site name for root node
                    linkName = string.IsNullOrEmpty(linkName) ? CMSContext.CurrentSite.DisplayName : linkName;

                    // Create breadcrumb
                    breadcrumbs[i, 0] = HTMLHelper.HTMLEncode(linkName);
                    breadcrumbs[i, 1] = "~/CMSModules/Ecommerce/Pages/Tools/Products/Product_List.aspx?nodeid=" + dr["NodeID"];
                    breadcrumbs[i, 3] = string.Format("EditDocument({0}); RefreshTree({0},{0});", dr["NodeID"]);

                    // Increment index
                    i++;
                }

                // Add 'properties' breadcrumb
                breadcrumbs[i, 0] = HTMLHelper.HTMLEncode(GetString((Action == "new") ? "com.productsection.new" : "com.productsection.properties"));
                breadcrumbs[i, 1] = "";
                breadcrumbs[i, 2] = "";
            }
        }

        return(breadcrumbs);
    }
示例#13
0
        private static void validateHeader(HttpRequestMessage request)
        {
            IEnumerable <string> actualHeader;

            Assert.True(request.Headers.TryGetValues(CorrelationHeaderInfo.CorrelationIdHeaderName, out actualHeader));
            Assert.Equal(1, actualHeader.Count());
            Assert.Equal(ContextResolver.GetContext <CorrelationContext>().CorrelationId, actualHeader.First());
        }
        private Task AssertContext(HttpContext context)
        {
            var ctx = ContextResolver.GetRequestContext <CorrelationContext>();

            Assert.NotNull(ctx);
            Assert.Equal(correlationId, ctx.CorrelationId);
            return(Task.FromResult(1));
        }
        private Task AssertContext(IDictionary <string, object> environment)
        {
            var ctx = ContextResolver.GetContext <CorrelationContext>();

            Assert.NotNull(ctx);
            Assert.Equal(correlationId, ctx.CorrelationId);
            return(Task.FromResult(1));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        chkBindObject.Text = HTMLHelper.HTMLEncode(ContextResolver.ResolveMacros(Caption));

        if (Form != null)
        {
            Form.OnAfterSave += Form_OnAfterSave;
        }
    }
示例#17
0
    /// <summary>
    /// Inits page
    /// </summary>
    private void InitPage()
    {
        // Disable debug for this page
        if (ValidationHelper.GetBoolean(UIContext["disabledebug"], false))
        {
            DisableDebugging();
        }

        // Master page must he addressed here to allow access to page controls on PreInit - DO NOT REMOVE!
        var master = Master as CMSMasterPage;

        if (UIContext.IsDialog)
        {
            master.PanelBody.CssClass = "DialogPageBody";
        }

        if (HandleHierarchy())
        {
            return;
        }

        switch (UIElement.ElementType)
        {
        case UIElementTypeEnum.PageTemplate:
            LoadTemplate();
            break;

        case UIElementTypeEnum.Url:
        {
            string url = ContextResolver.ResolveMacros(UIElement.ElementTargetURL);

            RedirectToUrl(url);
        }
        break;
        }

        if (PageTemplate.PageTemplateIsLayout)
        {
            // Layout template needs to propagate the return handler further. The return handler may be used in one of the child layout panes.
            var handlerName = QueryHelper.GetString("returnhandler", string.Empty);

            if (!string.IsNullOrEmpty(handlerName))
            {
                string script = string.Format(
                    @"
function {0}(parameterValue) {{
    if (wopener && wopener.{0}) {{
        wopener.{0}(parameterValue);
    }}
}}
", ScriptHelper.GetString(handlerName, false));

                ScriptHelper.RegisterStartupScript(this, typeof(string), "returnhandler", script, true);
            }
        }
    }
示例#18
0
        public void Initialize(ITelemetry telemetry)
        {
            //add request id to every event
            var ctx = ContextResolver.GetRequestContext <MyContext>();

            if (ctx != null)
            {
                telemetry.Context.Operation.Id = ctx.CorrelationId;
            }
        }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ContactInfo     contact  = new ContactInfo();
        ContextResolver resolver = CMSContext.CurrentResolver.CreateContextChild();

        resolver.SetNamedSourceData("Contact", contact);
        DescriptionMacroEditor.Resolver        = resolver;
        DescriptionMacroEditor.Editor.Language = LanguageEnum.Text;
    }
 public static void LogIncomingRequest(HttpContext context, TimeSpan elapsed)
 {
     Log.Write("incoming_request", new
     {
         context.Request,
         context.Response,
         Elapsed = elapsed,
         Context = ContextResolver.GetContext <CorrelationContext>()
     });
 }
        public void SiteAssetsFolder_Should_Be_Correctly_Set()
        {
            mockContentRepository
            .Setup(x => x.GetDefault <ContentFolder>(It.IsAny <ContentReference>()))
            .Returns(new ContentFolder());

            var contextResolver = new ContextResolver(mockContentRepository.Object, pageRouteHelper.Object);

            contextResolver.SiteAssetsFolder.Should().NotBeNull();
        }
示例#22
0
        public async Task SuccessFlow()
        {
            var correlationId = Guid.NewGuid().ToString();

            ContextResolver.SetContext(new CorrelationContext(correlationId));

            var innerHandler = setupMockHandler(validateHeader);
            var client       = HttpClientBuilder.CreateClient(innerHandler.Object, new[] { new CorrelationContextInjector() });
            await client.GetAsync("http://bing.com");
        }
示例#23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonLdContextModule"/> class.
        /// </summary>
        /// <param name="pathProvider">@context path provider</param>
        /// <param name="provider">custom @context provider</param>
        public JsonLdContextModule(IContextPathMapper pathProvider, IContextProvider provider)
            : base(pathProvider.BasePath)
        {
            this.resolver = new ContextResolver(provider);

            foreach (var path in pathProvider.Contexts)
            {
                this.Get(path.Path, this.ServeContextOf(path.ModelType));
            }
        }
示例#24
0
        public void ContextResolverSetClear()
        {
            var ctx = new TestContext {
                CorrelationId = "1", OtherId = "2"
            };

            ContextResolver.SetRequestContext(ctx);
            ContextResolver.ClearContext();
            Assert.Null(ContextResolver.GetRequestContext <TestContext>());
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        String text    = String.Empty;
        String url     = TargetUrl;
        bool   enabled = true;
        String onClick = String.Empty;

        // If new element is set, load it directly, otherwise use first element with prefix 'new' in its name.
        UIElementInfo uiNew = String.IsNullOrEmpty(NewElement) ? UIContext.UIElement.GetNewElement() :
                              UIElementInfoProvider.GetUIElementInfo(UIContext.UIElement.ElementResourceID, NewElement);

        bool   openInDialog = false;
        String dialogWidth  = null;
        String dialogHeight = null;

        if (uiNew != null)
        {
            UIContextData data = new UIContextData();
            data.LoadData(uiNew.ElementProperties);
            text    = UIElementInfoProvider.GetElementCaption(uiNew);
            enabled = UIContextHelper.CheckElementVisibilityCondition(uiNew);
            url     = ContextResolver.ResolveMacros(UIContextHelper.GetElementUrl(uiNew, UIContext));

            openInDialog = data["OpenInDialog"].ToBoolean(false);
            dialogWidth  = data["DialogWidth"].ToString(null);
            dialogHeight = data["DialogHeight"].ToString(null);

            // Set on-click for JavaScript type
            if (uiNew.ElementType == UIElementTypeEnum.Javascript)
            {
                onClick = url;
                url     = String.Empty;
            }
            else
            {
                // For URL append dialog hash if needed
                url = UIContextHelper.AppendDialogHash(UIContext, url);
            }
        }

        // If url is non empty add action
        if (((url != String.Empty) || (onClick != String.Empty)) && (HeaderActions != null))
        {
            HeaderActions.AddAction(new HeaderAction()
            {
                Text          = GetString(text),
                RedirectUrl   = url,
                Enabled       = enabled,
                OnClientClick = onClick,
                OpenInDialog  = openInDialog,
                DialogWidth   = dialogWidth,
                DialogHeight  = dialogHeight
            });
        }
    }
示例#26
0
 /// <summary>
 /// Resolves the macros within current WebPart context, with special handling for onclickaction field.
 /// </summary>
 /// <param name="inputText">Input text to resolve</param>
 public string ResolveOnClickMacros(string inputText)
 {
     // Special "macro" with two '%' will be resolveed later
     if (!String.IsNullOrEmpty(inputText) && !inputText.Contains("%%"))
     {
         ContextResolver resolver = ContextResolver.CreateContextChild();
         resolver.KeepUnresolvedMacros = true;
         return(resolver.ResolveMacros(inputText, false));
     }
     return(inputText);
 }
示例#27
0
        public void PutStringGetObject()
        {
            var guid = Guid.NewGuid().ToString();

            ContextResolver.SetRequestContext(guid);

            var got = ContextResolver.GetRequestContext <object>();

            Assert.NotNull(got);
            Assert.Equal(guid, got.ToString());
        }
示例#28
0
        public void ContextResolverSetGet()
        {
            var ctx = new TestContext {
                CorrelationId = "1", OtherId = "2"
            };

            ContextResolver.SetRequestContext(ctx);
            var gotCtx = ContextResolver.GetRequestContext <TestContext>();

            TestContextHelper.AssertAreEqual(ctx, gotCtx);
        }
    private string GetConsentReferenceMarkup()
    {
        var consentReferenceMarkupFieldName = "ConsentReferenceMarkup";

        if (FieldInfo.SettingIsMacro(consentReferenceMarkupFieldName))
        {
            return(ContextResolver.ResolveMacros(FieldInfo.SettingsMacroTable[consentReferenceMarkupFieldName] as string));
        }

        return(FieldInfo.Settings[consentReferenceMarkupFieldName] as string);
    }
示例#30
0
        public async Task NoInjectors()
        {
            var correlationId = Guid.NewGuid().ToString();

            ContextResolver.SetContext(correlationId);

            var innerHandler = setupMockHandler(validateNoHeader);
            var client       = HttpClientBuilder.CreateClient(innerHandler.Object, new List <IContextInjector <string, HttpRequestMessage> >());

            await client.GetAsync("http://bing.com");
        }
 /// <summary>
 /// Sets additional context values to resolver.
 /// </summary>
 /// <param name="resolver">Context resolver</param>
 private static void SetContext(ContextResolver resolver)
 {
     resolver.Context.DisableContextObjectMacros = true;
 }
    /// <summary>
    /// Generate documentation page.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Get current resolver
        resolver = CMSContext.CurrentResolver.CreateContextChild();

        plImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/plus.png");
        minImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/minus.png");

        webPartId = QueryHelper.GetString("webPartId", String.Empty);
        if (webPartId != String.Empty)
        {
            wpi = WebPartInfoProvider.GetWebPartInfo(webPartId);
        }

        string aliasPath = QueryHelper.GetString("aliaspath", String.Empty);
        // Ensure correct view mode
        if (String.IsNullOrEmpty(aliasPath))
        {
            // Ensure the dashboard mode for the dialog
            if (QueryHelper.Contains("dashboard"))
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets);
                PortalContext.DashboardName = QueryHelper.GetString("dashboard", String.Empty);
                PortalContext.DashboardSiteName = QueryHelper.GetString("sitename", String.Empty);
            }
            // Ensure the design mode for the dialog
            else
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.Design);
            }
        }

        // If widgetId is in query create widget documentation
        widgetID = QueryHelper.GetString("widgetId", String.Empty);
        if (widgetID != String.Empty)
        {
            // Get widget from instance
            string zoneId = QueryHelper.GetString("zoneid", String.Empty);
            Guid instanceGuid = QueryHelper.GetGuid("instanceGuid", Guid.Empty);
            int templateID = QueryHelper.GetInteger("templateID", 0);
            bool newItem = QueryHelper.GetBoolean("isNew", false);
            bool isInline = QueryHelper.GetBoolean("Inline", false);

            PageInfo pi = null;
            try
            {
                // Load page info from alias path and page template
                pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateID);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi != null)
            {
                PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

                if (templateInstance != null)
                {
                    // Get the instance of widget
                    WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGuid, widgetID);

                    // Info for zone type
                    WebPartZoneInstance zone = templateInstance.GetZone(zoneId);

                    if (zone != null)
                    {
                        zoneType = zone.WidgetZoneType;
                    }

                    if (widgetInstance != null)
                    {
                        // Create widget from webpart instance
                        wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
                    }
                }
            }

            // If inline widget display columns as in editor zone
            if (isInline)
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }

            // If no zone set (only global admins allowed to continue)
            if (zoneType == WidgetZoneTypeEnum.None)
            {
                if (!CMSContext.CurrentUser.UserSiteManagerAdmin)
                {
                    RedirectToAccessDenied(GetString("attach.actiondenied"));
                }
            }

            // If wi is still null (new item f.e.)
            if (wi == null)
            {
                // Try to get widget info directly by ID
                if (!newItem)
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(widgetID);
                }
                else
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetID, 0));
                }
            }
        }

        String itemDescription = String.Empty;
        String itemType = String.Empty;
        String itemDisplayName = String.Empty;
        String itemDocumentation = String.Empty;
        int itemID = 0;

        // Check whether webpart was found
        if (wpi != null)
        {
            itemDescription = wpi.WebPartDescription;
            itemType = PortalObjectType.WEBPART;
            itemID = wpi.WebPartID;
            itemDisplayName = wpi.WebPartDisplayName;
            itemDocumentation = wpi.WebPartDocumentation;
        }
        // Or widget was found
        else if (wi != null)
        {
            itemDescription = wi.WidgetDescription;
            itemType = PortalObjectType.WIDGET;
            itemID = wi.WidgetID;
            itemDisplayName = wi.WidgetDisplayName;
            itemDocumentation = wi.WidgetDocumentation;
        }

        if ((wpi != null) || (wi != null))
        {
            // Get WebPart (widget) image
            DataSet ds = MetaFileInfoProvider.GetMetaFiles(itemID, itemType);

            // Set image url of exists
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                MetaFileInfo mtfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                if (mtfi != null)
                {
                    if (mtfi.MetaFileImageWidth > 385)
                    {
                        imgTeaser.Width = 385;
                    }

                    imgTeaser.ImageUrl = ResolveUrl("~/CMSPages/GetMetaFile.aspx?fileguid=" + mtfi.MetaFileGUID.ToString());
                }
            }
            else
            {
                // Set default image
                imgTeaser.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/imagenotavailable.png");
            }

            // Additional image information
            imgTeaser.ToolTip = HTMLHelper.HTMLEncode(itemDisplayName);
            imgTeaser.AlternateText = HTMLHelper.HTMLEncode(itemDisplayName);

            // Set description of webpart
            ltlDescription.Text = HTMLHelper.HTMLEncode(itemDescription);

            // Get description from parent weboart if webpart is inherited
            if ((wpi != null) && ((wpi.WebPartDescription == null || wpi.WebPartDescription == "") && (wpi.WebPartParentID > 0)))
            {
                WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                if (pwpi != null)
                {
                    ltlDescription.Text = HTMLHelper.HTMLEncode(pwpi.WebPartDescription);
                }
            }

            FormInfo fi = null;

            // Generate properties
            if (wpi != null)
            {
                // Get form info from parent if webpart is inherited
                if (wpi.WebPartParentID != 0)
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null)
                    {
                        fi = GetWebPartProperties(pwpi);
                    }
                }
                else
                {
                    fi = GetWebPartProperties(wpi);
                }
            }
            else if (wi != null)
            {
                fi = GetWidgetProperties(wi);
            }

            // Generate properties
            if (fi != null)
            {
                GenerateProperties(fi);
            }

            // Generate documentation text
            if (itemDocumentation == null || itemDocumentation.Trim() == "")
            {
                if ((wpi != null) && (wpi.WebPartParentID != 0))
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null && pwpi.WebPartDocumentation.Trim() != "")
                    {
                        ltlContent.Text = HTMLHelper.ResolveUrls(pwpi.WebPartDocumentation, null);
                    }
                    else
                    {
                        ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                    }
                }
                else
                {
                    ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                }
            }
            else
            {
                ltlContent.Text = HTMLHelper.ResolveUrls(itemDocumentation, null);
            }
        }
    }
示例#33
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Security test
        if (!CMSContext.CurrentUser.UserSiteManagerAdmin)
        {
            RedirectToAccessDenied(GetString("attach.actiondenied"));
        }

        // Add link to external stylesheet
        CSSHelper.RegisterCSSLink(this, "~/App_Themes/Default/CMSDesk.css");

        // Get current resolver
        resolver = CMSContext.CurrentResolver.CreateContextChild();

        DataSet ds = null;
        DataSet cds = null;

        // Check init settings
        bool allWidgets = QueryHelper.GetBoolean("allWidgets", false);
        bool allWebParts = QueryHelper.GetBoolean("allWebparts", false);

        // Get webpart (widget) from querystring - only if no allwidget or allwebparts set
        bool isWebpartInQuery = false;
        bool isWidgetInQuery = false;
        String webpartQueryParam = String.Empty;

        //If not show all widgets or webparts - check if any widget or webpart is present
        if ((!allWidgets) && (!allWebParts))
        {
            webpartQueryParam = QueryHelper.GetString("webpart", "");
            if (!string.IsNullOrEmpty(webpartQueryParam))
            {
                isWebpartInQuery = true;
            }
            else
            {
                webpartQueryParam = QueryHelper.GetString("widget", "");
                if (!string.IsNullOrEmpty(webpartQueryParam))
                {
                    isWidgetInQuery = true;
                }
            }
        }

        // Set development option if is required
        if (QueryHelper.GetString("details", "0") == "1")
        {
            development = true;
        }

        // Generate all webparts
        if (allWebParts)
        {
            // Get all webpart categories
            cds = WebPartCategoryInfoProvider.GetAllCategories();
        }
        // Generate all widgets
        else if (allWidgets)
        {
            // Get all widget categories
            cds = WidgetCategoryInfoProvider.GetWidgetCategories(String.Empty, String.Empty, 0, String.Empty);
        }
        // Generate single webpart
        else if (isWebpartInQuery)
        {
            // Split weparts
            string[] webparts = webpartQueryParam.Split(';');
            if (webparts.Length > 0)
            {
                string webpartWhere = SqlHelperClass.GetWhereCondition("WebpartName", webparts);
                ds = WebPartInfoProvider.GetWebParts(webpartWhere, null);

                // If any webparts found
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    StringBuilder categoryWhere = new StringBuilder("");
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        categoryWhere.Append(ValidationHelper.GetString(dr["WebpartCategoryID"], "NULL") + ",");
                    }

                    string ctWhere = "CategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                    cds = WebPartCategoryInfoProvider.GetCategories(ctWhere, null);
                }
            }
        }
        // Generate single widget
        else if (isWidgetInQuery)
        {
            string[] widgets = webpartQueryParam.Split(';');
            if (widgets.Length > 0)
            {
                string widgetsWhere = SqlHelperClass.GetWhereCondition("WidgetName", widgets);
                ds = WidgetInfoProvider.GetWidgets(widgetsWhere, null, 0, String.Empty);
            }

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                StringBuilder categoryWhere = new StringBuilder("");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    categoryWhere.Append(ValidationHelper.GetString(dr["WidgetCategoryID"], "NULL") + ",");
                }

                string ctWhere = "WidgetCategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                cds = WidgetCategoryInfoProvider.GetWidgetCategories(ctWhere, null, 0, String.Empty);
            }
        }

        if (allWidgets || isWidgetInQuery)
        {
            documentationTitle = "Kentico CMS Widgets";
            Page.Header.Title = "Widgets documentation";
        }

        if (!allWebParts && !allWidgets && !isWebpartInQuery && !isWidgetInQuery)
        {
            pnlContent.Visible = false;
            pnlInfo.Visible = true;
        }

        // Check whether at least one category is present
        if (!DataHelper.DataSourceIsEmpty(cds))
        {
            string namePrefix = ((isWidgetInQuery) || (allWidgets)) ? "Widget" : String.Empty;

            // Loop through all web part categories
            foreach (DataRow cdr in cds.Tables[0].Rows)
            {
                // Get all webpart in the categories
                if (allWebParts)
                {
                    ds = WebPartInfoProvider.GetAllWebParts(Convert.ToInt32(cdr["CategoryId"]));
                }
                // Get all widgets in the category
                else if (allWidgets)
                {
                    int categoryID = Convert.ToInt32(cdr["WidgetCategoryId"]);
                    ds = WidgetInfoProvider.GetWidgets("WidgetCategoryID = " + categoryID.ToString(), null, 0, null);
                }

                // Check whether current category contains at least one webpart
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    // Generate category name code
                    menu += "<br /><strong>" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "</strong><br /><br />";

                    // Loop through all web web parts in categories
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // Init
                        isImagePresent = false;
                        undocumentedProperties = 0;
                        documentation = 0;

                        // Webpart (Widget) information
                        string itemDisplayName = String.Empty;
                        string itemDescription = String.Empty;
                        string itemDocumentation = String.Empty;
                        string itemType = String.Empty;
                        int itemID = 0;

                        WebPartInfo wpi = null;
                        WidgetInfo wi = null;

                        // Set webpart info
                        if ((isWebpartInQuery) || (allWebParts))
                        {
                            wpi = new WebPartInfo(dr);
                            if (wpi != null)
                            {
                                itemDisplayName = wpi.WebPartDisplayName;
                                itemDescription = wpi.WebPartDescription;
                                itemDocumentation = wpi.WebPartDocumentation;
                                itemID = wpi.WebPartID;
                                itemType = PortalObjectType.WEBPART;

                                if (wpi.WebPartCategoryID != ValidationHelper.GetInteger(cdr["CategoryId"], 0))
                                {
                                    wpi = null;
                                }
                            }
                        }
                        // Set widget info
                        else if ((isWidgetInQuery) || (allWidgets))
                        {
                            wi = new WidgetInfo(dr);
                            if (wi != null)
                            {
                                itemDisplayName = wi.WidgetDisplayName;
                                itemDescription = wi.WidgetDescription;
                                itemDocumentation = wi.WidgetDocumentation;
                                itemType = PortalObjectType.WIDGET;
                                itemID = wi.WidgetID;

                                if (wi.WidgetCategoryID != ValidationHelper.GetInteger(cdr["WidgetCategoryId"], 0))
                                {
                                    wi = null;
                                }
                            }
                        }

                        // Check whether web part (widget) exists
                        if ((wpi != null) || (wi != null))
                        {
                            // Link GUID
                            Guid mguid = Guid.NewGuid();

                            // Whether description is present in webpart
                            bool isDescription = false;

                            // Image url
                            string wimgurl = GetItemImage(itemID, itemType);

                            // Set description text
                            string descriptionText = itemDescription;

                            // Parent webpart info
                            WebPartInfo pwpi = null;

                            // If webpart look for parent's description and documentation
                            if (wpi != null)
                            {
                                // Get parent description if webpart is inherited
                                if (wpi.WebPartParentID > 0)
                                {
                                    pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                                    if (pwpi != null)
                                    {
                                        if ((descriptionText == null || descriptionText.Trim() == ""))
                                        {
                                            // Set description from parent
                                            descriptionText = pwpi.WebPartDescription;
                                        }

                                        // Set documentation text from parent if WebPart is inherited
                                        if ((wpi.WebPartDocumentation == null) || (wpi.WebPartDocumentation.Trim() == ""))
                                        {
                                            itemDocumentation = pwpi.WebPartDocumentation;
                                            if (!String.IsNullOrEmpty(itemDocumentation))
                                            {
                                                documentation = 2;
                                            }
                                        }
                                    }
                                }
                            }

                            // Set description as present
                            if (descriptionText.Trim().Length > 0)
                            {
                                isDescription = true;
                            }

                            // Generate HTML for menu and content
                            menu += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a>&nbsp;";

                            // Generate webpart header
                            content += "<table style=\"width:100%;\"><tr><td><h1><a name=\"_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "&nbsp;>&nbsp;" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a></h1></td><td style=\"text-align:right;\">&nbsp;<a href=\"#top\" class=\"noprint\">top</a></td></tr></table>";

                            // Generate WebPart content
                            content +=
                                @"<table style=""width: 100%; height: 200px; border: solid 1px #DDDDDD;"">
                                   <tr>
                                     <td style=""width: 50%; text-align:center; border-right: solid 1px #DDDDDD; vertical-align: middle;margin-left: auto; margin-right:auto; text-align:center;"">
                                         <img src=""" + wimgurl + @""" alt=""imageTeaser"">
                                     </td>
                                     <td style=""width: 50%; vertical-align: center;text-align:center;"">"
                                         + HTMLHelper.HTMLEncode(descriptionText) + @"
                                     </td>
                                   </tr>
                                </table>";

                            // Properties content
                            content += "<div class=\"DocumentationWebPartsProperties\">";

                            // Generate content
                            if (wpi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wpi));
                            }
                            else if (wi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wi));
                            }

                            // Close content area
                            content += "</div>";

                            // Generate documentation text content
                            content += "<br /><div style=\"border: solid 1px #dddddd;width: 100%;\">" +
                                DataHelper.GetNotEmpty(HTMLHelper.ResolveUrls(itemDocumentation, null), "<strong>Additional documentation text is not provided.</strong>") +
                                "</div>";

                            // Set page break tag for print
                            content += "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />";

                            // If development is required - highlight missing description, images and doc. text
                            if (development)
                            {
                                // Check image
                                if (!isImagePresent)
                                {
                                    menu += "<span style=\"color:Brown;\">image&nbsp;</span>";
                                }

                                // Check properties
                                if (undocumentedProperties > 0)
                                {
                                    menu += "<span style=\"color:Red;\">properties(" + undocumentedProperties + ")&nbsp;</span>";
                                }

                                // Check properties
                                if (!isDescription)
                                {
                                    menu += "<span style=\"color:#37627F;\">description&nbsp;</span>";
                                }

                                // Check documentation text
                                if (String.IsNullOrEmpty(itemDocumentation))
                                {
                                    documentation = 1;
                                }

                                switch (documentation)
                                {
                                    // Display information about missing documentation
                                    case 1:
                                        menu += "<span style=\"color:Green;\">documentation&nbsp;</span>";
                                        break;

                                    // Display information about inherited documentation
                                    case 2:
                                        menu += "<span style=\"color:Green;\">documentation (inherited)&nbsp;</span>";
                                        break;
                                }
                            }

                            menu += "<br />";
                        }
                    }
                }
            }
        }

        ltlContent.Text = menu + "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />" + content;
    }
 /// <summary>
 /// Sets additional context values to resolver.
 /// </summary>
 /// <param name="resolver">Context resolver</param>
 private static void SetContext(ContextResolver resolver)
 {
     resolver.CurrentDocument = TreeNode.New("CMS.root");
     resolver.CurrentPageInfo = new PageInfo();
     resolver.CurrentPageInfo.PageTemplateInfo = new PageTemplateInfo();
 }
    /// <summary>
    /// Resolve custom macros for specified input value.
    /// </summary>
    /// <param name="value">Value to resolve</param>
    /// <param name="dr">Current data row</param>
    /// <param name="columnName">Column name</param>
    /// <param name="sum">Summary of all items</param>
    private string ResolveCustomMacros(string value, DataRow dr, string columnName, double sum)
    {
        // Ensure resolver
        if (itemResolver == null)
        {
            itemResolver = CMSContext.CurrentResolver.CreateContextChild();
        }

        // Get current item value
        double itemvalue = ValidationHelper.GetDouble(dr[columnName], 0.0);

        // Custom macros definition
        string[,] macros = new string[4, 2];
        macros[0, 0] = "xval";
        macros[0, 1] = Convert.ToString(dr[0]);
        macros[1, 0] = "yval";
        macros[1, 1] = Convert.ToString(itemvalue);
        macros[2, 0] = "ser";
        macros[2, 1] = columnName;
        macros[3, 0] = "pval";
        macros[3, 1] = Convert.ToString(itemvalue / sum * 100);

        // Set custom macros
        itemResolver.SourceParameters = macros;
        // Resolve macros
        return itemResolver.ResolveMacros(value);
    }
示例#36
0
    /// <summary>
    /// Sends the email.
    /// </summary>
    protected void btnSend_Click(object sender, EventArgs e)
    {
        // Check "modify" permission
        if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Users", "Modify"))
        {
            RedirectToAccessDenied("CMS.Users", "Modify");
        }

        // Validate first
        string errorMessage = new Validator().IsEmail(this.txtFrom.Text, GetString("general.correctemailformat")).Result;

        // Get recipients
        string groupIds = null;
        if (groupsControl != null)
        {
            groupIds = Convert.ToString(this.groupsControl.Value);
        }
        string userIDs = Convert.ToString(this.users.Value);
        string roleIDs = Convert.ToString(this.roles.Value);

        if (string.IsNullOrEmpty(groupIds) && string.IsNullOrEmpty(userIDs) && string.IsNullOrEmpty(roleIDs))
        {
            errorMessage = GetString("massemail.norecipients");
        }

        if (!string.IsNullOrEmpty(errorMessage))
        {
            this.lblError.Text = errorMessage;
            this.lblError.Visible = true;
            return;
        }

        // Get resolver to resolve context macros
        ContextResolver resolver = new ContextResolver();

        // Create the message
        EmailMessage message = new EmailMessage();
        message.Subject = resolver.ResolveMacros(this.txtSubject.Text);
        message.From = this.txtFrom.Text;
        if (plcText.Visible)
        {
            message.Body = resolver.ResolveMacros(htmlText.ResolvedValue);
        }
        if (plcPlainText.Visible)
        {
            message.PlainTextBody = resolver.ResolveMacros(txtPlainText.Text);
        }

        // Get the attachments
        HttpPostedFile[] attachments = this.uploader.PostedFiles;
        foreach (HttpPostedFile att in attachments)
        {
            message.Attachments.Add(new EmailAttachment(StreamWrapper.New(att.InputStream), Path.GetFileName(att.FileName), Guid.NewGuid(), DateTime.Now, siteId));
        }

        // Check if list of roleIds contains generic role 'Everyone'
        bool containsEveryone = false;
        RoleInfo roleEveryone = null;

        if (!String.IsNullOrEmpty(roleIDs))
        {
            roleEveryone = RoleInfoProvider.GetRoleInfo(CMSConstants.ROLE_EVERYONE, siteId);
            if ((roleEveryone != null) && (";" + roleIDs + ";").Contains(";" + roleEveryone.RoleID.ToString() + ";"))
            {
                containsEveryone = true;
            }
        }

        // Send messages using email engine
        EmailSender.SendMassEmails(message, userIDs, roleIDs, groupIds, siteId, containsEveryone);

        this.lblInfo.Text = GetString("massemail.emailsent");
        this.lblInfo.Visible = true;

        this.btnClear.Visible = true;
    }