コード例 #1
0
ファイル: Client.cs プロジェクト: okolobaxa/uploadcare-csharp
 /// <summary>
 /// Initializes a client with custom access keys.
 /// Can use simple or secure authentication.
 /// </summary>
 /// <param name="publicKey"> Public key </param>
 /// <param name="privateKey"> Private key </param>
 /// <param name="simpleAuth"> If false, HMAC-based authentication is used </param>
 public Client(string publicKey, string privateKey, bool simpleAuth = true)
 {
     _publicKey = publicKey;
     _privateKey = privateKey;
     _simpleAuth = simpleAuth;
     _requestHelper = new RequestHelper(this);
 }
コード例 #2
0
ファイル: TokenHelper.cs プロジェクト: AAlben/Mall_WeChart_Nf
        /// <summary>
        /// 进行 Token 请求,将值存储在静态类中
        /// </summary>
        public static void RequestServiceToken()
        {
            //表示 请求 成功与否
            bool flag = false;

            //1.请求 Token
            string url = "https://api.weixin.qq.com/cgi-bin/token";

            //2.带参数

            var dnmXML = XMLHelper.LoadConfigXML("SystemConfigXML");

            var par = new
            {
                grant_type = "client_credential",
                appid = dnmXML.SystemConfig.AppID,
                secret = dnmXML.SystemConfig.AppSecret
            };

            RequestHelper _requestHelper = new RequestHelper();

            string strPar = _requestHelper.JoinArguments(par);

            //接收准备
            string s_access_token = string.Empty;
            string s_expires_in = string.Empty;

            //3.请求
            using (HttpClient htpClt = new HttpClient())
            {
                string rqtResult = htpClt.GetStringAsync(new Uri(url + strPar)).Result;

                dynamic dnm = JsonConvert.DeserializeObject(rqtResult);

                if (dnm.errorcode != null)
                {
                    flag = false; //失败
                }
                else
                {
                    flag = true; //成功
                    s_access_token = dnm.access_token;
                    s_expires_in = dnm.expires_in;
                }
            }

            if (flag)
            {
                //4.给静态对象赋值
                TokenEntity.Token = s_access_token;
                TokenEntity.DateLength = int.Parse(s_expires_in);
                TokenEntity.ExpiresDate = DateTime.Now.AddSeconds(TokenEntity.DateLength);
            }
        }
コード例 #3
0
	/// <summary>
	/// Salva a pontuaçao do jogador deixando a plataforma decidir quantas moedas serao dadas
	/// </summary>
	/// <returns>RequestModel com todas informaçoes desse tipo de requisicao</returns>
	/// <param name="__score">Pontuaçao do jogador</param>
	/// <param name="__stage">A fase dessa pontuaçao</param>
	/// <param name="__timeSpent">Tempo gasto nessa fase</param>
	/// <param name="__stars">Quantidade de estrelas ganhas nessa fase</param>
	/// <param name="__callbackRequestCompleted">__callback request completed.</param>
	/// <param name="__callbackRequestError">__callback request error.</param>
	/// <param name="__callbackRequestStarted">__callback request started.</param>
	/// <param name="__callbackRequestFinalized">__callback request finalized.</param>
	public static SavePlayerScoreRM savePlayerScore(float __score,
	                                                int __stage,
	                                                int __timeSpent,
	                                                int __stars,
	                                                RequestHelper.RequestHandlerDelegate __callbackRequestCompleted = null,
	                                                RequestHelper.RequestHandlerDelegate __callbackRequestError = null,
	                                                RequestHelper.RequestHandlerDelegate __callbackRequestStarted = null,
	                                                RequestHelper.RequestHandlerDelegate __callbackRequestFinalized = null)
	{
		return savePlayerScore(__score, __stage, __timeSpent, -1, __stars, __callbackRequestCompleted, __callbackRequestError, __callbackRequestStarted, __callbackRequestFinalized);
	}
コード例 #4
0
	/// <summary>
	/// Retorna o ranking do minigame (disponivel apenas pra webplayer integrado com a plataforma)
	/// </summary>
	/// <returns>RequestModel com todas informaçoes desse tipo de requisicao</returns>
	/// <param name="__period">Periodo do ranking (usar constantes da classe RequestHelper)</param>
	/// <param name="__page">Numero da pagina</param>
	/// <param name="__itensPerPage">Quantidade de pontuaçoes por pagina</param>
	/// <param name="__callbackRequestCompleted">__callback request completed.</param>
	/// <param name="__callbackRequestError">__callback request error.</param>
	/// <param name="__callbackRequestStarted">__callback request started.</param>
	/// <param name="__callbackRequestFinalized">__callback request finalized.</param>
	public static GetMinigameRankingRM getMinigameRanking(  string __period, 
															int __page, 
															int __itensPerPage,
															RequestHelper.RequestHandlerDelegate __callbackRequestCompleted = null,
															RequestHelper.RequestHandlerDelegate __callbackRequestError = null,
															RequestHelper.RequestHandlerDelegate __callbackRequestStarted = null,
															RequestHelper.RequestHandlerDelegate __callbackRequestFinalized = null)
	{
		GetMinigameRankingRM request = new GetMinigameRankingRM();
		request.cvo.setupParameters(__period, __page, __itensPerPage);
		setupRequest(request, __callbackRequestCompleted, __callbackRequestError, __callbackRequestStarted, __callbackRequestFinalized);
		return request;
	}
コード例 #5
0
	/// <summary>
	/// Salva a pontuaçao do jogador
	/// </summary>
	/// <returns>RequestModel com todas informaçoes desse tipo de requisicao</returns>
	/// <param name="__score">Pontuaçao do jogador</param>
	/// <param name="__stage">A fase dessa pontuaçao</param>
	/// <param name="__timeSpent">Tempo gasto nessa fase</param>
	/// <param name="__coins">Quantidade de coins ganhos nessa fase</param>
	/// <param name="__stars">Quantidade de estrelas ganhas nessa fase</param>
	/// <param name="__callbackRequestCompleted">__callback request completed.</param>
	/// <param name="__callbackRequestError">__callback request error.</param>
	/// <param name="__callbackRequestStarted">__callback request started.</param>
	/// <param name="__callbackRequestFinalized">__callback request finalized.</param>
	public static SavePlayerScoreRM savePlayerScore(float __score,
													int __stage,
													int __timeSpent,
													int __coins,
													int __stars,
													RequestHelper.RequestHandlerDelegate __callbackRequestCompleted = null,
													RequestHelper.RequestHandlerDelegate __callbackRequestError = null,
													RequestHelper.RequestHandlerDelegate __callbackRequestStarted = null,
													RequestHelper.RequestHandlerDelegate __callbackRequestFinalized = null)
	{
		SavePlayerScoreRM request = new SavePlayerScoreRM();
		request.cvo.setupParameters(__score, __stage, __timeSpent, __coins, __stars);
		setupRequest(request, __callbackRequestCompleted, __callbackRequestError, __callbackRequestStarted, __callbackRequestFinalized);
		return request;
	}
コード例 #6
0
ファイル: MethodBase.cs プロジェクト: gruan01/Bing-Translate
        /// <summary>
        /// 获取API调用的结果字符串
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        internal virtual async Task<string> GetResult(ApiClient client) {
            var url = client.GetApiUrl(this);
            var dic = this.GetParams();
            var rh = new RequestHelper(client.Cookies);

            if (!client.Token.IsInvalid) {
                rh.RequestHeader = new Dictionary<string, string>();
                rh.RequestHeader.Add("Authorization", string.Format("Bearer {0}", client.Token.Token));
            }

            var ctx = "";
            if (this.RequestType == HttpMethods.Get) {
                ctx = rh.Get(url, dic);
            } else {
                ctx = rh.Post(url, dic);
            }
            return ctx;
        }
コード例 #7
0
 /// <summary>
 /// 记录错误信息
 /// </summary>
 /// <param name="ex">错误数据对象</param>
 /// <returns></returns>
 public static int InsertByError(Exception ex)
 {
     try
     {
         if ((ex is System.Threading.ThreadAbortException))
         {
             return(-1);
         }
         DawnAuthErrorMDL errInfo = new DawnAuthErrorMDL();
         if (ex.InnerException != null)
         {
             errInfo.ErrTime    = System.DateTime.Now;
             errInfo.ErrAddress = string.IsNullOrEmpty(RequestHelper.GetUrl()) == true ? "非法数据!(页面信息)" : RequestHelper.GetUrl();
             errInfo.ErrMessage = string.IsNullOrEmpty(ex.InnerException.Message) == true ? "非法数据!(错误信息)" : ex.InnerException.Message;
             errInfo.ErrTarget  = string.IsNullOrEmpty(ex.InnerException.TargetSite.ToString()) == true ? "非法数据!(异常方法)" : ex.InnerException.TargetSite.ToString();
             errInfo.ErrTrace   = string.IsNullOrEmpty(ex.InnerException.StackTrace) == true ? "非法数据!(表示形式)" : ex.InnerException.StackTrace;
             errInfo.ErrSource  = string.IsNullOrEmpty(ex.InnerException.Source) == true ? "非法数据!(数据源)" : ex.InnerException.Source;
             errInfo.ErrIp      = string.IsNullOrEmpty(RequestHelper.GetIPAddress()) == true ? "非法数据!(IP地址)" : RequestHelper.GetIPAddress();
             errInfo.ErrUid     = DawnauthHandler.UserId;
             errInfo.ErrUname   = string.IsNullOrEmpty(DawnauthHandler.UserSurname) ? "未登录" : DawnauthHandler.UserSurname;
         }
         else
         {
             errInfo.ErrTime    = System.DateTime.Now;
             errInfo.ErrAddress = string.IsNullOrEmpty(RequestHelper.GetUrl()) == true ? "非法数据!(页面信息)" : RequestHelper.GetUrl();
             errInfo.ErrMessage = string.IsNullOrEmpty(ex.Message) == true ? "非法数据!(错误信息)" : ex.Message;
             errInfo.ErrTarget  = string.IsNullOrEmpty(ex.TargetSite.ToString()) == true ? "非法数据!(异常方法)" : ex.TargetSite.ToString();
             errInfo.ErrTrace   = string.IsNullOrEmpty(ex.StackTrace) == true ? "非法数据!(表示形式)" : ex.StackTrace;
             errInfo.ErrSource  = string.IsNullOrEmpty(ex.Source) == true ? "非法数据!(数据源)" : ex.Source;
             errInfo.ErrIp      = string.IsNullOrEmpty(RequestHelper.GetIPAddress()) == true ? "非法数据!(IP地址)" : RequestHelper.GetIPAddress();
             errInfo.ErrUid     = DawnauthHandler.UserId;
             errInfo.ErrUname   = string.IsNullOrEmpty(DawnauthHandler.UserSurname) ? "未登录" : DawnauthHandler.UserSurname;
         }
         int res = DawnAuthErrorBLL.Insert(errInfo);
         return(res);
     }
     catch
     {
         return(-1);
     }
 }
コード例 #8
0
	/// <summary>
	/// Retorna o historico do jogador com todas as fases jogadas por ele
	/// </summary>
	/// <returns>RequestModel com todas informaçoes desse tipo de requisicao</returns>
	/// <param name="__callbackRequestCompleted">__callback request completed.</param>
	/// <param name="__callbackRequestError">__callback request error.</param>
	/// <param name="__callbackRequestStarted">__callback request started.</param>
	/// <param name="__callbackRequestFinalized">__callback request finalized.</param>
	public static GetPlayerHistoryRM getPlayerHistory(RequestHelper.RequestHandlerDelegate __callbackRequestCompleted = null,
														RequestHelper.RequestHandlerDelegate __callbackRequestError = null,
														RequestHelper.RequestHandlerDelegate __callbackRequestStarted = null,
														RequestHelper.RequestHandlerDelegate __callbackRequestFinalized = null)
	{
		GetPlayerHistoryRM request = new GetPlayerHistoryRM();
		request.cvo.setupParameters();
		setupRequest(request, __callbackRequestCompleted, __callbackRequestError, __callbackRequestStarted, __callbackRequestFinalized);
		return request;
	}
