Example #1
0
    public virtual void Start()
    {
        // Attach Scripts to holders
        sc_ScriptHelper   = Camera.main.GetComponent<ScriptHelper>();
        sc_AudioManager   = sc_ScriptHelper.sc_AudioManager;
        sc_FadeToScene    = sc_ScriptHelper.sc_FadeToScene;
        sc_GameController = sc_ScriptHelper.sc_GameController;
        sc_ScoreTracker   = sc_ScriptHelper.sc_ScoreTracker;

        _Animator = gameObject.GetComponent<Animation>();
    }
Example #2
0
    void Start()
    {
        // Attach Scripts to holders
        sc_ScriptHelper   = Camera.main.GetComponent<ScriptHelper>();
        sc_BallController = sc_ScriptHelper.sc_BallController;
        sc_GameController = sc_ScriptHelper.sc_GameController;
        sc_LevelManager   = sc_ScriptHelper.sc_LevelManager;

        foreach ( Transform child in transform)
        {
            if (child.name == "top")
                TopBoundary = child.gameObject;
            if (child.name == "bottom")
                BottomBoundary = child.gameObject;
            if (child.name == "left")
                LeftBoundary = child.gameObject;
            if (child.name == "right")
                RightBoundary = child.gameObject;
        }
    }
Example #3
0
    void Start()
    {
        // Attach Scripts to holders
        sc_ScriptHelper     = Camera.main.GetComponent<ScriptHelper>();
        sc_BallController   = sc_ScriptHelper.sc_BallController;
        sc_BoundaryManager  = sc_ScriptHelper.sc_BoundaryManager;
        sc_CameraController = sc_ScriptHelper.sc_CameraController;
        sc_GameController   = sc_ScriptHelper.sc_GameController;
        sc_RowManager       = sc_ScriptHelper.sc_RowManager;

        // Set intermission time intertval
        Time_Between_Intermission = 5.0f;

        // Set intermission height
        BallIntermissionHeight = 65;

        // Set speed at which rows move up
        LevelSpeed = 2.0f;
        sc_RowManager.SET_RowSpeed(LevelSpeed);

        StartCoroutine( StartInitermission() );
    }
	protected void cmdTestAlert_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		result += "测试方法 ScriptHelper.Alert(string)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Alert", FunctionType.Method, new Type[] { typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "'你好1'" },
				new object[] { "'\"你好2\"'" }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.Alert(string, bool)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Alert", FunctionType.Method, new Type[] { typeof ( string ), typeof ( bool ) }, null, null, null,
			new object[][] {
				new object[] { "'你好1, 追加? true'", true },
				new object[] { "'\"你好2\", 追加? false'", false }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this );
	}
Example #5
0
	protected void cmdTestVal_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		JQuery jQuery1 = new JQuery ( "'#myTextBox1'" );
		JQuery jQuery2 = new JQuery ( jQuery1 );

		result += "测试方法 JQuery.Val()<br />";

		tracer.Execute ( jQuery1, null, "Val", FunctionType.Method, new Type[] { }, null, null, null,
			new object[][] {
				new object[] { }
			},
			false
			);

		result += "jQuery1.Code = " + jQuery1.Code + "<br />";

		result += "测试方法 JQuery.Val(string)<br />";

		tracer.Execute ( jQuery2, null, "Val", FunctionType.Method, new Type[] { typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "'jack'" }
			},
			false
			);

		result += "jQuery2.Code = " + jQuery2.Code + "<br />";

		ScriptHelper scriptHelper = new ScriptHelper ();
		scriptHelper.Alert ( "'myTextBox1.value = ' + " + jQuery1.Code );

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
		jQuery2.Build ( this, option: ScriptBuildOption.Startup );
	}
Example #6
0
    void Start()
    {
        // Attach Scripts to holders
        sc_ScriptHelper     = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ScriptHelper>();
        sc_GameController   = sc_ScriptHelper.sc_GameController;
        sc_HighScoreManager = sc_ScriptHelper.sc_HighScoreManager;

        // Initialize score text
        score_text = gameObject.GetComponent<TextMesh>();
        score_text.text = "0";

        // If user hit retry or quit, hurry score count
        Hurry_GameOver_ScoreCount = false;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ucSelectString.Scope        = ReportInfo.OBJECT_TYPE;
        pnlConnectionString.Visible = MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.reporting", "SetConnectionString");
        Title = "Report General";

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ReloadPage", ScriptHelper.GetScript("function ReloadPage() { \n" + Page.ClientScript.GetPostBackEventReference(btnHdnReload, null) + "}"));

        reportId = QueryHelper.GetInteger("reportId", 0);

        // control initializations
        rfvReportDisplayName.ErrorMessage = GetString("Report_New.EmptyDisplayName");
        rfvReportName.ErrorMessage        = GetString("Report_New.EmptyCodeName");

        lblReportDisplayName.Text = GetString("Report_New.DisplayNameLabel");
        lblReportName.Text        = GetString("Report_New.NameLabel");
        lblReportCategory.Text    = GetString("Report_General.CategoryLabel");
        lblLayout.Text            = GetString("Report_General.LayoutLabel");
        lblGraphs.Text            = GetString("Report_General.GraphsLabel") + ":";
        lblHtmlGraphs.Text        = GetString("Report_General.HtmlGraphsLabel") + ":";
        lblTables.Text            = GetString("Report_General.TablesLabel") + ":";
        lblValues.Text            = GetString("Report_General.TablesValues") + ":";

        actionsElem.ActionsList.Add(new SaveAction());
        actionsElem.ActionPerformed += actionsElem_ActionPerformed;

        AttachmentTitle.TitleText = GetString("general.attachments");

        attachmentList.AllowPasteAttachments = true;
        attachmentList.ObjectID   = reportId;
        attachmentList.ObjectType = ReportInfo.OBJECT_TYPE;
        attachmentList.Category   = ObjectAttachmentsCategories.LAYOUT;

        // Get report info
        ri = ReportInfoProvider.GetReportInfo(reportId);

        if (ri == null)
        {
            URLHelper.SeeOther(AdministrationUrlHelper.GetInformationUrl("editedobject.notexists"));
        }

        if (!RequestHelper.IsPostBack())
        {
            LoadData();
        }

        htmlTemplateBody.AutoDetectLanguage = false;
        htmlTemplateBody.DefaultLanguage    = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
        htmlTemplateBody.EditorAreaCSS      = "";

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ReportingHTML", ScriptHelper.GetScript(" var reporting_htmlTemplateBody = '" + htmlTemplateBody.ClientID + "'"));

        // initialize item list controls
        ilGraphs.Report     = ri;
        ilTables.Report     = ri;
        ilValues.Report     = ri;
        ilHtmlGraphs.Report = ri;

        ilGraphs.EditUrl     = "ReportGraph_Edit.aspx";
        ilTables.EditUrl     = "ReportTable_Edit.aspx";
        ilValues.EditUrl     = "ReportValue_Edit.aspx";
        ilHtmlGraphs.EditUrl = "ReportHtmlGraph_Edit.aspx";

        ilGraphs.ItemType     = ReportItemType.Graph;
        ilTables.ItemType     = ReportItemType.Table;
        ilValues.ItemType     = ReportItemType.Value;
        ilHtmlGraphs.ItemType = ReportItemType.HtmlGraph;

        // Refresh script
        string script = "function RefreshWOpener(w) { if (w.refreshPageOnClose){ " + ControlsHelper.GetPostBackEventReference(this, "arg") + " }}";

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ReportingRefresh", ScriptHelper.GetScript(script));
    }
    /// <summary>
    /// Disables libraries drop-down list when empty.
    /// </summary>
    private void SetLibrariesEmpty()
    {
        LibraryID = 0;
        librarySelector.Enabled = false;

        ScriptHelper.RegisterStartupScript(Page, typeof(Page), "DialogsDisableMenuActions", ScriptHelper.GetScript("if(DisableNewFileBtn){ DisableNewFileBtn(); } if(DisableNewFolderBtn){ DisableNewFolderBtn(); }"));
    }
	protected void cmdAdd1_Click ( object sender, EventArgs e )
	{
		// 创建 ScriptHelper 对象
		ScriptHelper scriptHelper = new ScriptHelper ();
		string name = this.txtName1.Text;
		string ageString = this.txtAge1.Text;

		bool isInfoValid = true;

		int age = 0;

		if ( name == string.Empty )
		{
			// 没有写姓名, 添加弹出消息框的脚本
			scriptHelper.Alert ( "'请填写姓名'" );
			isInfoValid = false;
		}
		else if ( name.Length < 2 || name.Length > 4 )
		{
			// 姓名格式错误, 添加弹出消息框的脚本
			scriptHelper.Alert ( "'姓名应有 2 到 4 个字'" );
			isInfoValid = false;
		}
		else if ( !int.TryParse ( ageString, out age ) )
		{
			// 年龄格式错误, 添加弹出消息框的脚本
			scriptHelper.Alert ( "'年龄应该是数字'" );
			isInfoValid = false;
		}

		if ( !isInfoValid )
		{
			// 因为存在错误, 生成脚本到页面并返回
			scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
			return;
		}

		int result = 0;
		// 在这里将数据提交到数据库, 并将下面的语句去掉
		result = new Random ().Next ( 0, 2 );

		switch ( result )
		{
			case 0:
				// 添加成功, 添加显示成功消息的脚本
				scriptHelper.Alert ( "'添加成功'" );
				// 设置页面的标签 span1 为绿色并显示姓名和年龄
				ScriptHelper.RegisterAttribute ( this, "span1", "innerHTML", string.Format ( "被添加内容: {0}, {1}", name, age ) );
				ScriptHelper.RegisterAttribute ( this, "span1", "style.color", "#00ff00" );
				break;

			case 1:
				// 添加失败, 添加显示失败消息的脚本
				scriptHelper.Alert ( "'添加失败'" );
				// 设置页面的标签 span1 为红色并显示姓名和年龄
				ScriptHelper.RegisterAttribute ( this, "span1", "innerHTML", string.Format ( "被添加内容: {0}, {1}", name, age ) );
				ScriptHelper.RegisterAttribute ( this, "span1", "style.color", "#ff0000" );
				break;
		}

		// 生成脚本到页面
		scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
	}
	protected void cmdOK3_Click ( object sender, EventArgs e )
	{
		// 创建 ScriptHelper 对象
		ScriptHelper scriptHelper = new ScriptHelper ();
		string password = this.txtPassword3.Text;

		// 隐藏第一步, 设置记录的用户名到隐藏字段
		ScriptHelper.RegisterAttribute ( this, "r1", "style.display", "none" );
		ScriptHelper.RegisterHidden ( this, "r1name", this.Request["r1name"] );

		if ( password == string.Empty )
		{
			// 没有写密码, 添加弹出消息框的脚本, 并显示第二步
			scriptHelper.Alert ( "'请填写密码'" );
			ScriptHelper.RegisterAttribute ( this, "r2", "style.display", "block" );
		}
		else
		{
			// 显示注册结果
			ScriptHelper.RegisterAttribute ( this, "r3", "style.display", "block" );
			ScriptHelper.RegisterAttribute ( this, "rr1", "innerText", string.Format ( "用户名: {0}, 密码: {1}", this.Request["r1name"], password ) );
		}

		// 生成脚本
		scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
	}
    protected override void OnPreRender(EventArgs e)
    {
        // Load alternate text value
        if (!RequestHelper.IsPostBack())
        {
            ScriptHelper.RegisterWOpenerScript(Page);
            // Set alternate text
            string scriptAlt = @"if (wopener) {
                                var hdnAlt = wopener.document.getElementById('" + QueryHelper.GetString(DialogParameters.IMG_ALT_CLIENTID, "") + @"');
                                var txt = document.getElementById('" + txtAlt.ClientID + @"');
                                if ((hdnAlt != null) && (txt != null)) {
                                        txt.value = hdnAlt.value;
                                    }
                                }";
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "DialogAltImageScript", ScriptHelper.GetScript(scriptAlt));
        }

        base.OnPreRender(e);
    }
	protected void cmdTestBuild_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		result += "测试方法 ScriptHelper.Build(Page)<br />";

		scriptHelper.Alert ( "'测试 Build 1'" );

		tracer.Execute ( scriptHelper, null, "Build", FunctionType.Method, new Type[] { typeof ( Page ) }, null, null, null,
			new object[][] {
				new object[] { this }
			},
			false
			);

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";
		result += "测试方法 ScriptHelper.Build(Page, ScriptBuildOption)<br />";

		scriptHelper.Clear ();
		scriptHelper.Alert ( "'测试 Build 2'" );

		tracer.Execute ( scriptHelper, null, "Build", FunctionType.Method, new Type[] { typeof ( Page ), typeof ( ScriptBuildOption ) }, null, null, null,
			new object[][] {
				new object[] { this, ScriptBuildOption.OnlyCode }
			},
			false
			);

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";
		result += "测试方法 ScriptHelper.Build(Page, string)<br />";

		scriptHelper.Clear ();
		scriptHelper.Alert ( "'测试 Build 3'" );

		tracer.Execute ( scriptHelper, null, "Build", FunctionType.Method, new Type[] { typeof ( Page ), typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { this, "myscript" },
				new object[] { this, "myscript" }
			},
			false
			);

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";
		result += "测试方法 ScriptHelper.Build(Page, string, ScriptBuildOption)<br />";

		scriptHelper.Clear ();
		scriptHelper.Alert ( "'测试 Build 4'" );

		tracer.Execute ( scriptHelper, null, "Build", FunctionType.Method, new Type[] { typeof ( Page ), typeof ( string ), typeof ( ScriptBuildOption ) }, null, null, null,
			new object[][] {
				new object[] { this, "myscript1", ScriptBuildOption.None },
				new object[] { this, "myscript2", ScriptBuildOption.OnlyCode },
				new object[] { this, "myscript3", ScriptBuildOption.Startup },
				new object[] { this, "myscript3", ScriptBuildOption.Startup }
			},
			false
			);

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

	}
