Esempio n. 1
0
        public DockContent()
        {
            _fixer = new FormHelper(this);
            _fixer.EnableBoundsTracking = false;

            ElementProvider.Install(new DockContentElementProvider(this));
        }
Esempio n. 2
0
 public UserControl()
 {
     _fixer = new FormHelper(this)
     {
         EnableBoundsTracking = false
     };
 }
        /// <summary>
        /// Initializes a new instance of class CrmConnectionStatusBar
        /// </summary>
        public CrmConnectionStatusBar(FormHelper formHelper)
        {
            resources = new System.ComponentModel.ComponentResourceManager(typeof(CrmConnectionStatusBar));

            ConnectionManager.Instance.ConnectionListUpdated += cManager_ConnectionListUpdated;
            _formHelper = formHelper;

            // Build connection control
            this.BuildConnectionControl();

            // Add label that will display information about connection
            ToolStripStatusLabel informationLabel = new ToolStripStatusLabel
            {
                Spring = true,
                TextAlign = ContentAlignment.MiddleRight
            };

            this.Items.Add(informationLabel);

            ToolStripProgressBar progress = new ToolStripProgressBar
            {
                Minimum = 0,
                Maximum = 100,
                Visible = false
            };
            this.Items.Add(progress);

            base.RenderMode = ToolStripRenderMode.Professional;
        }
        public void CreateFormHelper()
        {
            _viewBag = new Dictionary<string, object>();
            var viewReq = new ViewRequest();
            _ctx = new ViewContext(null, _viewBag, new object(), viewReq);

            _formHlpr = new FormHelper(_ctx);
            _url = new StubTargetUrl();
        }
Esempio n. 5
0
        public Form()
        {
            _fixer = new FormHelper(this)
            {
                EnableBoundsTracking = true
            };

            _lastSizeGripStyle = SizeGripStyle;
        }
Esempio n. 6
0
 private void button_help_Click(object sender, EventArgs e)
 {
     if (helper == null || helper.IsDisposed)
     {
         helper = new FormHelper();
         helper.Show();
         helper.Location = Postion.getPostion(helper, 0.5f, 0.5f, this);
     }
     else
     {
         helper.Activate();
     }
 }
        /// <summary>
        /// Initializes a new instance of class CrmConnectionStatusBar
        /// </summary>
        public CrmConnectionStatusBar(FormHelper formHelper)
        {
            resources = new System.ComponentModel.ComponentResourceManager(typeof(CrmConnectionStatusBar));

            ConnectionManager.Instance.ConnectionListUpdated += cManager_ConnectionListUpdated;
            _formHelper = formHelper;

            // Build connection control
            this.BuildConnectionControl();

            // Add label that will display information about connection
            ToolStripLabel informationLabel = new ToolStripLabel();
            this.Items.Add(informationLabel);
            base.RenderMode = ToolStripRenderMode.Professional;
        }
        public Form1()
        {
            InitializeComponent();
            // Create the connection manager with its events
            this.cManager = ConnectionManager.Instance;
            this.cManager.ConnectionSucceed += new ConnectionManager.ConnectionSucceedEventHandler(cManager_ConnectionSucceed);
            this.cManager.ConnectionFailed += new ConnectionManager.ConnectionFailedEventHandler(cManager_ConnectionFailed);
            this.cManager.StepChanged += new ConnectionManager.StepChangedEventHandler(cManager_StepChanged);
            this.cManager.RequestPassword += new ConnectionManager.RequestPasswordEventHandler(cManager_RequestPassword);
            formHelper = new FormHelper(this);

            // Instantiate and add the connection control to the form
            ccsb = new CrmConnectionStatusBar(formHelper);
            this.Controls.Add(ccsb);

            this.ccsb.SetMessage("A message to display...");
        }
Esempio n. 9
0
        public Form1()
        {
            InitializeComponent();

            // Create the connection manager with its events
            this.cManager = new ConnectionManager();
            this.cManager.ConnectionSucceed += new ConnectionManager.ConnectionSucceedEventHandler(cManager_ConnectionSucceed);
            this.cManager.ConnectionFailed += new ConnectionManager.ConnectionFailedEventHandler(cManager_ConnectionFailed);
            this.cManager.StepChanged += new ConnectionManager.StepChangedEventHandler(cManager_StepChanged);
            this.cManager.RequestPassword += new ConnectionManager.RequestPasswordEventHandler(cManager_RequestPassword);
            this.cManager.UseProxy += new ConnectionManager.UseProxyEventHandler(cManager_UseProxy);
            formHelper = new FormHelper(this, cManager);

            // Instantiate and add the connection control to the form
            ccsb = new CrmConnectionStatusBar(this.cManager, formHelper);
            this.Controls.Add(ccsb);
        }
		public void Init()
		{
			var en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture	= en;
			Thread.CurrentThread.CurrentUICulture = en;

			helper = new FormHelper();
			model = new ModelWithValidation();

			var controller = new HomeController();
			var controllerContext = new ControllerContext();

			controllerContext.PropertyBag.Add("model", model);

			helper.SetController(controller, controllerContext);
		}
		public void Init()
		{
			CultureInfo en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture = en;
			Thread.CurrentThread.CurrentUICulture = en;

			helper = new FormHelper();
			helper.UseWebValidatorProvider(new JQueryValidator());
			model = new ModelWithValidation();

			HomeController controller = new HomeController();
			ControllerContext controllerContext = new ControllerContext();

			controllerContext.PropertyBag.Add("model", model);

			helper.SetController(controller, controllerContext);
		}
		/// <summary>
		/// Get a report with the default form data and return the reports index view
		/// </summary>
		/// <param name="ReportsForm"></param>
		/// <returns></returns>
		public ActionResult Index( FormCollection ReportsForm )
		{
			using( FAutoScopedLogTimer LogTimer = new FAutoScopedLogTimer( this.GetType().ToString(), bCreateNewLog: true ) )
			{
				FormHelper FormData = new FormHelper( Request, ReportsForm, "JustReport" );

				// Handle 'CopyToJira' button
				int BuggIDToBeAddedToJira = 0;
				foreach( var Entry in ReportsForm )
				{
                    if (Entry.ToString().Contains("CopyToJira-"))
					{
                        int.TryParse(Entry.ToString().Substring("CopyToJira-".Length), out BuggIDToBeAddedToJira);
						break;
					}
				}
                
				var results = GetResults( FormData, BuggIDToBeAddedToJira );
				results.GenerationTime = LogTimer.GetElapsedSeconds().ToString( "F2" );
				return View( "Index", results );
			}
		}
Esempio n. 13
0
    /// <summary>
    /// Provides operations necessary to create and store new content file.
    /// </summary>
    private void HandleContentUpload()
    {
        string message            = string.Empty;
        bool   newDocumentCreated = false;

        try
        {
            if (NodeParentNodeID == 0)
            {
                throw new Exception(GetString("dialogs.document.parentmissing"));
            }

            // Check license limitations
            if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Insert))
            {
                throw new Exception(GetString("cmsdesk.documentslicenselimits"));
            }

            // Check if class exists
            DataClassInfo ci = DataClassInfoProvider.GetDataClassInfo("CMS.File");
            if (ci == null)
            {
                throw new Exception(string.Format(GetString("dialogs.newfile.classnotfound"), "CMS.File"));
            }


            #region "Check permissions"

            // Get the node
            TreeNode parentNode = TreeProvider.SelectSingleNode(NodeParentNodeID, LocalizationContext.PreferredCultureCode, true);
            if (parentNode != null)
            {
                // Check whether node class is allowed on site and parent node
                if (!DocumentHelper.IsDocumentTypeAllowed(parentNode, ci.ClassID) || (ClassSiteInfoProvider.GetClassSiteInfo(ci.ClassID, parentNode.NodeSiteID) == null))
                {
                    throw new Exception(GetString("Content.ChildClassNotAllowed"));
                }
            }

            // Check user permissions
            if (!RaiseOnCheckPermissions("Create", this))
            {
                if (!MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(parentNode, "CMS.File"))
                {
                    throw new Exception(string.Format(GetString("dialogs.newfile.notallowed"), NodeClassName));
                }
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

            // Create new document
            string fileName = Path.GetFileNameWithoutExtension(ucFileUpload.FileName);
            string ext      = Path.GetExtension(ucFileUpload.FileName);

            if (IncludeExtension)
            {
                fileName += ext;
            }

            // Make sure the file name with extension respects maximum file name
            fileName = TreePathUtils.EnsureMaxFileNameLength(fileName, ci.ClassName);

            node = TreeNode.New("CMS.File", TreeProvider);
            node.DocumentCulture = LocalizationContext.PreferredCultureCode;
            node.DocumentName    = fileName;
            if (NodeGroupID > 0)
            {
                node.SetValue("NodeGroupID", NodeGroupID);
            }

            // Load default values
            FormHelper.LoadDefaultValues(node.NodeClassName, node);
            node.SetValue("FileDescription", "");
            node.SetValue("FileName", fileName);
            node.SetValue("FileAttachment", Guid.Empty);

            // Set default template ID
            node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID);

            // Insert the document
            DocumentHelper.InsertDocument(node, parentNode, TreeProvider);

            newDocumentCreated = true;

            // Add the file
            DocumentHelper.AddAttachment(node, "FileAttachment", ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);

            // Create default SKU if configured
            if (ModuleManager.CheckModuleLicense(ModuleName.ECOMMERCE, RequestContext.CurrentDomain, FeatureEnum.Ecommerce, ObjectActionEnum.Insert))
            {
                node.CreateDefaultSKU();
            }

            // Update the document
            DocumentHelper.UpdateDocument(node, TreeProvider);

            // Get workflow info
            wi = node.GetWorkflow();

            // Check if auto publish changes is allowed
            if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(SiteContext.CurrentSiteName))
            {
                // Automatically publish document
                node.MoveToPublishedStep(null);
            }
        }
        catch (Exception ex)
        {
            // Delete the document if something failed
            if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
            {
                DocumentHelper.DeleteDocument(node, TreeProvider, false, true, true);
            }

            message = ex.Message;
        }
        finally
        {
            // Create node info string
            string nodeInfo = "";
            if ((node != null) && (node.NodeID > 0) && (IncludeNewItemInfo))
            {
                nodeInfo = node.NodeID.ToString();
            }

            // Ensure message text
            message = HTMLHelper.EnsureLineEnding(message, " ");

            string containerId = QueryHelper.GetString("containerid", "");

            // Call function to refresh parent window
            string afterSaveScript = null;
            if (!string.IsNullOrEmpty(AfterSaveJavascript))
            {
                afterSaveScript = String.Format(@"
if (window.{0} != null){{
    window.{0}();
}} else if ((window.parent != null) && (window.parent.{0} != null)){{
    window.parent.{0}();
}}", AfterSaveJavascript);
            }

            afterSaveScript += String.Format(@"
if (typeof(parent.DFU) !== 'undefined') {{ 
    parent.DFU.OnUploadCompleted({0}); 
}} 
if ((window.parent != null) && (/parentelemid={1}/i.test(window.location.href)) && (window.parent.InitRefresh_{1} != null)){{
    window.parent.InitRefresh_{1}({2}, false, false{3}{4});
}}", ScriptHelper.GetString(containerId), ParentElemID, ScriptHelper.GetString(message.Trim()), ((nodeInfo != "") ? ", '" + nodeInfo + "'" : ""), (InsertMode ? ", 'insert'" : ", 'update'"));

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, ScriptHelper.GetScript(afterSaveScript));
        }
    }