コード例 #9
0
        public void GetCourseRoomInfo(HttpContext context)
        {
            int intSuccess = (int)errNum.Success;

            try
            {
                HttpRequest request    = context.Request;
                string      TeacherUID = RequestHelper.string_transfer(request, "TeacherUID");

                List <Course>    Course_List    = Constant.Course_List;
                List <CourseRel> CourseRel_List = Constant.CourseRel_List;
                var query = new object();
                if (!string.IsNullOrEmpty(TeacherUID))
                {
                    query = from Course_ in Course_List
                            join CourseRel_ in CourseRel_List on Course_.UniqueNo equals CourseRel_.Course_Id
                            join CR in Constant.CourseRoom_List on Course_.UniqueNo equals CR.Coures_Id
                            //where CR.StudySection_Id == sectionId
                            where CR.TeacherUID == TeacherUID
                            select new
                    {
                        //课程名称
                        Course_Name = Course_.Name,
                        //课程编号
                        Course_No = Course_.UniqueNo,
                        //课程分类id
                        CourseRel_Id = CourseRel_.CourseType_Id,
                        //
                        TeacharUniqueNo = CR.TeacherUID,
                    };
                }
                else
                {
                    query = from Course_ in Course_List
                            join CourseRel_ in CourseRel_List on Course_.UniqueNo equals CourseRel_.Course_Id
                            join CR in Constant.CourseRoom_List on Course_.UniqueNo equals CR.Coures_Id
                            //where CR.StudySection_Id == sectionId
                            select new
                    {
                        //课程名称
                        Course_Name = Course_.Name,
                        //课程编号
                        Course_No = Course_.UniqueNo,
                        //课程分类id
                        CourseRel_Id = CourseRel_.CourseType_Id,
                        //
                        TeacharUniqueNo = CR.TeacherUID,
                    };
                }

                jsonModel = JsonModel.get_jsonmodel(intSuccess, "success", query);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            finally
            {
                //无论后端出现什么问题,都要给前端有个通知【为防止jsonModel 为空 ,全局字段 jsonModel 特意声明之后进行初始化】
                context.Response.Write("{\"result\":" + Constant.jss.Serialize(jsonModel) + "}");
            }
        }
コード例 #10
0
        public void AddCourseType(HttpContext context)
        {
            HttpRequest request        = context.Request;
            string      CourseTypeName = RequestHelper.string_transfer(request, "CourseTypeName");
            string      CreateUID      = RequestHelper.string_transfer(request, "CreateUID");
            int         SectionId      = RequestHelper.int_transfer(request, "SectionId");
            int         IsEnable       = RequestHelper.int_transfer(request, "IsEnable");

            try
            {
                //课程变更【启用禁用】
                if (!string.IsNullOrEmpty(CourseTypeName))
                {
                    //获取课程类型 课程的值 +1
                    Sys_Dictionary dic_max = (from t in Constant.Sys_Dictionary_List where t.Type == "0" orderby Convert.ToInt32(t.Key) descending select t).ToList()[0];
                    if (dic_max != null)
                    {
                        int            va         = Convert.ToInt32(dic_max.Key) + 1;
                        Sys_Dictionary dictionary = new Sys_Dictionary()
                        {
                            Pid        = 0,
                            Key        = Convert.ToString(va),
                            Value      = CourseTypeName,
                            Type       = "0",
                            SectionId  = SectionId,
                            CreateTime = DateTime.Now,
                            EditTime   = DateTime.Now,
                            CreateUID  = CreateUID,
                            EditUID    = CreateUID,
                            IsDelete   = 0,
                            Sort       = 0,
                            IsEnable   = (byte)IsEnable,
                        };
                        //添加一个课程类型
                        jsonModel = Constant.Sys_DictionaryService.Add(dictionary);

                        if (jsonModel.errNum == 0)
                        {
                            dictionary.Id = Convert.ToInt32(jsonModel.retData);
                            Constant.Sys_Dictionary_List.Add(dictionary);
                        }
                    }
                    else
                    {
                        jsonModel = JsonModel.get_jsonmodel((int)errNum.Failed, "failed", "数据出现异常");
                    }
                }
                else
                {
                    jsonModel = JsonModel.get_jsonmodel((int)errNum.Failed, "failed", "数据出现异常");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            finally
            {
                //无论后端出现什么问题,都要给前端有个通知【为防止jsonModel 为空 ,全局字段 jsonModel 特意声明之后进行初始化】
                context.Response.Write("{\"result\":" + Constant.jss.Serialize(jsonModel) + "}");
            }
        }
コード例 #11
0
    protected void LoadData()
    {
        if (!EditedNewsletter.CheckPermissions(PermissionsEnum.Modify, CurrentSiteName, CurrentUser))
        {
            RedirectToAccessDenied(EditedNewsletter.TypeInfo.ModuleName, "Configure");
        }

        int siteId = EditedNewsletter.NewsletterSiteID;

        // Initialize template selectors
        string whereTemplate = "TemplateType='{0}' AND TemplateSiteID=" + siteId;

        subscriptionTemplate.WhereCondition   = String.Format(whereTemplate, EmailTemplateTypeEnum.Subscription.ToStringRepresentation());
        unsubscriptionTemplate.WhereCondition = String.Format(whereTemplate, EmailTemplateTypeEnum.Unsubscription.ToStringRepresentation());
        optInSelector.WhereCondition          = String.Format(whereTemplate, EmailTemplateTypeEnum.DoubleOptIn.ToStringRepresentation());
        usTemplates.WhereCondition            = String.Format(whereTemplate, EmailTemplateTypeEnum.Issue.ToStringRepresentation());

        // Check if the newsletter is dynamic and adjust config dialog
        isDynamic = String.Equals(EditedNewsletter.NewsletterSource, NewsletterSource.Dynamic, StringComparison.InvariantCultureIgnoreCase);

        // Display template/dynamic based newsletter config and online marketing config
        plcDynamic.Visible   = isDynamic;
        plcTemplates.Visible = !isDynamic;
        plcTracking.Visible  = TrackingEnabled;
        plcOM.Visible        = OnlineMarketingEnabled;

        if (!RequestHelper.IsPostBack())
        {
            if (QueryHelper.GetBoolean("saved", false))
            {
                // If user was redirected from newsletter_new.aspx, display the 'Changes were saved' message
                ShowChangesSaved();
            }

            // Fill config dialog with newsletter data
            GetNewsletterValues(EditedNewsletter);

            if (!isDynamic)
            {
                LoadTemplates();
            }
            else
            {
                // Check if dynamic newsletter subject is empty
                bool subjectEmpty = string.IsNullOrEmpty(EditedNewsletter.NewsletterDynamicSubject);
                radPageTitle.Checked = subjectEmpty;
                radFollowing.Checked = !subjectEmpty;
                txtSubject.Enabled   = radFollowing.Checked;

                if (!subjectEmpty)
                {
                    txtSubject.Text = EditedNewsletter.NewsletterDynamicSubject;
                }

                txtNewsletterDynamicURL.Value = EditedNewsletter.NewsletterDynamicURL;

                TaskInfo task = TaskInfoProvider.GetTaskInfo(EditedNewsletter.NewsletterDynamicScheduledTaskID);
                if (task != null)
                {
                    chkSchedule.Checked                = true;
                    schedulerInterval.Visible          = true;
                    schedulerInterval.ScheduleInterval = task.TaskInterval;
                }
                else
                {
                    chkSchedule.Checked       = false;
                    schedulerInterval.Visible = false;
                }
            }
        }
    }
コード例 #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        this.RegisterExportScript();

        //// Images
        imgNewCategory.ImageUrl  = GetImageUrl("Objects/CMS_WebPartCategory/add.png");
        imgNewReport.ImageUrl    = GetImageUrl("Objects/Reporting_report/add.png");
        imgDeleteItem.ImageUrl   = GetImageUrl("Objects/CMS_WebPart/delete.png");
        imgExportObject.ImageUrl = GetImageUrl("Objects/CMS_WebPart/export.png");
        imgCloneReport.ImageUrl  = GetImageUrl("CMSModules/CMS_WebParts/clone.png");

        // Resource strings
        lnkDeleteItem.Text   = GetString("Development-Report_Tree.DeleteSelected");
        lnkNewCategory.Text  = GetString("Development-Report_Tree.NewCategory");
        lnkNewReport.Text    = GetString("Development-Report_Tree.NewReport");
        lnkExportObject.Text = GetString("Development-Report_Tree.ExportObject");
        lnkCloneReport.Text  = GetString("Development-Report_Tree.CloneReport");

        // Setup menu action scripts
        lnkNewReport.Attributes.Add("onclick", "NewItem('report');");
        lnkNewCategory.Attributes.Add("onclick", "NewItem('reportcategory');");
        lnkDeleteItem.Attributes.Add("onclick", "DeleteItem();");
        lnkExportObject.Attributes.Add("onclick", "ExportObject();");
        lnkCloneReport.Attributes.Add("onclick", "CloneReport();");

        // Widgets
        lnkDeleteItem.ToolTip   = GetString("Development-Report_Tree.DeleteSelected");
        lnkNewCategory.ToolTip  = GetString("Development-Report_Tree.NewCategory");
        lnkNewReport.ToolTip    = GetString("Development-Report_Tree.NewReport");
        lnkExportObject.ToolTip = GetString("Development-Report_Tree.ExportObject");
        lnkCloneReport.ToolTip  = GetString("Development-Report_Tree.CloneReport");

        pnlSubBox.CssClass = BrowserHelper.GetBrowserClass();

        //// URLs for menu actions
        string script = "var categoryURL = '" + ResolveUrl("ReportCategory_Edit_Frameset.aspx") + "';\n";

        script += "var reportURL = '" + ResolveUrl("Report_Edit.aspx") + "';\n";
        script += "var doNotReloadContent = false;\n";

        // Script for deleting widget or category
        string delPostback  = ControlsHelper.GetPostBackEventReference(this.Page, "##");
        string deleteScript = "function DeleteItem() { \n" +
                              " if ((selectedItemId > 0) && (selectedItemParent > 0) && " +
                              " confirm('" + GetString("general.deleteconfirmation") + "')) {\n " +
                              delPostback.Replace("'##'", "selectedItemType+';'+selectedItemId+';'+selectedItemParent") + ";\n" +
                              "}\n" +
                              "}\n";

        script += deleteScript;

        // Preselect tree item
        if (!RequestHelper.IsPostBack())
        {
            int  categoryId = QueryHelper.GetInteger("categoryid", 0);
            int  reportID   = QueryHelper.GetInteger("reportid", 0);
            bool reload     = QueryHelper.GetBoolean("reload", false);

            // Select category
            if (categoryId > 0)
            {
                ReportCategoryInfo rci = ReportCategoryInfoProvider.GetReportCategoryInfo(categoryId);
                if (rci != null)
                {
                    // If not set explicitly stop reloading of right frame
                    if (!reload)
                    {
                        script += "doNotReloadContent = true;";
                    }
                    script += SelectAtferLoad(rci.CategoryPath, categoryId, "reportcategory", rci.CategoryParentID, true);
                }
            }
            // Select report
            else if (reportID > 0)
            {
                ReportInfo ri = ReportInfoProvider.GetReportInfo(reportID);
                if (ri != null)
                {
                    ReportCategoryInfo rci = ReportCategoryInfoProvider.GetReportCategoryInfo(ri.ReportCategoryID);
                    if (rci != null)
                    {
                        // If not set explicitly stop reloading of right frame
                        if (!reload)
                        {
                            script += "doNotReloadContent = true;";
                        }
                        string path = rci.CategoryPath + "/" + ri.ReportName;
                        script += SelectAtferLoad(path, reportID, "report", ri.ReportCategoryID, true);
                    }
                }
            }
            // Select root by default
            else
            {
                ReportCategoryInfo rci = ReportCategoryInfoProvider.GetReportCategoryInfo("/");
                if (rci != null)
                {
                    script += SelectAtferLoad("/", rci.CategoryID, "reportcategory", 0, true);
                }

                // Directly dispatch an action, if set by URL
                if (QueryHelper.GetString("action", null) == "newcategory")
                {
                    script += "NewItem('reportcategory');";
                }
            }
        }

        ltlScript.Text += ScriptHelper.GetScript(script);
    }
コード例 #13
0
        public async Task <IActionResult> ModelValidation(string org, string service, int instanceId)
        {
            // Dependency Injection: Getting the Service Specific Implementation based on the service parameter data store
            // Will compile code and load DLL in to memory for AltinnCore
            IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(org, service);

            // Create and populate the RequestContext object and make it available for the service implementation so
            // service developer can implement logic based on information about the request and the user performing
            // the request
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, instanceId);

            requestContext.UserContext = _userHelper.GetUserContext(HttpContext);
            requestContext.Reportee    = requestContext.UserContext.Reportee;
            requestContext.Form        = Request.Form;

            // Get the serviceContext containing all metadata about current service
            ServiceContext serviceContext = _execution.GetServiceContext(org, service);

            // Assign the Requestcontext and ViewBag to the serviceImplementation so
            // service developer can use the information in any of the service events that is called
            serviceImplementation.SetContext(requestContext, ViewBag, serviceContext, null, ModelState);

            // Set the platform services to the ServiceImplementation so the AltinnCore service can take
            // use of the plattform services
            PlatformServices platformServices = new PlatformServices(_authorization, _repository, _execution, org, service);

            serviceImplementation.SetPlatformServices(platformServices);

            ViewBag.PlatformServices = platformServices;

            // Getting the populated form data from database
            dynamic serviceModel = _form.GetFormModel(
                instanceId,
                serviceImplementation.GetServiceModelType(),
                org,
                service,
                requestContext.UserContext.ReporteeId);

            serviceImplementation.SetServiceModel(serviceModel);

            // Do Model Binding and update form data
            await TryUpdateModelAsync(serviceModel);

            // ServiceEvent : HandleValidationEvent
            // Perform Validation defined by the service developer.
            await serviceImplementation.RunServiceEvent(ServiceEventType.Validation);

            ApiResult apiResult = new ApiResult();

            ModelHelper.MapModelStateToApiResult(ModelState, apiResult, serviceContext);

            if (apiResult.Status.Equals(ApiStatusType.ContainsError))
            {
                Response.StatusCode = 202;
            }
            else
            {
                Response.StatusCode = 200;
            }

            return(new ObjectResult(apiResult));
        }
コード例 #14
0
    /// <summary>
    /// OnPrerender check whether.
    /// </summary>
    protected override void OnPreRender(EventArgs e)
    {
        postTreeElem.Selected = ValidationHelper.GetInteger(hdnSelected.Value, SelectedPost);
        if ((mSelectedPost == 0) && (RequestHelper.IsAJAXRequest()))
        {
            mSelectedPost = postTreeElem.Selected;
        }

        if (mSelectedPost > 0)
        {
            ForumPostInfo fpi = ForumPostInfoProvider.GetForumPostInfo(mSelectedPost);
            if ((fpi != null) && (ForumContext.CurrentForum != null) && (fpi.PostForumID == ForumContext.CurrentForum.ForumID))
            {
                plcPostPreview.Visible = true;
                ltlPostSubject.Text    = HTMLHelper.HTMLEncode(fpi.PostSubject);
                ltlPostText.Text       = ResolvePostText(fpi.PostText);
                ltlSignature.Text      = GetSignatureArea(fpi, "<div class=\"SignatureArea\">", "</div>");
                ltlPostTime.Text       = TimeZoneHelper.ConvertToUserTimeZone(fpi.PostTime, false, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite).ToString();
                ltlPostUser.Text       = "<span class=\"PostUserName\">" + GetUserName(fpi) + "</span>";
                ltlAvatar.Text         = AvatarImage(fpi);
                mUnapproved            = !fpi.PostApproved ? " Unapproved" : "";

                if (ForumContext.CurrentForum.ForumEnableAdvancedImage)
                {
                    ltlPostText.AllowedControls = ControlsHelper.ALLOWED_FORUM_CONTROLS;
                }
                else
                {
                    ltlPostText.AllowedControls = "none";
                }

                attachmentDisplayer.ClearData();
                attachmentDisplayer.PostID = fpi.PostId;
                attachmentDisplayer.PostAttachmentCount = fpi.PostAttachmentCount;
                attachmentDisplayer.ReloadData();


                #region "Badge"

                if (DisplayBadgeInfo)
                {
                    if (fpi.PostUserID > 0)
                    {
                        UserInfo ui = UserInfoProvider.GetUserInfo(fpi.PostUserID);
                        if ((ui != null) && (!ui.IsPublic()))
                        {
                            BadgeInfo bi = BadgeInfoProvider.GetBadgeInfo(ui.UserSettings.UserBadgeID);
                            if (bi != null)
                            {
                                ltlBadge.Text = "<div class=\"Badge\">" + HTMLHelper.HTMLEncode(bi.BadgeDisplayName) + "</div>";
                                if (!String.IsNullOrEmpty(bi.BadgeImageURL))
                                {
                                    ltlBadge.Text += "<div class=\"BadgeImage\"><img alt=\"" + HTMLHelper.HTMLEncode(bi.BadgeDisplayName) + "\" src=\"" + HTMLHelper.HTMLEncode(GetImageUrl(bi.BadgeImageURL)) + "\" /></div>";
                                }
                            }
                        }
                    }

                    // Set public badge if no badge is set
                    if (String.IsNullOrEmpty(ltlBadge.Text))
                    {
                        ltlBadge.Text = "<div class=\"Badge\">" + GetString("Forums.PublicBadge") + "</div>";
                    }
                }

                #endregion


                #region "Post actions"

                // Get the parent thread ID (for reply and quote)
                int threadId = ForumPostInfoProvider.GetPostRootFromIDPath(fpi.PostIDPath);

                ltlReply.Text     = GetLink(fpi, GetString("Forums_WebInterface_ForumPost.replyLinkText"), "PostActionLink", ForumActionType.Reply, threadId);
                ltlQuote.Text     = GetLink(fpi, GetString("Forums_WebInterface_ForumPost.quoteLinkText"), "PostActionLink", ForumActionType.Quote, threadId);
                ltlSubscribe.Text = GetLink(fpi, GetString("Forums_WebInterface_ForumPost.Subscribe"), "PostActionLink", ForumActionType.SubscribeToPost, threadId);

                ltlAnswer.Text    = GetLink(fpi, GetString("general.yes"), "ActionLink", ForumActionType.IsAnswer);
                ltlNotAnswer.Text = GetLink(fpi, GetString("general.no"), "ActionLink", ForumActionType.IsNotAnswer);

                if (ltlAnswer.Text != String.Empty)
                {
                    ltlWasHelpful.Text = GetString("Forums_WebInterface_ForumPost.Washelpful") + "&nbsp;";
                    ltlAnswer.Text    += "|";
                }

                ltlAddPostToFavorites.Text = GetLink(fpi, GetString("Forums_WebInterface_ForumPost.AddPostToFavorites"), "ActionLink", ForumActionType.AddPostToFavorites);

                ltlDelete.Text      = GetLink(fpi, GetString("general.delete"), "ActionLink", ForumActionType.Delete);
                ltlEdit.Text        = GetLink(fpi, GetString("general.edit"), "ActionLink", ForumActionType.Edit);
                ltlAttachments.Text = GetLink(fpi, GetString("general.attachments"), "ActionLink", ForumActionType.Attachment);

                #endregion


                #region "Extended actions"

                if ((EnableFriendship || EnableMessaging) && (fpi.PostUserID > 0))
                {
                    GenerateActionScripts = true;

                    ltlActions.Text = "<div class=\"PostExtendedActions\">";

                    if (EnableMessaging)
                    {
                        ltlActions.Text += "<a class=\"SendMessage\" onclick=\"PrivateMessage(" + fpi.PostUserID + "); return false;\" title=\"" + GetString("sendmessage.sendmessage") + "\"  href=\"#\"><span>" + GetString("sendmessage.sendmessage") + "</span></a>";
                    }

                    if (EnableFriendship)
                    {
                        ltlActions.Text += "<a class=\"Friendship\" onclick=\"FriendshipRequest(" + fpi.PostUserID + "); return false;\" title=\"" + GetString("friends.requestfriendship") + "\" href=\"#\"><span>" + GetString("friends.requestfriendship") + "</span></a>";
                    }

                    ltlActions.Text += "</div>";
                }

                #endregion


                // Hide separators
                if ((ltlReply.Text == "") || (ltlReply.Text != "" && ltlQuote.Text == ""))
                {
                    plcFirstSeparator.Visible = false;
                }

                if ((ltlSubscribe.Text == "") || (ltlSubscribe.Text != "" && ltlQuote.Text == ""))
                {
                    plcSecondSeparator.Visible = false;
                }

                if (ltlReply.Text != "" && ltlSubscribe.Text != "")
                {
                    plcFirstSeparator.Visible = true;
                }

                pnlManage.Visible = (EnableOnSiteManagement && (ForumContext.CurrentForum != null)) ? ForumContext.UserIsModerator(ForumContext.CurrentForum.ForumID, CommunityGroupID) : false;
                if (pnlManage.Visible)
                {
                    ltlApprove.Text    = GetLink(fpi, GetString("general.approve"), "ActionLink", ForumActionType.Appprove);
                    ltlApproveAll.Text = GetLink(fpi, GetString("forums.approveall"), "ActionLink", ForumActionType.ApproveAll);
                    ltlReject.Text     = GetLink(fpi, GetString("general.reject"), "ActionLink", ForumActionType.Reject);
                    ltlRejectAll.Text  = GetLink(fpi, GetString("forums.rejectall"), "ActionLink", ForumActionType.RejectAll);
                    ltlSplit.Text      = GetLink(fpi, GetString("forums.splitthread"), "ActionLink", ForumActionType.SplitThread);
                    ltlMove.Text       = GetLink(fpi, GetString("forums.movethread"), "ActionLink", ForumActionType.MoveToTheOtherForum, threadId);
                }
            }
        }
        else
        {
            plcPostPreview.Visible = false;
        }

        if (ControlsHelper.IsInUpdatePanel(this))
        {
            ControlsHelper.GetUpdatePanel(this).Update();
        }

        base.OnPreRender(e);
    }
コード例 #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Handle export settings
        if (!RequestHelper.IsCallback() && !RequestHelper.IsPostBack())
        {
            ExportSettings = GetNewSettings();
        }

        if (!RequestHelper.IsCallback())
        {
            // Display BETA warning
            lblBeta.Visible = CMSVersion.IsBetaVersion();
            lblBeta.Text    = string.Format(GetString("export.BETAwarning"), CMSVersion.GetFriendlySystemVersion(false));

            bool notTargetPermissions = false;
            bool notTempPermissions   = false;

            ctrlAsyncSelection.OnFinished += CtrlAsyncSelectionOnFinished;
            ctrlAsyncSelection.OnError    += CtrlAsyncSelectionOnError;

            ctlAsyncExport.OnCancel += ctlAsyncExport_OnCancel;

            // Init steps
            if (wzdExport.ActiveStepIndex < 2)
            {
                configExport.Settings = ExportSettings;
                if (!RequestHelper.IsPostBack())
                {
                    configExport.SiteId = SiteId;
                }

                pnlExport.Settings = ExportSettings;

                // Ensure directories and check permissions
                try
                {
                    DirectoryHelper.EnsureDiskPath(ExportSettings.TargetPath + "\\temp.file", ExportSettings.WebsitePath);
                    notTargetPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TargetPath, true, true, false, false);
                }
                catch (UnauthorizedAccessException)
                {
                    notTargetPermissions = true;
                }
                catch (IOExceptions.IOException ex)
                {
                    pnlWrapper.Visible = false;
                    SetAlertLabel(lblErrorBlank, ex.Message);
                    return;
                }
                try
                {
                    DirectoryHelper.EnsureDiskPath(ExportSettings.TemporaryFilesPath + "\\temp.file", ExportSettings.WebsitePath);
                    notTempPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TemporaryFilesPath, true, true, false, false);
                }
                catch (UnauthorizedAccessException)
                {
                    notTempPermissions = true;
                }
                catch (IOExceptions.IOException ex)
                {
                    pnlWrapper.Visible = false;
                    SetAlertLabel(lblErrorBlank, ex.Message);
                    return;
                }
            }

            if (notTargetPermissions || notTempPermissions)
            {
                string folder = (notTargetPermissions) ? ExportSettings.TargetPath : ExportSettings.TemporaryFilesPath;
                pnlWrapper.Visible     = false;
                pnlPermissions.Visible = true;
                SetAlertLabel(lblErrorBlank, String.Format(GetString("ExportSite.ErrorPermissions"), folder, WindowsIdentity.GetCurrent().Name));
                lnkPermissions.Target      = "_blank";
                lnkPermissions.Text        = GetString("Install.ErrorPermissions");
                lnkPermissions.NavigateUrl = DocumentationHelper.GetDocumentationTopicUrl(HELP_TOPIC_DISKPERMISSIONS_LINK);
            }
            else
            {
                // Try to delete temporary files from previous export
                if (!RequestHelper.IsPostBack())
                {
                    try
                    {
                        ExportProvider.DeleteTemporaryFiles(ExportSettings, false);
                    }
                    catch (Exception ex)
                    {
                        pnlWrapper.Visible = false;
                        SetAlertLabel(lblErrorBlank, GetString("ImportSite.ErrorDeletionTemporaryFiles") + " " + ex.Message);
                        return;
                    }
                }

                ControlsHelper.EnsureScriptManager(Page).EnablePageMethods = true;

                // Javascript functions
                string script = String.Format(
                    @"
function Finished(sender) {{
    var errorElement = document.getElementById('{2}');

    var errorText = sender.getErrors();
    if (errorText != '') {{ 
        errorElement.innerHTML = errorText;
        document.getElementById('{4}').style.removeProperty('display');
    }}

    var warningElement = document.getElementById('{3}');
    
    var warningText = sender.getWarnings();
    if (warningText != '') {{ 
        warningElement.innerHTML = warningText;
        document.getElementById('{5}').style.removeProperty('display');
    }}    

    var actDiv = document.getElementById('actDiv');
    if (actDiv != null) {{ 
        actDiv.style.display = 'none'; 
    }}

    BTN_Disable('{0}');
    BTN_Enable('{1}');
}}
",
                    CancelButton.ClientID,
                    FinishButton.ClientID,
                    lblError.LabelClientID,
                    lblWarning.LabelClientID,
                    pnlError.ClientID,
                    pnlWarning.ClientID
                    );

                // Register the script to perform get flags for showing buttons retrieval callback
                ScriptHelper.RegisterClientScriptBlock(this, GetType(), "Finished", ScriptHelper.GetScript(script));

                // Add cancel button attribute
                CancelButton.Attributes.Add("onclick", ctlAsyncExport.GetCancelScript(true) + "return false;");

                wzdExport.NextButtonClick     += wzdExport_NextButtonClick;
                wzdExport.PreviousButtonClick += wzdExport_PreviousButtonClick;
                wzdExport.FinishButtonClick   += wzdExport_FinishButtonClick;

                if (!RequestHelper.IsPostBack())
                {
                    configExport.InitControl();
                }
            }
        }
    }