Example #13
0
 /// <summary>
 /// Adds the script to the page
 /// </summary>
 /// <param name="script">JavaScript code</param>
 public override void AddScript(string script)
 {
     ScriptHelper.RegisterStartupScript(Page, typeof(string), script.GetHashCode().ToString(), script);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!StopProcessing)
        {
            if (Config.OutputFormat == OutputFormatEnum.URL)
            {
                plcMediaType.Visible = false;
                plcRefresh.Visible   = false;

                if (String.IsNullOrEmpty(QueryHelper.GetString(DialogParameters.IMG_ALT_CLIENTID, String.Empty)))
                {
                    pnlProperties.CssClass = "DialogWebProperties DialogWebPropertiesTiny";
                }
            }

            if (Config.UseSimpleURLProperties)
            {
                plcAlternativeText.Visible = false;
            }

            drpMediaType.SelectedIndexChanged += drpMediaType_SelectedIndexChanged;

            imgRefresh.ToolTip = imgRefresh.ScreenReaderDescription = GetString("dialogs.web.refresh");
            imgRefresh.Click  += imgRefresh_Click;

            // Get reference causing postback to hidden button
            string postBackRef = ControlsHelper.GetPostBackEventReference(hdnButton, "");
            ltlScript.Text  = ScriptHelper.GetScript("function RaiseHiddenPostBack(){" + postBackRef + ";}\n");
            plcInfo.Visible = false;

            // OnChange and OnKeyDown event triggers
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "txtUrlChange", ScriptHelper.GetScript("$j(function(){ $j('" + txtUrl.ClientID + "').change(function (){ $j('#" + imgRefresh.ClientID + "').trigger('click');});});"));
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "txtUrlKeyDown", ScriptHelper.GetScript("$j(function(){ $j('#" + txtUrl.ClientID + "').keydown(function(event){ if (event.keyCode == 13) { $j('#" + imgRefresh.ClientID + "').trigger('click'); return false;}});});"));

            InitializeDesignScripts();

            if (!RequestHelper.IsPostBack())
            {
                InitFromQueryString();
                DisplayProperties();

                if (Config.OutputFormat == OutputFormatEnum.BBMedia)
                {
                    // For BB editor properties are always visible and only image is allowed.
                    plcBBMediaProp.Visible      = true;
                    propBBMedia.NoSelectionText = "";
                    drpMediaType.Items.Remove(new ListItem(GetString("dialogs.web.select"), ""));
                }

                Hashtable selectedItem = SessionHelper.GetValue("DialogParameters") as Hashtable;
                if ((selectedItem != null) && (selectedItem.Count > 0))
                {
                    LoadSelectedItem(selectedItem);
                    SessionHelper.SetValue("DialogParameters", null);
                }
                else
                {
                    // Try get selected item from session
                    selectedItem = SessionHelper.GetValue("DialogSelectedParameters") as Hashtable;
                    if ((selectedItem != null) && (selectedItem.Count > 0))
                    {
                        LoadSelectedItem(selectedItem);
                    }
                }
            }
        }
    }
Example #15
0
 private void DocumentManager_OnAfterAction(object sender, DocumentManagerEventArgs e)
 {
     // Refresh tree
     ScriptHelper.RefreshTree(this, Node.NodeID, Node.NodeParentID);
 }
Example #16
0
        /************************************************************
         * Function name : btnSend_Click
         * Purpose       : Send버튼 클릭될 때 처리
         *                 Rev 대상 컬럼 : 교재명, 저자, 금액, 교재소개, 파일, 교재목차, 출판사
         *
         *                 textbook_nm, author, price, textbook_intro, textbook_file_nm, textbook_desc, publisher
         *                 Rev 대상 컬럼이 아닌컬럼의 변경이 발생되면, 신규 생성하여 선박으로 전송 처리
         * Input         : void
         * Output        : void
         *************************************************************/
        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                // Data가 변경이 되었는지 여부
                if (IsDataChanged())
                {
                    if (this.IsDataValidation())
                    {
                        string[] xTempParams = new string[2];
                        string   xTextBookID = "";
                        string   xRtn        = "";

                        //temp_save 모드가 아니고..  Rev 변경이 되었는지 여부 확인
                        if ((Request.QueryString["TEMP_FLG"] != null && Request.QueryString["TEMP_FLG"].ToString() != "Y") &&
                            IsRevDataChanged())
                        {
                            string[] xParams = new string[3];

                            xParams[0] = ViewState["TEXTBOOK_ID"].ToString();                                                                                                         // textbook_id
                            xParams[1] = (ViewState["REV_COLUMNS"] != null && !string.IsNullOrEmpty(ViewState["REV_COLUMNS"].ToString())) ? ViewState["REV_COLUMNS"].ToString() : ""; // rev_columns
                            xParams[2] = Session["USER_ID"].ToString();;                                                                                                              // ins_id

                            xRtn = SBROKER.GetString("CLT.WEB.BIZ.LMS.CURR.vp_c_textbook_md",
                                                     "SetTextBookRevInsert",
                                                     LMS_SYSTEM.CURRICULUM,
                                                     "CLT.WEB.UI.LMS.CURR", (object)xParams);
                        }
                        else
                        {
                            // 입력 처리
                            object[] xParams = new object[17];

                            xParams[0] = this.ddlTextBookType.SelectedItem.Value; // textbook_type
                            xParams[1] = this.ddlTextBookLang.SelectedItem.Value; // textbook_lang
                            xParams[2] = this.ddlCourseGroup.SelectedItem.Value;  // course_group
                            xParams[3] = this.ddlCourseField.SelectedItem.Value;  // course_field

                            xParams[4] = this.txtAuthor.Text;                     // author
                            xParams[5] = this.txtPrice.Text;                      // price
                            xParams[6] = this.txtPublisher.Text;                  // publisher
                            xParams[7] = this.txtTextBookDesc.Text;               // textbook_desc
                            xParams[8] = this.txtTextBookIntro.Text;              // textbook_intro
                            xParams[9] = this.txtTextBookNM.Text;                 // textbook_nm

                            // 파일 변경이 있을 경우, file object를 그대로 넘기고

                            if (ViewState["TEXTBOOK_FILE_NM"].ToString() != this.txtFileNM.Value)
                            {
                                xParams[10] = base.ConvertToFileUpload(this.FileUpload1.PostedFile);
                                xParams[11] = this.txtFileNM.Value;
                            }
                            else
                            {
                                xParams[10] = null;
                                xParams[11] = this.txtFileNM.Value;
                            }

                            //if (this.FileUpload1.PostedFile != null && this.FileUpload1.PostedFile.ContentLength > 0)
                            //{
                            //    xParams[10] = this.FileUpload1.PostedFile; // textbook_file
                            //    xParams[11] = null; // textbook_filename
                            //}
                            ////파일 변경이 없을 경우, 기존과 동일하게 file명만 넘긴다.
                            //else
                            //{
                            //    xParams[10] = null; // textbook_file
                            //    xParams[11] = this.txtFileNM.Value; // textbook_filename
                            //}

                            xParams[12] = Session["USER_ID"].ToString(); // Ins_ID
                            xParams[13] = "1";                           // send_flg
                            xParams[14] = (Request.QueryString["TEMP_FLG"] != null && Request.QueryString["TEMP_FLG"].ToString() == "Y") ? "Y" : "N";
                            xParams[15] = ViewState["TEXTBOOK_ID"].ToString();

                            xParams[16] = txtPubDt.Text.Replace(".", "").Trim() == string.Empty ? null : txtPubDt.Text; // 사용자 입사일자 enter_dt

                            xRtn = SBROKER.GetString("CLT.WEB.BIZ.LMS.CURR.vp_c_textbook_md",
                                                     "SetTextBookInsert",
                                                     LMS_SYSTEM.CURRICULUM,
                                                     "CLT.WEB.UI.LMS.CURR", (object)xParams);

                            if (xRtn != string.Empty)
                            {
                                //A001: {0}이(가) 저장되었습니다.
                                ScriptHelper.Page_Alert(this.Page, MsgInfo.GetMsg("A001",
                                                                                  new string[] { "교재" },
                                                                                  new string[] { "Textbook" },
                                                                                  Thread.CurrentThread.CurrentCulture
                                                                                  ));
                                //저장 후 신규 id 값으로 재조회
                                ViewState["TEXTBOOK_ID"] = xRtn;
                                this.BindData();
                            }
                            else
                            {
                                //A004: {0}이(가) 입력되지 않았습니다.
                                ScriptHelper.Page_Alert(this.Page, MsgInfo.GetMsg("A004",
                                                                                  new string[] { "교재" },
                                                                                  new string[] { "Textbook" },
                                                                                  Thread.CurrentThread.CurrentCulture
                                                                                  ));
                            }
                        }
                    }
                    else
                    {
                        //A012: {0}의 필수 항목 입력이 누락되었습니다.
                        ScriptHelper.Page_Alert(this.Page, MsgInfo.GetMsg("A012",
                                                                          new string[] { "교재" },
                                                                          new string[] { "Textbook" },
                                                                          Thread.CurrentThread.CurrentCulture
                                                                          ));
                    }
                }
                else
                {
                    //A023: 변경내용을 재 확인 바랍니다.
                    ScriptHelper.Page_Alert(this.Page, MsgInfo.GetMsg("A023",
                                                                      new string[] { null },
                                                                      new string[] { null },
                                                                      Thread.CurrentThread.CurrentCulture
                                                                      ));
                }
            }
            catch (Exception ex)
            {
                base.NotifyError(ex);
            }
        }