Esempio n. 14
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Dept_Load(object sender, EventArgs e)
        {
            FormHelper gen = new FormHelper();

            gen.GenerateForm("FDept", this.groupBox1, new Point(6, 20));
            gen.GenerateForm("FODept", this.panel1, new Point(6, 20));
            gen.GenerateForm("FBDept", this.panel2, new Point(6, 20));
            //保存按钮:保存并关闭
            btnSave.Click += new EventHandler(btnSave_Click);
            btnOk.Click += new EventHandler(btnOk_Click);
            //btnDel.Click += new EventHandler(btnDel_Click);
            //弹出部门选择
            //Dept_PCode.Click+=new EventHandler(Dept_PCode_Click);
            //Dept_PName.Click += new EventHandler(Dept_PCode_Click);

            //弹出人员选择窗口
            //Dept_Owner.Click += new EventHandler(Dept_Owner_Click);
            //Dept_OwnerName.Click += new EventHandler(Dept_Owner_Click);
            //Dept_OMob.Click += new EventHandler(Dept_Owner_Click);
            //Dept_OTel.Click += new EventHandler(Dept_Owner_Click);
            BindModelHelper modelHepler = new BindModelHelper();
            //操作类型
            switch (operationType)
            {
                case OperationTypeEnum.Look:
                    break;
                case OperationTypeEnum.Edit:

                    //modelHepler.BindModelToControl<Bse_Department>(GModel, AllControls());
                    modelHepler.BindModelToControl<Bse_Department>(GModel, this.groupBox1.Controls, "");
                    modelHepler.BindModelToControl<Bse_Department>(GModel, this.panel1.Controls, "");
                    modelHepler.BindModelToControl<Bse_Department>(GModel, this.panel2.Controls, "");

                    break;
                case OperationTypeEnum.Add:
                    GModel = new Bse_Department();
                    GModel.Dept_Code = instance.GenerateDeptCode();
                    modelHepler.BindModelToControl<Bse_Department>(GModel, this.groupBox1.Controls, "");
                    modelHepler.BindModelToControl<Bse_Department>(GModel, this.panel1.Controls, "");
                    modelHepler.BindModelToControl<Bse_Department>(GModel, this.panel2.Controls, "");
                    break;
                default:
                    break;
            }
        }
Esempio n. 15
0
 private void 系统参数ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     listView1.Visible = false;
     FormHelper.CreateForm <FrmSetting>();
 }
 private void btn上传组员分配_Click(object sender, EventArgs e)
 {
     FormHelper.GetCSVPath(txt组员分配Path);
 }
 private void btn上传当月入库时间差_Click(object sender, EventArgs e)
 {
     FormHelper.GetCSVPath(txt当月入库时间差Path);
 }
        /**************** button event ****************/

        #region 导出表格说明
        private void lkDecs_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FormHelper.GenerateTableDes(typeof(_退货信息), typeof(_缺货率详情), typeof(_入库时间差详情), typeof(_压价详情), typeof(_组员分配));
        }
Esempio n. 19
0
 private void RenderRequestTypesTabPage()
 {
     FormHelper.RenderTabPage(createRequestTabControl, requestTypesTabPage);
     BindRequestTypesListBox();
 }
Esempio n. 20
0
 private void RenderForm()
 {
     FormHelper.HideHeaderTabPage(createRequestTabControl);
     RenderRequestTypesTabPage();
 }
Esempio n. 21
0
        private async Task UpsertVariant(TreeNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            var externalId = GetPageExternalId(node.NodeGUID);
            var endpoint   = GetVariantEndpoint(node);

            var contentType = DataClassInfoProvider.GetDataClassInfo(node.NodeClassName);

            if (contentType == null)
            {
                throw new InvalidOperationException($"Content type {node.NodeClassName} not found.");
            }

            var formInfo = FormHelper.GetFormInfo(node.ClassName, false);

            if (formInfo == null)
            {
                throw new InvalidOperationException($"Form info for {node.NodeClassName} not found.");
            }

            var fieldsToSync  = ContentTypeSync.GetItemsToSync(node.NodeClassName).OfType <FormFieldInfo>();
            var fieldElements = await Task.WhenAll(
                fieldsToSync.Select(async(field) => new
            {
                element = new
                {
                    external_id = ContentTypeSync.GetFieldExternalId(contentType.ClassGUID, field.Guid)
                },
                value = await GetElementValue(node, field)
            })
                );

            var unsortedAttachmentsElement = new
            {
                element = new
                {
                    external_id = ContentTypeSync.GetFieldExternalId(contentType.ClassGUID, ContentTypeSync.UNSORTED_ATTACHMENTS_GUID)
                },
                value = (object)GetAttachmentGuids(node, null).Select(guid => new {
                    external_id = AssetSync.GetAttachmentExternalId(guid)
                })
            };
            var categoriesElement = new
            {
                element = new
                {
                    external_id = ContentTypeSync.GetFieldExternalId(contentType.ClassGUID, TaxonomySync.CATEGORIES_GUID)
                },
                value = (object)GetCategoryGuids(node).Select(guid => new {
                    external_id = TaxonomySync.GetCategoryTermExternalId(guid)
                }).ToList()
            };

            var relationshipElements = GetRelationshipElements(node);

            var payload = new
            {
                elements = fieldElements
                           .Concat(new[] {
                    unsortedAttachmentsElement,
                    categoriesElement,
                })
                           .Concat(relationshipElements)
                           .ToList()
            };

            await ExecuteWithoutResponse(endpoint, HttpMethod.Put, payload, true);
        }
Esempio n. 22
0
        private void ManageConnectionControl()
        {
            cManager = ConnectionManager.Instance;
            cManager.RequestPassword   += (sender, e) => fHelper.RequestPassword(e.ConnectionDetail);
            cManager.StepChanged       += (sender, e) => ccsb.SetMessage(e.CurrentStep);
            cManager.ConnectionSucceed += (sender, e) =>
            {
                Controls.Remove(infoPanel);
                if (infoPanel != null)
                {
                    infoPanel.Dispose();
                }

                currentConnectionDetail = e.ConnectionDetail;
                service = e.OrganizationService;
                ccsb.SetConnectionStatus(true, e.ConnectionDetail);
                ccsb.SetMessage(string.Empty);

                if (e.Parameter != null)
                {
                    var control = e.Parameter as UserControl;
                    if (control != null)
                    {
                        var realUserControl = control;
                        DisplayPluginControl(realUserControl);
                    }
                    else if (e.Parameter.ToString() == "ApplyConnectionToTabs" && tabControl1.TabPages.Count > 1)
                    {
                        ApplyConnectionToTabs();
                    }
                    else
                    {
                        var args = e.Parameter as RequestConnectionEventArgs;
                        if (args != null)
                        {
                            var userControl = (UserControl)args.Control;

                            args.Control.UpdateConnection(e.OrganizationService, currentConnectionDetail, args.ActionName, args.Parameter);

                            userControl.Parent.Text = string.Format("{0} ({1})",
                                                                    userControl.Parent.Text.Split(' ')[0],
                                                                    e.ConnectionDetail.ConnectionName);
                        }
                    }
                }
                else if (tabControl1.TabPages.Count > 1)
                {
                    ApplyConnectionToTabs();
                }

                this.StartPluginWithConnection();
            };
            cManager.ConnectionFailed += (sender, e) =>
            {
                this.Invoke(new Action(() =>
                {
                    Controls.Remove(infoPanel);
                    if (infoPanel != null)
                    {
                        infoPanel.Dispose();
                    }

                    MessageBox.Show(this, e.FailureReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    currentConnectionDetail = null;
                    service = null;
                    ccsb.SetConnectionStatus(false, null);
                    ccsb.SetMessage(e.FailureReason);

                    this.StartPluginWithConnection();
                }));
            };

            fHelper = new FormHelper(this);
            ccsb    = new CrmConnectionStatusBar(fHelper)
            {
                Dock = DockStyle.Bottom
            };
            Controls.Add(ccsb);
        }
    /// <summary>
    /// Adds the inline widget without the properties dialog.
    /// </summary>
    /// <param name="widgetId">The widget id</param>
    private string AddInlineWidgetWithoutDialog(int widgetId)
    {
        string script = string.Empty;

        if (widgetId > 0)
        {
            // New widget - load widget info by id
            WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetId);

            if ((wi != null) && wi.WidgetForInline)
            {
                // Test permission for user
                var currentUser = MembershipContext.AuthenticatedUser;
                if (!WidgetRoleInfoProvider.IsWidgetAllowed(widgetId, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
                {
                    return(string.Empty);
                }

                // If user is editor, more properties are shown
                WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User;
                if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName))
                {
                    zoneType = WidgetZoneTypeEnum.Editor;
                }

                WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);

                // Merge the parent web part properties definition with the widget properties definition
                string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);

                // Create the FormInfo for the current widget properties definition
                FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, zoneType, widgetProperties, true);
                DataRow  dr = null;

                if (fi != null)
                {
                    // Get data rows with required columns
                    dr = PortalHelper.CombineWithDefaultValues(fi, wi);

                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible);

                    // Override default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName);
                }

                // Save inline widget script
                script = PortalHelper.GetAddInlineWidgetScript(wi, dr, fi.GetFields(true, true), Enumerable.Empty <string>());

                script += " CloseDialog(false);";

                if (!string.IsNullOrEmpty(script))
                {
                    // Add to recently used widgets collection
                    MembershipContext.AuthenticatedUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName);
                }
            }
        }

        return(script);
    }
Esempio n. 24
0
    /// <summary>
    /// Gets FormEngineUserControl instance for the input SettingsKeyInfo object.
    /// </summary>
    /// <param name="key">SettingsKeyInfo</param>
    /// <param name="groupNo">Number representing index of the processing settings group</param>
    /// <param name="keyNo">Number representing index of the processing SettingsKeyInfo</param>
    private FormEngineUserControl GetFormEngineUserControl(SettingsKeyInfo key, int groupNo, int keyNo)
    {
        if (string.IsNullOrEmpty(key.KeyEditingControlPath))
        {
            return(null);
        }

        // Try to get form control by its name
        FormEngineUserControl control = null;
        var formUserControl           = FormUserControlInfoProvider.GetFormUserControlInfo(key.KeyEditingControlPath);

        if (formUserControl != null)
        {
            var fileName       = "";
            var formProperties = "";

            if (formUserControl.UserControlParentID > 0)
            {
                // Get parent user control
                var parentFormUserControl = FormUserControlInfoProvider.GetFormUserControlInfo(formUserControl.UserControlParentID);
                if (parentFormUserControl != null)
                {
                    fileName       = parentFormUserControl.UserControlFileName;
                    formProperties = formUserControl.UserControlMergedParameters;
                }
            }
            else
            {
                // Current user control info
                fileName       = formUserControl.UserControlFileName;
                formProperties = formUserControl.UserControlParameters;
            }

            // Create FormInfo and load control
            control = Page.LoadUserControl(fileName) as FormEngineUserControl;
            if (control != null)
            {
                FormInfo fi = FormHelper.GetFormControlParameters(formUserControl.UserControlCodeName, formProperties, true);
                control.LoadDefaultProperties(fi);

                if (!string.IsNullOrEmpty(key.KeyFormControlSettings))
                {
                    control.FieldInfo = FormHelper.GetFormControlSettingsFromXML(key.KeyFormControlSettings);
                    control.LoadControlFromFFI();
                }
            }
        }
        else
        {
            // Try to load the control
            try
            {
                control = Page.LoadUserControl(key.KeyEditingControlPath) as FormEngineUserControl;
            }
            catch
            {
            }
        }

        if (control == null)
        {
            return(null);
        }

        control.ID         = string.Format(@"key{0}{1}", groupNo, keyNo);
        control.IsLiveSite = false;

        if (string.IsNullOrEmpty(key.KeyEditingControlPath))
        {
            return(control);
        }

        // Set properties to the specific controls
        switch (key.KeyEditingControlPath.ToLowerCSafe())
        {
        // Class names selectors
        case "~/cmsformcontrols/classes/selectclassnames.ascx":
            control.SetValue("SiteID", 0);
            break;
        }

        return(control);
    }