コード例 #16
0
        public async Task <IActionResult> StartService(StartServiceModel startServiceModel)
        {
            // Dependency Injection: Getting the Service Specific Implementation based on the service parameter data store
            // Will compile code and load DLL in to memory for AltinnCore
            IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(startServiceModel.Org, startServiceModel.Service);

            // Get the service context containing metadata about the service
            ServiceContext serviceContext = _execution.GetServiceContext(startServiceModel.Org, startServiceModel.Service);

            // Create and populate the RequestContext object and make it available for the service implementation so
            // service developer can implement logic based on information about the request and the user performing
            // the request
            RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, 0);

            requestContext.UserContext = _userHelper.GetUserContext(HttpContext);

            // Populate the reportee information
            requestContext.UserContext.Reportee = _register.GetParty(startServiceModel.ReporteeID);
            requestContext.Reportee             = requestContext.UserContext.Reportee;

            // Create platform service and assign to service implementation making it possible for the service implementation
            // to use plattform services. Also make it available in ViewBag so it can be used from Views
            PlatformServices platformServices = new PlatformServices(_authorization, _repository, _execution, startServiceModel.Org, startServiceModel.Service);

            serviceImplementation.SetPlatformServices(platformServices);
            ViewBag.PlatformServices = platformServices;

            // Assign the different context information to the service implementation making it possible for
            // the service developer to take use of this information
            serviceImplementation.SetContext(requestContext, ViewBag, serviceContext, null, ModelState);

            object serviceModel = null;

            if (!string.IsNullOrEmpty(startServiceModel.PrefillKey))
            {
                _form.GetPrefill(
                    startServiceModel.Org,
                    startServiceModel.Service,
                    serviceImplementation.GetServiceModelType(),
                    startServiceModel.ReporteeID,
                    startServiceModel.PrefillKey);
            }

            if (serviceModel == null)
            {
                // If the service model was not loaded from prefill.
                serviceModel = serviceImplementation.CreateNewServiceModel();
            }

            // Assign service model to the implementation
            serviceImplementation.SetServiceModel(serviceModel);

            // Run Instansiation event
            await serviceImplementation.RunServiceEvent(ServiceEventType.Instantiation);

            // Run validate Instansiation event where
            await serviceImplementation.RunServiceEvent(ServiceEventType.ValidateInstantiation);

            // If ValidateInstansiation event has not added any errors the new form is saved and user is redirercted to the correct
            if (ModelState.IsValid)
            {
                if (serviceContext.WorkFlow.Any() && serviceContext.WorkFlow[0].StepType.Equals(StepType.Lookup))
                {
                    return(RedirectToAction("Lookup", new { org = startServiceModel.Org, service = startServiceModel.Service }));
                }

                // Create a new instance Id
                int formID = _execution.GetNewServiceInstanceID(startServiceModel.Org, startServiceModel.Service);

                _form.SaveFormModel(
                    serviceModel,
                    formID,
                    serviceImplementation.GetServiceModelType(),
                    startServiceModel.Org,
                    startServiceModel.Service,
                    requestContext.UserContext.ReporteeId);

                return(Redirect($"/runtime/{startServiceModel.Org}/{startServiceModel.Service}/{formID}/#Preview"));
            }

            startServiceModel.ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId)
                                             .Select(x => new SelectListItem
            {
                Text  = x.ReporteeNumber + " " + x.ReporteeName,
                Value = x.PartyID.ToString()
            }).ToList();

            HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString());
            return(View(startServiceModel));
        }
コード例 #17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userId = QueryHelper.GetInteger("objectid", 0);

        // Get user info object and check if UI should be displayed
        ui = UserInfoProvider.GetUserInfo(userId);
        CheckUserAvaibleOnSite(ui);
        EditedObject = ui;

        ucUserName.UseDefaultValidationGroup = false;
        cultureSelector.DisplayAllCultures   = true;
        lblResetToken.Text = GetString("mfauthentication.token.reset");

        // Register picture delete script
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PictDelConfirm",
                                               ScriptHelper.GetScript("function DeleteConfirmation(){ return confirm(" + ScriptHelper.GetString(GetString("MyProfile.PictDeleteConfirm")) + ");}"));

        // Check that only global administrator can edit global administrator's accounts
        if (!CheckGlobalAdminEdit(ui))
        {
            plcTable.Visible = false;
            ShowError(GetString("Administration-User_List.ErrorGlobalAdmin"));
        }

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

        // Set hide action if user extend validity of his own account
        if (ui.UserID == CurrentUser.UserID)
        {
            btnExtendValidity.OnClientClick = "window.top.HideWarning()";
        }

        // Register help variable for user is external confirmation
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "IsExternal", ScriptHelper.GetScript("var isExternal = " + chkIsExternal.Checked.ToString().ToLowerCSafe() + ";"));

        // Javascript code for "Is external user" confirmation
        string javascript = ScriptHelper.GetScript(
            @"function CheckExternal() {
                            var checkbox = document.getElementById('" + chkIsExternal.ClientID + @"')
                            if(checkbox.checked && !isExternal) {                                                                    
                                if(!confirm('" + GetString("user.confirmexternal") + @"')) {                                                                       
                                    checkbox.checked = false ;                                    
                                }
                            }}");

        // Register script to the page
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), ClientID + "CheckExternal", javascript);

        // Assign to ok button
        if (!chkIsExternal.Checked)
        {
            btnOk.OnClientClick = "CheckExternal()";
        }

        // Display impersonation link if current user is global administrator and edited user is not global admin
        if (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && (ui.UserID != CurrentUser.UserID) && !ui.IsPublic() && ui.Enabled)
        {
            string message = GetImpersonalMessage(ui);

            HeaderAction action = new HeaderAction();
            action.Text          = GetString("Membership.Impersonate");
            action.Tooltip       = GetString("Membership.Impersonate");
            action.OnClientClick = "if (!confirm('" + message + "')) { return false; }";
            action.CommandName   = "impersonate";
            CurrentMaster.HeaderActions.AddAction(action);

            CurrentMaster.HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;
        }
    }