Example #17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterModule(this, "CMS/Mole");

        ScriptHelper.RegisterModule(this, "CMS/BreadcrumbsPin", new
        {
            pinId = "js-single-object-dashboard-pin"
        });

        ScriptHelper.RegisterModule(this, "CMS/Header", new
        {
            selectorId      = siteSelector.DropDownSingleSelect.ClientID,
            dashboardLinkId = lnkDashboard.ClientID
        });

        EnsureHideMessageCallback();

        CheckTrial();

        // Display the techPreview info if there is a key in the web.config
        pnlTechPreview.Visible = ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CMSUseTechnicalPreview"], false) && CheckWarningMessage(SESSION_KEY_TECH_PREVIEW);

        pwdExpiration.ShowChangePasswordLink      = true;
        pwdExpiration.ExpirationTextBefore        = GetString("passwordexpiration.expired");
        pwdExpiration.ExpirationWarningTextBefore = string.Format(GetString("passwordexpiration.willexpire"), MembershipContext.AuthenticatedUser.UserPasswordExpiration);

        string scHideWarning = @"
function HideWarning(id, key) {
    if(key) {
        HideMessage(key);    
    }
    
    if(!id) {
        id = '" + pnlPwdExp.ClientID + @"';
    }
    
    var panel = $cmsj('#' + id);
    if(panel) {
        panel.hide();
        window.top.layouts[0].resizeAll(); 
    }
}

function ReceiveMessage() {}
";

        ScriptHelper.RegisterStartupScript(this, typeof(string), "HideHeaderWarning", scHideWarning, true);

        // Site selector settings
        siteSelector.UpdatePanel.RenderMode = UpdatePanelRenderMode.Inline;
        siteSelector.AllowAll = false;
        siteSelector.UniSelector.OnSelectionChanged   += SiteSelector_OnSelectionChanged;
        siteSelector.DropDownSingleSelect.AutoPostBack = true;
        siteSelector.OnlyRunningSites = true;

        // Allow empty for not-existing current site
        if (SiteContext.CurrentSite == null)
        {
            siteSelector.AllowEmpty = true;
        }

        if (!RequestHelper.IsPostBack())
        {
            siteSelector.Value = SiteContext.CurrentSiteID;
        }

        // Show only assigned sites for not global admins
        if (!MembershipContext.AuthenticatedUser.IsGlobalAdministrator)
        {
            siteSelector.UserId = MembershipContext.AuthenticatedUser.UserID;
        }

        StringBuilder script = new StringBuilder();

        script.Append(
            @"
function CheckChanges() {
    var innerFrame = parent.frames['cmsdesktop'];
    if (innerFrame.CheckChanges && !innerFrame.CheckChanges())
    {
        return false; 
    }
    else
    {
        return true;
    }
}
");

        ScriptHelper.RegisterStartupScript(this, typeof(string), "headerScript", ScriptHelper.GetScript(script.ToString()));
        ScriptHelper.RegisterModule(this, "CMS/Breadcrumbs", new
        {
            moreBreadcrumbsText = GetString("breadcrumbs.more"),
            splitViewModeText   = GetString("SplitMode.Compare")
        });

        EnsureSupportChat();
        EnsureStagingTaskGroupMenu();

        lnkDashboard.Attributes.Add("href", "#");
    }
Example #18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            Visible = false;
            gridElem.StopProcessing = true;
            // Do not load data
        }
        else
        {
            // Check permissions
            RaiseOnCheckPermissions("Read", this);

            if (StopProcessing)
            {
                return;
            }

            if (IsLiveSite)
            {
                dialogsUrl = "~/CMSModules/Friends/CMSPages/";
            }
            Visible = true;
            // Register the dialog script
            ScriptHelper.RegisterDialogScript(Page);

            // Register script for action 'Remove'
            StringBuilder actionScript = new StringBuilder();
            actionScript.AppendLine("function FM_RemoveAction_" + ClientID + "()");
            actionScript.AppendLine("{");
            actionScript.AppendLine("   if(!" + gridElem.GetCheckSelectionScript(false) + ")");
            actionScript.AppendLine("   {");
            actionScript.AppendLine("      if (confirm(" + ScriptHelper.GetString(GetString("friends.ConfirmRemove")) + "))");
            actionScript.AppendLine("      {");
            actionScript.AppendLine(Page.ClientScript.GetPostBackEventReference(btnRemoveSelected, null) + ";");
            actionScript.AppendLine("      }");
            actionScript.AppendLine("   }");
            actionScript.AppendLine("   else");
            actionScript.AppendLine("   {");
            actionScript.AppendLine("       FM_ShowLabel('" + lblInfo.ClientID + "');");
            actionScript.AppendLine("   }");
            actionScript.AppendLine("   return false;");
            actionScript.AppendLine("}");

            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "actionScript_" + ClientID, ScriptHelper.GetScript(actionScript.ToString()));
            // Add action to button
            btnRemoveSelected.OnClientClick = "return FM_RemoveAction_" + ClientID + "();";

            // Register the refreshing script
            string refreshScript = ScriptHelper.GetScript("function refreshList(){" + Page.ClientScript.GetPostBackEventReference(hdnRefresh, string.Empty) + "}");
            ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "friendsListRefresh", refreshScript);

            // Register script for displaying label
            StringBuilder showLabelScript = new StringBuilder();
            showLabelScript.AppendLine("function FM_ShowLabel(labelId)");
            showLabelScript.AppendLine("{");
            showLabelScript.AppendLine("   var label = document.getElementById(labelId);");
            showLabelScript.AppendLine("   if (label != null)");
            showLabelScript.AppendLine("   {");
            showLabelScript.AppendLine("      label.innerHTML = '" + GetString("friends.selectfriends") + "';");
            showLabelScript.AppendLine("      label.style['display'] = 'block';");
            showLabelScript.AppendLine("   }");
            showLabelScript.AppendLine("}");
            ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "showLabel", ScriptHelper.GetScript(showLabelScript.ToString()));

            // Register reject script
            StringBuilder rejectScript = new StringBuilder();
            rejectScript.AppendLine("function FM_Reject_" + ClientID + "(item, gridId, url)");
            rejectScript.AppendLine("{");
            rejectScript.AppendLine("   var items = '';");
            rejectScript.AppendLine("   if(item == null)");
            rejectScript.AppendLine("   {");
            rejectScript.AppendLine("       items = document.getElementById(gridId).value;");
            rejectScript.AppendLine("   }");
            rejectScript.AppendLine("   else");
            rejectScript.AppendLine("   {");
            rejectScript.AppendLine("       items = item;");
            rejectScript.AppendLine("   }");
            rejectScript.AppendLine("   if((url != null) && (items != '') && (items != '|'))");
            rejectScript.AppendLine("   {");
            rejectScript.AppendLine("       modalDialog(url + '&ids=' + items, 'rejectDialog', 480, 350);");
            rejectScript.AppendLine("   }");
            rejectScript.AppendLine("   else");
            rejectScript.AppendLine("   {");
            rejectScript.AppendLine("       FM_ShowLabel('" + lblInfo.ClientID + "');");
            rejectScript.AppendLine("   }");
            rejectScript.AppendLine("   return false;");
            rejectScript.AppendLine("}");
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "rejectScript_" + ClientID, ScriptHelper.GetScript(rejectScript.ToString()));

            // Add action to button
            btnRejectSelected.OnClientClick = "return FM_Reject_" + ClientID + "(null,'" + gridElem.SelectionHiddenField.ClientID + "','" + DialogUrl + "');";
            // Hide label
            lblInfo.Attributes["style"] = "display: none;";

            // Setup grid
            gridElem.OnAction            += gridElem_OnAction;
            gridElem.OnExternalDataBound += gridElem_OnExternalDataBound;
            gridElem.OrderBy              = "UserName";
            gridElem.IsLiveSite           = IsLiveSite;

            // Where condition
            gridElem.WhereCondition = "FriendStatus = " + Convert.ToInt32(FriendshipStatusEnum.Approved);

            // Add parameter @UserID
            if (gridElem.QueryParameters == null)
            {
                gridElem.QueryParameters = new QueryDataParameters();
            }
            gridElem.QueryParameters.Add("@UserID", UserID);
        }
    }
    protected void hdnButton_Click(object sender, EventArgs e)
    {
        Hashtable properties = GetSelectedItem();
        string    script;

        if (Config.OutputFormat == OutputFormatEnum.URL)
        {
            properties[DialogParameters.URL_URL]          = txtUrl.Text.Trim();
            properties[DialogParameters.EDITOR_CLIENTID]  = Config.EditorClientID;
            properties[DialogParameters.IMG_ALT]          = txtAlt.Text.Trim();
            properties[DialogParameters.IMG_ALT_CLIENTID] = QueryHelper.GetString(DialogParameters.IMG_ALT_CLIENTID, String.Empty);
            script = CMSDialogHelper.GetUrlItem(properties);
        }
        else
        {
            switch (drpMediaType.SelectedValue)
            {
            case "image":
                script = CMSDialogHelper.GetImageItem(properties);
                break;

            case "av":
                script = CMSDialogHelper.GetAVItem(properties);
                break;

            case "flash":
                script = CMSDialogHelper.GetFlashItem(properties);
                break;

            default:
                script = CMSDialogHelper.GetUrlItem(properties);
                break;
            }
        }
        if (!String.IsNullOrEmpty(script))
        {
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "insertItemScript", ScriptHelper.GetScript(script));
        }
    }
	protected void cmdTestAppendScript_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		result += "测试方法 ScriptHelper.AppendScript(string)<br />";

		scriptHelper.Confirm ( "'有名字?'", "n" );

		tracer.Execute ( scriptHelper, null, "AppendScript", FunctionType.Method, new Type[] { typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "if(n){n = '有名字';}else{n = '没有名字';}" }
			},
			false
			);

		scriptHelper.Alert ( "'名字? ' + n" );

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this );
	}
 /// <summary>
 /// Initialize design jQuery scripts.
 /// </summary>
 private void InitializeDesignScripts()
 {
     ScriptHelper.RegisterStartupScript(Page, typeof(Page), "designScript", ScriptHelper.GetScript("setTimeout('InitializeDesign();',200);$j(window).resize(function() { InitializeDesign(); });"));
 }
	protected void cmdTestSetTimeout_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		result += "测试方法 ScriptHelper.SetTimeout(string, int)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "SetTimeout", FunctionType.Method, new Type[] { typeof ( string ), typeof ( int ) }, null, null, null,
			new object[][] {
				new object[] { "'alert(\"hello, 5 秒钟触发\")'", 5000 },
				new object[] { "function(){alert('函数方式触发, 5 秒钟触发');}", 5000 }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.SetTimeout(string, int, string)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "SetTimeout", FunctionType.Method, new Type[] { typeof ( string ), typeof ( int ), typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "'alert(\"hello, 20 秒钟触发, 句柄保存到 timer1\")'", 20000, "timer1" },
				new object[] { "function(){alert('函数方式触发, 20 秒钟触发, 句柄保存到 timer2');}", 20000, "timer2" }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.SetTimeout(string, int, bool)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "SetTimeout", FunctionType.Method, new Type[] { typeof ( string ), typeof ( int ), typeof ( bool ) }, null, null, null,
			new object[][] {
				new object[] { "'alert(\"hello, 5 秒钟触发, 不追加\")'", 5000, false },
				new object[] { "function(){alert('函数方式触发, 5 秒钟触发, 不追加');}", 5000, false }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.SetTimeout(string, int, string, bool)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "SetTimeout", FunctionType.Method, new Type[] { typeof ( string ), typeof ( int ), typeof ( string ), typeof ( bool ) }, null, null, null,
			new object[][] {
				new object[] { "'alert(\"hello, 20 秒钟触发, 句柄保存到 timer1, 不追加\")'", 20000, "timer1", false },
				new object[] { "function(){alert('函数方式触发, 20 秒钟触发, 句柄保存到 timer2, 不追加');}", 20000, "timer2", false }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this );
	}
Example #23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!RequestHelper.IsCallback())
        {
            // Register the dialog script
            ScriptHelper.RegisterJQuery(Page);
            ScriptHelper.RegisterDialogScript(Page);

            string script =
                @"
function InitTreeParams(action, param1, param2)
{
    var elm = $cmsj('#" + pnlTreeArea.ClientID + @"');
    $cmsj('#hdnScroll').val(elm.scrollTop());
    $cmsj('#hdnAction').val(action); 
    $cmsj('#hdnParam1').val(param1); 
    $cmsj('#hdnParam2').val(param2);
}

function ProcessRequest(action, param1, param2)
{
    InitTreeParams(action, param1, param2);
" + Page.ClientScript.GetPostBackEventReference(this, null) + ";" +
                @"}
";

            iconRefresh.OnClientClick = "TreeRefresh(); return false;";

            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "processRequestScript", ScriptHelper.GetScript(script));
            AddScript("var currentNode = document.getElementById('treeSelectedNode');");
        }
    }
	protected void cmdTestConfirm_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		result += "测试方法 ScriptHelper.Confirm(string)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Confirm", FunctionType.Method, new Type[] { typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "'确定1?'" },
				new object[] { "'\"确定2?\"'" }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.Confirm(string, string)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Confirm", FunctionType.Method, new Type[] { typeof ( string ), typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "'确定? 返回结果到变量 c1'", "c1" },
				new object[] { "'确定? 但没有返回到变量'", null }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.Confirm(string, bool)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Confirm", FunctionType.Method, new Type[] { typeof ( string ), typeof ( bool ) }, null, null, null,
			new object[][] {
				new object[] { "'确定1? 追加? true'", true },
				new object[] { "'\"确定2?\", 追加? false'", false }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.Confirm(string, string, bool)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Confirm", FunctionType.Method, new Type[] { typeof ( string ), typeof ( string ), typeof ( bool ) }, null, null, null,
			new object[][] {
				new object[] { "'确定? 返回结果到变量 c1, 追加? true'", "c1", true },
				new object[] { "'确定? 但没有返回到变量, 追加? false'", null, false }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this );
	}