Esempio n. 25
0
 public SystemMonitorConfig()
 {
     InitializeComponent();
     FormHelper.InitHabitToForm(this);
     loader = new ConfigLoader <SystemConfig>(this);
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Form"></param>
        /// <returns></returns>
	    public ActionResult GenerateCSV(FormCollection Form)
        {
            using (var logTimer = new FAutoScopedLogTimer(this.GetType().ToString(), bCreateNewLog: true))
            {
                var formData = new FormHelper(Request, Form, "JustReport");
                var results = GetResults(formData);
                results.GenerationTime = logTimer.GetElapsedSeconds().ToString("F2");
                return View("CSV", results);
            }
        }
        private void btnAnalyze_Click(object sender, EventArgs e)
        {
            var list停售退货信息    = new List <_退货信息>();
            var list滞销退货信息    = new List <_退货信息>();
            var list缺货率详情     = new List <_缺货率详情>();
            var list上月入库时间差详情 = new List <_入库时间差详情>();
            var list当月入库时间差详情 = new List <_入库时间差详情>();
            var list压价信息      = new List <_压价详情>();
            var list组员分配      = new List <_组员分配>();


            var d停售退货奖励比率 = nup停售退货奖励比率.Value / 100;
            var d滞销退货奖励比率 = nup滞销退货奖励比率.Value / 100;
            var d压价奖励比率   = nup压价奖励比率.Value / 100;

            _dGrade1 = nupGrad1.Value;
            _dGrade2 = nupGrad2.Value;
            _dGrade3 = nupGrad3.Value;

            #region 读取数据
            var actReadData = new Action(() =>
            {
                var strError = string.Empty;

                ShowMsg("开始读取停售退货信息");
                FormHelper.ReadCSVFile <_退货信息>(txt停售退货Path.Text, ref list停售退货信息, ref strError);
                if (!string.IsNullOrEmpty(strError))
                {
                    ShowMsg("读取停售退货信息出现异常:" + strError);
                }

                ShowMsg("开始读取滞销退货信息");
                FormHelper.ReadCSVFile <_退货信息>(txt滞销退货Path.Text, ref list滞销退货信息, ref strError);
                if (!string.IsNullOrEmpty(strError))
                {
                    ShowMsg("读取滞销退货信息出现异常:" + strError);
                }

                ShowMsg("开始读取缺货率详情信息");
                FormHelper.ReadCSVFile <_缺货率详情>(txt缺货率Path.Text, ref list缺货率详情, ref strError);
                if (!string.IsNullOrEmpty(strError))
                {
                    ShowMsg("读取缺货率信息出现异常:" + strError);
                }

                ShowMsg("开始读取上月入库时间差信息");
                FormHelper.ReadCSVFile <_入库时间差详情>(txt上月入库时间差Path.Text, ref list上月入库时间差详情, ref strError);
                if (!string.IsNullOrEmpty(strError))
                {
                    ShowMsg("读取上月入库时间差信息出现异常:" + strError);
                }

                ShowMsg("开始读取当月入库时间差信息");
                FormHelper.ReadCSVFile <_入库时间差详情>(txt当月入库时间差Path.Text, ref list当月入库时间差详情, ref strError);
                if (!string.IsNullOrEmpty(strError))
                {
                    ShowMsg("读取当月入库时间差信息出现异常:" + strError);
                }


                ShowMsg("开始读取压价信息");
                FormHelper.ReadCSVFile <_压价详情>(txt压价信息Path.Text, ref list压价信息, ref strError);
                if (!string.IsNullOrEmpty(strError))
                {
                    ShowMsg("读取压价信息出现异常:" + strError);
                }


                ShowMsg("开始读取组员分配信息");
                FormHelper.ReadCSVFile <_组员分配>(txt组员分配Path.Text, ref list组员分配, ref strError);
                if (!string.IsNullOrEmpty(strError))
                {
                    ShowMsg("读取组员分配信息出现异常:" + strError);
                }
            });
            #endregion


            #region 处理数据
            actReadData.BeginInvoke((obj) =>
            {
                var list统计结果      = new List <_工资统计>();
                var list缺货率详细信息   = new List <_缺货率详细信息>();
                var list入库时间差详细信息 = new List <_入库时间差详细信息>();

                var list整合人员姓名 = list停售退货信息.Select(x => x._退货人员).Distinct().ToList();


                list整合人员姓名.ForEach(str整合人员姓名 =>
                {
                    var model  = new _工资统计();
                    model._采购员 = str整合人员姓名;


                    #region 计算停售退货奖励
                    {
                        var ref停售退货Item = list停售退货信息.Where(x => x._退货人员 == str整合人员姓名).FirstOrDefault();
                        if (ref停售退货Item != null)
                        {
                            model._停售退货奖励 = d停售退货奖励比率 * ref停售退货Item._退款金额;
                        }
                    }
                    #endregion

                    #region 计算滞销退货奖励
                    {
                        var ref滞销退货Item = list滞销退货信息.Where(x => x._退货人员 == str整合人员姓名).FirstOrDefault();
                        if (ref滞销退货Item != null)
                        {
                            model._滞销退货奖励 = d滞销退货奖励比率 * ref滞销退货Item._退款金额;
                        }
                    }
                    #endregion

                    //计算缺货率和入库时间差共用
                    var ref组员姓名 = new List <string>();

                    #region 获取所有组员信息
                    {
                        var str组员信息Item = list组员分配.Where(x => x._整合人员 == str整合人员姓名).FirstOrDefault();
                        if (str组员信息Item != null && !string.IsNullOrEmpty(str组员信息Item._组员))
                        {
                            ref组员姓名.AddRange(str组员信息Item._组员.Split(';').ToList());
                        }
                    }
                    #endregion

                    #region 计算组员缺货率奖励
                    {
                        var ref组员缺货率 = new List <decimal>();
                        ref组员姓名.ForEach(str组员姓名 =>
                        {
                            var ref组员缺货率list = list缺货率详情.Where(x => x._采购员 == str组员姓名).ToList();
                            if (ref组员缺货率list != null && ref组员缺货率list.Count > 0)
                            {
                                var _订单总和 = ref组员缺货率list.Select(x => x._交易订单数量).Sum();
                                var _缺货订单 = ref组员缺货率list.Select(x => x._缺货订单数量).Sum();
                                var _缺货率  = _订单总和 != 0 ? _缺货订单 / _订单总和 : 0;
                                ref组员缺货率.Add(_缺货率);

                                var tmp    = new _缺货率详细信息();
                                tmp._采购员   = str组员姓名;
                                tmp._组长    = str整合人员姓名;
                                tmp._总订单   = _缺货订单;
                                tmp._总缺货订单 = _缺货订单;
                                tmp._缺货率   = _缺货率;
                                list缺货率详细信息.Add(tmp);
                            }
                        });

                        if (ref组员缺货率.Count > 0)
                        {
                            var _所有组员平均缺货率 = ref组员缺货率.Average();
                            model._缺货率奖励   = Calcu缺货率奖励(_所有组员平均缺货率);
                        }
                    }
                    #endregion

                    #region 计算入库时间差
                    {
                        var ref组员入库时间差 = new List <decimal>();
                        ref组员姓名.ForEach(str组员姓名 =>
                        {
                            var list上月入库时间差 = list上月入库时间差详情.Where(x => x._采购员 == str组员姓名).ToList();
                            var list当月入库时间差 = list当月入库时间差详情.Where(x => x._采购员 == str组员姓名).ToList();

                            var _上月平均入库时间差 = list上月入库时间差.Count > 0 ? list上月入库时间差.Select(x => x._采购入库时间差).Sum() / list上月入库时间差.Count : 0;
                            var _当月平均入库时间差 = list当月入库时间差详情.Count > 0 ? list当月入库时间差详情.Select(x => x._采购入库时间差).Sum() / list当月入库时间差详情.Count : 0;
                            ref组员入库时间差.Add(_当月平均入库时间差 - _上月平均入库时间差);

                            var tmp      = new _入库时间差详细信息();
                            tmp._采购员     = str组员姓名;
                            tmp._组长      = str整合人员姓名;
                            tmp._上月入库时间差 = _上月平均入库时间差;
                            tmp._当月入库时间差 = _当月平均入库时间差;
                            list入库时间差详细信息.Add(tmp);
                        });

                        if (ref组员入库时间差.Count > 0)
                        {
                            var _所有组员平均入库时间差 = ref组员入库时间差.Average();
                            model._入库时间差奖励   = Calcu入库时间差奖励(_所有组员平均入库时间差);
                        }
                    }
                    #endregion

                    #region 计算压价奖励
                    {
                        var ref压价Item = list压价信息.Where(x => x._采购员 == str整合人员姓名).FirstOrDefault();
                        if (ref压价Item != null)
                        {
                            model._压价奖励奖励 = d压价奖励比率 * ref压价Item._压价额;
                        }
                    }
                    #endregion


                    list统计结果.Add(model);
                });



                Export(list统计结果, list缺货率详细信息, list入库时间差详细信息);
            }, null);
            #endregion
        }
Esempio n. 28
0
 private void RenderSummaryTabPage()
 {
     FormHelper.RenderTabPage(createRequestTabControl, summaryTabPage);
 }
 private void btn上传滞销退货_Click(object sender, EventArgs e)
 {
     FormHelper.GetCSVPath(txt滞销退货Path);
 }
Esempio n. 30
0
    /// <summary>
    /// Creates a field item
    /// </summary>
    /// <param name="ffi">Form field info</param>
    /// <param name="i">Field index</param>
    private void CreateField(FormFieldInfo ffi, ref int i)
    {
        // Check if is defined inherited default value
        bool doNotInherit = IsDefined(ffi.Name);
        // Get default value
        string inheritedDefaultValue = GetDefaultValue(ffi.Name);

        // Current hashtable for client id
        Hashtable currentHashTable = new Hashtable();

        // First item is name
        currentHashTable[0] = ffi.Name;
        currentHashTable[3] = ffi.Caption;

        // Begin new row and column
        Literal table2 = new Literal();

        pnlEditor.Controls.Add(table2);
        table2.Text = "<tr class=\"InheritWebPart\"><td>";

        // Property label
        Label lblName = new Label();

        pnlEditor.Controls.Add(lblName);
        lblName.Text    = ResHelper.LocalizeString(ffi.Caption);
        lblName.ToolTip = ResHelper.LocalizeString(ffi.Description);
        if (!lblName.Text.EndsWithCSafe(":"))
        {
            lblName.Text += ":";
        }

        // New column
        Literal table3 = new Literal();

        pnlEditor.Controls.Add(table3);
        table3.Text = "</td><td>";

        // Type string for JavaScript function
        string jsType = "textbox";

        // Type switcher
        if (FormHelper.IsFieldOfType(ffi, FormFieldControlTypeEnum.CheckBoxControl))
        {
            // Checkbox type field
            CheckBox chk = new CheckBox();
            pnlEditor.Controls.Add(chk);
            chk.Checked = ValidationHelper.GetBoolean(ffi.DefaultValue, false);
            chk.InputAttributes.Add("disabled", "disabled");

            chk.Attributes.Add("id", chk.ClientID + "_upperSpan");

            if (doNotInherit)
            {
                chk.InputAttributes.Remove("disabled");
                chk.Enabled = true;
                chk.Checked = ValidationHelper.GetBoolean(inheritedDefaultValue, false);
            }

            jsType = "checkbox";
            currentHashTable[1] = chk.ClientID;
        }
        else if (FormHelper.IsFieldOfType(ffi, FormFieldControlTypeEnum.CalendarControl))
        {
            // Date time picker
            DateTimePicker dtPick = new DateTimePicker();
            pnlEditor.Controls.Add(dtPick);
            String value = ffi.DefaultValue;
            dtPick.Enabled       = false;
            dtPick.SupportFolder = ResolveUrl("~/CMSAdminControls/Calendar");

            if (doNotInherit)
            {
                dtPick.Enabled = true;
                value          = inheritedDefaultValue;
            }

            if (ValidationHelper.IsMacro(value))
            {
                dtPick.DateTimeTextBox.Text = value;
            }
            else
            {
                dtPick.SelectedDateTime = ValidationHelper.GetDateTime(value, DataHelper.DATETIME_NOT_SELECTED, CultureHelper.EnglishCulture);
            }

            jsType = "calendar";
            currentHashTable[1] = dtPick.ClientID;
        }
        else
        {
            // Other types represent by textbox
            CMSTextBox txt = new CMSTextBox();
            pnlEditor.Controls.Add(txt);

            // Convert from default culture to current culture if needed (type double, datetime)
            txt.Text = (String.IsNullOrEmpty(ffi.DefaultValue) || ValidationHelper.IsMacro(ffi.DefaultValue)) ? ffi.DefaultValue : ValidationHelper.GetString(DataHelper.ConvertValue(ffi.DefaultValue, GetDataType(ffi.Name)), String.Empty);

            txt.CssClass = "TextBoxField";
            txt.Enabled  = ffi.Enabled;
            txt.Enabled  = false;

            if (ffi.DataType == FormFieldDataTypeEnum.LongText)
            {
                txt.TextMode = TextBoxMode.MultiLine;
                txt.Rows     = 3;
            }

            if (doNotInherit)
            {
                txt.Enabled = true;
                txt.Text    = (String.IsNullOrEmpty(inheritedDefaultValue) || ValidationHelper.IsMacro(ffi.DefaultValue)) ? inheritedDefaultValue : ValidationHelper.GetString(DataHelper.ConvertValue(inheritedDefaultValue, GetDataType(ffi.Name)), String.Empty);
            }

            currentHashTable[1] = txt.ClientID;
        }

        // New column
        Literal table4 = new Literal();

        pnlEditor.Controls.Add(table4);
        table4.Text = "</td><td>" + ffi.DataType.ToString() + "</td><td>";


        // Inherit checkbox
        CheckBox chkInher = new CheckBox();

        pnlEditor.Controls.Add(chkInher);
        chkInher.Checked = true;

        // Uncheck checkbox if this property is not inherited
        if (doNotInherit)
        {
            chkInher.Checked = false;
        }

        chkInher.Text = GetString("DefaultValueEditor.Inherited");

        string defValue = (ffi.DefaultValue == null) ? String.Empty : ffi.DefaultValue;

        if (!String.IsNullOrEmpty(ffi.DefaultValue))
        {
            if (!ValidationHelper.IsMacro(ffi.DefaultValue))
            {
                defValue = ValidationHelper.GetString(DataHelper.ConvertValue(defValue, GetDataType(ffi.Name)), String.Empty);
            }
            else
            {
                defValue = MacroResolver.RemoveSecurityParameters(defValue, true, null);
            }
        }

        // Set default value for JavaScript function
        defValue = "'" + defValue.Replace("\r\n", "\\n") + "'";

        if (jsType == "checkbox")
        {
            defValue = ValidationHelper.GetBoolean(ffi.DefaultValue, false).ToString().ToLowerCSafe();
        }

        // Add JavaScript attribute with js function call
        chkInher.Attributes.Add("onclick", "CheckClick(this, '" + currentHashTable[1].ToString() + "', " + defValue + ", '" + jsType + "' );");

        // Insert current checkbox id
        currentHashTable[2] = chkInher.ClientID;

        // Add current hashtable to the controls hashtable
        ((Hashtable)Controls)[i] = currentHashTable;

        // End current row
        Literal table5 = new Literal();

        pnlEditor.Controls.Add(table5);
        table5.Text = "</td></tr>";

        i++;
    }
 private void btn上传压价信息_Click(object sender, EventArgs e)
 {
     FormHelper.GetCSVPath(txt压价信息Path);
 }
        public void ConvertMetadataAttributeModels(BaseUsage source, long metadataStructureId, int stepId)
        {
            Source = source;



            //if (Source is MetadataAttributeUsage)
            //{

            //    MetadataAttributeUsage mau = (MetadataAttributeUsage)Source;

            //    if (mau.MetadataAttribute.Self is MetadataCompoundAttribute)
            //    {
            //        MetadataCompoundAttribute mca = (MetadataCompoundAttribute)mau.MetadataAttribute.Self;

            //        if (mca != null)
            //        {
            //            foreach (MetadataNestedAttributeUsage usage in mca.MetadataNestedAttributeUsages)
            //            {
            //                if (UsageHelper.IsSimple(usage))
            //                {
            //                    MetadataAttributeModels.Add(MetadataAttributeModel.Convert(usage, mau, metadataStructureId, Number));
            //                }
            //            }
            //        }
            //    }
            //}

            //if (Source is MetadataNestedAttributeUsage)
            //{
            //    MetadataNestedAttributeUsage mnau = (MetadataNestedAttributeUsage)Source;
            //    if (mnau.Member.Self is MetadataCompoundAttribute)
            //    {
            //        MetadataCompoundAttribute mca = (MetadataCompoundAttribute)mnau.Member.Self;

            //        if (mca != null)
            //        {
            //            foreach (MetadataNestedAttributeUsage usage in mca.MetadataNestedAttributeUsages)
            //            {
            //                if (UsageHelper.IsSimple(usage))
            //                {
            //                    MetadataAttributeModels.Add(MetadataAttributeModel.Convert(usage, mnau, metadataStructureId, Number));
            //                }
            //            }
            //        }
            //    }
            //}

            if (Source is MetadataPackageUsage)
            {
                MetadataPackageUsage mpu = (MetadataPackageUsage)Source;
                if (mpu.MetadataPackage is MetadataPackage)
                {
                    MetadataPackage mp = mpu.MetadataPackage;

                    if (mp != null)
                    {
                        foreach (MetadataAttributeUsage usage in mp.MetadataAttributeUsages)
                        {
                            if (metadataStructureUsageHelper.IsSimple(usage))
                            {
                                MetadataAttributeModels.Add(FormHelper.CreateMetadataAttributeModel(usage, mpu, metadataStructureId, Number, stepId));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 33
0
 private void 设备运行参数设置ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     listView1.Visible = false;
     FormHelper.CreateForm <FrmParmeterConfig>();
 }
Esempio n. 34
0
        private void InitData()
        {
            FormHelper gen = new FormHelper();

            //gen.GenerateForm("FLogin", this.groupBox1, new Point(6, 20));
        }
Esempio n. 35
0
    protected override void OnInit(EventArgs e)
    {
        var currentUser = MembershipContext.AuthenticatedUser;

        // Check UIProfile
        if (!currentUser.IsAuthorizedPerUIElement("CMS.Content", new[] { "EditForm", "Edit" }, SiteContext.CurrentSiteName))
        {
            RedirectToUIElementAccessDenied("CMS.Content", "EditForm");
        }

        base.OnInit(e);

        DocumentManager.OnAfterAction  += DocumentManager_OnAfterAction;
        DocumentManager.OnLoadData     += DocumentManager_OnLoadData;
        DocumentManager.OnBeforeAction += DocumentManager_OnBeforeAction;

        // Register scripts
        string script = "function " + formElem.ClientID + "_RefreshForm(){" + Page.ClientScript.GetPostBackEventReference(btnRefresh, "") + " }";

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), formElem.ClientID + "_RefreshForm", ScriptHelper.GetScript(script));

        ScriptHelper.RegisterCompletePageScript(this);
        ScriptHelper.RegisterLoader(this);
        ScriptHelper.RegisterDialogScript(this);

        formElem.OnBeforeDataLoad += formElem_OnBeforeDataLoad;
        formElem.OnAfterDataLoad  += formElem_OnAfterDataLoad;

        // Update view mode
        if (!RequiresDialog)
        {
            PortalContext.ViewMode = ViewModeEnum.EditForm;
        }

        // Analyze the action parameter
        switch (Action)
        {
        case "new":
        case "convert":
        {
            newdocument = true;

            // Check if document type is allowed under parent node
            if ((ParentNodeID > 0) && (ClassID > 0))
            {
                // Check class
                ci = DataClassInfoProvider.GetDataClassInfo(ClassID);
                if (ci == null)
                {
                    throw new Exception("[Content/Edit.aspx]: Class ID '" + ClassID + "' not found.");
                }

                if (ci.ClassName.ToLowerCSafe() == "cms.blog")
                {
                    if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Blogs, ObjectActionEnum.Insert))
                    {
                        RedirectToAccessDenied(String.Format(GetString("cmsdesk.bloglicenselimits"), ""));
                    }
                }

                if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Insert))
                {
                    RedirectToAccessDenied(String.Format(GetString("cmsdesk.documentslicenselimits"), ""));
                }

                // Check if need template selection, if so, then redirect to template selection page
                int templateId = TemplateID;
                if (!ProductSection && ci.ClassShowTemplateSelection && (templateId < 0))
                {
                    URLHelper.Redirect("~/CMSModules/Content/CMSDesk/TemplateSelection.aspx" + RequestContext.CurrentQueryString);
                }

                // Set default template ID
                formElem.DefaultPageTemplateID = (templateId > 0) ? templateId : ci.ClassDefaultPageTemplateID;

                string newClassName = ci.ClassName;
                formElem.FormName = newClassName + ".default";

                DocumentManager.Mode               = FormModeEnum.Insert;
                DocumentManager.ParentNodeID       = ParentNodeID;
                DocumentManager.NewNodeCultureCode = ParentCulture;
                DocumentManager.NewNodeClassID     = ClassID;

                // Check allowed document type
                TreeNode parentNode = DocumentManager.ParentNode;
                if ((parentNode == null) || !DocumentHelper.IsDocumentTypeAllowed(parentNode, ClassID))
                {
                    AddNotAllowedScript("child");
                }

                if (!currentUser.IsAuthorizedToCreateNewDocument(DocumentManager.ParentNode, DocumentManager.NewNodeClassName))
                {
                    AddNotAllowedScript("new");
                }
            }

            if (RequiresDialog)
            {
                SetTitle(GetString("Content.NewTitle"));
            }
            else
            {
                EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: String.Format(GetString("content.newdocument"), ci.ClassDisplayName));
            }
        }
        break;

        case "newculture":
        {
            newculture = true;
            int nodeId = QueryHelper.GetInteger("nodeid", 0);
            DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion;
            formElem.NodeID      = nodeId;

            // Check permissions
            bool authorized = false;
            if (nodeId > 0)
            {
                // Get the node
                TreeNode treeNode = DocumentManager.Tree.SelectSingleNode(nodeId);
                if (treeNode != null)
                {
                    DocumentManager.NewNodeClassID     = treeNode.GetIntegerValue("NodeClassID", 0);
                    DocumentManager.ParentNodeID       = ParentNodeID;
                    DocumentManager.NewNodeCultureCode = ParentCulture;
                    DocumentManager.SourceDocumentID   = QueryHelper.GetInteger("sourcedocumentid", 0);
                    authorized = currentUser.IsAuthorizedToCreateNewDocument(treeNode.NodeParentID, treeNode.NodeClassName);

                    if (authorized)
                    {
                        string className = DocumentManager.NewNodeClassName;
                        if (className.ToLowerCSafe() == "cms.blog")
                        {
                            if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Blogs, ObjectActionEnum.Insert))
                            {
                                RedirectToAccessDenied(String.Format(GetString("cmsdesk.bloglicenselimits"), ""));
                            }
                        }

                        if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Insert))
                        {
                            RedirectToAccessDenied(String.Format(GetString("cmsdesk.documentslicenselimits"), ""));
                        }

                        ci = DataClassInfoProvider.GetDataClassInfo(className);
                        formElem.FormName = className + ".default";
                    }

                    // Setup page title
                    PageTitle.TitleText = GetString("Content.NewCultureVersionTitle");
                }
            }

            if (!authorized)
            {
                AddNotAllowedScript("newculture");
            }

            if (RequiresDialog)
            {
                SetTitle(GetString("content.newcultureversiontitle"));
            }
            else
            {
                if (!IsProductsUI)
                {
                    EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: GetString("content.newcultureversiontitle"));
                }
            }
        }
        break;

        default:
        {
            TreeNode node = Node;
            if (node == null)
            {
                RedirectToNewCultureVersionPage();
            }
            else
            {
                EnableSplitMode      = true;
                DocumentManager.Mode = FormModeEnum.Update;
                ci = DataClassInfoProvider.GetDataClassInfo(node.NodeClassName);
                if (RequiresDialog)
                {
                    menuElem.ShowSaveAndClose = true;

                    // Add the document name to the properties header title
                    string nodeName = node.GetDocumentName();
                    // Get name for root document
                    if (node.IsRoot())
                    {
                        nodeName = SiteContext.CurrentSite.DisplayName;
                    }

                    SetTitle(GetString("Content.EditTitle") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(nodeName)) + "\"");
                }
            }
        }
        break;
        }

        formElem.Visible = true;

        // Display / hide the CK editor toolbar area
        FormInfo fi = FormHelper.GetFormInfo(ci.ClassName, false);

        if (fi.UsesHtmlArea())
        {
            // Add script to display toolbar
            if (formElem.HtmlAreaToolbarLocation.ToLowerCSafe() == "out:cktoolbar")
            {
                mShowToolbar = true;
            }
        }

        // Init form for product section edit
        if (ProductSection)
        {
            // Form prefix
            formElem.FormPrefix = "ecommerce";

            // Hide Apply workflow action
            menuElem.ShowApplyWorkflow = false;
        }

        if (RequiresDialog)
        {
            plcCKFooter.Visible = false;
        }
    }