コード例 #18
0
    /// <summary>
    /// Saves data of edited user from TextBoxes into DB.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        UserPrivilegeLevelEnum privilegeLevel = (UserPrivilegeLevelEnum)drpPrivilege.Value.ToInteger(0);

        // Check "modify" permission
        if (!CurrentUser.IsAuthorizedPerResource("CMS.Users", "Modify"))
        {
            RedirectToAccessDenied("CMS.Users", "Modify");
        }

        string result = ValidateGlobalAndDeskAdmin(userId);

        var isExternal = chkIsExternal.Checked;

        // Find whether user name is valid (external users are not checked as their user names can contain various special characters)
        if (result == String.Empty)
        {
            if (!isExternal && !ucUserName.IsValid())
            {
                result = ucUserName.ValidationError;
            }
        }

        String userName = ValidationHelper.GetString(ucUserName.Value, String.Empty);

        if (result == String.Empty)
        {
            // Finds whether required fields are not empty
            result = new Validator().NotEmpty(txtFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result;
        }

        // Store the old display name
        var oldDisplayName = ui.Generalized.ObjectDisplayName;

        if ((result == String.Empty) && (ui != null))
        {
            // If site prefixed allowed - ad site prefix
            if ((SiteID != 0) && UserInfoProvider.UserNameSitePrefixEnabled(SiteContext.CurrentSiteName))
            {
                if (!UserInfoProvider.IsSitePrefixedUser(userName))
                {
                    userName = UserInfoProvider.EnsureSitePrefixUserName(userName, SiteContext.CurrentSite);
                }
            }

            // Validation for site prefixed users
            if (!UserInfoProvider.IsUserNamePrefixUnique(userName, ui.UserID))
            {
                ShowError(GetString("Administration-User_New.siteprefixeduserexists"));
                return;
            }

            // Ensure same password
            password = ui.GetValue("UserPassword").ToString();

            // Test for unique username
            UserInfo uiTest = UserInfoProvider.GetUserInfo(userName);
            if ((uiTest == null) || (uiTest.UserID == userId))
            {
                if (ui == null)
                {
                    ui = new UserInfo();
                }

                bool globAdmin = ui.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin);
                bool editor    = ui.SiteIndependentPrivilegeLevel == UserPrivilegeLevelEnum.Editor;

                // Email format validation
                if (!txtEmail.IsValid())
                {
                    ShowError(GetString("Administration-User_New.WrongEmailFormat"));
                    return;
                }

                bool oldGlobal = ui.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin);
                bool oldEditor = ui.SiteIndependentPrivilegeLevel == UserPrivilegeLevelEnum.Editor;

                // Define domain variable
                string domains = null;

                // Get all user sites
                var userSites = UserInfoProvider.GetUserSites(userId).Column("SiteDomainName");
                if (userSites.Count > 0)
                {
                    foreach (var userSite in userSites)
                    {
                        domains += ValidationHelper.GetString(userSite["SiteDomainName"], string.Empty) + ";";
                    }

                    // Remove  ";" at the end
                    if (domains != null)
                    {
                        domains = domains.Remove(domains.Length - 1);
                    }
                }
                else
                {
                    DataSet siteDs = SiteInfoProvider.GetSites().Columns("SiteDomainName");
                    if (!DataHelper.DataSourceIsEmpty(siteDs))
                    {
                        // Create list of available site domains
                        domains = TextHelper.Join(";", DataHelper.GetStringValues(siteDs.Tables[0], "SiteDomainName"));
                    }
                }

                // Check limitations for Global administrator
                if (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && ((privilegeLevel == UserPrivilegeLevelEnum.GlobalAdmin) || (privilegeLevel == UserPrivilegeLevelEnum.Admin)) && !oldGlobal)
                {
                    if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Administrators, ObjectActionEnum.Insert, globAdmin))
                    {
                        ShowError(GetString("License.MaxItemsReachedGlobal"));
                        return;
                    }
                }

                // Check limitations for editors
                if ((privilegeLevel == UserPrivilegeLevelEnum.Editor) && !oldEditor && userSites.Count > 0)
                {
                    if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Editors, ObjectActionEnum.Insert, editor))
                    {
                        ShowError(GetString("License.MaxItemsReachedEditor"));
                        return;
                    }
                }

                // Check whether email is unique if it is required
                string email = txtEmail.Text.Trim();
                if (!UserInfoProvider.IsEmailUnique(email, ui))
                {
                    ShowError(GetString("UserInfo.EmailAlreadyExist"));
                    return;
                }

                // Set properties
                ui.Email        = email;
                ui.FirstName    = txtFirstName.Text.Trim();
                ui.FullName     = txtFullName.Text.Trim();
                ui.LastName     = txtLastName.Text.Trim();
                ui.MiddleName   = txtMiddleName.Text.Trim();
                ui.UserName     = userName;
                ui.Enabled      = CheckBoxEnabled.Checked;
                ui.UserIsHidden = chkIsHidden.Checked;
                ui.IsExternal   = isExternal;
                ui.UserIsDomain = chkIsDomain.Checked;
                ui.SetValue("UserPassword", password);
                ui.UserID = userId;
                ui.UserStartingAliasPath = txtUserStartingPath.Text.Trim();
                ui.UserMFRequired        = chkIsMFRequired.Checked;


                // Global admin can set anything
                if (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)
                    // Other users can set only editor and non privileges
                    || ((privilegeLevel != UserPrivilegeLevelEnum.Admin) && (privilegeLevel != UserPrivilegeLevelEnum.GlobalAdmin))
                    // Admin can manage his own privilege
                    || ((privilegeLevel == UserPrivilegeLevelEnum.Admin) && (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && (CurrentUser.UserID == ui.UserID))))
                {
                    ui.SiteIndependentPrivilegeLevel = privilegeLevel;
                }

                LoadUserLogon(ui);

                // Set values of cultures.
                string culture = ValidationHelper.GetString(cultureSelector.Value, "");
                ui.PreferredCultureCode = culture;

                if (lstUICulture.SelectedValue == "0")
                {
                    ui.PreferredUICultureCode = "";
                }
                else
                {
                    // Set preferred UI culture
                    CultureInfo ci = CultureInfoProvider.GetCultureInfo(ValidationHelper.GetInteger(lstUICulture.SelectedValue, 0));
                    ui.PreferredUICultureCode = ci.CultureCode;
                }

                // Refresh page breadcrumbs if display name changed
                if (ui.Generalized.ObjectDisplayName != oldDisplayName)
                {
                    ScriptHelper.RefreshTabHeader(Page, ui.FullName);
                }

                using (CMSActionContext context = new CMSActionContext())
                {
                    // Check whether the username of the currently logged user has been changed
                    if (CurrentUserChangedUserName())
                    {
                        // Ensure that an update search task will be created but NOT executed when updating the user
                        context.EnableSmartSearchIndexer = false;
                    }

                    try
                    {
                        // Update the user
                        UserInfoProvider.SetUserInfo(ui);
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("Users", "SAVE", ex);
                        ShowError(GetString("general.errorsaving"));
                        return;
                    }

                    // Check whether the username of the currently logged user has been changed
                    if (CurrentUserChangedUserName())
                    {
                        // Ensure that current user is not logged out if he changes his user name
                        if (RequestHelper.IsFormsAuthentication())
                        {
                            FormsAuthentication.SetAuthCookie(ui.UserName, false);

                            // Update current user
                            MembershipContext.AuthenticatedUser = new CurrentUserInfo(ui, true);

                            // Reset current user
                            CurrentUser = null;
                        }
                    }
                }

                ShowChangesSaved();
            }
            else
            {
                // If user exists
                ShowError(GetString("Administration-User_New.UserExists"));
            }
        }
        else
        {
            ShowError(result);
        }

        if ((ui.UserInvalidLogOnAttempts == 0) && (ui.UserAccountLockReason != UserAccountLockCode.FromEnum(UserAccountLockEnum.MaximumInvalidLogonAttemptsReached)))
        {
            btnResetLogonAttempts.Enabled = false;
        }

        LoadPasswordExpiration(ui);
    }
コード例 #19
0
        /// <summary>
        /// Asynchornously generate the sequence of pages.
        /// </summary>
        /// <param name="options">Options when querying for the pages.</param>
        public IAsyncEnumerable <T> EnumPagesAsync(PageQueryOptions options)
        {
            var actualPagingSize = GetActualPagingSize(options);

            return(RequestHelper.EnumPagesAsync(this, options, actualPagingSize).Cast <T>());
        }
コード例 #20
0
	private static void setupRequest(BaseRequestModel __r,
			                          RequestHelper.RequestHandlerDelegate __callbackRequestCompleted = null,
			                          RequestHelper.RequestHandlerDelegate __callbackRequestError = null,
			                          RequestHelper.RequestHandlerDelegate __callbackRequestStarted = null,
			                          RequestHelper.RequestHandlerDelegate __callbackRequestFinalized = null)
	{
		__r.callbackRequestCompleted += __callbackRequestCompleted;
		__r.callbackRequestError += __callbackRequestError;
		__r.callbackRequestStarted += __callbackRequestStarted;
		__r.callbackRequestFinalized += __callbackRequestFinalized;
		ExternalCommunicator.instance.addRequest(__r);
	}
コード例 #21
0
    protected void LoadData()
    {
        // Get newsletter object and check if exists
        Newsletter newsletterObj = NewsletterProvider.GetNewsletter(newsletterId);

        EditedObject = newsletterObj;

        // Initialize issue selectors
        int siteId = newsletterObj.NewsletterSiteID;

        subscriptionTemplate.WhereCondition   = "TemplateType='S' AND TemplateSiteID=" + siteId;
        unsubscriptionTemplate.WhereCondition = "TemplateType='U' AND TemplateSiteID=" + siteId;
        issueTemplate.WhereCondition          = "TemplateType='I' AND TemplateSiteID=" + siteId;
        optInSelector.WhereCondition          = "TemplateType='D' AND TemplateSiteID=" + siteId;

        // Check if the newsletter is dynamic and adjust config dialog
        isDynamic = newsletterObj.NewsletterType == NewsletterType.Dynamic;

        lblDynamic.Visible = pnlDynamic.Visible = lblNewsletterDynamicURL.Visible =
            txtNewsletterDynamicURL.Visible = plcUrl.Visible = chkSchedule.Visible =
                lblSchedule.Visible         = plcInterval.Visible = isDynamic;

        lblTemplateBased.Visible = lblIssueTemplate.Visible = issueTemplate.Visible = !isDynamic;

        if (RequestHelper.IsPostBack())
        {
            if (isDynamic)
            {
                schedulerInterval.Visible = chkSchedule.Checked;
            }
            else
            {
                plcInterval.Visible = false;
            }

            return;
        }

        // Fill config dialog with newsletter data
        GetNewsletterValues(newsletterObj);

        if (!isDynamic)
        {
            issueTemplate.Value = newsletterObj.NewsletterTemplateID.ToString();
            return;
        }

        // Check if dynamic newsletter subject is empty
        bool subjectEmpty = string.IsNullOrEmpty(newsletterObj.NewsletterDynamicSubject);

        radPageTitle.Checked = subjectEmpty;
        radFollowing.Checked = !subjectEmpty;
        radPageTitle_CheckedChanged(null, null);
        if (!subjectEmpty)
        {
            txtSubject.Text = newsletterObj.NewsletterDynamicSubject;
        }

        txtNewsletterDynamicURL.Text = newsletterObj.NewsletterDynamicURL;

        TaskInfo task = TaskInfoProvider.GetTaskInfo(newsletterObj.NewsletterDynamicScheduledTaskID);

        if (task != null)
        {
            chkSchedule.Checked = plcInterval.Visible = true;
            schedulerInterval.ScheduleInterval = task.TaskInterval;
        }
        else
        {
            chkSchedule.Checked       = false;
            schedulerInterval.Visible = false;
        }
    }
コード例 #22
0
        /// <summary>
        /// 拼接查询Sql语句及参数
        /// </summary>
        /// <param name="nv">页面传递的参数集合</param>
        /// <param name="notIn">排除字段</param>
        /// <param name="arrParam">out查询参数</param>
        /// <returns>查询Sql语句</returns>
        public virtual string GetSearchSql(string notIn, out object[] arrParam)
        {
            StringBuilder sb     = new StringBuilder();
            string        value  = "";
            string        value1 = "";
            string        value2 = "";
            ArrayList     param  = new ArrayList();


            //CatalogID
            if (!("," + notIn.ToLower() + ",").Contains(",catalogid,"))
            {
                value = RequestHelper.GetString("CatalogID");
                if (!string.IsNullOrEmpty(value))
                {
                    sb.Append(" AND [`CatalogID`]=?");
                    param.Add(value);
                }
            }


            //InfoNo
            if (!("," + notIn.ToLower() + ",").Contains(",infono,"))
            {
                value = RequestHelper.GetString("InfoNo");
                if (!string.IsNullOrEmpty(value))
                {
                    string[] arrValue = value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arrValue.Length > 1)
                    {
                        for (int i = 0; i < arrValue.Length; i++)
                        {
                            sb.Append(" AND [`InfoNo`] like ?");
                            param.Add("%" + arrValue[i] + "%");
                        }
                    }
                    else
                    {
                        sb.Append(" AND [`InfoNo`] like ?");
                        param.Add("%" + value + "%");
                    }
                }
            }


            //Title
            if (!("," + notIn.ToLower() + ",").Contains(",title,"))
            {
                value = RequestHelper.GetString("Title");
                if (!string.IsNullOrEmpty(value))
                {
                    string[] arrValue = value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arrValue.Length > 1)
                    {
                        for (int i = 0; i < arrValue.Length; i++)
                        {
                            sb.Append(" AND [`Title`] like ?");
                            param.Add("%" + arrValue[i] + "%");
                        }
                    }
                    else
                    {
                        sb.Append(" AND [`Title`] like ?");
                        param.Add("%" + value + "%");
                    }
                }
            }


            //HtmlContent
            if (!("," + notIn.ToLower() + ",").Contains(",htmlcontent,"))
            {
                value = RequestHelper.GetString("HtmlContent");
                if (!string.IsNullOrEmpty(value))
                {
                    string[] arrValue = value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arrValue.Length > 1)
                    {
                        for (int i = 0; i < arrValue.Length; i++)
                        {
                            sb.Append(" AND CONTAINS(*,?)");
                            param.Add(arrValue[i]);
                        }
                    }
                    else
                    {
                        sb.Append(" AND CONTAINS(*,?)");
                        param.Add(value);
                    }
                }
            }
            arrParam = param.ToArray();
            return(sb.ToString());
        }
コード例 #23
0
    /// <summary>
    /// Loads data of edited workflow from DB into TextBoxes.
    /// </summary>
    protected void LoadData(WorkflowStepInfo wsi)
    {
        // Timeout UI is always enabled for wait step type
        ucTimeout.AllowNoTimeout = (wsi.StepType != WorkflowStepTypeEnum.Wait);

        // Display action parameters form only for action step type
        if (ShowActionParametersForm)
        {
            WorkflowActionInfo action = WorkflowActionInfo.Provider.Get(wsi.StepActionID);
            if (action != null)
            {
                if (!RequestHelper.IsPostBack())
                {
                    pnlContainer.CssClass += " " + action.ActionName.ToLowerInvariant();
                }
                ucActionParameters.FormInfo = new FormInfo(action.ActionParameters);
                lblParameters.Text = String.Format(GetString("workflowstep.parameters"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(action.ActionDisplayName)));
            }

            ParametersForm.AllowMacroEditing = true;
            ParametersForm.ShowValidationErrorMessage = false;
            ParametersForm.ResolverName = WorkflowHelper.GetResolverName(CurrentWorkflow);
            ucActionParameters.Parameters = wsi.StepActionParameters;
            ucActionParameters.ReloadData(!RequestHelper.IsPostBack());
            ucActionParameters.Visible = ucActionParameters.CheckVisibility();
        }

        plcParameters.Visible = ucActionParameters.Visible;

        if (plcTimeoutTarget.Visible)
        {
            ucTimeoutTarget.WorkflowStepID = CurrentStepInfo.StepID;
        }

        // Initialize condition edit for certain step types
        ucSourcePointEdit.StopProcessing = true;

        if ((CurrentWorkflow != null) && !CurrentWorkflow.IsBasic)
        {
            bool conditionStep = (wsi.StepType == WorkflowStepTypeEnum.Condition);
            if (conditionStep || (wsi.StepType == WorkflowStepTypeEnum.Wait) || (!wsi.StepIsStart && !wsi.StepIsAction && !wsi.StepIsFinished && (wsi.StepType != WorkflowStepTypeEnum.MultichoiceFirstWin)))
            {
                // Initialize source point edit control
                var sourcePoint = CurrentStepInfo.StepDefinition.DefinitionPoint;
                if (sourcePoint != null)
                {
                    plcCondition.Visible = ShowSourcePointForm;
                    lblCondition.ResourceString = GetHeaderResourceString(wsi.StepType);

                    ucSourcePointEdit.StopProcessing = false;
                    ucSourcePointEdit.SourcePointGuid = sourcePoint.Guid;
                    ucSourcePointEdit.SimpleMode = !conditionStep;
                    ucSourcePointEdit.ShowCondition = GetShowCondition(wsi);
                    ucSourcePointEdit.RuleCategoryNames = CurrentWorkflow.IsAutomation ? ModuleName.ONLINEMARKETING : WorkflowInfo.OBJECT_TYPE;
                }
            }
        }

        if (!RequestHelper.IsPostBack())
        {
            if (ShowTimeoutForm)
            {
                ucTimeout.TimeoutEnabled = wsi.StepDefinition.TimeoutEnabled;
                ucTimeout.ScheduleInterval = wsi.StepDefinition.TimeoutInterval;
            }
        }
    }