Example #25
0
    public void RaisePostBackEvent(string eventArgument)
    {
        var currentUser = MembershipContext.AuthenticatedUser;

        // Current Node ID
        int nodeId = ValidationHelper.GetInteger(Param1, 0);

        TreeProvider tree = new TreeProvider(currentUser);

        string documentName = string.Empty;
        string action       = Action.ToLowerCSafe();
        string siteName     = SiteContext.CurrentSiteName;

        // Process the request
        switch (action)
        {
        case "refresh":
            treeElem.SelectedNodeID = nodeId;
            AddScript("currentNodeId = " + nodeId + ";");
            break;

        case "moveup":
        case "movedown":
        case "movetop":
        case "movebottom":
            // Move the document up (document order)
            try
            {
                if (nodeId == 0)
                {
                    AddAlert(GetString("ContentRequest.ErrorMissingSource"));
                    return;
                }

                // Get document to move
                TreeNode node = tree.SelectSingleNode(nodeId);

                // Check whether node exists
                if (node == null)
                {
                    ShowError(GetString("ContentRequest.ErrorMissingSource"));
                    return;
                }

                // Check the permissions for document
                if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)
                {
                    // Root of products tree can not be moved
                    if (!IsProductTree || (node.NodeAliasPath.CompareToCSafe(StartingAliasPath, true) != 0))
                    {
                        switch (action)
                        {
                        case "moveup":
                            tree.MoveNodeUp(node);
                            break;

                        case "movedown":
                            tree.MoveNodeDown(node);
                            break;

                        case "movetop":
                            tree.SetNodeOrder(node, DocumentOrderEnum.First);
                            break;

                        case "movebottom":
                            tree.SetNodeOrder(node, DocumentOrderEnum.Last);
                            break;
                        }

                        // Log the synchronization tasks for the entire tree level
                        DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, node.NodeAliasPath, tree);

                        // Select the document in the tree
                        documentName = node.GetDocumentName();

                        treeElem.ExpandNodeID   = node.NodeParentID;
                        treeElem.SelectedNodeID = node.NodeID;
                        AddScript("currentNodeId = " + node.NodeID + ";");
                    }
                }
                else
                {
                    // Select the document in the tree
                    treeElem.SelectedNodeID = nodeId;

                    AddAlert(GetString("ContentRequest.MoveDenied"));
                }
            }
            catch (Exception ex)
            {
                EventLogProvider.LogEvent(EventType.ERROR, "Content", "MOVE", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, SiteContext.CurrentSite.SiteID);
                AddAlert(GetString("ContentRequest.MoveFailed") + " : " + ex.Message);
            }
            break;

        case "setculture":
            // Set the preferred culture code
            try
            {
                // Set the culture code
                string language = ValidationHelper.GetString(Param2, string.Empty);
                if (!string.IsNullOrEmpty(language))
                {
                    LocalizationContext.PreferredCultureCode = language;
                    treeElem.Culture = language;
                }
                // Refresh the document
                if (nodeId > 0)
                {
                    treeElem.SelectedNodeID = nodeId;

                    AddScript("SelectNode(" + nodeId + ");");
                }
            }
            catch (Exception ex)
            {
                EventLogProvider.LogEvent(EventType.ERROR, "Content", "SETCULTURE", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, SiteContext.CurrentSite.SiteID);
                AddAlert(GetString("ContentRequest.ErrorChangeLanguage"));
            }
            break;

        case "setdevice":
            // Set the device profile
            try
            {
                // Set the device name
                string deviceName = ValidationHelper.GetString(Param2, string.Empty);
                DeviceContext.CurrentDeviceProfileName = deviceName;

                // Refresh the document
                if (nodeId > 0)
                {
                    treeElem.SelectedNodeID = nodeId;

                    AddScript("SelectNode(" + nodeId + ");");
                }
            }
            catch (Exception ex)
            {
                EventLogProvider.LogEvent(EventType.ERROR, "Content", "SETDEVICE", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, SiteContext.CurrentSite.SiteID);
                AddAlert(GetString("ContentRequest.ErrorChangeLanguage"));
            }
            break;

        // Sorting
        case "sortalphaasc":
        case "sortalphadesc":
        case "sortdateasc":
        case "sortdatedesc":

            int siteId = SiteContext.CurrentSite.SiteID;

            try
            {
                // Get document to sort
                TreeNode node = tree.SelectSingleNode(nodeId);

                // Check the permissions for document
                if ((node != null) && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed) &&
                    (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) == AuthorizationResultEnum.Allowed))
                {
                    siteId = node.NodeSiteID;

                    switch (action)
                    {
                    case "sortalphaasc":
                        tree.SortNodesAlphabetically(nodeId, siteId, true);
                        break;

                    case "sortalphadesc":
                        tree.SortNodesAlphabetically(nodeId, siteId, false);
                        break;

                    case "sortdateasc":
                        tree.SortNodesByDate(nodeId, siteId, true);
                        break;

                    case "sortdatedesc":
                        tree.SortNodesByDate(nodeId, siteId, false);
                        break;
                    }

                    // Log the synchronization tasks for the entire tree level
                    string fakeAlias = node.NodeAliasPath.TrimEnd('/') + "/child";
                    DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, fakeAlias, tree);
                }
                else
                {
                    AddAlert(GetString("ContentRequest.SortDenied"));
                }

                // Refresh the tree
                if (nodeId > 0)
                {
                    treeElem.ExpandNodeID   = nodeId;
                    treeElem.SelectedNodeID = nodeId;
                    if (IsProductTree)
                    {
                        AddScript("window.frames['contentview'].location.replace(window.frames['contentview'].location);");
                    }
                    else
                    {
                        AddScript("SelectNode(" + nodeId + ");");
                    }
                }
            }
            catch (Exception ex)
            {
                EventLogProvider.LogEvent(EventType.ERROR, "Content", "SORT", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, siteId);
                AddAlert(GetString("ContentRequest.ErrorSort"));
            }

            break;
        }

        // Maintain scrollbar position
        string script =
            @"
SetSelectedNodeId(currentNodeId);
MaintainScroll('" + nodeId + @"','" + pnlTreeArea.ClientID + @"', " + ScrollPosition + @");
HideAllContextMenus();
";

        ScriptHelper.RegisterStartupScript(Page, typeof(string), "MaintainScrollbar", script, true);
    }
Example #26
0
 /// <summary>
 /// Adds the script to the output request window.
 /// </summary>
 /// <param name="script">Script to add</param>
 public override void AddScript(string script)
 {
     ltlScript.Text += ScriptHelper.GetScript(script);
 }
Example #27
0
 /// <summary>
 /// Adds the alert message to the output request window.
 /// </summary>
 /// <param name="message">Message to display</param>
 private void AddAlert(string message)
 {
     ScriptHelper.RegisterStartupScript(this, typeof(string), message.GetHashCode().ToString(), ScriptHelper.GetAlertScript(message));
 }
Example #28
0
    /// <summary>
    /// Saves metadata and file name of attachment.
    /// </summary>
    /// <param name="newFileName">New attachment file name</param>
    /// <returns>Returns True if attachment was successfully saved.</returns>
    private bool SaveAttachment(string newFileName)
    {
        bool saved = false;

        // Save new data
        try
        {
            DocumentAttachment attachment = InfoObject as DocumentAttachment;

            if (attachment != null)
            {
                // Set new file name
                if (!string.IsNullOrEmpty(newFileName))
                {
                    string name = newFileName + attachment.AttachmentExtension;
                    attachment.AttachmentName = name;

                    if (!IsAttachmentNameUnique(attachment))
                    {
                        // Attachment already exists.
                        ShowError(GetString("img.errors.fileexists"));
                        return(false);
                    }
                }

                // Ensure automatic check-in/ check-out
                bool autoCheck = false;

                var wm = WorkflowManager.GetInstance(TreeProvider);

                if (!nodeIsParent && (Node != null))
                {
                    var wi = wm.GetNodeWorkflow(Node);
                    if (wi != null)
                    {
                        autoCheck = !wi.UseCheckInCheckOut(SiteName);
                    }

                    // Check out the document
                    if (autoCheck)
                    {
                        var nextStep = VersionManager.CheckOut(Node, Node.IsPublished, true);
                        VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID;

                        if (IsWorkflowFinished(nextStep))
                        {
                            attachment = (DocumentAttachment)AttachmentInfoProvider.GetAttachmentInfo(attachment.AttachmentGUID, SiteName);
                        }
                    }
                }

                if (attachment != null)
                {
                    // Set filename title and description
                    attachment.AttachmentTitle       = ObjectTitle;
                    attachment.AttachmentDescription = ObjectDescription;

                    attachment.AllowPartialUpdate = true;

                    if (!nodeIsParent && (Node != null))
                    {
                        DocumentHelper.UpdateAttachment(Node, attachment);

                        // Check in the document
                        if (autoCheck)
                        {
                            if (VersionManager != null)
                            {
                                if (VersionHistoryID > 0 && (Node != null))
                                {
                                    VersionManager.CheckIn(Node, null);
                                }
                            }
                        }
                    }
                    else if (nodeIsParent)
                    {
                        attachment.Update();
                    }

                    saved = true;

                    string fullRefresh = "false";

                    if (autoCheck || (Node == null))
                    {
                        fullRefresh = "true";
                    }

                    // Refresh parent update panel
                    LtlScript.Text = ScriptHelper.GetScript("RefreshMetaData(" + ScriptHelper.GetString(ExternalControlID) + ", '" + fullRefresh + "', '" + attachment.AttachmentGUID + "', 'refresh')");
                }
            }
        }
        catch (Exception ex)
        {
            ShowError(GetString("metadata.errors.processing"));
            EventLogProvider.LogException("Metadata editor", "SAVEATTACHMENT", ex);
        }

        return(saved);
    }
 void Start()
 {
     // Attach Scripts to holders
     sc_ScriptHelper   = Camera.main.GetComponent<ScriptHelper>();
     sc_GameController = sc_ScriptHelper.sc_GameController;
 }