Esempio n. 36
0
 /// <summary>
 /// 从实体载入数据到窗体上
 /// </summary>
 /// <param name="entity">实体</param>
 protected void LoadData(object entity)
 {
     FormHelper.SetDataToForm(this, entity);
 }
        /// <summary>
		/// Retrieve all Buggs matching the search criteria.
		/// </summary>
		/// <param name="FormData">The incoming form of search criteria from the client.</param>
		/// <param name="BuggIDToBeAddedToJira">ID of the bugg that will be added to JIRA</param>
		/// <returns>A view to display the filtered Buggs.</returns>
		private ReportsViewModel GetResults( FormHelper FormData, int BuggIDToBeAddedToJira )
		{
            var branchName = FormData.BranchName ?? "";
            var startDate = FormData.DateFrom;
            var endDate = FormData.DateTo;

            return GetResults(branchName, startDate, endDate, BuggIDToBeAddedToJira);
		}
Esempio n. 38
0
 /// <summary>
 /// 初始化操作习惯,比如按回车等效于Tab
 /// </summary>
 protected void InitHabit()
 {
     FormHelper.InitHabitToForm(this);
 }
		public void SetUp()
		{
			var en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture = en;
			Thread.CurrentThread.CurrentUICulture = en;

			Layout = null;
			PropertyBag = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
			Helpers = new HelperDictionary();
			var services = new StubMonoRailServices
			               	{
			               		UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), new StubRoutingEngine()),
			               		UrlTokenizer = new DefaultUrlTokenizer(),
			               		CacheProvider = new StubCacheProvider()
			               	};
			services.AddService(typeof(ICacheProvider), services.CacheProvider);

			var urlInfo = new UrlInfo(
				"example.org", "test", "", "http", 80,
				"http://test.example.org/test_area/test_controller/test_action.tdd",
				Area, ControllerName, Action, "tdd", "no.idea");
			Response = new StubResponse();
			EngineContext = new StubEngineContext(new StubRequest(), Response, services,
			                                          urlInfo);

			services.AddService(typeof(IEngineContext), EngineContext);
			EngineContext.AddService<IEngineContext>(EngineContext);

			EngineContext.AddService<IUrlBuilder>(services.UrlBuilder);
			EngineContext.AddService<IUrlTokenizer>(services.UrlTokenizer);
			EngineContext.AddService<ICacheProvider>(services.CacheProvider);

			ViewComponentFactory = new DefaultViewComponentFactory();
			ViewComponentFactory.Service(EngineContext);

			EngineContext.AddService<IViewComponentFactory>(ViewComponentFactory);
			services.AddService(typeof(IViewComponentFactory), ViewComponentFactory);

			EngineContext.AddService<IViewComponentDescriptorProvider>(new DefaultViewComponentDescriptorProvider());
			services.AddService(typeof(IViewComponentDescriptorProvider), EngineContext.GetService<IViewComponentDescriptorProvider>());

			ControllerContext = new ControllerContext { Helpers = Helpers, PropertyBag = PropertyBag };
			EngineContext.CurrentControllerContext = ControllerContext;

			Helpers["formhelper"] = Helpers["form"] = new FormHelper(EngineContext);
			Helpers["urlhelper"] = Helpers["url"] = new UrlHelper(EngineContext);
			Helpers["dicthelper"] = Helpers["dict"] = new DictHelper(EngineContext);
			Helpers["DateFormatHelper"] = Helpers["DateFormat"] = new DateFormatHelper(EngineContext);

			var viewPath = Path.Combine(ViewSourcePath, "Views");

			var loader = new FileAssemblyViewSourceLoader(viewPath);

			services.ViewSourceLoader = loader;
			services.AddService(typeof(IViewSourceLoader), services.ViewSourceLoader);
			EngineContext.AddService<IViewSourceLoader>(services.ViewSourceLoader);

			Controller = new BaseTestFixtureController();
			Controller.Contextualize(EngineContext, ControllerContext);

			VelocityViewEngine = new NVelocityViewEngine();
			services.AddService(typeof(IViewEngine), VelocityViewEngine);
			EngineContext.AddService<IViewEngine>(VelocityViewEngine);

			VelocityViewEngine.SetViewSourceLoader(loader);
			VelocityViewEngine.Service(services);

			var viewEngineManager = new DefaultViewEngineManager();
			viewEngineManager.RegisterEngineForExtesionLookup(VelocityViewEngine);
			services.EmailTemplateService = new EmailTemplateService(viewEngineManager);

			BeforEachTest();
		}