コード例 #24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Initialize current user for the async actions
        currentUser = MembershipContext.AuthenticatedUser;

        if (!RequestHelper.IsCallback())
        {
            // Check 'Manage object tasks' permission
            if (!currentUser.IsAuthorizedPerResource("cms.staging", "ManageAllTasks"))
            {
                RedirectToAccessDenied("cms.staging", "ManageAllTasks");
            }

            currentSiteId   = SiteContext.CurrentSiteID;
            currentSiteName = SiteContext.CurrentSiteName;

            ucDisabledModule.SettingsKeys = "CMSStagingLogObjectChanges;CMSStagingLogDataChanges;CMSStagingLogChanges";
            ucDisabledModule.InfoText     = GetString("AllTasks.TaskSeparator");
            ucDisabledModule.AtLeastOne   = true;
            ucDisabledModule.ShowButtons  = false;
            ucDisabledModule.SiteOrGlobal = true;
            ucDisabledModule.ParentPanel  = pnlNotLogged;

            if (!ucDisabledModule.Check())
            {
                pnlFooter.Visible  = false;
                plcContent.Visible = false;
                return;
            }

            // Register the dialog script
            ScriptHelper.RegisterDialogScript(this);
            serverId = QueryHelper.GetInteger("serverid", 0);

            // Setup title
            if (!ControlsHelper.CausedPostBack(btnSyncSelected, btnSyncAll))
            {
                plcContent.Visible = true;

                // Initialize buttons
                btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");
                btnCancel.Text                  = GetString("General.Cancel");
                btnDeleteAll.OnClientClick      = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");";
                btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");";
                btnSyncSelected.OnClientClick   = "return !" + gridTasks.GetCheckSelectionScript();

                // Initialize grid
                gridTasks.ZeroRowsText         = GetString("Tasks.NoTasks");
                gridTasks.OnAction            += gridTasks_OnAction;
                gridTasks.OnDataReload        += gridTasks_OnDataReload;
                gridTasks.OnExternalDataBound += gridTasks_OnExternalDataBound;
                gridTasks.ShowActionsMenu      = true;
                gridTasks.Columns              = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount";

                StagingTaskInfo ti = new StagingTaskInfo();
                gridTasks.AllColumns = SqlHelper.MergeColumns(ti.ColumnNames);

                pnlLog.Visible = false;
            }
        }

        ctlAsync.OnFinished   += ctlAsync_OnFinished;
        ctlAsync.OnError      += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel     += ctlAsync_OnCancel;
    }
コード例 #25
0
ファイル: System.ascx.cs プロジェクト: kudutest2/Kentico
    protected void Page_Load(object sender, EventArgs e)
    {
        this.timRefresh.Interval = 1000 * ValidationHelper.GetInteger(this.drpRefresh.SelectedValue, 0);

        // Check permissions
        RaiseOnCheckPermissions("READ", this);

        if (StopProcessing)
        {
            return;
        }

        // Get values from counters
        long totalSystemRequests       = RequestHelper.TotalSystemPageRequests.GetValue(null);
        long totalPageRequests         = RequestHelper.TotalPageRequests.GetValue(null);
        long totalPageNotFoundRequests = RequestHelper.TotalPageNotFoundRequests.GetValue(null);
        long totalNonPageRequests      = RequestHelper.TotalNonPageRequests.GetValue(null);
        long totalGetFileRequests      = RequestHelper.TotalGetFileRequests.GetValue(null);

        // Reevaluate RPS
        if (mLastRPS != DateTime.MinValue)
        {
            double seconds = DateTime.Now.Subtract(mLastRPS).TotalSeconds;
            if ((seconds < 3) && (seconds > 0))
            {
                mRPSSystemPageRequests   = (totalSystemRequests - mLastSystemPageRequests) / seconds;
                mRPSPageRequests         = (totalPageRequests - mLastPageRequests) / seconds;
                mRPSPageNotFoundRequests = (totalPageNotFoundRequests - mLastPageNotFoundRequests) / seconds;
                mRPSNonPageRequests      = (totalNonPageRequests - mLastNonPageRequests) / seconds;
                mRPSGetFileRequests      = (totalGetFileRequests - mLastGetFileRequests) / seconds;
            }
            else
            {
                mRPSGetFileRequests      = -1;
                mRPSNonPageRequests      = -1;
                mRPSPageNotFoundRequests = -1;
                mRPSPageRequests         = -1;
                mRPSSystemPageRequests   = -1;
            }
        }

        mLastRPS = DateTime.Now;

        // Update last values
        mLastGetFileRequests      = totalGetFileRequests;
        mLastNonPageRequests      = totalNonPageRequests;
        mLastPageNotFoundRequests = totalPageNotFoundRequests;
        mLastPageRequests         = totalPageRequests;
        mLastSystemPageRequests   = totalSystemRequests;

        // Do not count this page with async postback
        if (RequestHelper.IsAsyncPostback())
        {
            RequestHelper.TotalSystemPageRequests.Decrement(null);
        }

        pnlSystemInfo.GroupingText = GetString("Administration-System.SystemInfo");
        pnlSystemTime.GroupingText = GetString("Administration-System.SystemTimeInfo");

        pnlDatabaseInfo.GroupingText = GetString("Administration-System.DatabaseInfo");
        lblServerName.Text           = GetString("Administration-System.ServerName");
        lblServerVersion.Text        = GetString("Administration-System.ServerVersion");
        lblDBName.Text = GetString("Administration-System.DatabaseName");
        lblDBSize.Text = GetString("Administration-System.DatabaseSize");

        lblMachineName.Text      = GetString("Administration-System.MachineName");
        lblMachineNameValue.Text = HTTPHelper.MachineName;

        lblAspAccount.Text      = GetString("Administration-System.Account");
        lblValueAspAccount.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;


        // Get application pool name
        lblPool.Text      = GetString("Administration-System.Pool");
        lblValuePool.Text = GetString("General.NA");

        try
        {
            lblValuePool.Text = SystemHelper.GetApplicationPoolName();
        }
        catch
        {
        }

        // Get application trust level
        lblTrustLevel.Text      = GetString("Administration-System.TrustLevel");
        lblValueTrustLevel.Text = GetString("General.NA");

        try
        {
            lblValueTrustLevel.Text = SystemHelper.CurrentTrustLevel.ToString();
        }
        catch
        {
        }

        lblAspVersion.Text      = GetString("Administration-System.Version");
        lblValueAspVersion.Text = System.Environment.Version.ToString();

        pnlMemory.GroupingText = GetString("Administration-System.MemoryStatistics");

        lblAlocatedMemory.Text = GetString("Administration-System.Memory");
        lblPeakMemory.Text     = GetString("Administration-System.PeakMemory");
        lblVirtualMemory.Text  = GetString("Administration-System.VirtualMemory");
        lblPhysicalMemory.Text = GetString("Administration-System.PhysicalMemory");
        lblIP.Text             = GetString("Administration-System.IP");

        pnlPageViews.GroupingText = GetString("Administration-System.PageViews");
        lblPageViewsValues.Text   = GetString("Administration-System.PageViewsValues");

        lblPages.Text         = GetString("Administration-System.Pages");
        lblSystemPages.Text   = GetString("Administration-System.SystemPages");
        lblNonPages.Text      = GetString("Administration-System.NonPages");
        lblGetFilePages.Text  = GetString("Administration-System.GetFilePages");
        lblPagesNotFound.Text = GetString("Administration-System.PagesNotFound");
        lblPending.Text       = GetString("Administration-System.Pending");

        pnlCache.GroupingText   = GetString("Administration-System.CacheStatistics");
        lblCacheExpired.Text    = GetString("Administration-System.CacheExpired");
        lblCacheRemoved.Text    = GetString("Administration-System.CacheRemoved");
        lblCacheUnderused.Text  = GetString("Administration-System.CacheUnderused");
        lblCacheItems.Text      = GetString("Administration-System.CacheItems");
        lblCacheDependency.Text = GetString("Administration-System.CacheDependency");

        pnlGC.GroupingText = GetString("Administration-System.GC");

        btnClear.Text           = GetString("Administration-System.btnClear");
        btnClearCache.Text      = GetString("Administration-System.btnClearCache");
        btnRestart.Text         = GetString("Administration-System.btnRestart");
        btnRestartWebfarm.Text  = GetString("Administration-System.btnRestartWebfarm");
        btnClearCounters.Text   = GetString("Administration-System.btnClearCounters");
        btnRestartServices.Text = GetString("Administration-System.btnRestartServices");

        // Hide button if wefarms are not enabled or disallow restarting webfarms for Windows Azure
        if (!WebSyncHelperClass.WebFarmEnabled || AzureHelper.IsRunningOnAzure)
        {
            this.btnRestartWebfarm.Visible = false;
        }

        // Hide the web farm restart button if this web farm server is not enabled
        if (!RequestHelper.IsPostBack())
        {
            WebFarmServerInfo webFarmServerObj = WebFarmServerInfoProvider.GetWebFarmServerInfo(WebSyncHelperClass.ServerName);
            if ((webFarmServerObj != null) && (!webFarmServerObj.ServerEnabled))
            {
                this.btnRestartWebfarm.Visible = false;
            }
        }

        // Hide restart service button if services folder doesn't exist
        this.btnRestartServices.Visible = SystemHelper.IsFullTrustLevel && WinServiceHelper.ServicesAvailable();

        // Hide the performance counters clear button if the health monitoring is not enabled or feature is not available
        this.btnClearCounters.Visible = SystemHelper.IsFullTrustLevel && LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.HealthMonitoring);

        LoadData();

        if (!RequestHelper.IsPostBack())
        {
            switch (QueryHelper.GetString("lastaction", String.Empty).ToLower())
            {
            case "restarted":
                lblInfo.Text = GetString("Administration-System.RestartSuccess");
                break;

            case "webfarmrestarted":
                if (ValidationHelper.ValidateHash("WebfarmRestarted", QueryHelper.GetString("restartedhash", String.Empty)))
                {
                    lblInfo.Text = GetString("Administration-System.WebframRestarted");
                    // Restart other servers - create webfarm task for application restart
                    WebSyncHelperClass.CreateTask(WebFarmTaskTypeEnum.RestartApplication, "RestartApplication", "", null);
                }
                else
                {
                    lblInfo.Text = GetString("general.actiondenied");
                }
                break;

            case "countercleared":
                lblInfo.Text = GetString("Administration-System.CountersCleared");
                break;

            case "winservicesrestarted":
                lblInfo.Text = GetString("Administration-System.WinServicesRestarted");
                break;
            }
        }

        lblRunTime.Text    = GetString("Administration.System.RunTime");
        lblServerTime.Text = GetString("Administration.System.ServerTime");

        // Remove miliseconds from the end of the time string
        string timeSpan = (DateTime.Now - CMSAppBase.ApplicationStart).ToString();
        int    index    = timeSpan.LastIndexOf('.');

        if (index >= 0)
        {
            timeSpan = timeSpan.Remove(index);
        }

        // Display application run time
        lblRunTimeValue.Text    = timeSpan;
        lblServerTimeValue.Text = Convert.ToString(DateTime.Now) + " " + TimeZoneHelper.GetGMTStringOffset(TimeZoneHelper.ServerTimeZone);

        lblIPValue.Text = Request.UserHostAddress;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register JQuery
        ScriptHelper.RegisterJQuery(Page);

        SelectSite.StopProcessing = !DisplaySiteSelector;
        plcSelectSite.Visible     = DisplaySiteSelector;

        bool hasSelected = SelectedCategory != null;

        // Ensure correct object type for cloning
        if (hasSelected)
        {
            gridSubCategories.ObjectType = SelectedCategory.CategoryIsPersonal ? CategoryInfo.OBJECT_TYPE_USERCATEGORY : CategoryInfo.OBJECT_TYPE;
        }

        // Check if selection is valid
        CheckSelection();

        // Stop processing grids, when no category selected
        gridDocuments.UniGrid.StopProcessing            = !hasSelected;
        gridDocuments.UniGrid.FilterForm.StopProcessing = !hasSelected;
        gridDocuments.UniGrid.Visible = hasSelected;

        gridSubCategories.StopProcessing            = !hasSelected;
        gridSubCategories.FilterForm.StopProcessing = !hasSelected;
        gridSubCategories.Visible = hasSelected;

        if (!StopProcessing)
        {
            if (!RequestHelper.IsPostBack())
            {
                // Start in mode of creating new category when requested
                if (StartInCreatingMode)
                {
                    SwitchToNew();
                }
                else
                {
                    SwitchToInfo();
                }
            }

            // Use images according to culture
            var imageUrl = (CultureHelper.IsUICultureRTL()) ? GetImageUrl("RTL/Design/Controls/Tree") : GetImageUrl("Design/Controls/Tree");
            treeElemG.LineImagesFolder = imageUrl;
            treeElemP.LineImagesFolder = imageUrl;

            treeElemG.StopProcessing = !DisplaySiteCategories;
            treeElemP.StopProcessing = !DisplayPersonalCategories;

            // Prepare node templates
            treeElemP.SelectedNodeTemplate = treeElemG.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
            treeElemP.NodeTemplate         = treeElemG.NodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";

            // Init tree provider objects
            treeElemG.ProviderObject = CreateTreeProvider(SiteID, 0);
            treeElemP.ProviderObject = CreateTreeProvider(0, UserID);

            // Expand first level by default
            treeElemP.ExpandPath = treeElemG.ExpandPath = "/";

            if (SelectedCategory != null)
            {
                catEdit.UserID   = SelectedCategory.CategoryUserID;
                catEdit.Category = SelectedCategory;

                catNew.UserID                = SelectedCategory.CategoryUserID;
                catNew.ParentCategoryID      = SelectedCategory.CategoryID;
                catNew.SiteID                = SiteID;
                catNew.AllowCreateOnlyGlobal = SiteID == 0;
                gridDocuments.SiteName       = filterDocuments.SelectedSite;

                PreselectCategory(SelectedCategory, false);
            }
            else
            {
                catNew.UserID                = CustomCategoriesRootSelected ? UserID : 0;
                catNew.SiteID                = CustomCategoriesRootSelected ? 0 : SiteID;
                catNew.ParentCategoryID      = 0;
                catNew.AllowCreateOnlyGlobal = SiteID == 0;
            }

            // Create root node for global and site categories
            string rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootcategory") + "</span>";
            string rootText = treeElemG.ReplaceMacros(treeElemG.NodeTemplate, 0, 6, rootName, "", 0, null, null);

            rootText = rootText.Replace("##NODECUSTOMNAME##", rootName);
            rootText = rootText.Replace("##NODECODENAME##", "CategoriesRoot");
            rootText = rootText.Replace("##PARENTID##", CATEGORIES_ROOT_PARENT_ID.ToString());

            treeElemG.SetRoot(rootText, "NULL", null, null, null);

            // Create root node for personal categories
            rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootpersonalcategory") + "</span>";
            rootText = treeElemP.ReplaceMacros(treeElemP.NodeTemplate, 0, 6, rootName, "", 0, null, null);

            rootText = rootText.Replace("##NODECUSTOMNAME##", rootName);
            rootText = rootText.Replace("##NODECODENAME##", "PersonalCategoriesRoot");
            rootText = rootText.Replace("##PARENTID##", PERSONAL_CATEGORIES_ROOT_PARENT_ID.ToString());
            treeElemP.SetRoot(rootText, "NULL", null, null, null);

            // Prepare script for selecting category
            string script = @"
var menuHiddenId = '" + hidSelectedElem.ClientID + @"';

function deleteConfirm() {
    return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + @"); 
}

function Refresh(catId, parentId) {
        // This method is used in Category cloning action
        NodeSelected(catId, parentId, true);
    }

function NodeSelected(elementId, parentId, isEdit) {
    // Set menu actions value
    var menuElem = $cmsj('#' + menuHiddenId);
    if (menuElem.length = 1) {
        menuElem[0].value = elementId + '|' + parentId;
    }

    if (isEdit) {
        " + ControlsHelper.GetPostBackEventReference(hdnButton, "edit") + @"
    } else {
        " + ControlsHelper.GetPostBackEventReference(hdnButton, "tree") + @"
    }
}";

            ltlScript.Text = ScriptHelper.GetScript(script);
        }
    }