Example #30
0
 private void HandlePossibleErrors()
 {
     CurrentLog.Close();
     ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "terminatePendingCallbacks", ScriptHelper.GetScript("var __pendingCallbacks = new Array();"));
     if (!String.IsNullOrEmpty(CurrentError))
     {
         lblError.Text    = CurrentError;
         lblError.Visible = true;
     }
 }
Example #31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register the main CMS script
        ScriptHelper.RegisterCMS(this.Page);

        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);
        ctlAsync.OnFinished   += ctlAsync_OnFinished;
        ctlAsync.OnError      += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel     += ctlAsync_OnCancel;

        ucFilter.Column    = "FileName";
        btnFilter.Text     = ResHelper.GetString("general.show");
        btnFilter.CssClass = "ContentButton";

        if (StorageHelper.IsExternalStorage)
        {
            imgExternalStoragePrepare.ImageUrl = ResolveUrl(GetImageUrl("CMSModules/CMS_Content/Dialogs/importprepare.png"));
            lnkExternalStoragePrepare.Text     = GetString("dialogs.mediaview.azureprepare");

            ScriptHelper.RegisterProgress(Page);
        }
        else
        {
            CurrentMaster.HeaderActionsPlaceHolder.Visible = false;
        }

        if (!RequestHelper.IsCallback())
        {
            CurrentUserInfo user = CMSContext.CurrentUser;

            // Check permissions for CMS Desk -> Tools -> File Import
            if (!user.IsAuthorizedPerUIElement("CMS.Tools", "FileImport"))
            {
                RedirectToCMSDeskUIElementAccessDenied("CMS.Tools", "FileImport");
            }

            if (!user.IsAuthorizedPerResource("CMS.FileImport", "ImportFiles"))
            {
                RedirectToCMSDeskAccessDenied("CMS.FileImport", "ImportFiles");
            }

            // Set visibility of panels
            pnlContent.Visible = true;
            pnlLog.Visible     = false;

            ScriptHelper.RegisterCMS(this.Page);

            // Initialize culture selector
            this.cultureSelector.SiteID = CMSContext.CurrentSiteID;
            this.pathElem.SiteID        = CMSContext.CurrentSiteID;

            // Prepare unigrid
            GetPath();
            gridImport.DataSource           = GetFileSystemDataSource(ucFilter.WhereCondition);
            gridImport.OnExternalDataBound += new OnExternalDataBoundEventHandler(gridImport_OnExternalDataBound);
            gridImport.SelectionJavascript  = "UpdateCount";
            gridImport.ZeroRowsText         = GetString("Tools.FileImport.NoFiles");
            gridImport.OnShowButtonClick   += new EventHandler(gridImport_OnShowButtonClick);

            // Prepare async panel
            titleElemAsync.TitleText  = GetString("tools.fileimport.importing");
            titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_FileImport/module.png");
            btnCancel.Text            = GetString("general.cancel");
            btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");

            lblTitle.Text    = GetString("Tools.FileImport.ImportedFiles") + " " + rootPath + ": ";
            lblSelected.Text = string.Format(GetString("Tools.FileImport.SelectedCount"), filesCount);

            if (!RequestHelper.IsPostBack())
            {
                this.cultureSelector.Value = CMSContext.PreferredCultureCode;

                // Initialize temporary lists
                resultListIndex  = null;
                resultListValues = null;
                errorFiles       = null;
            }

            ltlScript.Text += ScriptHelper.GetScript(
                " function UpdateCount(id, checked) {\n" +
                " var hidden = document.getElementById(\"" + hdnSelected.ClientID + "\")\n" +
                " var label =  document.getElementById(\"" + lblSelectedValue.ClientID + "\")\n" +
                " if (hidden.value.indexOf('|'+id+'|') != -1) {  \n" +
                "   if (checked == false) { \n" +
                "     hidden.value=hidden.value.replace('|'+id+'|', '');  \n" +
                "   } \n" +
                " } else { \n" +
                "   if (checked == true) { \n" +
                "     hidden.value = hidden.value + '|'+id+'|';  \n" +
                "   } \n" +
                " } \n" +
                "  label.innerHTML = (hidden.value.split('|').length - 1) / 2; \n" +
                " }\n");
        }
    }
Example #32
0
	protected void cmdTestIs_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		JQuery jQuery = new JQuery ( "'li'" );

		result += "测试方法 JQuery.Is(string)<br />";

		tracer.Execute ( jQuery, null, "Is", FunctionType.Method, new Type[] { typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "'.happy'" }
			},
			false
			);

		result += "jQuery.Code = " + jQuery.Code + "<br />";

		ScriptHelper scriptHelper = new ScriptHelper ();
		scriptHelper.Alert ( "'li is(.happay) = ' + " + jQuery.Code );

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
	}
Example #33
0
    void Start()
    {
        // Attach Scripts to holders
        sc_ScriptHelper   = Camera.main.GetComponent<ScriptHelper>();
        sc_AudioManager   = sc_ScriptHelper.sc_AudioManager;
        sc_BallController = sc_ScriptHelper.sc_BallController;
        sc_FadeToScene    = sc_ScriptHelper.sc_FadeToScene;

        // Tell screen to not dim
        Screen.sleepTimeout = SleepTimeout.NeverSleep;

        // Set booleans
        isGamePaused   = false;
        isGameOver     = false;
        gameOver_Once  = false;
        hasGameStarted = false;
        useGameInput   = true;

        // Set Product Version Number
        Product_VersionNumber = 1.0f;

        // Make screen fade in
        sc_FadeToScene.FadeInScene(1.5f);
    }
Example #34
0
 /// <summary>
 /// Adds the script to the output request window.
 /// </summary>
 /// <param name="script">Script to add</param>
 public void AddScript(string script)
 {
     ScriptHelper.RegisterStartupScript(this, typeof(string), script.GetHashCode().ToString(), ScriptHelper.GetScript(script));
 }
    /// <summary>
    /// Registers required scripts
    /// </summary>
    private void RegisterScripts()
    {
        // Ensure Script Manager is the first control on the page
        using (ScriptManager sMgr = ScriptManager.GetCurrent(Page))
        {
            sMgr?.Services.Add(new ServiceReference("~/CMSModules/Content/FormControls/Tags/TagSelectorService.asmx"));
        }

        ScriptHelper.RegisterDialogScript(Page);
        ScriptHelper.RegisterStartupScript(this, typeof(string), "TagSelector_" + ClientID, ScriptHelper.GetScript(GetTagScript()));
    }
Example #36
0
    void Start()
    {
        // Attach Scripts to holders
        sc_ScriptHelper    = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ScriptHelper>();
        sc_BoundaryManager = sc_ScriptHelper.sc_BoundaryManager;
        sc_GameController = sc_ScriptHelper.sc_GameController;
        sc_LevelManager    = sc_ScriptHelper.sc_LevelManager;

        Time_Between_Rows = 2.0f;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterTooltip(Page);

        // Initialize events
        ctlAsync.OnFinished   += ctlAsync_OnFinished;
        ctlAsync.OnError      += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel     += ctlAsync_OnCancel;

        if (IsCallback)
        {
            this.pnlContent.Visible = false;

            gridFiles.StopProcessing    = true;
            siteSelector.StopProcessing = true;

            return;
        }


        // Setup the controls
        gridFiles.OnExternalDataBound += new OnExternalDataBoundEventHandler(gridFiles_OnExternalDataBound);
        gridFiles.OnAction            += new OnActionEventHandler(gridFiles_OnAction);

        ControlsHelper.RegisterPostbackControl(this.btnOk);

        currentSiteId = CMSContext.CurrentSiteID;

        // Setup the site selection
        siteSelector.DropDownSingleSelect.AutoPostBack = true;

        if (!RequestHelper.IsPostBack() && (currentSiteId > 0))
        {
            siteSelector.Value = currentSiteId;
        }

        siteId = ValidationHelper.GetInteger(siteSelector.Value, 0);
        if (siteId > 0)
        {
            siteWhere = "AttachmentSiteID = " + siteId;
            gridFiles.WhereCondition = siteWhere;
        }

        if (!RequestHelper.IsPostBack())
        {
            // Fill in the actions
            drpAction.Items.Add(new ListItem(GetString("general.selectaction"), ""));

            bool copyDB   = true;
            bool copyFS   = true;
            bool deleteDB = true;
            bool deleteFS = true;

            if (siteId > 0)
            {
                bool fs = StoreInFileSystem(siteId);
                bool db = StoreInDatabase(siteId);

                copyFS   = deleteDB = fs;
                deleteFS = db;
                copyDB   = db && fs;
            }

            if (copyDB)
            {
                drpAction.Items.Add(new ListItem("Copy to database", "copytodatabase"));
            }
            if (copyFS)
            {
                drpAction.Items.Add(new ListItem("Copy to file system", "copytofilesystem"));
            }
            if (deleteDB)
            {
                drpAction.Items.Add(new ListItem("Delete from database", "deleteindatabase"));
            }
            if (deleteFS)
            {
                drpAction.Items.Add(new ListItem("Delete from file system", "deleteinfilesystem"));
            }
        }
    }
Example #38
0
    void Start()
    {
        // Attach Scripts to holders
        sc_ScriptHelper    = Camera.main.GetComponent<ScriptHelper>();
        sc_BoundaryManager = sc_ScriptHelper.sc_BoundaryManager;
        sc_GameController  = sc_ScriptHelper.sc_GameController;
        sc_LevelManager    = sc_ScriptHelper.sc_LevelManager;

        // Get users saved settings for ball sensitivity
        ball_speed = PlayerPrefs.GetFloat("glow_ball_speed", 9.0f);

        if (!isTestBall)
        // Set the ball to the first intermission height
        SET_BallToIntermission();
    }