Esempio n. 40
0
 protected virtual bool Save()
 {
     if (this.entity == null)
     {
         log.Debug("实体为空,开始创建实体!");
         this.entity = this.GetEntity();
     }
     log.Debug("从窗体上获取实体值!");
     FormHelper.GetDataFromForm(this, entity);
     log.Debug("保存或者创建新实体之前的动作!");
     this.BeforeSave(entity);
     if (this.lbId.Text.Length == 0 || this.lbId.Text.Trim() == "0")
     {
         log.Debug("开始检查创建新实体的数据校验!");
         if (this.CheckBeforeCreate())
         {
             log.Debug("开始把新实体插入数据库前的数据组合!");
             this.BeforeCreateEntity(entity);
             if (SimpleOrmOperator.Create(entity))
             {
                 log.Debug("插入数据库完成,并准备同步数据!");
                 this.AfterSuccessCreate();
                 FormHelper.SetDataToForm(this, entity);
                 MessageBoxHelper.Show("添加成功!");
                 if (refresher != null)
                 {
                     refresher.Add(entity);
                 }
             }
             else
             {
                 MessageBoxHelper.Show("添加失败!");
                 return(false);
             }
         }
         else
         {
             //MessageBoxHelper.Show("添加失败!");
             return(false);
         }
     }
     else
     {
         log.Debug("开始检查更新新实体的数据校验!");
         if (this.CheckBeforeUpdate())
         {
             log.Debug("开始把新实体更新数据库前的数据组合!");
             this.BeforeUpdateEntity(entity);
             if (SimpleOrmOperator.Update(entity))
             {
                 log.Debug("更新新实体成功,并准备数据库同步!");
                 this.AfterSuccessUpdate();
                 MessageBoxHelper.Show("修改成功!");
                 if (refresher != null)
                 {
                     refresher.Update(entity);
                 }
             }
             else
             {
                 MessageBoxHelper.Show("修改失败!");
                 return(false);
             }
         }
         else
         {
             return(false);
         }
     }
     return(true);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (EditedObject == null)
        {
            RedirectToAccessDenied(GetString("general.invalidparameters"));
        }

        Save += btnOK_Click;

        // Check permissions for CMS Desk -> Tools
        var user = MembershipContext.AuthenticatedUser;

        if (!user.IsAuthorizedPerUIElement("CMS", "CMSDesk.Content"))
        {
            RedirectToUIElementAccessDenied("CMS", "CMSDesk.Content");
        }

        // Check permissions for CMS Desk -> Tools -> BizForms
        if (!user.IsAuthorizedPerUIElement("cms.form", "Form"))
        {
            RedirectToUIElementAccessDenied("cms.form", "Form");
        }

        // Check 'ReadData' permission
        if (!user.IsAuthorizedPerResource("cms.form", "ReadData", SiteInfoProvider.GetSiteName(FormInfo.FormSiteID)))
        {
            RedirectToAccessDenied("cms.form", "ReadData");
        }

        // Check authorized roles for this form
        if (!FormInfo.IsFormAllowedForUser(MembershipContext.AuthenticatedUser.UserName, SiteContext.CurrentSiteName))
        {
            RedirectToAccessDenied(GetString("Bizforms.FormNotAllowedForUserRoles"));
        }

        List <String> columnNames  = null;
        DataClassInfo dci          = null;
        Hashtable     reportFields = new Hashtable();
        FormInfo      fi           = null;

        // Initialize controls
        PageTitle.TitleText = GetString("BizForm_Edit_Data_SelectFields.Title");
        CurrentMaster.DisplayActionsPanel = true;

        HeaderActions.AddAction(new HeaderAction
        {
            Text          = GetString("UniSelector.SelectAll"),
            OnClientClick = "ChangeFields(true); return false;",
            ButtonStyle   = ButtonStyle.Default,
        });

        HeaderActions.AddAction(new HeaderAction
        {
            Text          = GetString("UniSelector.DeselectAll"),
            OnClientClick = "ChangeFields(false); return false;",
            ButtonStyle   = ButtonStyle.Default,
        });

        if (!RequestHelper.IsPostBack())
        {
            if (FormInfo != null)
            {
                // Get dataclass info
                dci = DataClassInfoProvider.GetDataClassInfo(FormInfo.FormClassID);

                if (dci != null)
                {
                    // Get columns names
                    fi = FormHelper.GetFormInfo(dci.ClassName, false);

                    columnNames = fi.GetColumnNames(false);
                }

                // Get report fields
                if (String.IsNullOrEmpty(FormInfo.FormReportFields))
                {
                    reportFields = LoadReportFields(columnNames);
                }
                else
                {
                    reportFields.Clear();

                    foreach (string field in FormInfo.FormReportFields.Split(';'))
                    {
                        // Add field key to hastable
                        reportFields[field] = null;
                    }
                }

                if (columnNames != null)
                {
                    FormFieldInfo ffi  = null;
                    ListItem      item = null;

                    MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + FormInfo.ClassName);

                    foreach (string name in columnNames)
                    {
                        ffi = fi.GetFormField(name);

                        // Add checkboxes to the list
                        item = new ListItem(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(GetFieldCaption(ffi, name, resolver))), name);
                        if (reportFields.Contains(name))
                        {
                            // Select checkbox if field is reported
                            item.Selected = true;
                        }
                        chkListFields.Items.Add(item);
                    }
                }
            }
        }
    }