コード例 #27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string templateType = QueryHelper.GetString("templatetype", String.Empty);

        // If not in site manager - filter class selector for only site documents
        if (!IsSiteManager)
        {
            ucClassSelector.SiteID = CMSContext.CurrentSiteID;
        }

        if (!RequestHelper.IsPostBack())
        {
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.item"), "item"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.alternatingitem"), "alternatingitem"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.firstitem"), "firstitem"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.lastitem"), "lastitem"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.header"), "header"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.footer"), "footer"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.singleitem"), "singleitem"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.separator"), "separator"));
            drpTemplateType.Items.Add(new ListItem(GetString("hiertransf.currentitem"), "currentitem"));

            //If new template type set via url
            if (!String.IsNullOrEmpty(templateType))
            {
                //lblTemplateType.Text = ConvertTemplateTypeToString(templateType);
                if (templateType != "all")
                {
                    drpTemplateType.SelectedValue = templateType;
                }
                else
                {
                    drpTemplateType.SelectedValue = "item";
                }
            }
        }

        //Info and error messages
        lblInfo.Text = GetString("general.changessaved");

        //First edit after save ... show info message
        if (ShowInfoLabel)
        {
            lblInfo.Visible = true;
        }

        if (!String.IsNullOrEmpty(templateType))
        {
            mTemplateType = HierarchicalTransformations.StringToUniViewItemType(templateType);
        }

        //Load transformations xml
        mTransformations = new HierarchicalTransformations("ClassName");
        if (TransInfo != null)
        {
            if (!String.IsNullOrEmpty(TransInfo.TransformationHierarchicalXML))
            {
                mTransformations.LoadFromXML(TransInfo.TransformationHierarchicalXML);
            }
        }

        //Edit
        if (HierarchicalID != Guid.Empty)
        {
            mHierInfo = mTransformations.GetTransformation(HierarchicalID);
            //Load Transformation values
            if (!RequestHelper.IsPostBack())
            {
                txtLevel.Text                 = mHierInfo.ItemLevel.ToString();
                ucTransformations.Value       = mHierInfo.TransformationName;
                ucClassSelector.Value         = mHierInfo.Value;
                templateType                  = HierarchicalTransformations.UniViewItemTypeToString(mHierInfo.ItemType);
                drpTemplateType.SelectedValue = templateType;
                mTemplateType                 = mHierInfo.ItemType;
            }
        }
    }
コード例 #28
0
ファイル: System.ascx.cs プロジェクト: kudutest2/Kentico
    /// <summary>
    /// Loads the data.
    /// </summary>
    protected void LoadData()
    {
        lblValueAlocatedMemory.Text = DataHelper.GetSizeString(GC.GetTotalMemory(false));

        lblValueVirtualMemory.Text  = "N/A";
        lblValuePhysicalMemory.Text = "N/A";
        lblValuePeakMemory.Text     = "N/A";

        // Process memory
        try
        {
            lblValueVirtualMemory.Text  = DataHelper.GetSizeString(SystemHelper.GetVirtualMemorySize());
            lblValuePhysicalMemory.Text = DataHelper.GetSizeString(SystemHelper.GetWorkingSetSize());
            lblValuePeakMemory.Text     = DataHelper.GetSizeString(SystemHelper.GetPeakWorkingSetSize());
        }
        catch
        {
        }

        this.lblValuePages.Text         = GetViewValues(RequestHelper.TotalPageRequests.GetValue(null), 0, mRPSPageRequests);
        this.lblValuePagesNotFound.Text = GetViewValues(RequestHelper.TotalPageNotFoundRequests.GetValue(null), 0, mRPSPageNotFoundRequests);
        this.lblValueSystemPages.Text   = GetViewValues(RequestHelper.TotalSystemPageRequests.GetValue(null), 0, mRPSSystemPageRequests);
        this.lblValueNonPages.Text      = GetViewValues(RequestHelper.TotalNonPageRequests.GetValue(null), 0, mRPSNonPageRequests);
        this.lblValueGetFilePages.Text  = GetViewValues(RequestHelper.TotalGetFileRequests.GetValue(null), 0, mRPSGetFileRequests);

        long pending = RequestHelper.PendingRequests.GetValue(null);

        if (pending > 1)
        {
            // Current request does not count as pending at the time of display
            pending--;
        }
        if (pending < 0)
        {
            pending = 0;
        }

        this.lblValuePending.Text = pending.ToString();

        this.lblCacheItemsValue.Text      = Cache.Count.ToString();
        this.lblCacheExpiredValue.Text    = CacheHelper.Expired.GetValue(null).ToString();
        this.lblCacheRemovedValue.Text    = CacheHelper.Removed.GetValue(null).ToString();
        this.lblCacheUnderusedValue.Text  = CacheHelper.Underused.GetValue(null).ToString();
        this.lblCacheDependencyValue.Text = CacheHelper.DependencyChanged.GetValue(null).ToString();

        // GC collections
        try
        {
            this.plcGC.Controls.Clear();

            int generations = GC.MaxGeneration;
            for (int i = 0; i <= generations; i++)
            {
                int    count     = GC.CollectionCount(i);
                string genString = "<tr><td style=\"white-space: nowrap; width: 200px;\">" + GetString("GC.Generation") + " " + i.ToString() + ":</td><td>" + count.ToString() + "</td></tr>";

                this.plcGC.Controls.Add(new LiteralControl(genString));
            }
        }
        catch
        {
        }

        lblDBNameValue.Text        = TableManager.DatabaseName;
        lblServerVersionValue.Text = TableManager.DatabaseServerVersion;

        // DB information
        if (!RequestHelper.IsPostBack())
        {
            lblDBSizeValue.Text     = TableManager.DatabaseSize;
            lblServerNameValue.Text = TableManager.DatabaseServerName;
        }
    }
コード例 #29
0
 /// <summary>
 /// 下游用户错误写日志方法
 /// </summary>
 /// <param name="message">错误消息</param>
 /// <param name="appId">应用ID</param>
 /// <param name="errorType">下游错误类型[1:订单号重复,2:重复发起支付,3:其他]</param>
 /// <param name="location">报错位置</param>
 /// <param name="summary">错误摘要[可选]</param>
 public static void DownstreamErrorLog(string message, int appId, EnumForLogForApi.ErrorType errorType, string summary = "下游用户错误", string location = "")
 {
     Logger.DownstreamErrorLog(0, message, RequestHelper.GetClientIp(), appId, errorType, location, summary);
 }
コード例 #30
0
ファイル: RCDetail.aspx.cs プロジェクト: xuefuruanjian/ems
 protected void Page_Load(object sender, EventArgs e)
 {
     CenterTitle.Text = RequestHelper.GetQueryString <string>("CourseName");
 }
コード例 #31
0
 /// <summary>
 /// 上游通知异常写日志方法
 /// </summary>
 /// <param name="message">错误消息</param>
 /// <param name="channelId">通道ID</param>
 /// <param name="location">报错位置</param>
 /// <param name="summary">错误摘要[可选]</param>
 public static void UpstreamNotifyErrorLog(string message, int channelId, string summary = "上游通知异常", string location = "")
 {
     Logger.UpstreamNotifyErrorLog(0, message, RequestHelper.GetClientIp(), channelId, (int)EnumForLogForApi.ErrorType.Unknown, location, summary);
 }