Example #39
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            gridComments.Visible = false;
            return;
        }

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostBackReference", ScriptHelper.GetScript("function postBack () {" + ControlsHelper.GetPostBackEventReference(this, String.Empty) + ";}"));

        ScriptHelper.RegisterDialogScript(Page);
        gridComments.OnAction              += gridComments_OnAction;
        gridComments.OnExternalDataBound   += gridComments_OnExternalDataBound;
        gridComments.OnDataReload          += gridComments_OnDataReload;
        gridComments.HideControlForZeroRows = true;
        gridComments.ShowActionsMenu        = true;
        gridComments.Columns = "CommentID, CommentDate, CommentApproved, CommentUserName, CommentText, CommentIsSpam";

        // Get all possible column names.
        BlogCommentInfo bci = new BlogCommentInfo();

        gridComments.AllColumns = SqlHelper.MergeColumns(bci.ColumnNames);

        btnAction.Text          = GetString("General.Ok");
        btnAction.OnClientClick = "return MassConfirm('" + drpAction.ClientID + "'," + ScriptHelper.GetString(GetString("MyBlogs.Comments.ConfirmDelete")) + ");";

        currentUser = MembershipContext.AuthenticatedUser;

        // Load action dropdown
        if (!URLHelper.IsPostback())
        {
            // Actions dropdown
            drpAction.Items.Add(new ListItem(GetString("General.SelectAction"), string.Empty));
            drpAction.Items.Add(new ListItem(GetString("General.Approve"), "approve"));
            drpAction.Items.Add(new ListItem(GetString("General.Reject"), "reject"));
            drpAction.Items.Add(new ListItem(GetString("MyBlogs.Comments.IsSpam"), "spam"));
            drpAction.Items.Add(new ListItem(GetString("MyBlogs.Comments.IsNoSpam"), "nospam"));
            drpAction.Items.Add(new ListItem(GetString("General.Delete"), "delete"));
        }

        if (!ShowFilter)
        {
            filterElem.Visible   = false;
            gridComments.OrderBy = OrderBy;
        }

        if (!RequestHelper.IsPostBack() && !string.IsNullOrEmpty(ItemsPerPage))
        {
            gridComments.Pager.DefaultPageSize = ValidationHelper.GetInteger(ItemsPerPage, -1);
        }

        RegisterScripts();
    }
	protected void cmdTestNavigate_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		/*
		result += "测试方法 ScriptHelper.Navigate(string)<br />";

		tracer.Execute ( scriptHelper, null, "Navigate", FunctionType.Method, new Type[] { typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "'http://www.google.com/'" }
			},
			false
			);
		*/

		result += "测试方法 ScriptHelper.Navigate(string, NavigateOption)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Navigate", FunctionType.Method, new Type[] { typeof ( string ), typeof ( NavigateOption ) }, null, null, null,
			new object[][] {
				new object[] { "'http://www.google.com/'", NavigateOption.NewWindow },
				new object[] { "'http://www.google.com/'", NavigateOption.SelfWindow }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.Navigate(string, NavigateOption, bool)<br />";

		foreach ( object code in tracer.Execute ( scriptHelper, null, "Navigate", FunctionType.Method, new Type[] { typeof ( string ), typeof ( NavigateOption ), typeof ( bool ) }, null, null, null,
			new object[][] {
				new object[] { "'http://www.google.com/'", NavigateOption.NewWindow, true },
				new object[] { "'http://www.google.com/'", NavigateOption.SelfWindow, false }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this );
	}
Example #41
0
    /// <summary>
    /// Registers JS scripts.
    /// </summary>
    protected void RegisterScripts()
    {
        string script =
            string.Format(@"// Insert desired HTML at the current cursor position of the CK editor
function InsertHTML(htmlString) {{
    // Get the editor instance that we want to interact with
    var oEditor = CKEDITOR.instances['{0}'];

    // Check the active editing mode
    if (oEditor.mode == 'wysiwyg') {{
        // Insert the desired HTML.
        oEditor.insertHtml(htmlString);
    }}
    else alert('You must be on WYSIWYG mode!');
}}

// Set content of the CK editor - replace the actual one
function SetContent(newContent) {{
    // Get the editor instance that we want to interact with.
    var oEditor = CKEDITOR.instances['{0}'];

    // Set the editor content (replace the actual one).
    oEditor.setData(newContent);
}}

function PasteImage(imageurl) {{
    imageurl = '<img src=""' + imageurl + '"" />';
    return InsertHTML(imageurl);
}}

// Returns HTML code with standard table layout
function GenerateTableLayout() {{
    var tableLayout = """";

    // indicates whether any row definition was added to the table
    var rowAdded = false;

    // list of attributes
    var list = document.getElementById('{1}');

    // attributes count
    var optionsCount = 0;
    if (list != null) {{
        optionsCount = list.options.length;
    }}

    for (var i = 0; i < optionsCount; i++) {{
        tableLayout += ""<tr><td>$$label:"" + list.options[i].value + ""$$</td><td>$$value:"" + list.options[i].value + ""$$</td></tr>"";
        rowAdded = true;
    }}

    if (rowAdded) {{
        tableLayout = ""<table><tbody>"" + tableLayout + ""</tbody></table>"";
    }}

    return tableLayout;
}}

// Insert desired HTML at the current cursor position of the CK editor if it is not already inserted 
function InsertAtCursorPosition(htmlString) {{
    InsertHTML(htmlString);
}}

function ConfirmDelete() {{
    return confirm(document.getElementById('confirmdelete').value);
}}", htmlEditor.ClientID, lstAvailableFields.ClientID);

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "Autoresponder_" + ClientID, script, true);
    }
	protected void cmdTestClear_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		result += "测试方法 ScriptHelper.Clear(string)<br />";

		scriptHelper.Confirm ( "'有名字?'", "n" );
		scriptHelper.Alert ( "'一句话'" );

		tracer.Execute ( scriptHelper, null, "Clear", FunctionType.Method, null, null, null, null,
			new object[][] {
				new object[] { }
			},
			false
			);

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this );
	}
    /// <summary>
    /// Registers helper scripts.
    /// </summary>
    private void RegisterScripts()
    {
        // Register dialog script
        string resolvedAvatarsPage;

        if (IsLiveSite)
        {
            resolvedAvatarsPage = ApplicationUrlHelper.ResolveDialogUrl(AuthenticationHelper.IsAuthenticated() ? "~/CMSModules/Avatars/CMSPages/AvatarsGallery.aspx" : "~/CMSModules/Avatars/CMSPages/PublicAvatarsGallery.aspx");
        }
        else
        {
            resolvedAvatarsPage = ResolveUrl("~/CMSModules/Avatars/Dialogs/AvatarsGallery.aspx");
        }

        ScriptHelper.RegisterDialogScript(Page);
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "SelectAvatar",
                                               ScriptHelper.GetScript("function SelectAvatar(avatarType, clientId) { " +
                                                                      "modalDialog('" + resolvedAvatarsPage + "?avatartype=' + avatarType + '&clientid=' + clientId, 'permissionDialog', 680, 270); return false;}"));
        ltlScript.Text = ScriptHelper.GetScript("function UpdateForm(){ ; } \n");

        // Setup btnShowGallery action
        btnShowGallery.Attributes.Add("onclick", "SelectAvatar('" + AvatarInfoProvider.GetAvatarTypeString(AvatarTypeEnum.Group) + "', '" + ClientID + "'); return false;");


        // Get image size param(s) for preview
        string sizeParams = string.Empty;

        // Keep aspect ratio is set - property was set directly or indirectly by max side size property.
        if (KeepAspectRatio)
        {
            sizeParams += "&maxsidesize=" + (MaxPictureWidth > MaxPictureHeight ? MaxPictureWidth : MaxPictureHeight);
        }
        else
        {
            sizeParams += "&width=" + MaxPictureWidth + "&height=" + MaxPictureHeight;
        }

        string getAvatarPath = ResolveUrl("~/CMSPages/GetAvatar.aspx");

        // Create id for div with selected image preview
        divId = ClientID + "imgDiv";

        // Javascript which creates selected image preview and saves image guid  to hidden field
        StringBuilder sbScript = new StringBuilder();

        sbScript.Append(@"
function ", ClientID, @"updateHidden(guidPrefix, clientId)
{
    if (clientId == '", ClientID, @"')
    {
        avatarGuid = guidPrefix.substring(4);
        if (avatarGuid != '')
        {
            hidden = document.getElementById('", hiddenAvatarGuid.ClientID, @"');
            hidden.value = avatarGuid ;
            div = document.getElementById('", divId, @"');
            div.style.display='';
            div.innerHTML = '<img src=""", getAvatarPath, @"?avatarguid=' + avatarGuid + '", sizeParams, @""" />&#13;&#10;&nbsp;<img src=""", btnDeleteImage.ImageUrl, @""" border=""0"" onclick=""deleteImagePreview(\'", hiddenAvatarGuid.ClientID, @"\',\'", divId, @"\')"" style=""cursor:pointer""/>';
            placeholder = document.getElementById('", plcImageActions.ClientID, @"');
            if ( placeholder != null)
            {
                placeholder.style.display='none';
            }
        } 
    }
}");
        ControlsHelper.RegisterClientScriptBlock(this, Page, typeof(string), ClientID + "updateHidden", ScriptHelper.GetScript(sbScript.ToString()));
        sbScript.Clear();

        sbScript.Append(@"
function deleteImagePreview(hiddenId, divId)
{
    if(confirm(", ScriptHelper.GetString(GetString("myprofile.pictdeleteconfirm")), @"))
    {   
        hidden = document.getElementById(hiddenId);
        hidden.value = '' ;
        div = document.getElementById(divId);
        div.style.display='none';
        div.innerHTML = '';
    }
}");
        // JavaScript which deletes image preview
        ControlsHelper.RegisterClientScriptBlock(this, Page, typeof(string), "deleteImagePreviewScript", ScriptHelper.GetScript(sbScript.ToString()));
        sbScript.Clear();

        sbScript.Append(@"
function deleteAvatar(hiddenDeleteId, hiddenGuidId, placeholderId)
{
    if(confirm(", ScriptHelper.GetString(GetString("myprofile.pictdeleteconfirm")), @"))
    {
        hidden = document.getElementById(hiddenDeleteId);
        hidden.value = 'true' ;
        placeholder = document.getElementById(placeholderId);
        placeholder.style.display='none';
        hidden = document.getElementById(hiddenGuidId);
        hidden.value = '' ;
    }
    return false;
}");
        // JavaScript which pseudo deletes avatar
        ControlsHelper.RegisterClientScriptBlock(this, Page, typeof(string), "deleteAvatar", ScriptHelper.GetScript(sbScript.ToString()));
    }
    protected override void OnInit(EventArgs e)
    {
        // Register script for closing product section editing UI
        string script = "function CancelSectionEdit() { if(GetSelectedMode() == 'sectionedit'){ SetMode('edit',true);}}";

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "beforenodeselection", ScriptHelper.GetScript(script));

        UIContext[UIContextDataItemName.SELECTEDCULTURE] = Culture;

        // Pass the parameters
        menu.Values.Add(new UILayoutValue("ShowModeMenu", false));

        tree.Values.AddRange(new[] {
            new UILayoutValue("NodeID", NodeID),
            new UILayoutValue("ExpandNodeID", ExpandNodeID),
            new UILayoutValue("Culture", Culture),
            new UILayoutValue("StartingAliasPath", Page.ProductsStartingPath),
            new UILayoutValue("AllowGlobalObjects", Page.AllowGlobalObjects),
            new UILayoutValue("AllowProductsWithoutDocuments", ECommerceSettings.AllowProductsWithoutDocuments(SiteContext.CurrentSiteName)),
            new UILayoutValue("DisplayProductsInSectionsTree", ECommerceSettings.DisplayProductsInSectionsTree(SiteContext.CurrentSiteName)),
            new UILayoutValue("IsProductTree", true),
            new UILayoutValue("BeforeSelectNodeScript", "CancelSectionEdit();")
        });

        // Show pane only for multilingual site
        language.Visible = SiteContext.CurrentSite.HasMultipleCultures;
    }
Example #45
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request["WFID"]))
        {
            wfid = int.Parse(Request["WFID"]);
        }
        else
        {
            if (!string.IsNullOrEmpty(Request["PROCID"]))
            {
                procid = int.Parse(Request["PROCID"]);
                WF_PROCESS_TPL proc = BLLTable <WF_PROCESS_TPL> .GetRowData(WF_PROCESS_TPL.Attribute.PROCID, procid);

                wfid   = proc.WFID;
                title += proc.PROC_NAME + "-";
            }
            else
            {
                Response.Write("非法连接!");
                Response.End();
            }
        }
        if (!string.IsNullOrEmpty(Request["PROCID"]))
        {
            procid = int.Parse(Request["PROCID"]);
        }
        else
        {
            List <WF_PROCESS_TPL> lstProc = BLLTable <WF_PROCESS_TPL> .Select(WF_PROCESS_TPL.Attribute.WFID, wfid);

            if (lstProc.Count > 0)
            {
                procid = lstProc[0].PROCID;
                title += lstProc[0].PROC_NAME + "-";
            }
            else
            {
                ScriptHelper.AlertAndGo(Page, "此流程未配置过程!", "../PROCESS/PROCESSManage.aspx?WFID=" + wfid);
            }
        }
        preUrl = WebHelper.GetAppPath();
        theme  = preUrl + "Themes/" + BasePage._ThemeName;

        if (!IsPostBack)
        {
            string      strJs = "";
            WF_STEP_TPL cond  = new WF_STEP_TPL();
            cond.WFID   = wfid;
            cond.PROCID = procid;


            List <WF_STEP_TPL> lstStep = BLLTable <WF_STEP_TPL> .Factory(conn).Select(new WF_STEP_TPL(), cond);

            foreach (WF_STEP_TPL step in lstStep)
            {
                if (step.STEP_TYPE == 0)
                {
                    htmlText += "<div class='node node-start' type =0 id='" + step.STEP_ID + "'style='left:" + step.BLOCKX + "px;top:" + step.BLOCKY + "px;' ><span>" + step.STEP_NAME + "</span></div>";
                    strJs    += "jsPlumb.addEndpoint('" + step.STEP_ID + "',hollowCircle, { anchors: \"BottomCenter\",uuid:\'" + step.STEP_ID + "e\'  });";
                }
                else if (step.STEP_TYPE == 3)
                {
                    htmlText += "<div class='node node-end' type =3 id='" + step.STEP_ID + "'style='left:" + step.BLOCKX + "px;top:" + step.BLOCKY + "px;' ><span>" + step.STEP_NAME + "</span><div class='active-end'><span>" + step.STEP_NAME + "</span></div></div>";
                    strJs    += "jsPlumb.addEndpoint('" + step.STEP_ID + "', solidCircle, { anchors: \"TopCenter\",uuid:\'" + step.STEP_ID + "s\'  });";
                }
                else if (step.STEP_TYPE == 2)
                {
                    // htmlText += "<div class='node node-route' type =2 id='" + step.STEP_ID + "'style='left:" + step.BLOCKX + "px;top:" + step.BLOCKY + "px;' ><span>" + step.STEP_NAME + "</span><div class='route-content'><span>" + step.STEP_NAME + "</span></div></div>";
                    htmlText += "<div class='node roate' type =2 id='" + step.STEP_ID + "'style='left:" + step.BLOCKX + "px;top:" + step.BLOCKY + "px;' ><span>" + step.STEP_NAME + "</span></div>";
                    strJs    += "jsPlumb.addEndpoint('" + step.STEP_ID + "',  solidCircle,{ anchors: \"TopCenter\",uuid:\'" + step.STEP_ID + "s\'  });";
                    strJs    += "jsPlumb.addEndpoint('" + step.STEP_ID + "', hollowCircle, { anchors: \"BottomCenter\",uuid:\'" + step.STEP_ID + "e\'  });";
                }
                else
                {
                    htmlText += "<div class='node node-active' type =1 id='" + step.STEP_ID + "'style='left:" + step.BLOCKX + "px;top:" + step.BLOCKY + "px;' ><span>" + step.STEP_NAME + "</span><div class='active-content'><span>" + step.STEP_NAME + "</span></div></div>";
                    strJs    += "jsPlumb.addEndpoint('" + step.STEP_ID + "',hollowCircle, { anchors: \"BottomCenter\",uuid:\'" + step.STEP_ID + "e\'  });";
                    strJs    += "jsPlumb.addEndpoint('" + step.STEP_ID + "', solidCircle, { anchors: \"TopCenter\" ,uuid:\'" + step.STEP_ID + "s\' });";
                }
                strJs += "jsPlumb.draggable('" + step.STEP_ID + "');";
                strJs += "doubleclick(" + step.STEP_ID + "," + step.STEP_TYPE + ");";
            }

            WF_STEPATH_TPL condP = new WF_STEPATH_TPL();
            condP.WFID   = wfid;
            condP.PROCID = procid;

            List <WF_STEPATH_TPL> lstPath = BLLTable <WF_STEPATH_TPL> .Factory(conn).Select(new WF_STEPATH_TPL(), condP);

            foreach (WF_STEPATH_TPL path in lstPath)
            {
                //strJs += "jsPlumb.bind(\"connection\",function (connInfo, originalEvent) {	connInfo.connection.setLabel(\" \")});";
                strJs += "jsPlumb.connect({ uuids:[ \"" + path.STEP_ID + "e\",  \"" + path.NEXT_ID +
                         "s\"], detachable:true});";
            }
            //{uuids:["Window2BottomCenter", "Window3TopCenter"], editable:true}
            //HtmlGenericControl sss = new HtmlGenericControl();
            //sss.Attributes.Add("src", "/lib/StepCtr/StepCtr.js");
            //sss.Attributes.Add("type", "text/javascript");

            //Page.Header.Controls.AddAt(4, sss);
            // Response.Write("<script src=\"" + ResolveUrl("~/lib/jquery/jquery-1.11.1.min.js") + "\" type=\"text/javascript\"></script>");
            // Response.Write("<script src=\"" + ResolveUrl("~/lib/StepCtr/StepCtr.js") + "\" type=\"text/javascript\"></script>");


            script = "jsPlumb.ready(function () {" + strJs + "});";
            // ClientScript.RegisterStartupScript(this.GetType(), "myscript", script, true);
        }
    }
	protected void cmdTestClearTimeout_Click ( object sender, EventArgs e )
	{
		string result = string.Empty;
		Tracer tracer = new Tracer ();

		ScriptHelper scriptHelper = new ScriptHelper ();

		result += "测试方法 ScriptHelper.ClearTimeout(string)<br />";

		scriptHelper.SetInterval ( "'alert(\"句柄 timer1\");'", 5000, "timer1" );

		foreach ( object code in tracer.Execute ( scriptHelper, null, "ClearTimeout", FunctionType.Method, new Type[] { typeof ( string ) }, null, null, null,
			new object[][] {
				new object[] { "timer1" },
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "测试方法 ScriptHelper.ClearTimeout(string, bool)<br />";

		scriptHelper.SetInterval ( "'alert(\"句柄 timer2\");'", 5000, "timer2" );

		foreach ( object code in tracer.Execute ( scriptHelper, null, "ClearTimeout", FunctionType.Method, new Type[] { typeof ( string ), typeof ( bool ) }, null, null, null,
			new object[][] {
				new object[] { "timer2", false }
			},
			false
			)
			)
			result += "返回: " + code.ToString () + "<br />";

		result += "scriptHelper.Code = " + scriptHelper.Code + "<br />";

		this.lblResult.Text = result;

		scriptHelper.Build ( this );
	}
Example #47
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get Issue object
        IssueInfo issue = (IssueInfo)CMSContext.EditedObject;

        if ((issue == null) || (issue.IssueSiteID != CMSContext.CurrentSiteID))
        {
            return;
        }

        // Get newsletter object
        NewsletterInfo news = NewsletterInfoProvider.GetNewsletterInfo(issue.IssueNewsletterID);

        string      subject  = null;
        IssueHelper ih       = new IssueHelper();
        string      siteName = CMSContext.CurrentSiteName;

        InitGUI();

        // Get specific number of subscribers subscribed to the newsletter
        string where = "SubscriberID IN (SELECT SubscriberID FROM Newsletter_SubscriberNewsletter WHERE NewsletterID=" + issue.IssueNewsletterID + " AND (SubscriptionApproved=1 OR SubscriptionApproved IS NULL) AND (SubscriptionEnabled=1 OR SubscriptionEnabled IS NULL))";
        DataSet subscribers = SubscriberInfoProvider.GetSubscribers(where, null, MAX_PREVIEW_SUBSCRIBERS, null);

        string script;

        if (!DataHelper.DataSourceIsEmpty(subscribers))
        {
            // Limit max subscribers count to number of rows
            int maxCount = subscribers.Tables[0].Rows.Count;

            // Generate javascript based on subscribers
            script = string.Format(
                @"var currentSubscriberIndex = 0;
var newsletterIssueId ={0};
var guid = new Array({1});
var email = new Array({1});
var subject = new Array({1});
var subscribers = new Array(guid, email);", issue.IssueID, maxCount);

            SubscriberInfo subscriber = null;
            SubscriberInfo sbMember   = null;
            SortedDictionary <int, SubscriberInfo> subMembers = null;
            string infoLine = null;

            for (int i = 0; i < maxCount; i++)
            {
                // Get subscriber
                subscriber = new SubscriberInfo(subscribers.Tables[0].Rows[i]);
                if (subscriber != null)
                {
                    // Insert subscriber GUID
                    script = string.Format("{0} guid[{1}] = '{2}'; \n ", script, i, subscriber.SubscriberGUID);

                    // Get subscriber's member (different for user, role or contact group subscribers)
                    subMembers = SubscriberInfoProvider.GetSubscribers(subscriber, 1, 0, issue.IssueNewsletterID);
                    if ((subMembers != null) && (subMembers.Count > 0))
                    {
                        foreach (KeyValuePair <int, SubscriberInfo> item in subMembers)
                        {
                            // Get 1st subscriber's member
                            sbMember = item.Value;
                            if (sbMember != null)
                            {
                                // Create information line
                                infoLine = ScriptHelper.GetString(sbMember.SubscriberEmail, false);

                                // Add info about subscriber type
                                if (sbMember.SubscriberType.EqualsCSafe(SiteObjectType.USER, true))
                                {
                                    infoLine = string.Format("{0} ({1})", infoLine, GetString("objecttype.cms_user").ToLowerCSafe());
                                }
                                else if (sbMember.SubscriberType.EqualsCSafe(SiteObjectType.ROLE, true))
                                {
                                    infoLine = string.Format("{0} ({1})", infoLine, GetString("objecttype.cms_role").ToLowerCSafe());
                                }
                                else if (sbMember.SubscriberType.EqualsCSafe(PredefinedObjectType.CONTACTGROUP, true))
                                {
                                    infoLine = string.Format("{0} ({1})", infoLine, GetString("objecttype.om_contactgroup").ToLowerCSafe());
                                }
                                else if (sbMember.SubscriberType.EqualsCSafe(PredefinedObjectType.CONTACT, true))
                                {
                                    infoLine = string.Format("{0} ({1})", infoLine, GetString("objecttype.om_contact").ToLowerCSafe());
                                }

                                script = string.Format("{0}email[{1}] = '{2}'; \n ", script, i, infoLine);

                                // Resolve dynamic field macros ({%FirstName%}, {%LastName%}, {%Email%})
                                if (ih.LoadDynamicFields(sbMember, news, null, issue, true, siteName, null, null, null))
                                {
                                    subject = ih.ResolveDynamicFieldMacros(issue.IssueSubject);
                                }

                                // Create resolved subject
                                script = string.Format("{0}subject[{1}] = {2}; \n ", script, i, ScriptHelper.GetString(HTMLHelper.HTMLEncode(subject)));
                            }
                        }
                    }
                    else
                    {
                        script = string.Format("{0}email[{1}] = '{2}'; \n ", script, i, "(N/A)");

                        // Resolve dynamic field macros (newsletter and issue)
                        if (ih.LoadDynamicFields(null, news, null, issue, true, siteName, null, null, null))
                        {
                            subject = ih.ResolveDynamicFieldMacros(issue.IssueSubject);
                        }

                        // Create resolved subject
                        script = string.Format("{0}subject[{1}] = {2}; \n ", script, i, ScriptHelper.GetString(HTMLHelper.HTMLEncode(subject)));
                    }
                }
            }
        }
        else
        {
            // Resolve dynamic field macros ({%FirstName%}, {%LastName%}, {%Email%}) in subject
            if (ih.LoadDynamicFields(null, news, null, issue, true, siteName, null, null, null))
            {
                subject = ih.ResolveDynamicFieldMacros(issue.IssueSubject);
            }

            // Generate void javascript
            script = string.Format(
                @"var currentSubscriberIndex = 0;
var newsletterIssueId ={0};
var guid = new Array(1);
var email = new Array(1);
var subject = new Array(1);
subject[0] = '{1}';
var subscribers = new Array(guid, email);
guid[0] = 0;
email[0] = '(N/A)';", issue.IssueID, subject);
        }
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PreviewData", ScriptHelper.GetScript(script));

        if (!RequestHelper.IsPostBack())
        {
            ScriptHelper.RegisterStartupScript(this, typeof(string), "LoadPreview" + ClientID, ScriptHelper.GetScript("pageLoad();"));
        }
    }
	protected void cmdRun2_Click ( object sender, EventArgs e )
	{
		// 创建 ScriptHelper 对象
		ScriptHelper scriptHelper = new ScriptHelper ();
		string code = this.txtCode2.Text;

		if ( code == string.Empty )
		{
			// 没有脚本, 添加弹出消息框的脚本
			scriptHelper.Alert ( "'没有任何脚本'" );
			scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
			return;
		}

		ScriptHelper.RegisterAttribute ( this, this.lblCode2.ClientID, "innerText", code );
		scriptHelper.AppendCode ( code );

		// 生成脚本到页面
		scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
	}
Example #49
0
    protected override void Render(HtmlTextWriter writer)
    {
        if (SystemContext.DevelopmentMode)
        {
            // Render the resources
            var resources = LocalizationContext.CurrentResources;
            if (resources != null)
            {
                StringBuilder sb = new StringBuilder();

                // Sort the items by
                List <DictionaryEntry> list = new List <DictionaryEntry>(resources.Count);
                foreach (DictionaryEntry item in resources)
                {
                    list.Add(item);
                }
                list.Sort(CompareStrings);

                bool lastUnknown = false;

                sb.Append("<div class=\"MenuHeader\">", ResHelper.GetString("localizable.localize"), "</div>");

                var warningIcon = new CMSIcon {
                    CssClass = "icon-exclamation-triangle color-orange-80 warning-icon"
                }.GetRenderedHTML();

                foreach (DictionaryEntry item in list)
                {
                    string key   = (string)item.Key;
                    string value = ValidationHelper.GetString(item.Value, "");

                    // Handle the unknown status
                    bool unknown = key.EqualsCSafe(value, false);
                    if (!unknown && lastUnknown)
                    {
                        sb.Append("<div class=\"Separator\">&nbsp;</div>");
                    }
                    lastUnknown = unknown;

                    value = HTMLHelper.HTMLEncode(TextHelper.LimitLength(HTMLHelper.StripTags(value), 70));

                    sb.Append("<div class=\"Item\" onclick=\"EditString('", HTMLHelper.HTMLEncode(ScriptHelper.GetString(key, false)) + "'); return false;\"><div class=\"ItemPadding\">", (unknown ? warningIcon : ""), "<span class=\"Name\"><strong>", value, "</strong> (", TextHelper.LimitLength(HTMLHelper.HTMLEncode(key), 50), ")</span></div></div>");
                }

                ltlStrings.Text = sb.ToString();
            }
        }

        base.Render(writer);
    }
	protected void cmdNext3_Click ( object sender, EventArgs e )
	{
		// 创建 ScriptHelper 对象
		ScriptHelper scriptHelper = new ScriptHelper ();
		string name = this.txtName3.Text;

		if ( name == string.Empty )
			// 没有写用户名, 添加弹出消息框的脚本
			scriptHelper.Alert ( "'请填写用户名'" );
		else
		{
			// 隐藏第一步, 显示第二步, 记录用户名到隐藏字段
			ScriptHelper.RegisterAttribute ( this, "r1", "style.display", "none" );
			ScriptHelper.RegisterAttribute ( this, "r2", "style.display", "block" );
			ScriptHelper.RegisterHidden ( this, "r1name", name );
		}

		// 生成脚本
		scriptHelper.Build ( this, option: ScriptBuildOption.Startup );
	}
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void SaveReport()
    {
        // Check 'Modify' permission
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.reporting", "Modify"))
        {
            RedirectToAccessDenied("cms.reporting", "Modify");
        }
        string errorMessage = new Validator().NotEmpty(txtReportDisplayName.Text.Trim(), rfvReportDisplayName.ErrorMessage).NotEmpty(txtReportName.Text.Trim(), rfvReportName.ErrorMessage).Result;

        if (String.IsNullOrEmpty(errorMessage) && (!ValidationHelper.IsCodeName(txtReportName.Text.Trim())))
        {
            errorMessage = GetString("general.invalidcodename");
        }

        if (String.IsNullOrEmpty(errorMessage))
        {
            ReportInfo reportInfo = ReportInfoProvider.GetReportInfo(reportId);
            ReportInfo nri        = ReportInfoProvider.GetReportInfo(txtReportName.Text.Trim());

            // If report with given name already exists show error message
            if ((nri != null) && (nri.ReportID != reportInfo.ReportID))
            {
                ShowError(GetString("Report_New.ReportAlreadyExists"));
                return;
            }

            if (reportInfo != null)
            {
                reportInfo.ReportLayout = htmlTemplateBody.ResolvedValue;

                // If there was a change in report code name change codenames in layout
                if (reportInfo.ReportName != txtReportName.Text.Trim())
                {
                    // part of old macro
                    string oldValue = "?" + reportInfo.ReportName + ".";
                    string newValue = "?" + txtReportName.Text.Trim() + ".";

                    reportInfo.ReportLayout = reportInfo.ReportLayout.Replace(oldValue, newValue);

                    // Set updated text back to HTML editor
                    htmlTemplateBody.ResolvedValue = reportInfo.ReportLayout;
                }
                int categoryID = ValidationHelper.GetInteger(selectCategory.Value, reportInfo.ReportCategoryID);

                // If there was a change in display name refresh category tree
                if ((reportInfo.ReportDisplayName != txtReportDisplayName.Text.Trim()) || (reportInfo.ReportCategoryID != categoryID))
                {
                    ScriptHelper.RegisterClientScriptBlock(Page, typeof(String), "RefreshParent", ScriptHelper.GetScript("if (parent.refreshPage) {parent.refreshPage()} else parent.location = parent.location;"));
                }

                reportInfo.ReportDisplayName        = txtReportDisplayName.Text.Trim();
                reportInfo.ReportName               = txtReportName.Text.Trim();
                reportInfo.ReportAccess             = ReportAccessEnum.All;
                reportInfo.ReportCategoryID         = categoryID;
                reportInfo.ReportEnableSubscription = chkEnableSubscription.Checked;
                reportInfo.ReportConnectionString   = ValidationHelper.GetString(ucSelectString.Value, String.Empty);

                ReportInfoProvider.SetReportInfo(reportInfo);

                ShowChangesSaved();

                // Reload header if changes were saved
                ScriptHelper.RefreshTabHeader(Page, reportInfo.ReportDisplayName);
            }
        }
        else
        {
            ShowError(errorMessage);
        }
    }
	protected void cmdOK4_Click ( object sender, EventArgs e )
	{
		// 创建 ScriptHelper 对象
		ScriptHelper scriptHelper = new ScriptHelper ();

		// 声明用于存储颜色值得数组
		ScriptHelper.RegisterArray ( this, "colors", "10, 99, 10" );

		// 添加可以得到不同颜色的函数
		scriptHelper.AppendCode ( "function GetNextColor(){colors[0]++;colors[1]--;colors[2]+=2;if(colors[0]>99){colors[0]=10;}if(colors[1]<10){colors[1]=99;}if(colors[2]>99){colors[2]=10;}return '#' + colors[0].toString() + colors[1].toString() + colors[2].toString(); }" );

		// 设置时钟, 改变标签的颜色
		scriptHelper.SetInterval ( "function(){document.getElementById('span4').style.color = GetNextColor();}", 100 );

		// 生成脚本
		scriptHelper.Build ( this, option:ScriptBuildOption.Startup );
	}
    /// <summary>
    /// Renders complete rule.
    /// </summary>
    /// <param name="rule">Rule to render</param>
    private string GetRuleHTML(MacroRuleTree rule)
    {
        StringBuilder sb = new StringBuilder();

        // Append operator
        if (rule.Position > 0)
        {
            bool isAnd = (rule.Operator == "&&");
            sb.Append("<div class=\"MacroRuleOperator\" style=\"padding-left: ", 15 * (rule.Level - 1), "px\" onclick=\"ChangeOperator('", rule.IDPath, "', '", (isAnd ? "||" : "&&"), "');\">", (isAnd ? "and" : "or"), "</div>");
        }

        if (rule.IsLeaf)
        {
            sb.Append("<div id=\"", rule.IDPath, "\" class=\"MacroRule\" style=\"padding-left: ", 15 * (rule.Level - 1), "px\">");

            // Register position to a JS hashtable (for drag and drop purposes)
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "targetPosition" + counter, "targetPosition[" + counter++ + "] = '" + rule.Parent.IDPath + ";" + rule.Position + "';", true);

            sb.Append("<span id=\"ruleHandle" + rule.IDPath + "\"  class=\"MacroRuleHandle\">");
            string handleParams = "<span" + (rule.IsLeaf ? " onclick=\"SelectRule('" + rule.IDPath + "', $cmsj(this).parent()); return false;\"" : "") + "onmousedown=\"return false;\" onmouseover=\"ActivateBorder('ruleText" + rule.IDPath + "', 'MacroRuleText');\" onmouseout=\"DeactivateBorder('ruleText" + rule.IDPath + "', 'MacroRuleText');\">";
            string text         = handleParams.Replace("##ID##", "0") + HTMLHelper.HTMLEncode(rule.RuleText) + "</span>";
            if (rule.Parameters != null)
            {
                foreach (string key in rule.Parameters.Keys)
                {
                    MacroRuleParameter p = rule.Parameters[key];

                    string paramText = (string.IsNullOrEmpty(p.Text) ? p.DefaultText : p.Text.TrimStart('#'));
                    paramText = MacroRuleTree.GetParameterText(paramText, true, null, p.ApplyValueTypeConversion ? p.ValueType : "text");

                    var parameterText = "</span><span class=\"MacroRuleParameter\" onclick=\"ChangeParamValue('" + rule.IDPath + "', " + ScriptHelper.GetString(key) + ");\">" + paramText + "</span>" + handleParams;

                    text = Regex.Replace(text, "\\{" + key + "\\}", TextHelper.EncodeRegexSubstitutes(parameterText), CMSRegex.IgnoreCase);
                }
            }
            bool isSelected = hdnSelected.Value.Contains(";" + rule.IDPath + ";");
            sb.Append("<div id=\"ruleText", rule.IDPath, "\" class=\"MacroRuleText", (isSelected ? " RuleSelected" : ""), "\">", text, "</div>");
            sb.Append("</span>");
            sb.Append("</div>");
        }
        else
        {
            foreach (MacroRuleTree child in rule.Children)
            {
                sb.Append(GetRuleHTML(child));
            }
        }

        return(sb.ToString());
    }