Esempio n. 42
0
 protected void GetData(object entity)
 {
     FormHelper.GetDataFromForm(this, entity);
 }
Esempio n. 43
0
        private void ManageConnectionControl()
        {
            cManager = ConnectionManager.Instance;
            cManager.RequestPassword += (sender, e) => fHelper.RequestPassword(e.ConnectionDetail);
            cManager.StepChanged += (sender, e) => ccsb.SetMessage(e.CurrentStep);
            cManager.ConnectionSucceed += (sender, e) =>
            {
                var parameter = e.Parameter as ConnectionParameterInfo;
                if (parameter != null)
                {
                    Controls.Remove(parameter.InfoPanel);
                    parameter.InfoPanel.Dispose();
                }

                currentConnectionDetail = e.ConnectionDetail;
                service = e.OrganizationService;
                ccsb.SetConnectionStatus(true, e.ConnectionDetail);
                ccsb.SetMessage(string.Empty);

                if (parameter != null)
                {
                    var control = parameter.ConnectionParmater as UserControl;
                    if (control != null)
                    {
                        var pluginModel = control.Tag as Lazy<IXrmToolBoxPlugin, IPluginMetadata>;
                        if (pluginModel == null)
                        {
                            // Actual Plugin was passed, Just update the plugin's Tab.
                            UpdateTabConnection((TabPage)control.Parent);
                        }
                        else
                        {
                            this.DisplayPluginControl(pluginModel);
                        }
                    }
                    else if (parameter.ConnectionParmater.ToString() == "ApplyConnectionToTabs" && tabControl1.TabPages.Count > 1)
                    {
                        ApplyConnectionToTabs();
                    }
                    else
                    {
                        var args = parameter.ConnectionParmater as RequestConnectionEventArgs;
                        if (args != null)
                        {
                            var userControl = (UserControl)args.Control;

                            args.Control.UpdateConnection(e.OrganizationService, currentConnectionDetail, args.ActionName, args.Parameter);

                            userControl.Parent.Text = string.Format("{0} ({1})",
                                userControl.Parent.Text.Split(' ')[0],
                                e.ConnectionDetail.ConnectionName);
                        }
                    }
                }
                else if (tabControl1.TabPages.Count > 1)
                {
                    ApplyConnectionToTabs();
                }

                this.StartPluginWithConnection();
            };
            cManager.ConnectionFailed += (sender, e) =>
            {
                this.Invoke(new Action(() =>
                {
                    var infoPanel = ((ConnectionParameterInfo)e.Parameter).InfoPanel;
                    Controls.Remove(infoPanel);
                    if (infoPanel != null) infoPanel.Dispose();

                    MessageBox.Show(this, e.FailureReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    currentConnectionDetail = null;
                    service = null;
                    ccsb.SetConnectionStatus(false, null);
                    ccsb.SetMessage(e.FailureReason);

                    this.StartPluginWithConnection();
                }));
            };

            fHelper = new FormHelper(this);
            ccsb = new CrmConnectionStatusBar(fHelper) { Dock = DockStyle.Bottom };
            Controls.Add(ccsb);
        }
Esempio n. 44
0
 private static void LoadClasses()
 {
     formHelper = new FormHelper();
     DataManager.Init();
     IconManager.Init();
     Render.RenderRegistry.Init();
     settingsClass = new Settings();
     updateHelper = new UpdateHelper(Application.StartupPath, Globals.FileDownloadPath, new Version(Application.ProductVersion));
     fullScreenCheck = new FullScreenCheck();
     IconManager.LoadIcons();
 }
Esempio n. 45
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // EntityFactory.CheckEntityAndDB("WEC");
        if (Request["preUrl"] != null)
        {
            preUrl = Request["preUrl"];
        }
        //系统帐套
        if (MyConfigurationSettings.GetValue <string>("CloudSystem") == "1")
        {
            if (DataBase.Factory(BasePage.cloudConn).Exist("A8Account"))
            {
                A8Account        val   = new A8Account();
                List <A8Account> list1 = BLLTable <A8Account> .Factory(BasePage.cloudConn).Select(val);

                if (list1.Count > 0)
                {
                    HtmlSelect sel1 = new HtmlSelect();
                    sel1.Items.AddRange(FormHelper.GetListItem(A8Account.Attribute.ConnectStr, A8Account.Attribute.ConnectStr, A8Account.Attribute.FullName));
                    //sel1.InnerHtml;
                }
            }
        }
        //系统皮肤
        SYS_THEME theme = BLLTable <SYS_THEME> .Factory(conn).GetRowData(SYS_THEME.Attribute.THEME_NAME, _ThemeName);

        if (theme != null && !string.IsNullOrEmpty(theme.LOGIN_HTML))
        {
            Literal lll = new Literal();


            if (Request.Cookies["SYS_USER_USER_NAME"] != null)
            {
                name = Request.Cookies["SYS_USER_USER_NAME"].Value;
            }
            if (MyDebugger.IsAttached)//调试时加快速度
            {
                theme.LOGIN_HTML = theme.LOGIN_HTML.Replace("<%=name %>", "sys");
                theme.LOGIN_HTML = theme.LOGIN_HTML.Replace("name=\"password\"", "name=\"password\" value='123456'");
            }
            theme.LOGIN_HTML = theme.LOGIN_HTML.Replace("<%=name %>", name);

            //原模版有个脚本错误,屏蔽此问题
            //ie下密码为明文
            theme.LOGIN_HTML = theme.LOGIN_HTML.Replace("name=\"password\" type=\"text\"", "name=\"password\" type=\"password");

            lll.Text = theme.LOGIN_HTML;
            phLogin.Controls.Add(lll);

            string   appPath = WebHelper.GetAppPath();
            HtmlLink css     = new HtmlLink();
            css.Href = appPath + "Themes/" + _ThemeName + "/index.css";
            css.Attributes.Add("rel", "stylesheet");
            css.Attributes.Add("type", "text/css");

            this.Page.Header.Controls.Add(css);

            if (AgileFrame.Core.MyConfigurationSettings.GetValue("User_IsRunMode") == "Developer")
            {
                css      = new HtmlLink();
                css.Href = appPath + "Themes/" + _ThemeName + "/dev_index.css";
                css.Attributes.Add("rel", "stylesheet");
                css.Attributes.Add("type", "text/css");
                this.Page.Header.Controls.Add(css);
            }
        }
        else
        {
            phLogin.Controls.Add(TemplateControl.LoadControl("~/Themes/" + _ThemeName + "/Login.ascx"));
        }

        //string strIdentity = User.Identity.Name;
        //if (!string.IsNullOrEmpty(strIdentity))
        //{
        //    SYS_USER user = new SYS_USER();
        //    user = BLLTable<SYS_USER>.Factory(conn).GetRowData(SYS_USER.Attribute.USER_NAME, strIdentity);
        //    if (user != null)
        //    {
        //        bool tostaff = PowerHelper.SetCurLoginUser(user);
        //        if (tostaff == true)
        //        {
        //            Response.Redirect("Index.aspx");
        //        }
        //        else
        //        {
        //            AgileFrame.Core.ScriptHelper.Alert(Page, "您的用户未与员工信息关联,请联系管理员处理。");
        //        }
        //    }
        //}
        //if (MyDebugger.IsAttached)
        //{
        //    Response.Redirect("LoginBack.aspx?username=sys&password=123456");
        //}
    }