コード例 #32
0
        public void EditCourse(HttpContext context)
        {
            int         intSuccess = (int)errNum.Success;
            HttpRequest request    = context.Request;

            string Ids          = RequestHelper.string_transfer(request, "Ids");
            int    Enable       = RequestHelper.int_transfer(request, "Enable");
            int    CourseTypeId = RequestHelper.int_transfer(request, "CourseTypeId");
            int    Operation    = RequestHelper.int_transfer(request, "Operation");

            try
            {
                //课程变更【启用禁用】
                if (!string.IsNullOrEmpty(Ids))
                {
                    int[] Ids_ints = Split_Hepler.str_to_ints(Ids);

                    foreach (var id in Ids_ints)
                    {
                        //设置课程启用禁用
                        if (Operation == 1)
                        {
                            jsonModel = Constant.CourseService.GetEntityById(id);
                            if (jsonModel.errNum == 0)
                            {
                                Course s_course = jsonModel.retData as Course;
                                s_course.IsEnable = (byte)Enable;
                                JsonModel model = Constant.CourseService.Update(s_course);
                                if (jsonModel.errNum == 0)
                                {
                                    Course course = Constant.Course_List.FirstOrDefault(cour => cour.Id == id);
                                    course.IsEnable = s_course.IsEnable;
                                }
                            }
                        }
                        if (Operation == 2)
                        {
                            CourseRel courseRef = Constant.CourseRel_List.FirstOrDefault(re => re.Course_Id == Convert.ToString(id));
                            if (courseRef != null && CourseTypeId != 0)
                            {
                                CourseRel courseRef_Clone = Constant.Clone <CourseRel>(courseRef);
                                courseRef_Clone.CourseType_Id = Convert.ToString(CourseTypeId);
                                JsonModel model = Constant.CourseRelService.Update(courseRef_Clone);
                            }
                        }
                    }
                    jsonModel = JsonModel.get_jsonmodel(intSuccess, "success", "0");
                }
                else
                {
                    jsonModel = JsonModel.get_jsonmodel((int)errNum.Failed, "failed", "数据出现异常");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            finally
            {
                //无论后端出现什么问题,都要给前端有个通知【为防止jsonModel 为空 ,全局字段 jsonModel 特意声明之后进行初始化】
                context.Response.Write("{\"result\":" + Constant.jss.Serialize(jsonModel) + "}");
            }
        }
コード例 #33
0
ファイル: TokenHelper.cs プロジェクト: AAlben/Mall_WeChart_Nf
        /// <summary>
        /// 用地址信息
        /// </summary>
        /// <returns></returns>
        public string GetEditAddressParameters(HttpContextBase _base)
        {
            string parameter = "";
            try
            {
                string host = _base.Request.Url.Host;
                string path = _base.Request.Path;
                string queryString = _base.Request.Url.Query;
                //这个地方要注意,参与签名的是网页授权获取用户信息时微信后台回传的完整url
                string url = "http://" + host + path + queryString;

                //构造需要用SHA1算法加密的数据
                var par = new
                {
                    accesstoken = _base.Session["access_token"],
                    appid = ZZSCResource.DnmSystemConfig.SystemConfig.AppID,
                    noncestr = TokenHelper.GenerateNonceStr(),
                    timestamp = TokenHelper.GenerateTimeStamp(),
                    url = url
                };

                string param = new RequestHelper().JoinArguments(par);

                //Log.Debug(this.GetType().ToString(), "SHA1 encrypt param : " + param);
                //SHA1加密
                string addrSign = FormsAuthentication.HashPasswordForStoringInConfigFile(param.TrimStart('?'), "SHA1");
                //Log.Debug(this.GetType().ToString(), "SHA1 encrypt result : " + addrSign);

                //获取收货地址js函数入口参数
                var parNa = new
                {
                    addrSign = addrSign,
                    appId = ZZSCResource.DnmSystemConfig.SystemConfig.AppID,
                    noncestr = TokenHelper.GenerateNonceStr(),
                    timestamp = TokenHelper.GenerateTimeStamp(),
                    scope = "jsapi_address",
                    signType = "sha1"
                };

                SortedDictionary<string, object> dicPar = new SortedDictionary<string, object>();
                dicPar.Add("addrSign", addrSign);
                dicPar.Add("appId", ZZSCResource.DnmSystemConfig.SystemConfig.AppID);
                dicPar.Add("noncestr", TokenHelper.GenerateNonceStr());
                dicPar.Add("timestamp", TokenHelper.GenerateTimeStamp());
                dicPar.Add("scope", "jsapi_address");
                dicPar.Add("signType", "sha1");

                //转为json格式
                parameter = JsonConvert.SerializeObject(parNa);
                //parameter = JsonMapper.ToJson(dicPar);
                //Log.Debug(this.GetType().ToString(), "Get EditAddressParam : " + parameter);
            }
            catch (Exception ex)
            {
                //Log.Error(this.GetType().ToString(), ex.ToString());
                DBCommon.LogFileHelper.WriteLogByTxt(string.Format("GetEditAddressParameters方法异常:{0}", ex.ToString()));
                throw new Exception(ex.ToString());
            }

            return parameter;
        }
コード例 #34
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            plcOther.Controls.Clear();

            if (MembershipContext.AuthenticatedUser.IsAuthenticated())
            {
                // Set the layout of tab menu
                tabMenu.TabControlLayout = BasicTabControl.GetTabMenuLayout(TabControlLayout);

                // Remove 'saved' parameter from query string
                string absoluteUri = URLHelper.RemoveParameterFromUrl(URLRewriter.CurrentURL, "saved");

                CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser;

                // Get customer info
                GeneralizedInfo customer       = ModuleCommands.ECommerceGetCustomerInfoByUserId(currentUser.UserID);
                bool            userIsCustomer = (customer != null);

                // Get friends enabled setting
                bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(SiteContext.CurrentSiteName);

                // Get customer ID
                int customerId = 0;
                if (userIsCustomer)
                {
                    customerId = ValidationHelper.GetInteger(customer.ObjectID, 0);
                }

                // Selected page URL
                string selectedPage = string.Empty;

                // Menu initialization
                tabMenu.UrlTarget = "_self";
                ArrayList activeTabs = new ArrayList();
                string    tabName    = string.Empty;

                // Set array size of tab control
                int arraySize = 0;
                if (DisplayMyPersonalSettings)
                {
                    arraySize++;
                }
                if (DisplayMyMessages)
                {
                    arraySize++;
                }

                // Handle 'Notifications' tab displaying
                bool hideUnavailableUI       = SettingsKeyInfoProvider.GetBoolValue("CMSHideUnavailableUserInterface");
                bool showNotificationsTab    = (DisplayMyNotifications && ModuleEntryManager.IsModuleLoaded(ModuleEntry.NOTIFICATIONS) && (!hideUnavailableUI || LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.Notifications)));
                bool isWindowsAuthentication = RequestHelper.IsWindowsAuthentication();

                // Notification tab
                if (showNotificationsTab)
                {
                    arraySize++;
                }

                // Friends tab
                if (DisplayMyFriends && friendsEnabled)
                {
                    arraySize++;
                }

                // User password tab
                if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication)
                {
                    arraySize++;
                }

                // Subscriptions tab
                if (DisplayMySubscriptions)
                {
                    arraySize++;
                }

                // Memberships tab
                if (DisplayMyMemberships)
                {
                    arraySize++;
                }

                // Categories tab
                if (DisplayMyCategories)
                {
                    arraySize++;
                }

                // Ecommerce tabs
                if (DisplayMyCredits && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyDetails && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyAddresses && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyOrders && userIsCustomer)
                {
                    arraySize++;
                }
                tabMenu.Tabs = new string[arraySize, 5];

                // Personal tab
                if (DisplayMyPersonalSettings)
                {
                    // Set new tab
                    tabName = personalTab;
                    activeTabs.Add(tabName);
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyPersonalSettings");
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, personalTab));

                    if (currentUser != null)
                    {
                        selectedPage = tabName;
                    }
                }

                // These items can be displayed only for customer
                if (userIsCustomer && ModuleEntryManager.IsModuleLoaded(ModuleEntry.ECOMMERCE))
                {
                    if (DisplayMyDetails)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyDetails = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyDetails.ascx") as CMSAdminControl;
                        if (ucMyDetails != null)
                        {
                            ucMyDetails.ID = "ucMyDetails";
                            plcOther.Controls.Add(ucMyDetails);

                            // Set new tab
                            tabName = detailsTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyDetails");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, detailsTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyAddresses)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyAddresses = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyAddresses.ascx") as CMSAdminControl;
                        if (ucMyAddresses != null)
                        {
                            ucMyAddresses.ID = "ucMyAddresses";
                            plcOther.Controls.Add(ucMyAddresses);

                            // Set new tab
                            tabName = addressesTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAddresses");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, addressesTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyOrders)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyOrders = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyOrders.ascx") as CMSAdminControl;
                        if (ucMyOrders != null)
                        {
                            ucMyOrders.ID = "ucMyOrders";
                            plcOther.Controls.Add(ucMyOrders);

                            // Set new tab
                            tabName = ordersTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyOrders");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, ordersTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyCredits)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyCredit = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyCredit.ascx") as CMSAdminControl;
                        if (ucMyCredit != null)
                        {
                            ucMyCredit.ID = "ucMyCredit";
                            plcOther.Controls.Add(ucMyCredit);

                            // Set new tab
                            tabName = creditTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCredit");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, creditTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }
                }

                if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication)
                {
                    // Set new tab
                    tabName = passwordTab;
                    activeTabs.Add(tabName);
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.ChangePassword");
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, passwordTab));

                    if (selectedPage == string.Empty)
                    {
                        selectedPage = tabName;
                    }
                }

                if ((ucMyNotifications == null) && showNotificationsTab)
                {
                    // Try to load the control dynamically (if available)
                    ucMyNotifications = Page.LoadUserControl("~/CMSModules/Notifications/Controls/UserNotifications.ascx") as CMSAdminControl;
                    if (ucMyNotifications != null)
                    {
                        ucMyNotifications.ID = "ucMyNotifications";
                        plcOther.Controls.Add(ucMyNotifications);

                        // Set new tab
                        tabName = notificationsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyNotifications");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, notificationsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyMessages == null) && DisplayMyMessages && ModuleEntryManager.IsModuleLoaded(ModuleEntry.MESSAGING))
                {
                    // Try to load the control dynamically (if available)
                    ucMyMessages = Page.LoadUserControl("~/CMSModules/Messaging/Controls/MyMessages.ascx") as CMSAdminControl;
                    if (ucMyMessages != null)
                    {
                        ucMyMessages.ID = "ucMyMessages";
                        plcOther.Controls.Add(ucMyMessages);

                        // Set new tab
                        tabName = messagesTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyMessages");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, messagesTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyFriends == null) && DisplayMyFriends && ModuleEntryManager.IsModuleLoaded(ModuleEntry.COMMUNITY) && friendsEnabled)
                {
                    // Try to load the control dynamically (if available)
                    ucMyFriends = Page.LoadUserControl("~/CMSModules/Friends/Controls/MyFriends.ascx") as CMSAdminControl;
                    if (ucMyFriends != null)
                    {
                        ucMyFriends.ID = "ucMyFriends";
                        plcOther.Controls.Add(ucMyFriends);

                        // Set new tab
                        tabName = friendsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyFriends");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, friendsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyAllSubscriptions == null) && DisplayMySubscriptions)
                {
                    // Try to load the control dynamically (if available)
                    ucMyAllSubscriptions = Page.LoadUserControl("~/CMSModules/Membership/Controls/Subscriptions.ascx") as CMSAdminControl;
                    if (ucMyAllSubscriptions != null)
                    {
                        // Set control
                        ucMyAllSubscriptions.Visible = false;

                        ucMyAllSubscriptions.SetValue("ShowBlogs", DisplayBlogs);
                        ucMyAllSubscriptions.SetValue("ShowMessageBoards", DisplayMessageBoards);
                        ucMyAllSubscriptions.SetValue("ShowNewsletters", DisplayNewsletters);
                        ucMyAllSubscriptions.SetValue("ShowForums", DisplayForums);
                        ucMyAllSubscriptions.SetValue("ShowReports", DisplayReports);
                        ucMyAllSubscriptions.SetValue("sendconfirmationemail", SendConfirmationEmails);

                        ucMyAllSubscriptions.ID = "ucMyAllSubscriptions";
                        plcOther.Controls.Add(ucMyAllSubscriptions);

                        // Set new tab
                        tabName = subscriptionsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAllSubscriptions");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, subscriptionsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                // My memberships
                if ((ucMyMemberships == null) && DisplayMyMemberships)
                {
                    // Try to load the control dynamically
                    ucMyMemberships = Page.LoadUserControl("~/CMSModules/Membership/Controls/MyMemberships.ascx") as CMSAdminControl;

                    if (ucMyMemberships != null)
                    {
                        ucMyMemberships.SetValue("UserID", currentUser.UserID);

                        if (!String.IsNullOrEmpty(MembershipsPagePath))
                        {
                            ucMyMemberships.SetValue("BuyMembershipURL", DocumentURLProvider.GetUrl(MembershipsPagePath));
                        }

                        plcOther.Controls.Add(ucMyMemberships);

                        // Set new tab
                        tabName = membershipsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("myaccount.mymemberships");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, membershipsTab));

                        if (selectedPage == String.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyCategories == null) && DisplayMyCategories)
                {
                    // Try to load the control dynamically (if available)
                    ucMyCategories = Page.LoadUserControl("~/CMSModules/Categories/Controls/Categories.ascx") as CMSAdminControl;
                    if (ucMyCategories != null)
                    {
                        ucMyCategories.Visible = false;

                        ucMyCategories.SetValue("DisplaySiteCategories", false);
                        ucMyCategories.SetValue("DisplaySiteSelector", false);

                        ucMyCategories.ID = "ucMyCategories";
                        plcOther.Controls.Add(ucMyCategories);

                        // Set new tab
                        tabName = categoriesTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCategories");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, categoriesTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                // Set CSS class
                pnlBody.CssClass = CssClass;

                // Get page URL
                page = QueryHelper.GetString(ParameterName, selectedPage);

                // Set controls visibility
                ucChangePassword.Visible        = false;
                ucChangePassword.StopProcessing = true;

                if (ucMyAddresses != null)
                {
                    ucMyAddresses.Visible        = false;
                    ucMyAddresses.StopProcessing = true;
                }

                if (ucMyOrders != null)
                {
                    ucMyOrders.Visible        = false;
                    ucMyOrders.StopProcessing = true;
                }

                if (ucMyDetails != null)
                {
                    ucMyDetails.Visible        = false;
                    ucMyDetails.StopProcessing = true;
                }

                if (ucMyCredit != null)
                {
                    ucMyCredit.Visible        = false;
                    ucMyCredit.StopProcessing = true;
                }

                if (ucMyAllSubscriptions != null)
                {
                    ucMyAllSubscriptions.Visible        = false;
                    ucMyAllSubscriptions.StopProcessing = true;
                    ucMyAllSubscriptions.SetValue("CacheMinutes", CacheMinutes);
                }

                if (ucMyNotifications != null)
                {
                    ucMyNotifications.Visible        = false;
                    ucMyNotifications.StopProcessing = true;
                }

                if (ucMyMessages != null)
                {
                    ucMyMessages.Visible        = false;
                    ucMyMessages.StopProcessing = true;
                }

                if (ucMyFriends != null)
                {
                    ucMyFriends.Visible        = false;
                    ucMyFriends.StopProcessing = true;
                }

                if (ucMyMemberships != null)
                {
                    ucMyMemberships.Visible        = false;
                    ucMyMemberships.StopProcessing = true;
                }

                if (ucMyCategories != null)
                {
                    ucMyCategories.Visible        = false;
                    ucMyCategories.StopProcessing = true;
                }

                tabMenu.SelectedTab = activeTabs.IndexOf(page);

                // Select current page
                switch (page)
                {
                case personalTab:
                    if (myProfile != null)
                    {
                        // Get alternative form info
                        AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(AlternativeFormName);
                        if (afi != null)
                        {
                            myProfile.StopProcessing      = false;
                            myProfile.Visible             = true;
                            myProfile.AllowEditVisibility = AllowEditVisibility;
                            myProfile.AlternativeFormName = AlternativeFormName;
                        }
                        else
                        {
                            lblError.Text     = String.Format(GetString("altform.formdoesntexists"), AlternativeFormName);
                            lblError.Visible  = true;
                            myProfile.Visible = false;
                        }
                    }
                    break;

                // My details tab
                case detailsTab:
                    if (ucMyDetails != null)
                    {
                        ucMyDetails.Visible        = true;
                        ucMyDetails.StopProcessing = false;
                        ucMyDetails.SetValue("Customer", customer);
                    }
                    break;

                // My addresses tab
                case addressesTab:
                    if (ucMyAddresses != null)
                    {
                        ucMyAddresses.Visible        = true;
                        ucMyAddresses.StopProcessing = false;
                        ucMyAddresses.SetValue("CustomerId", customerId);
                    }
                    break;

                // My orders tab
                case ordersTab:
                    if (ucMyOrders != null)
                    {
                        ucMyOrders.Visible        = true;
                        ucMyOrders.StopProcessing = false;
                        ucMyOrders.SetValue("CustomerId", customerId);
                        ucMyOrders.SetValue("ShowOrderTrackingNumber", ShowOrderTrackingNumber);
                    }
                    break;

                // My credit tab
                case creditTab:
                    if (ucMyCredit != null)
                    {
                        ucMyCredit.Visible        = true;
                        ucMyCredit.StopProcessing = false;
                        ucMyCredit.SetValue("CustomerId", customerId);
                    }
                    break;

                // Password tab
                case passwordTab:
                    ucChangePassword.Visible            = true;
                    ucChangePassword.StopProcessing     = false;
                    ucChangePassword.AllowEmptyPassword = AllowEmptyPassword;
                    break;

                // Notification tab
                case notificationsTab:
                    if (ucMyNotifications != null)
                    {
                        ucMyNotifications.Visible        = true;
                        ucMyNotifications.StopProcessing = false;
                        ucMyNotifications.SetValue("UserId", currentUser.UserID);
                        ucMyNotifications.SetValue("UnigridImageDirectory", UnigridImageDirectory);
                    }
                    break;

                // My messages tab
                case messagesTab:
                    if (ucMyMessages != null)
                    {
                        ucMyMessages.Visible        = true;
                        ucMyMessages.StopProcessing = false;
                    }
                    break;

                // My friends tab
                case friendsTab:
                    if (ucMyFriends != null)
                    {
                        ucMyFriends.Visible        = true;
                        ucMyFriends.StopProcessing = false;
                        ucMyFriends.SetValue("UserID", currentUser.UserID);
                    }
                    break;

                // My subscriptions tab
                case subscriptionsTab:
                    if (ucMyAllSubscriptions != null)
                    {
                        ucMyAllSubscriptions.Visible        = true;
                        ucMyAllSubscriptions.StopProcessing = false;

                        ucMyAllSubscriptions.SetValue("userid", currentUser.UserID);
                        ucMyAllSubscriptions.SetValue("siteid", CMSContext.CurrentSiteID);
                    }
                    break;

                // My memberships tab
                case membershipsTab:
                    if (ucMyMemberships != null)
                    {
                        ucMyMemberships.Visible        = true;
                        ucMyMemberships.StopProcessing = false;
                    }
                    break;

                // My categories tab
                case categoriesTab:
                    if (ucMyCategories != null)
                    {
                        ucMyCategories.Visible        = true;
                        ucMyCategories.StopProcessing = false;
                    }
                    break;
                }
            }
            else
            {
                // Hide control if current user is not authenticated
                Visible = false;
            }
        }
    }
コード例 #35
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);

            // Check 'manage' permission
            var currentUser = MembershipContext.AuthenticatedUser;
            friendsManagePermission = currentUser != null && (currentUser.IsAuthorizedPerResource("CMS.Friends", "Manage") || (currentUser.UserID == UserID));

            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 + "();";
            // Hide label
            lblInfo.Attributes["style"] = "display: none;";

            // 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 = " + ScriptHelper.GetString(GetString("friends.selectfriends")) + ";");
            showLabelScript.AppendLine("      label.style['display'] = 'block';");
            showLabelScript.AppendLine("   }");
            showLabelScript.AppendLine("}");
            ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "showLabel", ScriptHelper.GetScript(showLabelScript.ToString()));

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

            // Register approval script
            StringBuilder approveScript = new StringBuilder();
            approveScript.AppendLine("function FM_Approve_" + ClientID + "(item, gridId, url)");
            approveScript.AppendLine("{");
            approveScript.AppendLine("   var items = '';");
            approveScript.AppendLine("   if(item == null)");
            approveScript.AppendLine("   {");
            approveScript.AppendLine("       items = document.getElementById(gridId).value;");
            approveScript.AppendLine("   }");
            approveScript.AppendLine("   else");
            approveScript.AppendLine("   {");
            approveScript.AppendLine("       items = item;");
            approveScript.AppendLine("   }");
            approveScript.AppendLine("   if((url != null) && (items != '') && (items != '|'))");
            approveScript.AppendLine("   {");
            approveScript.AppendLine("      modalDialog(url + '&ids=' + items, 'rejectDialog', 720, 320);");
            approveScript.AppendLine("   }");
            approveScript.AppendLine("   else");
            approveScript.AppendLine("   {");
            approveScript.AppendLine("       FM_ShowLabel('" + lblInfo.ClientID + "');");
            approveScript.AppendLine("   }");
            approveScript.AppendLine("   return false;");
            approveScript.AppendLine("}");
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "approveScript_" + ClientID, ScriptHelper.GetScript(approveScript.ToString()));

            // Add action to button
            btnApproveSelected.OnClientClick = "return FM_Approve_" + ClientID + "(null,'" + gridElem.SelectionHiddenField.ClientID + "','" + ApproveDialogUrl + "');";
            btnApproveSelected.Enabled       = friendsManagePermission;

            if (!RequestHelper.IsPostBack())
            {
                pnlInner.Visible = !ShowLink;
            }
            btnShowHide.ResourceString = !pnlInner.Visible ? "friends.showrejected" : "friends.hiderejected";

            if (!UseEncapsulation)
            {
                plcLink.Visible  = false;
                pnlInner.Visible = true;
            }

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

            // Where condition
            gridElem.WhereCondition = "(FriendStatus = " + Convert.ToInt32(FriendshipStatusEnum.Rejected) + ") AND (FriendRejectedBy = " + UserID + ")";

            // Add parameter @UserID
            if (gridElem.QueryParameters == null)
            {
                gridElem.QueryParameters = new QueryDataParameters();
            }
            gridElem.QueryParameters.Add("@UserID", UserID);

            pnlLinkButtons.Visible = IsLiveSite;

            if (!IsLiveSite)
            {
                var headerActions = ((CMSPage)Page).CurrentMaster.HeaderActions;
                headerActions.AddAction(new HeaderAction()
                {
                    Text          = GetString("friends.friendapproveall"),
                    OnClientClick = "return FM_Approve_" + ClientID + "(null,'" + gridElem.SelectionHiddenField.ClientID + "','" + ApproveDialogUrl + "');",
                    Enabled       = friendsManagePermission
                });
                headerActions.AddAction(new HeaderAction()
                {
                    Text          = GetString("friends.friendremoveall"),
                    OnClientClick = "return FM_RemoveAction_" + ClientID + "();",
                    Enabled       = friendsManagePermission
                });
            }
        }
    }
コード例 #36
0
    private void ReloadData()
    {
        if (Node != null)
        {
            // Check modify permission
            canEdit = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Denied);

            // Show owner editing only when authorized to change the permissions
            if (canEditOwner)
            {
                lblOwner.Visible = false;
                usrOwner.Visible = true;
                usrOwner.SetValue("AdditionalUsers", new[] { Node.NodeOwner });
            }
            else
            {
                usrOwner.Visible = false;
            }

            if (!RequestHelper.IsPostBack())
            {
                if (canEditOwner)
                {
                    usrOwner.Value = Node.GetValue("NodeOwner");
                }

                txtAlias.Text = Node.NodeAlias;
                chkExcludeFromSearch.Checked = Node.DocumentSearchExcluded;
            }

            // Load the data
            lblName.Text = HttpUtility.HtmlEncode(Node.GetDocumentName());

            lblAliasPath.Text = Convert.ToString(Node.NodeAliasPath);
            string typeName = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName).ClassDisplayName;
            lblType.Text   = HttpUtility.HtmlEncode(ResHelper.LocalizeString(typeName));
            lblNodeID.Text = Convert.ToString(Node.NodeID);

            // Modifier
            SetUserLabel(lblLastModifiedBy, "DocumentModifiedByUserId");

            // Get modified time
            TimeZoneInfo usedTimeZone;
            DateTime     lastModified = ValidationHelper.GetDateTime(Node.GetValue("DocumentModifiedWhen"), DateTimeHelper.ZERO_TIME);
            lblLastModified.Text = TimeZoneHelper.GetCurrentTimeZoneDateTimeString(lastModified, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite, out usedTimeZone);
            ScriptHelper.AppendTooltip(lblLastModified, TimeZoneHelper.GetUTCLongStringOffset(usedTimeZone), "help");

            if (!canEditOwner)
            {
                // Owner
                SetUserLabel(lblOwner, "NodeOwner");
            }

            // Creator
            SetUserLabel(lblCreatedBy, "DocumentCreatedByUserId");
            DateTime createdWhen = ValidationHelper.GetDateTime(Node.GetValue("DocumentCreatedWhen"), DateTimeHelper.ZERO_TIME);
            lblCreated.Text = TimeZoneHelper.GetCurrentTimeZoneDateTimeString(createdWhen, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite, out usedTimeZone);
            ScriptHelper.AppendTooltip(lblCreated, TimeZoneHelper.GetUTCLongStringOffset(usedTimeZone), "help");

            lblGUID.Text    = Convert.ToString(Node.NodeGUID);
            lblDocGUID.Text = (Node.DocumentGUID == Guid.Empty) ? ResHelper.Dash : Node.DocumentGUID.ToString();
            lblDocID.Text   = Convert.ToString(Node.DocumentID);

            // Culture
            CultureInfo ci = CultureInfo.Provider.Get(Node.DocumentCulture);
            lblCulture.Text = ((ci != null) ? ResHelper.LocalizeString(ci.CultureName) : Node.DocumentCulture);

            if (Node.IsPublished)
            {
                lblPublished.Text      = GetString("General.Yes");
                lblPublished.CssClass += " DocumentPublishedYes";
            }
            else
            {
                lblPublished.CssClass += " DocumentPublishedNo";
                lblPublished.Text      = GetString("General.No");
            }

            if (!canEdit)
            {
                // Disable form editing
                DisableFormEditing();
            }
        }
    }
コード例 #37
0
ファイル: TokenHelper.cs プロジェクト: AAlben/Mall_WeChart_Nf
        /// <summary>
        /// 根据Code取出 access_token、openid 值
        /// Remark:存储到Session中
        /// </summary>
        /// <param name="code"></param>
        public void GetOpenidAndAccessTokenFromCode(HttpContextBase _base, string code)
        {
            //Result Data
            string access_token = string.Empty;
            string openid = string.Empty;

            //Init Data
            bool flag = false;
            string url = "https://api.weixin.qq.com/sns/oauth2/access_token";

            var par = new
            {
                appid = ZZSCResource.DnmSystemConfig.SystemConfig.AppID,
                secret = ZZSCResource.DnmSystemConfig.SystemConfig.AppSecret,
                code = code,
                grant_type = "authorization_code"
            };

            string strPar = new RequestHelper().JoinArguments(par);

            //Request
            using (HttpClient htpClt = new HttpClient())
            {
                string rqtResult = htpClt.GetStringAsync(new Uri(url + strPar)).Result;

                dynamic dnm = JsonConvert.DeserializeObject(rqtResult);

                if (dnm.errorcode != null)
                {
                    flag = false; //失败
                }
                else
                {
                    flag = true; //成功
                    access_token = dnm.access_token;
                    openid = dnm.openid;

                    _base.Session["access_token"] = access_token;
                    _base.Session["openid"] = openid;
                }
            }
        }
コード例 #38
0
	/// <summary>
	/// Retorna os dados da plataforma (isso e chamado automaticamente atraves do prefab de integracao)
	/// </summary>
	/// <returns>RequestModel com todas informaçoes desse tipo de requisicao</returns>
	/// <param name="__callbackRequestCompleted">__callback request completed.</param>
	/// <param name="__callbackRequestError">__callback request error.</param>
	/// <param name="__callbackRequestStarted">__callback request started.</param>
	/// <param name="__callbackRequestFinalized">__callback request finalized.</param>
	public static GetPlatformDataRM getPlatformData(RequestHelper.RequestHandlerDelegate __callbackRequestCompleted = null,
														RequestHelper.RequestHandlerDelegate __callbackRequestError = null,
														RequestHelper.RequestHandlerDelegate __callbackRequestStarted = null,
														RequestHelper.RequestHandlerDelegate __callbackRequestFinalized = null)
	{
		throw new System.Exception("This request was already made on game start. You can get it through class PlatformDataManager.");
//		GetPlatformDataRM request = new GetPlatformDataRM();
//		request.cvo.setupParameters();
//		setupRequest(request, __callbackRequestCompleted, __callbackRequestError, __callbackRequestStarted, __callbackRequestFinalized);
//		return request;
	}
コード例 #39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckAdminPower("OrderRefundConfirm", PowerCheckType.Single);

            int id = RequestHelper.GetQueryString <int>("order_refund_id");

            var orderRefund = OrderRefundBLL.Read(id);

            if (orderRefund.Status != (int)OrderRefundStatus.Returning)
            {
                message = "无效的退款状态";
                return;
            }

            if (orderRefund.RefundBalance <= 0)
            {
                message = "退款金额必须大于0";
                return;
            }

            //需退款到第三方支付平台的退款单,一律在第三方支付退款成功后的回调页面操作
            if (orderRefund.RefundMoney > 0)
            {
                message = "请通过第三方平台进行退款";
                return;
            }

            var user = UserBLL.Read(orderRefund.OwnerId);

            if (user.Id < 0)
            {
                message = "无效的退款用户";
                return;
            }

            var order = OrderBLL.Read(orderRefund.OrderId);

            if (order.Id < 0)
            {
                message = "无效的退款订单";
                return;
            }


            //***********业务逻辑***************************************//

            /*************************************************************
            *  if (isSuccess)
            *  {
            *   msg = "退款完成";
            *
            *   //更新状态
            *   orderRefund.Status = (int)OrderRefundStatus.HasReturn;
            *   orderRefund.TmRefund = DateTime.Now;
            *   OrderRefundBLL.Update(orderRefund);
            *  }
            *  else
            *  {
            *   message = msg;
            *  }
            *
            *  OrderRefundActionBLL.Add(new OrderRefundActionInfo
            *  {
            *   OrderRefundId = orderRefund.Id,
            *   Status = isSuccess ? (int)BoolType.True : (int)BoolType.False,
            *   Tm = DateTime.Now,
            *   UserType = 2,
            *   UserId = base.AdminID,
            *   UserName = Cookies.Admin.GetAdminName(false),
            *   Remark = msg
            *  });
            *************************************************************/
        }
コード例 #40
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Handle Import settings
        if (!Page.IsCallback && !RequestHelper.IsPostBack())
        {
            // Initialize virtual path provider
            VirtualPathHelper.Init(Page);

            // Initialize import settings
            ImportSettings = GetNewSettings();
        }

        if (!Page.IsCallback)
        {
            if (!CMS.SettingsProvider.SettingsKeyProvider.UsingVirtualPathProvider)
            {
                lblWarning.Visible = true;
                lblWarning.Text    = GetString("ImportSite.VirtualPathProviderNotRunning");
            }

            ctrlAsync.OnFinished += ctrlAsync_OnFinished;
            ctrlAsync.OnError    += ctrlAsync_OnError;

            bool notTempPermissions = false;

            if (wzdImport.ActiveStepIndex < 3)
            {
                stpConfigImport.Settings = ImportSettings;
                stpSiteDetails.Settings  = ImportSettings;
                stpImport.Settings       = ImportSettings;

                // Ensure directory
                DirectoryHelper.EnsureDiskPath(ImportSettings.TemporaryFilesPath + "\\temp.file", ImportSettings.WebsitePath);
                // Check permissions
                notTempPermissions = !DirectoryHelper.CheckPermissions(ImportSettings.TemporaryFilesPath, true, true, false, false);
            }

            if (notTempPermissions)
            {
                pnlWrapper.Visible         = false;
                lblError.Text              = string.Format(GetString("ImportSite.ErrorPermissions"), ImportSettings.TemporaryFilesPath, WindowsIdentity.GetCurrent().Name);
                pnlPermissions.Visible     = true;
                lnkPermissions.Target      = "_blank";
                lnkPermissions.Text        = GetString("Install.ErrorPermissions");
                lnkPermissions.NavigateUrl = ResolveUrl("~/CMSMessages/ConfigurePermissions.aspx");
            }
            else
            {
                if (!RequestHelper.IsPostBack())
                {
                    // Delete temporary files
                    try
                    {
                        // Delete only folder structure if there is not special folder
                        bool onlyFolderStructure = !Directory.Exists(DirectoryHelper.CombinePath(ImportSettings.TemporaryFilesPath, ImportExportHelper.FILES_FOLDER));
                        ImportProvider.DeleteTemporaryFiles(ImportSettings, onlyFolderStructure);
                    }
                    catch (Exception ex)
                    {
                        pnlWrapper.Visible = false;
                        lblError.Text      = GetString("ImportSite.ErrorDeletionTemporaryFiles") + ex.Message;
                        return;
                    }
                }

                // Javascript functions
                string script =
                    "var imMessageText = '';\n" +
                    "var imErrorText = '';\n" +
                    "var imWarningText = '';\n" +
                    "var imMachineName = '" + SqlHelperClass.MachineName.ToLower() + "';\n" +
                    "var getBusy = false;\n" +
                    "function GetImportState(cancel)\n" +
                    "{ if(window.Activity){window.Activity();} if (getBusy && !cancel) return; getBusy = true; setTimeout(\"getBusy = false;\", 2000); var argument = cancel + ';' + imMessageText.length + ';' + imErrorText.length + ';' + imWarningText.length + ';' + imMachineName; return " + Page.ClientScript.GetCallbackEventReference(this, "argument", "SetImportStateMssg", "argument", true) + " }\n";

                script +=
                    "function SetImportStateMssg(rValue, context)\n" +
                    "{\n" +
                    "   getBusy = false;\n" +
                    "   if(rValue != '')\n" +
                    "   {\n" +
                    "       var args = context.split(';');\n" +
                    "       var values = rValue.split('" + SiteExportSettings.SEPARATOR + "');\n" +
                    "       var messageElement = document.getElementById('" + lblProgress.ClientID + "');\n" +
                    "       var errorElement = document.getElementById('" + lblError.ClientID + "');\n" +
                    "       var warningElement = document.getElementById('" + lblWarning.ClientID + "');\n" +
                    "       var messageText = imMessageText;\n" +
                    "       messageText = values[1] + messageText.substring(messageText.length - args[1]);\n" +
                    "       if(messageText.length > imMessageText.length){ imMessageText = messageElement.innerHTML = messageText; }\n" +
                    "       var errorText = imErrorText;\n" +
                    "       errorText = values[2] + errorText.substring(errorText.length - args[2]);\n" +
                    "       if(errorText.length > imErrorText.length){ imErrorText = errorElement.innerHTML = errorText; }\n" +
                    "       var warningText = imWarningText;\n" +
                    "       warningText = values[3] + warningText.substring(warningText.length - args[3]);\n" +
                    "       if(warningText.length > imWarningText.length){ imWarningText = warningElement.innerHTML = warningText; }\n" +
                    "       if((values=='') || (values[0]=='F'))\n" +
                    "       {\n" +
                    "           StopImportStateTimer();\n" +
                    "           BTN_Disable('" + CancelButton.ClientID + "');\n" +
                    "           BTN_Enable('" + FinishButton.ClientID + "');\n" +
                    "       }\n" +
                    "   }\n" +
                    "}\n";

                // Register the script to perform get flags for showing buttons retrieval callback
                ScriptHelper.RegisterClientScriptBlock(this, GetType(), "GetSetImportState", ScriptHelper.GetScript(script));

                // Add cancel button attribute
                CancelButton.Attributes.Add("onclick", "BTN_Disable('" + CancelButton.ClientID + "');" + "return CancelImport();");

                wzdImport.NextButtonClick     += wzdImport_NextButtonClick;
                wzdImport.PreviousButtonClick += wzdImport_PreviousButtonClick;
                wzdImport.FinishButtonClick   += wzdImport_FinishButtonClick;

                if (!RequestHelper.IsPostBack())
                {
                    stpConfigImport.InitControl();
                }
            }
        }
    }
コード例 #41
0
 private BoxManager()
 {
     _requestHelper = new RequestHelper();
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterTooltip(Page);

        // Initialize events
        ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished;
        ctlAsyncLog.OnError    += ctlAsyncLog_OnError;
        ctlAsyncLog.OnCancel   += ctlAsyncLog_OnCancel;

        ctlAsyncLog.Buttons.CssClass = "cms-edit-menu";

        HeaderActions.AddAction(new HeaderAction
        {
            Text        = GetString("srch.clearattachmentcache"),
            Tooltip     = GetString("srch.clearattachmentcache.tooltip"),
            CommandName = "clearcache"
        });

        HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;

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

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

            return;
        }


        // Setup the controls
        gridFiles.OnExternalDataBound += gridFiles_OnExternalDataBound;
        gridFiles.OnAction            += gridFiles_OnAction;

        ControlsHelper.RegisterPostbackControl(btnOk);

        currentSiteId = SiteContext.CurrentSiteID;

        CurrentMaster.DisplaySiteSelectorPanel = true;

        // 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;
            UIContext["SiteID"]      = siteId;
        }

        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)
            {
                var filesLocationType = GetFilesLocationType(siteId);

                bool fs = filesLocationType != FilesLocationTypeEnum.Database;
                bool db = filesLocationType != FilesLocationTypeEnum.FileSystem;

                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"));
            }
        }
    }
コード例 #43
0
ファイル: TokenHelper.cs プロジェクト: AAlben/Mall_WeChart_Nf
        /// <summary>
        /// 获取openid
        /// Remark:校验code
        /// </summary>
        public Tuple<bool, string> GetOpenidAndAccessToken(HttpContextBase _base)
        {
            if (!string.IsNullOrEmpty(_base.Request["code"]))
            {
                //获取code码,以获取openid和access_token
                string code = _base.Request["code"];
                GetOpenidAndAccessTokenFromCode(_base, code);

                return new Tuple<bool, string>(true, string.Empty);
            }
            else
            {
                //构造网页授权获取code的URL
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize";
                string host = _base.Request.Url.Host;
                string path = _base.Request.Path;
                string redirect_uri = HttpUtility.UrlEncode("http://" + host + path);

                var par = new
                {
                    appid = ZZSCResource.DnmSystemConfig.SystemConfig.AppID,
                    redirect_uri = redirect_uri,
                    response_type = "code",
                    scope = ZZSCResource.DnmSystemConfig.SystemConfig.scope,
                    state = "STATE" + "#wechat_redirect"
                };

                //Log
                string strPar = new RequestHelper().JoinArguments(par);

                //跳转
                return new Tuple<bool, string>(false, url + strPar);
            }
        }