Esempio n. 46
0
        public IActionResult AddNews(string id, long menuId, int sortId, string videoSource)
        {
            //权限
            if (!this.HasPermission(PermissionEnum.Edit))
            {
                return(this.GetResult(false, "无操作权限!"));
            }
            var menu = this.GetMenu(menuId);

            if (menu == null)
            {
                return(this.GetResult(false, "无访问权限!"));
            }
            //是否为单篇文章
            var isArticle = menu.Config == null || menu.Config.Fields == null || menu.Config.Fields.Count == 0;

            using (var db = this.GetMongodb())
            {
                try
                {
                    ActionHistory actionHistory = null;
                    Article       article       = null;
                    var           isNew         = string.IsNullOrEmpty(id);
                    if (isNew)
                    {
                        var lang = $"{Request.Form["Lang"]}".ToUpper();
                        if (string.IsNullOrEmpty(lang))
                        {
                            lang = this.Languages[0].id;
                        }
                        if (isArticle)
                        {
                            article = db.Articles.FirstOrDefault(a => a.MenuId == menuId && a.SortId == sortId && a.Lang == lang);
                        }
                        isNew = article == null;
                        if (isNew)
                        {
                            article          = new Article();
                            article.NumberId = db.Articles.GetId() + 100000;
                            article.ByOrder  = article.NumberId - 100000;
                            article.MenuId   = menuId;
                            article.SortId   = sortId;
                            article.AddDate  = DateTime.Now;
                        }
                    }
                    else
                    {
                        article = db.Articles.FirstOrDefault(a => a.Id == id && a.MenuId == menuId);
                        #region 记录修改历史
                        if (menu.HasFlag(MenuFlag.RecordHistory))
                        {
                            actionHistory = new ActionHistory()
                            {
                                TargetId   = article.Id.ToString(),
                                LastModify = DateTime.Now,
                                ModifyUser = this.LoginId,
                                IP         = HttpHelper.GetIP(),
                                Type       = ActionType.Article,
                                MenuId     = article.MenuId,
                                SortId     = article.SortId,
                                Before     = JsonHelper.ToJson(article)
                            };
                        }
                        #endregion
                    }
                    #region 处理视频
                    //var file = Request.Files["Video"];
                    //if (file != null && file.ContentLength > 0)
                    //{
                    //    if (file.ContentLength > 524288000)
                    //        return this.GetResult(new Exception("视频文件不能大于500M"));
                    //    if (!FormHelper.IsVideo(file.FileName))
                    //        return this.GetResult(new Exception("不支持的视频格式!"));
                    //    var savePath = $"/upFiles/article/{article.Id}/video";
                    //    var fileName = string.Format("{0}/{1}{2}", savePath, CommonHelper.GenerateOrderNumber().Substring(7), Path.GetExtension(file.FileName));
                    //    file.SaveAs(FormHelper.MapPath(fileName));
                    //    article.Video = fileName;
                    //}
                    //else
                    //{
                    //    article.Video = Request.Form["Video"];
                    //}
                    #endregion

                    List <FormField> fields = new List <FormField>();
                    fields.Add(new TextField("MenuId"));
                    fields.Add(new TextField("SortId"));
                    fields.Add(new TextField("Publish"));

                    #region 解析菜单设置
                    var config = menu.Config;
                    if (config != null && config.Fields.Count > 0)
                    {
                        foreach (var item in config.Fields)
                        {
                            var fieldType = Enum.Parse <MenuFieldType>(item.Type);
                            if (fieldType == MenuFieldType.Image)
                            {
                                var imageField = new ImageField(item.Name)
                                {
                                    Text = item.Title, SavePath = $"/upFiles/article/{article.Id}/{item.Name}", MaxLength = item.MaxLength > 0 ? item.MaxLength * 1024 : 2048, Required = item.Required
                                };
                                if (item.MaxSize != null && item.MaxSize.Width > 0 && item.MaxSize.Height > 0)
                                {
                                    imageField.Compress     = true;
                                    imageField.CompressSize = new System.Drawing.Size(item.MaxSize.Width, item.MaxSize.Height.GetValueOrDefault());
                                }
                                fields.Add(imageField);
                            }
                            else if (fieldType == MenuFieldType.Video)
                            {
                                if (videoSource == "1")
                                {
                                    fields.Add(new FormField()
                                    {
                                        Name = item.Name, Text = item.Title, Required = item.Required
                                    });
                                }
                                else
                                {
                                    fields.Add(new VideoField(item.Name)
                                    {
                                        Text = item.Title, SavePath = $"/upFiles/article/{article.Id}/{item.Name}", MaxLength = item.MaxLength > 0 ? item.MaxLength * 1024 : 51200, Required = item.Required
                                    });
                                }
                            }
                            else if (fieldType == MenuFieldType.File)
                            {
                                fields.Add(new FileField(item.Name)
                                {
                                    Text = item.Title, SavePath = $"/upFiles/article/{article.Id}/{item.Name}", MaxLength = item.MaxLength > 0 ? item.MaxLength * 1024 : 20480, Required = item.Required
                                });
                            }
                            else if (fieldType == MenuFieldType.Editor || fieldType == MenuFieldType.SmallEditor)
                            {
                                fields.Add(new EditorField(item.Name)
                                {
                                    Text = item.Title, Required = item.Name == "Content" ? true : item.Required, XXSFilter = false
                                });
                            }
                            else
                            {
                                fields.Add(new TextField(item.Name)
                                {
                                    Text = item.Title
                                });
                            }
                        }
                    }
                    else
                    {
                        fields.Add(new EditorField("Content")
                        {
                            Text = "文章内容", Required = true, XXSFilter = false
                        });
                    }
                    #endregion

                    FormHelper.SafeFill(article, fields.ToArray());

                    var isShowAudit = menu.HasFlag(MenuFlag.Audit) && HasPermission(PermissionEnum.Audit);
                    if (isShowAudit)
                    {
                        article.Publish = false;
                    }

                    #region 保存标签
                    if (article.Tags != null && article.Tags.Count > 0)
                    {
                        foreach (var tag in article.Tags)
                        {
                            if (!db.Labels.Any(a => a.MenuId == menuId && a.Sort == sortId && a.Name == tag))
                            {
                                db.Labels.Add(new Label()
                                {
                                    Name   = tag,
                                    MenuId = menuId,
                                    Sort   = sortId
                                });
                            }
                        }
                    }
                    #endregion
                    if (string.IsNullOrEmpty(article.Lang))
                    {
                        article.Lang = this.Languages[0].id;
                    }
                    article.LastModify = DateTime.Now;
                    if (menu.HasFlag(MenuFlag.Audit))
                    {
                        article.Status = (int)AuditingStatus.Waiting;
                    }
                    else
                    {
                        article.Status = (int)AuditingStatus.Success;
                    }
                    article.ModifyUser = this.LoginId;
                    #region 记录更新历史
                    if (actionHistory != null)
                    {
                        actionHistory.After = JsonHelper.ToJson(article);
                        db.ActionHistories.Add(actionHistory);
                    }
                    #endregion
                    db.Articles.Save(article);
                    return(this.GetResult(true));
                }
                catch (Exception ex)
                {
                    return(this.GetResult(ex));
                }
            }
        }
Esempio n. 47
0
 public override void Init()
 {
     base.Init();
     _formHlpr = new FormHelper(_helperContext);
     _url = new StubTargetUrl();
 }
Esempio n. 48
0
    protected void Page_Load(object sender, EventArgs e)
    {
        title      = valObj._ZhName + "±à¼­";
        Page.Title = title;
        if (!string.IsNullOrEmpty(Request["KNMA_ID"]))
        {
            keyid = Request["KNMA_ID"];
        }

        if (!string.IsNullOrEmpty(Request["KeyID"]))
        {
            keyid = Request["KeyID"];
        }
        if (!IsPostBack)
        {
            txtCLASS_ID.Items.AddRange(FormHelper.GetListItem(KM_KNMA.Attribute.CLASS_ID));
            txtUP_TYPE.Items.AddRange(FormHelper.GetListItem(KM_KNMA.Attribute.UP_TYPE));
            txtEA_SIGN.Items.AddRange(FormHelper.GetListItem(KM_KNMA.Attribute.EA_SIGN));
            txtADD_TIME.Value  = (DateTime.Now).ToString("yyyy-MM-dd");
            txtEDIT_TIME.Value = (DateTime.Now).ToString("yyyy-MM-dd");
            txtCAN_EDIT.Items.AddRange(FormHelper.GetListItem(KM_KNMA.Attribute.CAN_EDIT));
            txtCAN_COMMENTS.Items.AddRange(FormHelper.GetListItem(KM_KNMA.Attribute.CAN_COMMENTS));

            this.txtKNMA_ID.Disabled            = true;
            this.txtKNMA_ID.Attributes["class"] = "dis";
            try
            {
                if (keyid != "")
                {
                    valObj = BLLTable <KM_KNMA> .Factory(conn).GetRowData(KM_KNMA.Attribute.KNMA_ID, keyid);

                    if (valObj == null)
                    {
                        return;
                    }


                    txtKNMA_ID.Value = Convert.ToString(valObj.KNMA_ID);     //Convert.ToString

                    txtKNMA_NAME.Value = Convert.ToString(valObj.KNMA_NAME); //Convert.ToString

                    txtP_KNMA_ID.Value = Convert.ToString(valObj.P_KNMA_ID); //Convert.ToString

                    txtCONTENT.Value = Convert.ToString(valObj.CONTENT);     //Convert.ToString

                    txtCLASS_ID.Value = valObj.CLASS_ID.ToString();

                    txtUP_TYPE.Value = valObj.UP_TYPE.ToString();

                    txtEA_SIGN.Value = valObj.EA_SIGN.ToString();

                    txtAUTHOR.Value = Convert.ToString(valObj.AUTHOR);   //Convert.ToString

                    txtSORT_NO.Value = Convert.ToString(valObj.SORT_NO); //Convert.ToDecimal

                    txtDEPT_ID.Value = Convert.ToString(valObj.DEPT_ID); //Convert.ToString

                    txtADD_TIME.Value = (valObj.ADD_TIME == DateTime.MinValue) ? "" : valObj.ADD_TIME.ToString("yyyy-MM-dd");

                    txtEDIT_TIME.Value = (valObj.EDIT_TIME == DateTime.MinValue) ? "" : valObj.EDIT_TIME.ToString("yyyy-MM-dd");

                    txtPATH_ID.Value = Convert.ToString(valObj.PATH_ID);//Convert.ToString

                    txtCAN_EDIT.Value = valObj.CAN_EDIT.ToString();

                    txtCAN_COMMENTS.Value = valObj.CAN_COMMENTS.ToString();

                    txtADD_USER.Value = Convert.ToString(valObj.ADD_USER);   //Convert.ToString

                    txtEDIT_USER.Value = Convert.ToString(valObj.EDIT_USER); //Convert.ToString

                    txtS_LEVEL.Value = Convert.ToString(valObj.S_LEVEL);     //Convert.ToString

                    txtEXP1.Value = Convert.ToString(valObj.EXP1);           //Convert.ToString

                    txtEXP2.Value = Convert.ToString(valObj.EXP2);           //Convert.ToString

                    txtEXP3.Value = Convert.ToString(valObj.EXP3);           //Convert.ToString

                    txtEXP4.Value = Convert.ToString(valObj.EXP4);           //Convert.ToString
                }
            }
            catch (Exception ex)
            {
                litWarn.Text = ex.Message;
            }
        }
    }
Esempio n. 49
0
        /// <summary>
        /// Display the main user groups.
        /// </summary>
        /// <param name="formData"></param>
        /// <param name="userName">A form of user data passed up from the client.</param>
        /// <param name="userGroup">The name of the current user group to display users for.</param>
        /// <returns>A view to show a list of users in the current user group.</returns>
        public ActionResult Index(FormCollection formData, string userName, string userGroup = "General")
        {
            UsersViewModel model;

            using (var unitOfWork = new UnitOfWork(new CrashReportEntities()))
            {
                var group = unitOfWork.UserGroupRepository.First(data => data.Name == userGroup);

                if (!string.IsNullOrWhiteSpace(userName))
                {
                    var user = unitOfWork.UserRepository.GetByUserName(userName);
                    if (user != null && group != null)
                    {
                        user.UserGroup = group;
                        unitOfWork.UserRepository.Update(user);
                        unitOfWork.Save();
                    }
                }

                var formhelper = new FormHelper(Request, formData, "");
                var skip       = (formhelper.Page - 1) * formhelper.PageSize;
                var take       = formhelper.PageSize;

                model = new UsersViewModel
                {
                    UserGroup = userGroup,
                    User      = userName,
                    Users     =
                        unitOfWork.UserRepository.ListAll()
                        .Where(data => data.UserGroupId == @group.Id)
                        .OrderBy(data => data.UserName)
                        .Skip(skip)
                        .Take(take)
                        .Select(data => new UserViewModel()
                    {
                        Name = data.UserName, UserGroup = data.UserGroup.Name
                    })
                        .ToList()
                };

                var groupCounts =
                    unitOfWork.UserRepository.ListAll()
                    .GroupBy(data => data.UserGroup)
                    .Select(data => new { Key = data.Key, Count = data.Count() })
                    .ToDictionary(groupCount => groupCount.Key.Name, groupCount => groupCount.Count);

                model.GroupSelectList =
                    groupCounts.Select(
                        listItem =>
                        new SelectListItem
                {
                    Selected = listItem.Key == userGroup,
                    Text     = listItem.Key,
                    Value    = listItem.Key
                }).ToList();
                model.GroupCounts = groupCounts;
                model.PagingInfo  = new PagingInfo
                {
                    CurrentPage  = formhelper.Page,
                    PageSize     = formhelper.PageSize,
                    TotalResults = unitOfWork.UserRepository.ListAll().Count(data => data.UserGroupId == group.Id)
                };
            }

            return(View("Index", model));
        }
Esempio n. 50
0
        /// <summary>
        /// Provides operations necessary to create and store new cms file.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleContentUpload(UploaderHelper args, HttpContext context)
        {
            bool   newDocumentCreated = false;
            string name = args.Name;

            try
            {
                if (args.FileArgs.NodeID == 0)
                {
                    throw new Exception(ResHelper.GetString("dialogs.document.parentmissing"));
                }
                // Check license limitations
                if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert))
                {
                    throw new Exception(ResHelper.GetString("cmsdesk.documentslicenselimits"));
                }

                // Check user permissions
                if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(args.FileArgs.NodeID, "CMS.File"))
                {
                    throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), "CMS.File"));
                }

                // Check if class exists
                DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File");
                if (ci == null)
                {
                    throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.classnotfound"), "CMS.File"));
                }


                #region "Check permissions"

                // Get the node
                using (TreeNode parentNode = TreeProvider.SelectSingleNode(args.FileArgs.NodeID, args.FileArgs.Culture, true))
                {
                    if (parentNode != null)
                    {
                        if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID))
                        {
                            throw new Exception(ResHelper.GetString("Content.ChildClassNotAllowed"));
                        }
                    }
                    // Check user permissions
                    if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(parentNode, "CMS.File"))
                    {
                        throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), args.AttachmentArgs.NodeClassName));
                    }
                }

                #endregion


                args.IsExtensionAllowed();

                if (args.FileArgs.IncludeExtension)
                {
                    name += args.Extension;
                }

                // Make sure the file name with extension respects maximum file name
                name = TreePathUtils.EnsureMaxFileNameLength(name, ci.ClassName);

                node = TreeNode.New("CMS.File", TreeProvider);
                node.DocumentCulture = args.FileArgs.Culture;
                node.DocumentName    = name;
                if (args.FileArgs.NodeGroupID > 0)
                {
                    node.SetValue("NodeGroupID", args.FileArgs.NodeGroupID);
                }

                // Load default values
                FormHelper.LoadDefaultValues(node.NodeClassName, node);

                node.SetValue("FileDescription", "");
                node.SetValue("FileName", name);
                node.SetValue("FileAttachment", Guid.Empty);
                node.SetValue("DocumentType", args.Extension);

                node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID);

                // Insert the document
                DocumentHelper.InsertDocument(node, args.FileArgs.NodeID, TreeProvider);
                newDocumentCreated = true;

                // Add the attachment data
                DocumentHelper.AddAttachment(node, "FileAttachment", args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);

                // Create default SKU if configured
                if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))
                {
                    node.CreateDefaultSKU();
                }

                DocumentHelper.UpdateDocument(node, TreeProvider);

                // Get workflow info
                wi = node.GetWorkflow();

                // Check if auto publish changes is allowed
                if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName))
                {
                    // Automatically publish document
                    node.MoveToPublishedStep(null);
                }
            }
            catch (Exception ex)
            {
                // Delete the document if something failed
                if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
                {
                    DocumentHelper.DeleteDocument(node, TreeProvider, false, true, true);
                }

                args.Message = ex.Message;

                // Log the error
                EventLogProvider.LogException("MultiFileUploader", "UPLOADATTACHMENT", ex);
            }
            finally
            {
                // Create node info string
                string nodeInfo = ((node != null) && (node.NodeID > 0) && args.IncludeNewItemInfo) ? String.Format("'{0}', ", node.NodeID) : "";

                // Ensure message text
                args.Message = HTMLHelper.EnsureLineEnding(args.Message, " ");

                // Call function to refresh parent window
                if (!string.IsNullOrEmpty(args.AfterSaveJavascript))
                {
                    // Calling javascript function with parameters attachments url, name, width, height
                    args.AfterScript += string.Format(@"
                    if (window.{0} != null)
                    {{
                        window.{0}();
                    }}
                    else if((window.parent != null) && (window.parent.{0} != null))
                    {{
                        window.parent.{0}();
                    }}", args.AfterSaveJavascript);
                }

                // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end
                args.AfterScript += string.Format(@"
                if (window.InitRefresh_{0} != null)
                {{
                    window.InitRefresh_{0}('{1}', false, false, {2});
                }}
                else {{ 
                    if ('{1}' != '') {{
                        alert('{1}');
                    }}
                }}",
                                                  args.ParentElementID,
                                                  ScriptHelper.GetString(args.Message.Trim(), false),
                                                  nodeInfo + (args.IsInsertMode ? "'insert'" : "'update'"));

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
Esempio n. 51
0
 public DockContent()
 {
     _fixer = new FormHelper(this);
     _fixer.EnableBoundsTracking = false;
 }
		/// <summary>
		/// Retrieve all Buggs matching the search criteria.
		/// </summary>
		/// <param name="FormData">The incoming form of search criteria from the client.</param>
		/// <returns>A view to display the filtered Buggs.</returns>
		public CSV_ViewModel GetResults( FormHelper FormData )
		{
			using( FAutoScopedLogTimer LogTimer = new FAutoScopedLogTimer( this.GetType().ToString() ) )
			{
			    var anonymousGroup = _unitOfWork.UserGroupRepository.First(data => data.Name == "Anonymous");
                var anonymousGroupId = anonymousGroup.Id;
			    var anonumousIDs = new HashSet<int>(anonymousGroup.Users.Select(data => data.Id));
                var anonymousID = anonumousIDs.First();
                var userNamesForUserGroup = new HashSet<string>(anonymousGroup.Users.Select(data => data.UserName));

                // Enable to narrow results and improve debugging performance.
                //FormData.DateFrom = FormData.DateTo.AddDays( -1 );
                //FormData.DateTo = FormData.DateTo.AddDays( 1 );

                var FilteringQueryJoin = _unitOfWork.CrashRepository
                    .ListAll()
                    .Where(c => c.EpicAccountId != "")
                    // Only crashes and asserts
                    .Where(c => c.CrashType == 1 || c.CrashType == 2)
                    // Only anonymous user
                    .Where(c => c.UserNameId == anonymousID)
                    // Filter be date
                    .Where(c => c.TimeOfCrash > FormData.DateFrom && c.TimeOfCrash < FormData.DateTo)
                    .Select
                    (
                        c => new
                        {
                            GameName = c.GameName,
                            TimeOfCrash = c.TimeOfCrash.Value,
                            BuiltFromCL = c.ChangeListVersion,
                            PlatformName = c.PlatformName,
                            EngineMode = c.EngineMode,
                            MachineId = c.ComputerName,
                            Module = c.Module,
                            BuildVersion = c.BuildVersion,
                            Jira = c.Jira,
                            Branch = c.Branch,
                            CrashType = c.CrashType,
                            EpicId = c.EpicAccountId,
                            BuggId = c.Buggs.First().Id
                        }
                    );

                var FilteringQueryCrashes = _unitOfWork.CrashRepository
                    .ListAll()
                    .Where(c => c.EpicAccountId != "")
                    // Only crashes and asserts
                    .Where(c => c.CrashType == 1 || c.CrashType == 2)
                    // Only anonymous user
                    .Where(c => c.UserNameId == anonymousID);

                //Server timeout
                int TotalCrashes = _unitOfWork.CrashRepository.ListAll().Count();

                int TotalCrashesYearToDate = _unitOfWork.CrashRepository
                    .ListAll().Count(c => c.TimeOfCrash > new DateTime(DateTime.UtcNow.Year, 1, 1));

                var CrashesFilteredWithDateQuery = FilteringQueryCrashes
                    // Filter be date
                    .Where(c => c.TimeOfCrash > FormData.DateFrom && c.TimeOfCrash < FormData.DateTo);

                int CrashesFilteredWithDate = CrashesFilteredWithDateQuery
                    .Count();

                int CrashesYearToDateFiltered = FilteringQueryCrashes.Count(c => c.TimeOfCrash > new DateTime( DateTime.UtcNow.Year, 1, 1 ));

                //DB server timeout
                int AffectedUsersFiltered = FilteringQueryCrashes.Select( c => c.EpicAccountId ).Distinct().Count();

                //DB server time out
                int UniqueCrashesFiltered = FilteringQueryCrashes.Select( c => c.Pattern ).Count();

                int NumCrashes = FilteringQueryJoin.Count();
                
                // Export data to the file.
                string CSVPathname = Path.Combine(Settings.Default.CrashReporterCSV, DateTime.UtcNow.ToString("yyyy-MM-dd.HH-mm-ss"));
                CSVPathname += string
                    .Format("__[{0}---{1}]__{2}",
                    FormData.DateFrom.ToString("yyyy-MM-dd"),
                    FormData.DateTo.ToString("yyyy-MM-dd"),
                    NumCrashes)
                    + ".csv";

                string ServerPath = Server.MapPath(CSVPathname);
                var CSVFile = new StreamWriter(ServerPath, true, Encoding.UTF8);

                using (FAutoScopedLogTimer ExportToCSVTimer = new FAutoScopedLogTimer("ExportToCSV"))
                {
                    var RowType = FilteringQueryJoin.FirstOrDefault().GetType();

                    string AllProperties = "";
                    foreach (var Property in RowType.GetProperties())
                    {
                        AllProperties += Property.Name;
                        AllProperties += "; ";
                    }

                    // Write header
                    CSVFile.WriteLine(AllProperties);

                    foreach (var Row in FilteringQueryJoin)
                    {
                        var BVParts = Row.BuildVersion.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                        if (BVParts.Length > 2 && BVParts[0] != "0")
                        {
                            string CleanEngineVersion = string.Format("{0}.{1}.{2}", BVParts[0], BVParts[1], BVParts[2]);

                            string[] RowProperties = new string[]
                            {
                                Row.GameName,
                                Row.TimeOfCrash.ToString(),
                                Row.BuiltFromCL,
                                Row.PlatformName,
                                Row.EngineMode,
                                Row.MachineId,
                                Row.Module,
                                CleanEngineVersion,
                                Row.Jira,
                                Row.Branch,
                                Row.CrashType == 1 ? "Crash" : "Assert",
                                Row.EpicId,
                                Row.BuggId.ToString()
                            };

                            string JoinedLine = string.Join("; ", RowProperties);
                            JoinedLine += "; ";

                            CSVFile.WriteLine(JoinedLine);
                        }
                    }

                    CSVFile.Flush();
                    CSVFile.Close();
                    CSVFile = null;
                }

                List<FCSVRow> CSVRows = FilteringQueryJoin
                    .OrderByDescending(X => X.TimeOfCrash)
                    .Take(32)
                    .Select(c => new FCSVRow
                    {
                        GameName = c.GameName,
                        TimeOfCrash = c.TimeOfCrash,
                        BuiltFromCL = c.BuiltFromCL,
                        PlatformName = c.PlatformName,
                        EngineMode = c.EngineMode,
                        MachineId = c.MachineId,
                        Module = c.Module,
                        BuildVersion = c.BuildVersion,
                        Jira = c.Jira,
                        Branch = c.Branch,
                        CrashType = c.CrashType,
                        EpicId = c.EpicId,
                        BuggId = c.BuggId,
                    })
                    .ToList();

			    return new CSV_ViewModel()
                {
                    CSVRows = CSVRows,
                    CSVPathname = CSVPathname,
                    DateFrom = (long)(FormData.DateFrom - CrashesViewModel.Epoch).TotalMilliseconds,
                    DateTo = (long)(FormData.DateTo - CrashesViewModel.Epoch).TotalMilliseconds,
                    DateTimeFrom = FormData.DateFrom,
                    DateTimeTo = FormData.DateTo,
                    AffectedUsersFiltered = AffectedUsersFiltered,
                    UniqueCrashesFiltered = UniqueCrashesFiltered,
                    CrashesFilteredWithDate = CrashesFilteredWithDate,
                    TotalCrashes = TotalCrashes,
                    TotalCrashesYearToDate = TotalCrashesYearToDate,
                };
			}
		}