示例#1
0
 void Start()
 {
     playedOnce = false;
     warpPortal = FindObjectOfType<PortalController>();
     warpKey = FindObjectOfType<KeyPickup>();
     warpSFX = GetComponent<AudioSource>();
 }
示例#2
0
 void FixedUpdate()
 {
     if (!createPortal) { return; }
     if (portalB != null) {
         Destroy (portalB.gameObject.transform.root.gameObject, 0.0f);
     }
     Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
     portalB = portalA;
     GameObject obj = (GameObject) Instantiate(portal, new Vector3(pos.x, pos.y, 0f), Quaternion.identity);
     portalA = obj.GetComponentInChildren<PortalController>();
     createPortal = false;
 }
    private void PopulatePortalList2DDL()
    {
        PortalController portal_obj = new PortalController();
        DataTable dtNodes = portal_obj.GetList();

        ddlPortalList.Items.Clear();
        ddlPortalList.DataSource = dtNodes;
        ddlPortalList.DataTextField = "PortalName";
        ddlPortalList.DataValueField = "PortalId";
        ddlPortalList.DataBind();
        //ddlPortalList.Items.Insert(0, new ListItem("- Chọn -", "0"));
        ddlPortalList.SelectedIndex = 0;
        ddlPortalList.AutoPostBack = true;
    }
    void Start()
    {
        deathAnimation = false;
        isDead = false;
        EnemyMaxHP = enemyHP;
        player = FindObjectOfType<MasterController>();
        LM = FindObjectOfType<LevelManager>();
        warpPortal = FindObjectOfType<PortalController>();
        warpKey = FindObjectOfType<KeyPickup>();
        enemyHurtSFX = GetComponent<AudioSource>();

        if (GetComponent<EnemyAnimation>() != null)
        {
            enemyAnim = FindObjectOfType<EnemyAnimation>();
        }
        else
        {
            enemyAnim = null;
        }
    }
    //private PauseOverlay PauseMenu;
    void Start()
    {
        hasTouchedEnemy = false;
        groundWallC = GetComponentsInChildren<BoxCollider2D> ();
        afterClimbEffing = false;
        //	wallCheck = GetComponentInChildren<WallClimbingCheck> ();
        wallClimbing = false;
        releaseControl = false;
        //Debug.Log("1");
        disableInput = false;
        canExecuteSasuke = false;
        isExecutingSasuke = false;
        once = false;
        //aboutToCastFireball = false;
        levelUpAnimTimer = 0.0f;
        wallClimbingTimer = 0.0F;
        playedOnce = false;
        stunned = false;
        //wallQuaking = false;
        //Auto Hook to GameObjects Components
        boxColliders = GetComponents<BoxCollider2D>();
        circleCollider = GetComponent<CircleCollider2D>();
        rb2D = gameObject.GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        currentCharacter = startingCharacter;
        healthManager = FindObjectOfType<HealthManager>();
        defaultGravityScale = rb2D.gravityScale;
        warpPortal = FindObjectOfType<PortalController>();
        warpKey = FindObjectOfType<KeyPickup>();
        spRender = GetComponent<SpriteRenderer> ();
        //PauseMenu = FindObjectOfType<PauseOverlay>();

        //defaultDrag = rb2D.drag;

        if(Application.loadedLevel == 9)
        {
            executeSasukeTimer = 2.0f;
            sasukeBossFightOver = false;
            sasuke = FindObjectOfType<SasukeController>();
        }

        if(Application.loadedLevel == 12)
        {
            gizmoBossFightOver = false;
            gizmo = GameObject.Find("Gizmo");
        }

        switch(currentCharacter)
        {
            case 1:
                {
            //       boxColliders[0].offset = new Vector2(0.0f, 0.05f);
            //       circleCollider.offset = new Vector2(0.0f, -0.83f);
                    anim.runtimeAnimatorController = Resources.Load("Animations/Itachi") as RuntimeAnimatorController;

                    break;
                }
            case 2:
                {
        //	boxColliders[0].offset = new Vector2(0.0f, 0.05f);
          //             circleCollider.offset = new Vector2(0.0f, -0.83f);
                    anim.runtimeAnimatorController = Resources.Load("Animations/Cyborg") as RuntimeAnimatorController;
                    break;
                }
            case 3:
                {
        //            boxColliders[0].offset = new Vector2(0.0f, 0.05f);
         //           circleCollider.offset = new Vector2(0.0f, -0.56f);
         //           transform.position = new Vector3(transform.position.x, transform.position.y - 0.26992f, transform.position.z);
                    anim.runtimeAnimatorController = Resources.Load("Animations/Sonic") as RuntimeAnimatorController;
                    break;
                }
            default:
                {
                    Debug.Log("Invalid starting character supplied, check Inspector Value");
                    break;
                }
        }

        //Initialize Abilities
        canCastFireBall = true;
        canCastDarkStorm = true;
        canCastBlink = true;
        canCastBlast = true;
        canCastCharge = true;
        canCastQuake = true;
        canCastBackFlip = true;
        canCastChaosEmeralds = true;
        canCastSpinDash = true;
        canCastSpring = true;
        canCastTsukuyomi = true;
        canCastLightning = true;

        //Local Player Ability Animation
        isBlinking = false;
        isBackFlipping = false;
        isGoingSuper = false;
        isSpinDashing = false;
        isSpringing = false;
    }
        private string BuildRSS()
        {
            const int indent = 2;

            var counter = 0;

            var sb = new StringBuilder(1024);

            // build header
            sb.Append(XmlHeader + System.Environment.NewLine);
            sb.Append(RSSHeader + System.Environment.NewLine);

            // build channel
            var pc = new PortalController();
            var ps = PortalController.GetCurrentPortalSettings();

            var offSet = Convert.ToInt32(PortalSettings.Current.TimeZone.BaseUtcOffset.TotalMinutes);

            sb.Append(WriteElement("channel", indent));
            sb.Append(WriteElement("title", ps.PortalName, indent));
            sb.Append(WriteElement("link", "http://" + HttpContext.Current.Request.Url.Host, indent));
            sb.Append(WriteElement("description", ps.PortalName, indent));
            sb.Append(WriteElement("generator", "ActiveForums  5.0", indent));
            sb.Append(WriteElement("language", ps.DefaultLanguage, indent));

            if (ps.LogoFile != string.Empty)
            {
                var sLogo = "<image><url>http://" + HttpContext.Current.Request.Url.Host + ps.HomeDirectory + ps.LogoFile + "</url>";
                sLogo += "<title>" + ps.PortalName + "</title>";
                sLogo += "<link>http://" + HttpContext.Current.Request.Url.Host + "</link></image>";
                sb.Append(sLogo);
            }

            sb.Append(WriteElement("copyright", ps.FooterText.Replace("[year]", DateTime.Now.Year.ToString()), 2));
            sb.Append(WriteElement("lastBuildDate", "[LASTBUILDDATE]", 2));

            var lastBuildDate = DateTime.MinValue;

            // build items

            var forumids = Settings.RSSIgnoreSecurity ? Settings.Forums : AuthorizedForums;

            var useFriendly = Utilities.IsRewriteLoaded();
            var dr          = DataProvider.Instance().GetPosts(RequestPortalID, forumids, true, false, Settings.Rows, Settings.Tags);
            var sHost       = Utilities.GetHost();

            try
            {
                while (dr.Read())
                {
                    var groupName       = Convert.ToString(dr["GroupName"]);
                    var groupId         = Convert.ToInt32(dr["ForumGroupId"]);
                    var topicTabId      = Convert.ToInt32(dr["TabId"]);
                    var topicModuleId   = Convert.ToInt32(dr["ModuleId"]);
                    var forumName       = Convert.ToString(dr["ForumName"]);
                    var forumId         = Convert.ToInt32(dr["ForumId"]);
                    var subject         = Convert.ToString(dr["Subject"]);
                    var userName        = Convert.ToString(dr["AuthorUserName"]);
                    var postDate        = Convert.ToString(dr["DateCreated"]);
                    var body            = Utilities.StripHTMLTag(Convert.ToString(dr["Body"]));
                    var bodyHtml        = Convert.ToString(dr["Body"]);
                    var displayName     = Convert.ToString(dr["AuthorDisplayName"]);
                    var replyCount      = Convert.ToString(dr["ReplyCount"]);
                    var lastPostDate    = string.Empty;
                    var topicId         = Convert.ToInt32(dr["TopicId"]);
                    var replyId         = Convert.ToInt32(dr["ReplyId"]);
                    var firstName       = Convert.ToString(dr["AuthorFirstName"]);
                    var lastName        = Convert.ToString(dr["AuthorLastName"]);
                    var authorId        = Convert.ToInt32(dr["AuthorId"]);
                    var sForumUrl       = Convert.ToString(dr["PrefixURL"]);
                    var sTopicUrl       = Convert.ToString(dr["TopicURL"]);
                    var sGroupPrefixUrl = Convert.ToString(dr["GroupPrefixURL"]);

                    var dateCreated = Convert.ToDateTime(dr["DateCreated"]).AddMinutes(offSet);

                    if (lastBuildDate == DateTime.MinValue || dateCreated > lastBuildDate)
                    {
                        lastBuildDate = dateCreated;
                    }

                    var ts = DataCache.MainSettings(topicModuleId);

                    string url;
                    if (string.IsNullOrEmpty(sTopicUrl) || !useFriendly)
                    {
                        string[] Params = { ParamKeys.ViewType + "=" + Views.Topic, ParamKeys.ForumId + "=" + forumId, ParamKeys.TopicId + "=" + topicId };
                        url = Common.Globals.NavigateURL(topicTabId, "", Params);
                        if (url.IndexOf(HttpContext.Current.Request.Url.Host, StringComparison.CurrentCulture) == -1)
                        {
                            url = Common.Globals.AddHTTP(HttpContext.Current.Request.Url.Host) + url;
                        }
                    }
                    else
                    {
                        var ctlUtils = new ControlUtils();
                        sTopicUrl = ctlUtils.BuildUrl(topicTabId, topicModuleId, sGroupPrefixUrl, sForumUrl, groupId, forumId, topicId, sTopicUrl, -1, -1, string.Empty, 1, replyId, -1);
                        if (sHost.EndsWith("/") && sTopicUrl.StartsWith("/"))
                        {
                            sHost = sHost.Substring(0, sHost.Length - 1);
                        }
                        url = sHost + sTopicUrl;
                    }

                    sb.Append(WriteElement("item", indent));

                    sb.Append(WriteElement("title", subject, indent + 1));
                    if (Settings.RSSIncludeBody)
                    {
                        if (bodyHtml.IndexOf("<body>", StringComparison.CurrentCulture) > 0)
                        {
                            bodyHtml = TemplateUtils.GetTemplateSection(bodyHtml, "<body>", "</body>");
                        }
                        // Legacy Attachment functionality uses "attachid"
                        if (bodyHtml.Contains("&#91;IMAGE:"))
                        {
                            var          strHost = Common.Globals.AddHTTP(Common.Globals.GetDomainName(HttpContext.Current.Request)) + "/";
                            const string pattern = "(&#91;IMAGE:(.+?)&#93;)";
                            var          regExp  = new Regex(pattern);
                            var          matches = regExp.Matches(bodyHtml);
                            foreach (Match match in matches)
                            {
                                var sImage = "<img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + RequestPortalID + "&moduleid=" + RequestModuleID + "&attachid=" + match.Groups[2].Value + "\" border=\"0\" />";
                                bodyHtml = bodyHtml.Replace(match.Value, sImage);
                            }
                        }
                        // Legacy Attachment functionality uses "attachid"
                        if (bodyHtml.Contains("&#91;THUMBNAIL:"))
                        {
                            var          strHost = Common.Globals.AddHTTP(Common.Globals.GetDomainName(HttpContext.Current.Request)) + "/";
                            const string pattern = "(&#91;THUMBNAIL:(.+?)&#93;)";
                            var          regExp  = new Regex(pattern);
                            var          matches = regExp.Matches(bodyHtml);
                            foreach (Match match in matches)
                            {
                                var thumbId  = match.Groups[2].Value.Split(':')[0];
                                var parentId = match.Groups[2].Value.Split(':')[1];
                                var sImage   = "<a href=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + RequestPortalID + "&moduleid=" + RequestModuleID + "&attachid=" + parentId + "\" target=\"_blank\"><img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + RequestPortalID + "&moduleid=" + RequestModuleID + "&attachid=" + thumbId + "\" border=\"0\" /></a>";
                                bodyHtml = bodyHtml.Replace(match.Value, sImage);
                            }
                        }
                        bodyHtml = bodyHtml.Replace("src=\"/Portals", "src=\"" + Common.Globals.AddHTTP(HttpContext.Current.Request.Url.Host) + "/Portals");
                        bodyHtml = Utilities.ManageImagePath(bodyHtml, Common.Globals.AddHTTP(HttpContext.Current.Request.Url.Host));

                        sb.Append(WriteElement("description", bodyHtml, indent + 1));
                    }
                    else
                    {
                        sb.Append(WriteElement("description", string.Empty, indent + 1));
                    }
                    sb.Append(WriteElement("link", url, indent + 1));
                    sb.Append(WriteElement("comments", url, indent + 1));
                    sb.Append(WriteElement("pubDate", Convert.ToDateTime(postDate).AddMinutes(offSet).ToString("r"), indent + 1));
                    sb.Append(WriteElement("dc:creator", displayName, indent + 1));
                    sb.Append(WriteElement("guid", url, indent + 1));
                    sb.Append(WriteElement("slash:comments", replyCount, indent + 1));
                    sb.Append(WriteElement("/item", indent));
                }
                dr.Close();
                sb.Append("<atom:link href=\"http://" + HttpContext.Current.Request.Url.Host + HttpUtility.HtmlEncode(HttpContext.Current.Request.RawUrl) + "\" rel=\"self\" type=\"application/rss+xml\" />");
                sb.Append(WriteElement("/channel", 1));
                sb.Append("</rss>");
                sb.Replace("[LASTBUILDDATE]", lastBuildDate.ToString("r"));
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
示例#7
0
        public static string GetCookieDomain(int portalId)
        {
            string cookieDomain = String.Empty;

            if (PortalController.IsMemberOfPortalGroup(portalId))
            {
                //set cookie domain for portal group
                var groupController = new PortalGroupController();
                var group           = groupController.GetPortalGroups().SingleOrDefault(p => p.MasterPortalId == PortalController.GetEffectivePortalId(portalId));

                if (@group != null &&
                    !string.IsNullOrEmpty(@group.AuthenticationDomain) &&
                    PortalSettings.Current.PortalAlias.HTTPAlias.Contains(@group.AuthenticationDomain))
                {
                    cookieDomain = @group.AuthenticationDomain;
                }

                if (String.IsNullOrEmpty(cookieDomain))
                {
                    cookieDomain = FormsAuthentication.CookieDomain;
                }
            }
            else
            {
                //set cookie domain to be consistent with domain specification in web.config
                cookieDomain = FormsAuthentication.CookieDomain;
            }


            return(cookieDomain);
        }
示例#8
0
        public static void LocalizeSitePages(LocalizationProgress progress, int portalId, bool translatePages, string defaultLanguage)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    var languageCount   = LocaleController.Instance.GetLocales(portalId).Count;
                    var languageCounter = 0;

                    var pageList = GetPages(portalId).Where(p => string.IsNullOrEmpty(p.CultureCode)).ToList();

                    if (translatePages)
                    {
                        // populate default language
                        ProcessLanguage(pageList, LocaleController.Instance.GetLocale(defaultLanguage),
                                        defaultLanguage, languageCounter, languageCount, progress);
                    }
                    PublishLanguage(defaultLanguage, portalId, true);

                    PortalController.UpdatePortalSetting(portalId, "ContentLocalizationEnabled", "True");

                    if (translatePages)
                    {
                        // populate other languages
                        pageList = GetPages(portalId).Where(p => p.CultureCode == defaultLanguage).ToList();

                        foreach (var locale in LocaleController.Instance.GetLocales(portalId).Values.Where(l => l.Code != defaultLanguage))
                        {
                            languageCounter++;

                            //add translator role
                            Localization.AddTranslatorRole(portalId, locale);

                            //populate pages
                            ProcessLanguage(pageList, locale, defaultLanguage, languageCounter, languageCount, progress);

                            //Map special pages
                            PortalController.Instance.MapLocalizedSpecialPages(portalId, locale.Code);
                        }
                    }

                    //clear portal cache
                    DataCache.ClearPortalCache(portalId, true);
                    progress.Reset();
                    SaveProgressToFile(progress);
                }
                catch (Exception ex)
                {
                    try
                    {
                        Logger.Error(ex);
                        progress.Reset().Error = ex.ToString();
                        SaveProgressToFile(progress);
                    }
                    catch (Exception)
                    {
                        //ignore
                    }
                }
            });
        }
示例#9
0
        public List <FileResultModel> CropSaveBanner([FromUri] Guid organizationId, [FromBody] CropImage body)
        {
            try
            {
                var filename      = body.Filename;
                var yCropPosition = body.yCrop;
                var organization  = new OrganizationComponent(organizationId);
                var portal        = PortalController.GetCurrentPortalSettings();
                var currentUser   = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();
                var tempId        = Helper.HelperMethods.GenerateHash(currentUser.UserID).ToString();
                if (currentUser.IsInRole("Registered Users"))
                {
                    if (currentUser.IsInRole("Administrators") || organization.Organization.CreatedBy == DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID)
                    {
                        var fileResultModelList = new List <FileResultModel>();
                        yCropPosition = yCropPosition * -1;
                        string       extension             = ".png";//Path.GetExtension(filename);
                        string       fileRootName          = organizationId.ToString();
                        MemoryStream outStream             = new MemoryStream();
                        long         tmpSize               = 0;
                        string       ImageProcessingFolfer = Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\TempImages", filename);
                        Helper.HelperMethods.DeleteFiles(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", "*" + organizationId.ToString() + "*");
                        ImageFactory imageFactory = new ImageFactory(preserveExifData: true);
                        imageFactory.Load(ImageProcessingFolfer);
                        imageFactory.Save(outStream);// ();
                        tmpSize = outStream.Length;
                        Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", fileRootName + extension));


                        fileResultModelList.Add(new FileResultModel()
                        {
                            Extension   = extension,
                            Filename    = fileRootName,
                            Link        = portal.HomeDirectory + "OrgImages/HeaderImages/" + fileRootName + extension,
                            Description = "Original Image",
                            Size        = tmpSize
                        });



                        var   image           = imageFactory.Image;
                        var   originalHeight  = image.Size.Height;
                        var   originalWidth   = image.Size.Width;
                        float referenceHeight = 575;
                        float referenceWidth  = 1148;
                        float WidthFactor     = 1;
                        WidthFactor = referenceWidth / originalWidth;
                        float HeightFactor = 1;
                        HeightFactor = referenceHeight / originalHeight;
                        float standardHeight = 0;
                        standardHeight = originalHeight * WidthFactor;
                        float     cutTop        = Convert.ToSingle(yCropPosition) / WidthFactor;
                        float     cutBotom      = (standardHeight - referenceHeight - cutTop) / WidthFactor;
                        Size      sizeCrop      = new Size(Convert.ToInt32(referenceWidth / WidthFactor), Convert.ToInt32(referenceHeight / WidthFactor));
                        Point     pointCrop     = new Point(0, Convert.ToInt32(cutTop));
                        Rectangle rectangleCrop = new Rectangle(pointCrop, sizeCrop);
                        imageFactory.Crop(rectangleCrop);
                        System.Drawing.Size sizeBig = new System.Drawing.Size(Convert.ToInt32(referenceWidth), Convert.ToInt32(referenceHeight));
                        var img = imageFactory.Resize(sizeBig);


                        outStream = new MemoryStream();
                        imageFactory.Save(outStream);
                        tmpSize = outStream.Length;
                        Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", "cropBig" + fileRootName + extension));
                        fileResultModelList.Add(new FileResultModel()
                        {
                            Extension   = extension,
                            Filename    = "cropBig" + fileRootName,
                            Link        = portal.HomeDirectory + "OrgImages/HeaderImages/" + "cropBig" + fileRootName + extension,
                            Description = "Crop Big",
                            Size        = tmpSize
                        });


                        System.Drawing.Size sizeSmall = new System.Drawing.Size(Convert.ToInt32(600), Convert.ToInt32(300));
                        imageFactory.Resize(sizeSmall);
                        outStream = new MemoryStream();
                        imageFactory.Save(outStream);
                        tmpSize = outStream.Length;
                        Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", "cropThumb" + fileRootName + extension));



                        fileResultModelList.Add(new FileResultModel()
                        {
                            Extension   = extension,
                            Filename    = "cropThumb" + fileRootName,
                            Link        = portal.HomeDirectory + "OrgImages/HeaderImages/" + "cropThumb" + fileRootName + extension,
                            Description = "Crop Thumbnail",
                            Size        = tmpSize
                        });
                        Helper.HelperMethods.DeleteFiles(portal.HomeDirectoryMapPath + "OrgImages\\TempUserImages", filename + "*");
                        return(fileResultModelList);
                    }
                    else
                    {
                        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                    }
                }
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }
            catch (HttpResponseException e)
            {
                throw e;
            }
            catch (Exception ee)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ee);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
示例#10
0
 ///<summary>Last message sent by the User</summary>
 ///<returns>Message. Null when no message was sent</returns>
 /// <param name="sender">Sender's UserInfo</param>
 public virtual Message GetLastSentMessage(UserInfo sender)
 {
     return(CBO.FillObject <Message>(_dataService.GetLastSentMessage(sender.UserID, PortalController.GetEffectivePortalId(sender.PortalID))));
 }
示例#11
0
        /// <Summary>
        /// This handler handles requests for LinkClick.aspx, but only those specifc
        /// to file serving
        /// </Summary>
        /// <Param name="context">System.Web.HttpContext)</Param>
        public virtual void ProcessRequest(HttpContext context)
        {
            PortalSettings portalSettings = PortalController.GetCurrentPortalSettings();

            // get TabId
            int tabId = -1;

            if (context.Request.QueryString["tabid"] != null)
            {
                tabId = int.Parse(context.Request.QueryString["tabid"]);
            }

            // get ModuleId
            int moduleId = -1;

            if (context.Request.QueryString["mid"] != null)
            {
                moduleId = int.Parse(context.Request.QueryString["mid"]);
            }



            // get the URL
            string URL              = "";
            bool   blnClientCache   = true;
            bool   blnForceDownload = false;

            if (context.Request.QueryString["fileticket"] != null)
            {
                URL = "FileID=" + UrlUtils.DecryptParameter(context.Request.QueryString["fileticket"]);
            }
            if (context.Request.QueryString["userticket"] != null)
            {
                URL = "UserId=" + UrlUtils.DecryptParameter(context.Request.QueryString["userticket"]);
            }
            if (context.Request.QueryString["link"] != null)
            {
                URL = context.Request.QueryString["link"];
                if (URL.ToLower().StartsWith("fileid="))
                {
                    URL = ""; // restrict direct access by FileID
                }
            }

            if (!String.IsNullOrEmpty(URL))
            {
                TabType UrlType = Globals.GetURLType(URL);

                if (UrlType != TabType.File)
                {
                    URL = Globals.LinkClick(URL, tabId, moduleId, false);
                }

                if (UrlType == TabType.File && URL.ToLower().StartsWith("fileid=") == false)
                {
                    // to handle legacy scenarios before the introduction of the FileServerHandler
                    FileController objFiles = new FileController();
                    URL = "FileID=" + objFiles.ConvertFilePathToFileId(URL, portalSettings.PortalId);
                }

                // get optional parameters
                if (context.Request.QueryString["clientcache"] != null)
                {
                    blnClientCache = bool.Parse(context.Request.QueryString["clientcache"]);
                }

                if ((context.Request.QueryString["forcedownload"] != null) || (context.Request.QueryString["contenttype"] != null))
                {
                    blnForceDownload = bool.Parse(context.Request.QueryString["forcedownload"]);
                }

                // update clicks
                UrlController objUrls = new UrlController();
                objUrls.UpdateUrlTracking(portalSettings.PortalId, URL, moduleId, -1);

                // clear the current response
                context.Response.Clear();

                if (UrlType == TabType.File)
                {
                    // serve the file
                    if (tabId == Null.NullInteger)
                    {
                        if (!(FileSystemUtils.DownloadFile(portalSettings.PortalId, int.Parse(UrlUtils.GetParameterValue(URL)), blnClientCache, blnForceDownload)))
                        {
                            context.Response.Write(Services.Localization.Localization.GetString("FilePermission.Error"));
                        }
                    }
                    else
                    {
                        if (!(FileSystemUtils.DownloadFile(portalSettings, int.Parse(UrlUtils.GetParameterValue(URL)), blnClientCache, blnForceDownload)))
                        {
                            context.Response.Write(Services.Localization.Localization.GetString("FilePermission.Error"));
                        }
                    }
                }
                else
                {
                    // redirect to URL
                    context.Response.Redirect(URL, true);
                }
            }
        }
示例#12
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the Update button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	5/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        private void cmdUpdate_Click(Object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                PortalController.PortalTemplateInfo template = LoadPortalTemplateInfoForSelectedItem();

                try
                {
                    bool   blnChild;
                    string strPortalAlias;
                    string strChildPath  = string.Empty;
                    var    closePopUpStr = string.Empty;

                    var objPortalController = new PortalController();

                    //check template validity
                    var    messages       = new ArrayList();
                    string schemaFilename = Server.MapPath(string.Concat(AppRelativeTemplateSourceDirectory, "portal.template.xsd"));
                    string xmlFilename    = template.TemplateFilePath;
                    var    xval           = new PortalTemplateValidator();
                    if (!xval.Validate(xmlFilename, schemaFilename))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, "", String.Format(Localization.GetString("InvalidTemplate", LocalResourceFile), Path.GetFileName(template.TemplateFilePath)), ModuleMessage.ModuleMessageType.RedError);
                        messages.AddRange(xval.Errors);
                        lstResults.Visible    = true;
                        lstResults.DataSource = messages;
                        lstResults.DataBind();
                        validationPanel.Visible = true;
                        return;
                    }

                    //Set Portal Name
                    txtPortalAlias.Text = txtPortalAlias.Text.ToLowerInvariant();
                    txtPortalAlias.Text = txtPortalAlias.Text.Replace("http://", "");

                    //Validate Portal Name
                    if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                    {
                        blnChild       = true;
                        strPortalAlias = txtPortalAlias.Text;
                    }
                    else
                    {
                        blnChild = (optType.SelectedValue == "C");

                        strPortalAlias = blnChild ? txtPortalAlias.Text.Substring(txtPortalAlias.Text.LastIndexOf("/") + 1) : txtPortalAlias.Text;
                    }

                    string message = String.Empty;
                    ModuleMessage.ModuleMessageType messageType = ModuleMessage.ModuleMessageType.RedError;
                    if (!PortalAliasController.ValidateAlias(strPortalAlias, blnChild))
                    {
                        message = Localization.GetString("InvalidName", LocalResourceFile);
                    }

                    //check whether have conflict between tab path and portal alias.
                    var checkTabPath = string.Format("//{0}", strPortalAlias);
                    if (TabController.GetTabByTabPath(PortalSettings.PortalId, checkTabPath, string.Empty) != Null.NullInteger)
                    {
                        message = Localization.GetString("DuplicateWithTab", LocalResourceFile);
                    }

                    //Validate Password
                    if (txtPassword.Text != txtConfirm.Text)
                    {
                        if (!String.IsNullOrEmpty(message))
                        {
                            message += "<br/>";
                        }
                        message += Localization.GetString("InvalidPassword", LocalResourceFile);
                    }
                    string strServerPath = Globals.GetAbsoluteServerPath(Request);

                    //Set Portal Alias for Child Portals
                    if (String.IsNullOrEmpty(message))
                    {
                        if (blnChild)
                        {
                            strChildPath = strServerPath + strPortalAlias;

                            if (Directory.Exists(strChildPath))
                            {
                                message = Localization.GetString("ChildExists", LocalResourceFile);
                            }
                            else
                            {
                                if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                                {
                                    strPortalAlias = Globals.GetDomainName(Request, true) + "/" + strPortalAlias;
                                }
                                else
                                {
                                    strPortalAlias = txtPortalAlias.Text;
                                }
                            }
                        }
                    }

                    //Get Home Directory
                    string homeDir = txtHomeDirectory.Text != @"Portals/[PortalID]" ? txtHomeDirectory.Text : "";

                    //Validate Home Folder
                    if (!string.IsNullOrEmpty(homeDir))
                    {
                        if (string.IsNullOrEmpty(String.Format("{0}\\{1}\\", Globals.ApplicationMapPath, homeDir).Replace("/", "\\")))
                        {
                            message = Localization.GetString("InvalidHomeFolder", LocalResourceFile);
                        }
                        if (homeDir.Contains("admin") || homeDir.Contains("DesktopModules") || homeDir.ToLowerInvariant() == "portals/")
                        {
                            message = Localization.GetString("InvalidHomeFolder", LocalResourceFile);
                        }
                    }

                    //Validate Portal Alias
                    if (!string.IsNullOrEmpty(strPortalAlias))
                    {
                        PortalAliasInfo portalAlias = PortalAliasController.GetPortalAliasLookup(strPortalAlias.ToLower());
                        if (portalAlias != null)
                        {
                            message = Localization.GetString("DuplicatePortalAlias", LocalResourceFile);
                        }
                    }

                    //Create Portal
                    if (String.IsNullOrEmpty(message))
                    {
                        //Attempt to create the portal
                        UserInfo adminUser = new UserInfo();
                        int      intPortalId;
                        try
                        {
                            if (useCurrent.Checked)
                            {
                                adminUser = UserInfo;
                                adminUser.Membership.Password = UserController.GetPassword(ref adminUser, String.Empty);
                            }
                            else
                            {
                                adminUser = new UserInfo
                                {
                                    FirstName   = txtFirstName.Text,
                                    LastName    = txtLastName.Text,
                                    Username    = txtUsername.Text,
                                    DisplayName = txtFirstName.Text + " " + txtLastName.Text,
                                    Email       = txtEmail.Text,
                                    IsSuperUser = false,
                                    Membership  =
                                    {
                                        Approved         = true,
                                        Password         = txtPassword.Text,
                                        PasswordQuestion = txtQuestion.Text,
                                        PasswordAnswer   = txtAnswer.Text
                                    },
                                    Profile =
                                    {
                                        FirstName = txtFirstName.Text,
                                        LastName  = txtLastName.Text
                                    }
                                };
                            }
                            intPortalId = objPortalController.CreatePortal(txtPortalName.Text,
                                                                           adminUser,
                                                                           txtDescription.Text,
                                                                           txtKeyWords.Text,
                                                                           template,
                                                                           homeDir,
                                                                           strPortalAlias,
                                                                           strServerPath,
                                                                           strChildPath,
                                                                           blnChild);
                        }
                        catch (Exception ex)
                        {
                            intPortalId = Null.NullInteger;
                            message     = ex.Message;
                        }
                        if (intPortalId != -1)
                        {
                            //Create a Portal Settings object for the new Portal
                            PortalInfo objPortal   = objPortalController.GetPortal(intPortalId);
                            var        newSettings = new PortalSettings {
                                PortalAlias = new PortalAliasInfo {
                                    HTTPAlias = strPortalAlias
                                }, PortalId = intPortalId, DefaultLanguage = objPortal.DefaultLanguage
                            };
                            string webUrl = Globals.AddHTTP(strPortalAlias);
                            try
                            {
                                if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                                {
                                    message = Mail.SendMail(PortalSettings.Email,
                                                            txtEmail.Text,
                                                            PortalSettings.Email + ";" + Host.HostEmail,
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser),
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser),
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "");
                                }
                                else
                                {
                                    message = Mail.SendMail(Host.HostEmail,
                                                            txtEmail.Text,
                                                            Host.HostEmail,
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser),
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser),
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "");
                                }
                            }
                            catch (Exception exc)
                            {
                                DnnLog.Error(exc);

                                closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : "";
                                message       = string.Format(Localization.GetString("UnknownSendMail.Error", LocalResourceFile), webUrl, closePopUpStr);
                            }
                            var objEventLog = new EventLogController();
                            objEventLog.AddLog(objPortalController.GetPortal(intPortalId), PortalSettings, UserId, "", EventLogController.EventLogType.PORTAL_CREATED);

                            //Redirect to this new site
                            if (message == Null.NullString)
                            {
                                webUrl = (PortalSettings.EnablePopUps) ? UrlUtils.ClosePopUp(true, webUrl, false) : webUrl;
                                Response.Redirect(webUrl, true);
                            }
                            else
                            {
                                closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : "";
                                message       = string.Format(Localization.GetString("SendMail.Error", LocalResourceFile), message, webUrl, closePopUpStr);
                                messageType   = ModuleMessage.ModuleMessageType.YellowWarning;
                            }
                        }
                    }
                    UI.Skins.Skin.AddModuleMessage(this, "", message, messageType);
                }
                catch (Exception exc) //Module failed to load
                {
                    Exceptions.ProcessModuleLoadException(this, exc);
                }
            }
        }
示例#13
0
    private void TurnOnExitsFromPortal(PortalController portalController)
    {
        foreach (GameObject portal in portalController.bindedPortals) {

            portal.GetComponent<PortalController>().IsActive = true;
        }
    }
示例#14
0
文件: Routes.cs 项目: 921819535/cms
        /// <summary>
        /// 注册路由
        /// </summary>
        /// <param name="routes">路由集合</param>
        /// <param name="cmsHandleType"></param>
        private static void RegisterInstalledCmsRoutes(IEndpointRouteBuilder endpoints, Type portalType)
        {
            var portal = new PortalController();
            //路由前缀,前缀+虚拟路径
            //string routePrefix = (String.IsNullOrEmpty(prefix) ? "" : prefix + "/")
            //    + (String.IsNullOrEmpty(Settings.SYS_VIRTHPATH) ? String.Empty:Settings.SYS_VIRTHPATH + "/");

            // string urlPrefix = "/" + routePrefix;
            var urlPrefix   = String.Empty;
            var routePrefix = String.Empty;

            //Cms 控制器名称,如果继承默认的Handler,则使用默认的Handler
            var cmsControllerName =
                Regex.Replace(portalType.Name, "controller$", String.Empty, RegexOptions.IgnoreCase);

            //MVC路由规则词典
            IDictionary <UrlRulePageKeys, string[]> dict = new Dictionary <UrlRulePageKeys, string[]>();

            dict.Add(UrlRulePageKeys.Common, new[] { "cms_common", routePrefix + "{0}", urlPrefix + "{0}" });

            dict.Add(UrlRulePageKeys.Search,
                     new[] { "cms_search", routePrefix + "search", urlPrefix + "search?w={0}&c={1}" });
            dict.Add(UrlRulePageKeys.SearchPager, new[] { null, null, urlPrefix + "search?w={0}&c={1}&p={2}" });

            dict.Add(UrlRulePageKeys.Tag, new[] { "cms_tag", routePrefix + "tag", urlPrefix + "tag?t={0}" });
            dict.Add(UrlRulePageKeys.TagPager, new[] { null, null, urlPrefix + "tag?t={0}&p={1}" });

            dict.Add(UrlRulePageKeys.Category, new[] { "cms_category", routePrefix + "{*all_cate}", urlPrefix + "{0}/" });
            dict.Add(UrlRulePageKeys.CategoryPager, new[] { null, null, urlPrefix + "{0}/list_{1}.html" });

            dict.Add(UrlRulePageKeys.Archive,
                     new[] { "cms_archive", routePrefix + "{*all_html}", urlPrefix + "{0}/{1}.html" });
            dict.Add(UrlRulePageKeys.SinglePage, new[] { null, null, urlPrefix + "{0}.html" });

            //注册插件路由
            //Cms.Plugins.Extends.MapRoutes(routes);

            //Cms.Plugins.MapRoutes(routes);


            #region 系统路由

            //忽略静态目录
            //routes.IgnoreRoute("{staticDir}/{*pathInfo}", new { staticDir = "^(uploads|resources|content|static|plugins|libs|scripts|images|style|themes)$" });

            //templates路由处理(忽略静态文件)
            //routes.IgnoreRoute("templates/{*pathInfo}", new { pathInfo = "^(.+?)\\.(jpg|jpeg|css|js|json|xml|gif|png|bmp)$" });
            //routes.MapRoute("tpl_catchall", "templates/{*catchall}", new { controller = cmsControllerName, action = "Disallow" });

            #endregion


            /*
             * //搜索档案
             * endpoints.MapControllerRoute(dict[UrlRulePageKeys.Search][0] + "_site",
             *  "{site}/" + dict[UrlRulePageKeys.Search][1],
             *  new { controller = cmsControllerName, action = "Search", p = 1 }
             * );
             *
             *
             * //搜索档案
             * endpoints.MapControllerRoute(dict[UrlRulePageKeys.Search][0],
             * dict[UrlRulePageKeys.Search][1],
             *  new { controller = cmsControllerName, action = "Search", p = 1 }
             * );
             *
             * //标签档案
             * endpoints.MapControllerRoute(dict[UrlRulePageKeys.Tag][0],
             *  dict[UrlRulePageKeys.Tag][1],
             *  new { controller = cmsControllerName, action = "Tag", p = 1 }
             * );
             *
             * //栏目档案列表
             * endpoints.MapControllerRoute(dict[UrlRulePageKeys.Category][0],
             *  dict[UrlRulePageKeys.Category][1],
             *  new { controller = cmsControllerName, action = "Category", page = 1 },
             *  new { all_cate = "^(?!" +CmsVariables.DEFAULT_CONTROLLER_NAME+ ")((.+?)/(p\\d+\\.html)?|([^/]+/)*[^\\.]+)$" }
             * );
             *
             */

            //栏目档案列表
            endpoints.MapGet("{*cate:regex(^([^/]+/)*[^\\.]+$)}", portal.Category);
            endpoints.MapGet("{*cate:regex(^(.+)/list_\\d+.html$)}", portal.Category);

            // 显示档案,不包含"/list_\d.html"
            endpoints.MapGet("{*archive:regex(^((?!list_\\d+).)+.html$)}", portal.Archive);

            // 首页
            endpoints.MapGet("/", portal.Index);

            //默认路由
            // endpoints.MapControllerRoute("Default",
            //     routePrefix + "{controller}/{action}/{id*}",
            //     new { controller = cmsControllerName, action = "Index"}
            // );


            //endpoints.MapControllerRoute("allpath", "{*path}", new { controller = cmsControllerName, action = "NotFound" });


            IDictionary <UrlRulePageKeys, string> urlDict = new Dictionary <UrlRulePageKeys, string>();
            foreach (KeyValuePair <UrlRulePageKeys, string[]> p in dict)
            {
                urlDict.Add(p.Key, p.Value[2]);
            }

            //设置地址
            TemplateUrlRule.SetUrl(UrlRuleType.Mvc, urlDict);

            //使用MVC
            TemplateUrlRule.SetRule(UrlRuleType.Mvc);
        }
示例#15
0
 // Use this for initialization
 void Start()
 {
     isPickedUp = false;
     portal = FindObjectOfType<PortalController>();
     keySFX = GetComponentInParent<AudioSource>();
 }
示例#16
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Searches for and indexes modified users for the given portal.
        /// </summary>
        /// <returns>Count of indexed records</returns>
        /// -----------------------------------------------------------------------------
        public override int IndexSearchDocuments(int portalId,
                                                 ScheduleHistoryItem schedule, DateTime startDateLocal, Action <IEnumerable <SearchDocument> > indexer)
        {
            Requires.NotNull("indexer", indexer);
            const int saveThreshold      = BatchSize;
            var       totalIndexed       = 0;
            var       checkpointModified = false;

            startDateLocal = GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal);
            var searchDocuments = new Dictionary <string, SearchDocument>();

            var needReindex = PortalController.GetPortalSettingAsBoolean(UserIndexResetFlag, portalId, false);

            if (needReindex)
            {
                startDateLocal = SqlDateTime.MinValue.Value.AddDays(1);
            }

            var controller       = new ListController();
            var textDataType     = controller.GetListEntryInfo("DataType", "Text");
            var richTextDataType = controller.GetListEntryInfo("DataType", "RichText");

            var profileDefinitions = ProfileController.GetPropertyDefinitionsByPortal(portalId, false, false)
                                     .Cast <ProfilePropertyDefinition>()
                                     .Where(d => (textDataType != null && d.DataType == textDataType.EntryID) ||
                                            (richTextDataType != null && d.DataType == richTextDataType.EntryID))
                                     .ToList();

            try
            {
                int startUserId;
                var checkpointData = GetLastCheckpointData(portalId, schedule.ScheduleID);
                if (string.IsNullOrEmpty(checkpointData) || !int.TryParse(checkpointData, out startUserId))
                {
                    startUserId = Null.NullInteger;
                }

                int         rowsAffected;
                IList <int> indexedUsers;
                do
                {
                    rowsAffected = FindModifiedUsers(portalId, startDateLocal,
                                                     searchDocuments, profileDefinitions, out indexedUsers, ref startUserId);

                    if (rowsAffected > 0 && searchDocuments.Count >= saveThreshold)
                    {
                        //remove existing indexes
                        DeleteDocuments(portalId, indexedUsers);
                        var values = searchDocuments.Values;
                        totalIndexed += IndexCollectedDocs(indexer, values);
                        SetLastCheckpointData(portalId, schedule.ScheduleID, startUserId.ToString());
                        SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, values.Last().ModifiedTimeUtc.ToLocalTime());
                        searchDocuments.Clear();
                        checkpointModified = true;
                    }
                } while (rowsAffected > 0);

                if (searchDocuments.Count > 0)
                {
                    //remove existing indexes
                    DeleteDocuments(portalId, indexedUsers);
                    var values = searchDocuments.Values;
                    totalIndexed      += IndexCollectedDocs(indexer, values);
                    checkpointModified = true;
                }

                if (needReindex)
                {
                    PortalController.DeletePortalSetting(portalId, UserIndexResetFlag);
                }
            }
            catch (Exception ex)
            {
                checkpointModified = false;
                Exceptions.Exceptions.LogException(ex);
            }

            if (checkpointModified)
            {
                // at last reset start user pointer
                SetLastCheckpointData(portalId, schedule.ScheduleID, Null.NullInteger.ToString());
                SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, DateTime.Now);
            }
            return(totalIndexed);
        }
示例#17
0
        /// <summary>
        /// Returns a portal info object for the portal.
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="exceptionOnNull"></param>
        /// <remarks>This method wraps the PortalController.GetPortal method, and adds a check if the reuslt is null.</remarks>.
        /// <returns></returns>
        public static PortalInfo GetPortal(int portalId, bool exceptionOnNull)
        {
            PortalInfo pi = null;

            // 775 : change to use threadsafe dictionary
            SharedDictionary <int, PortalInfo> portals = (SharedDictionary <int, PortalInfo>)DataCache.GetCache(PortalsKey) ??
                                                         new SharedDictionary <int, PortalInfo>();

            using (portals.GetWriteLock())
            {
                if (portals.ContainsKey(portalId))
                {
                    // portal found, return
                    pi = portals[portalId];
                }
                else
                {
                    try
                    {
                        // if not found, get from database
                        pi = PortalController.Instance.GetPortal(portalId);

                        if (pi == null)
                        {
                            // Home page redirect loop when using default language not en-US and first request with secondary language
                            // calls get portal using culture code to support
                            string cultureCode = PortalController.GetActivePortalLanguage(portalId);
                            pi = PortalController.Instance.GetPortal(portalId, cultureCode);
                        }

                        if (pi != null)
                        {
                            // Home page redirect loop when using default language not en-US and first request with secondary language
                            // check for correct, default language code in portal object
                            string portalCultureCode = pi.CultureCode;
                            if (portalCultureCode != null &&
                                string.CompareOrdinal(portalCultureCode, pi.DefaultLanguage) != 0)
                            {
                                // portal culture code and default culture code are not the same.
                                // this means we will get the incorrect home page tab id
                                // call back and get the correct one as per the default language
                                PortalInfo defaultLangPortal = PortalController.Instance.GetPortal(portalId, pi.DefaultLanguage);
                                if (defaultLangPortal != null)
                                {
                                    pi = defaultLangPortal;
                                }
                            }
                        }

                        if (pi != null)
                        {
                            // add to dictionary and re-store in cache
                            portals.Add(pi.PortalID, pi);
                            DataCache.SetCache(PortalsKey, portals); // store back in dictionary
                        }
                    }

                    // ReSharper disable EmptyGeneralCatchClause
                    catch

                    // ReSharper restore EmptyGeneralCatchClause
                    {
                        // 912: capture as fall back any exception resulting from doing a portal lookup in 6.x
                        // this happens when portalId = -1
                        // no long, no handling, just passonwards with null portal
                    }
                }
            }

            if (exceptionOnNull && pi == null)
            {
                throw new NullReferenceException("No Portal Found for portalid : " + portalId.ToString());
            }

            return(pi);
        }
示例#18
0
 internal virtual int GetPortalSettingAsInteger(string key, int portalId, int defaultValue)
 {
     return(PortalController.GetPortalSettingAsInteger(key, portalId, defaultValue));
 }
示例#19
0
	public void Shoot ()
	{
		if (LevelFinishedController.instance.isTeleportEnabled())
	    {
			if ((firstPortal == null) ||  (secondPortal == null))
			{
				if (DronePowerController.instance.canSetUp() && !isDroneTooClose())
				{
					if ((firstPortal == null) ||
						((firstPortal != null) && (firstPortal.isSettled())))
					{
						Vector3 pos = new Vector3 (transform.position.x, 
						                           transform.position.y - 1,
						                           transform.position.z);
						GameObject portal = (GameObject) Instantiate (portalPrefab, pos, Quaternion.Euler(0, 0, 0));
						PortalController portalController = portal.GetComponent<PortalController>();
						portal.GetComponent<Rigidbody>().velocity = -transform.up * teleportSpeed;
						AudioController.instance.Play("029_DroneTele");

						// check groundController
						Physics.IgnoreLayerCollision(LayerMask.NameToLayer("players"), LayerMask.NameToLayer("item"), true);
						Physics.IgnoreLayerCollision(LayerMask.NameToLayer("monsters"), LayerMask.NameToLayer("item"), true);
						Physics.IgnoreLayerCollision(LayerMask.NameToLayer("flyingMonsters"), LayerMask.NameToLayer("item"), true);

						if (firstPortal == null)
						{
							firstPortal = portalController;
						}
						else
						{
							secondPortal = portalController;
							firstPortal.setTheOtherPortal(secondPortal);
							secondPortal.setTheOtherPortal(firstPortal);
							AudioController.instance.Play("029_DroneTele");
						}
						DronePowerController.instance.settingUp();
					}
				}
			}
			else
			{
				Destroy(firstPortal.gameObject);
				Destroy (secondPortal.gameObject);
				firstPortal = null;
				secondPortal = null;
				AudioController.instance.Play("034_CancelTele");
			}
		}
	}
示例#20
0
 internal virtual double GetPortalSettingAsDouble(string key, int portalId, double defaultValue)
 {
     return(PortalController.GetPortalSettingAsDouble(key, portalId, defaultValue));
 }
示例#21
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                bool blnValid = true;
//                string strTransactionID;
                int intRoleID   = 0;
                int intPortalID = PortalSettings.PortalId;
                int intUserID   = 0;
//                string strDescription;
                double dblAmount = 0;
//                string strEmail;
                bool   blnCancel           = false;
                string strPayPalID         = Null.NullString;
                var    objRoles            = new RoleController();
                var    objPortalController = new PortalController();
                string strPost             = "cmd=_notify-validate";
                foreach (string strName in Request.Form)
                {
                    string strValue = Request.Form[strName];
                    switch (strName)
                    {
                    case "txn_type":     //get the transaction type
                        string strTransactionType = strValue;
                        switch (strTransactionType)
                        {
                        case "subscr_signup":
                        case "subscr_payment":
                        case "web_accept":
                            break;

                        case "subscr_cancel":
                            blnCancel = true;
                            break;

                        default:
                            blnValid = false;
                            break;
                        }
                        break;

                    case "payment_status":     //verify the status
                        if (strValue != "Completed")
                        {
                            blnValid = false;
                        }
                        break;

                    case "txn_id":     //verify the transaction id for duplicates
//                            strTransactionID = strValue;
                        break;

                    case "receiver_email":     //verify the PayPalId
                        strPayPalID = strValue;
                        break;

                    case "mc_gross":     // verify the price
                        dblAmount = double.Parse(strValue);
                        break;

                    case "item_number":     //get the RoleID
                        intRoleID = Int32.Parse(strValue);
                        //RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID);
                        break;

                    case "item_name":     //get the product description
//                            strDescription = strValue;
                        break;

                    case "custom":     //get the UserID
                        intUserID = Int32.Parse(strValue);
                        break;

                    case "email":     //get the email
//                            strEmail = strValue;
                        break;
                    }

                    //reconstruct post for postback validation
                    strPost += string.Format("&{0}={1}", Globals.HTTPPOSTEncode(strName), Globals.HTTPPOSTEncode(strValue));
                }

                //postback to verify the source
                if (blnValid)
                {
                    Dictionary <string, string> settings = PortalController.GetPortalSettingsDictionary(PortalSettings.PortalId);
                    string strPayPalURL;

                    // Sandbox mode
                    if (settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"].Equals("true", StringComparison.InvariantCultureIgnoreCase))
                    {
                        strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
                    }
                    else
                    {
                        strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?";
                    }
                    var objRequest = Globals.GetExternalRequest(strPayPalURL);
                    objRequest.Method        = "POST";
                    objRequest.ContentLength = strPost.Length;
                    objRequest.ContentType   = "application/x-www-form-urlencoded";
                    using (var objStream = new StreamWriter(objRequest.GetRequestStream()))
                    {
                        objStream.Write(strPost);
                    }

                    string strResponse;
                    using (var objResponse = (HttpWebResponse)objRequest.GetResponse())
                    {
                        using (var sr = new StreamReader(objResponse.GetResponseStream()))
                        {
                            strResponse = sr.ReadToEnd();
                        }
                    }
                    switch (strResponse)
                    {
                    case "VERIFIED":
                        break;

                    default:
                        //possible fraud
                        blnValid = false;
                        break;
                    }
                }
                if (blnValid)
                {
                    int        intAdministratorRoleId = 0;
                    string     strProcessorID         = Null.NullString;
                    PortalInfo objPortalInfo          = objPortalController.GetPortal(intPortalID);
                    if (objPortalInfo != null)
                    {
                        intAdministratorRoleId = objPortalInfo.AdministratorRoleId;
                        strProcessorID         = objPortalInfo.ProcessorUserId.ToLower();
                    }

                    if (intRoleID == intAdministratorRoleId)
                    {
                        //admin portal renewal
                        strProcessorID = Host.ProcessorUserId.ToLower();
                        float portalPrice = objPortalInfo.HostFee;
                        if ((portalPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objPortalController.UpdatePortalExpiry(intPortalID);
                        }
                        else
                        {
                            var objEventLog     = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID   = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID     = intUserID;
                            objEventLogInfo.LogTypeKey    = EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString();
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                    else
                    {
                        //user subscription
                        RoleInfo objRoleInfo = TestableRoleController.Instance.GetRole(intPortalID, r => r.RoleID == intRoleID);
                        float    rolePrice   = objRoleInfo.ServiceFee;
                        float    trialPrice  = objRoleInfo.TrialFee;
                        if ((rolePrice.ToString() == dblAmount.ToString() || trialPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objRoles.UpdateUserRole(intPortalID, intUserID, intRoleID, blnCancel);
                        }
                        else
                        {
                            var objEventLog     = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID   = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID     = intUserID;
                            objEventLogInfo.LogTypeKey    = EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString();
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                }
            }
            catch (Exception exc) //Page failed to load
            {
                Exceptions.ProcessPageLoadException(exc);
            }
        }
示例#22
0
 internal virtual string GetPortalSetting(string settingName, int portalId, string defaultValue)
 {
     return(PortalController.GetPortalSetting(settingName, portalId, defaultValue));
 }
示例#23
0
        private void BindLogin()
        {
            List <AuthenticationInfo> authSystems         = AuthenticationController.GetEnabledAuthenticationServices();
            AuthenticationLoginBase   defaultLoginControl = null;

            foreach (AuthenticationInfo authSystem in authSystems)
            {
                try
                {
                    //Figure out if known Auth types are enabled (so we can improve perf and stop loading the control)
                    bool enabled = true;
                    if (authSystem.AuthenticationType == "Facebook" || authSystem.AuthenticationType == "Google" ||
                        authSystem.AuthenticationType == "Live" || authSystem.AuthenticationType == "Twitter")
                    {
                        enabled = PortalController.GetPortalSettingAsBoolean(authSystem.AuthenticationType + "_Enabled", PortalId, false);
                    }

                    if (enabled)
                    {
                        var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);
                        BindLoginControl(authLoginControl, authSystem);
                        if (authSystem.AuthenticationType == "DNN")
                        {
                            defaultLoginControl = authLoginControl;
                        }

                        //Check if AuthSystem is Enabled
                        if (authLoginControl.Enabled)
                        {
                            var oAuthLoginControl = authLoginControl as OAuthLoginBase;
                            if (oAuthLoginControl != null)
                            {
                                //Add Login Control to List
                                _oAuthControls.Add(oAuthLoginControl);
                            }
                            else
                            {
                                //Add Login Control to List
                                _loginControls.Add(authLoginControl);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Exceptions.LogException(ex);
                }
            }
            int authCount = _loginControls.Count;

            switch (authCount)
            {
            case 0:
                //No enabled controls - inject default dnn control
                if (defaultLoginControl == null)
                {
                    //No controls enabled for portal, and default DNN control is not enabled by host, so load system default (DNN)
                    AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN");
                    var authLoginControl          = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);
                    BindLoginControl(authLoginControl, authSystem);
                    DisplayLoginControl(authLoginControl, false, false);
                }
                else
                {
                    //Portal has no login controls enabled so load default DNN control
                    DisplayLoginControl(defaultLoginControl, false, false);
                }
                break;

            case 1:
                //We don't want the control to render with tabbed interface
                DisplayLoginControl(_loginControls[0], false, false);
                break;

            default:
                foreach (AuthenticationLoginBase authLoginControl in _loginControls)
                {
                    DisplayTabbedLoginControl(authLoginControl, tsLogin.Tabs);
                }

                break;
            }
            BindOAuthControls();
        }
示例#24
0
        public HttpResponseMessage Notifications(int afterNotificationId, int numberOfRecords)
        {
            try
            {
                var portalId = PortalController.GetEffectivePortalId(UserController.Instance.GetCurrentUserInfo().PortalID);
                var notificationsDomainModel = NotificationsController.Instance.GetNotifications(UserInfo.UserID, portalId, afterNotificationId, numberOfRecords);

                var notificationsViewModel = new NotificationsViewModel
                {
                    TotalNotifications = NotificationsController.Instance.CountNotifications(UserInfo.UserID, portalId),
                    Notifications      = new List <NotificationViewModel>(notificationsDomainModel.Count)
                };

                foreach (var notification in notificationsDomainModel)
                {
                    var notificationViewModel = new NotificationViewModel
                    {
                        NotificationId   = notification.NotificationID,
                        Subject          = notification.Subject,
                        From             = notification.From,
                        Body             = notification.Body,
                        DisplayDate      = Common.Utilities.DateUtils.CalculateDateForDisplay(notification.CreatedOnDate),
                        SenderAvatar     = string.Format(Globals.UserProfilePicRelativeUrl(), notification.SenderUserID, 64, 64),
                        SenderProfileUrl = Globals.UserProfileURL(notification.SenderUserID),
                        Actions          = new List <NotificationActionViewModel>()
                    };

                    var notificationType        = NotificationsController.Instance.GetNotificationType(notification.NotificationTypeID);
                    var notificationTypeActions = NotificationsController.Instance.GetNotificationTypeActions(notification.NotificationTypeID);

                    foreach (var notificationTypeAction in notificationTypeActions)
                    {
                        var notificationActionViewModel = new NotificationActionViewModel
                        {
                            Name        = LocalizeActionString(notificationTypeAction.NameResourceKey, notificationType.DesktopModuleId),
                            Description = LocalizeActionString(notificationTypeAction.DescriptionResourceKey, notificationType.DesktopModuleId),
                            Confirm     = LocalizeActionString(notificationTypeAction.ConfirmResourceKey, notificationType.DesktopModuleId),
                            APICall     = notificationTypeAction.APICall
                        };

                        notificationViewModel.Actions.Add(notificationActionViewModel);
                    }

                    if (notification.IncludeDismissAction)
                    {
                        notificationViewModel.Actions.Add(new NotificationActionViewModel
                        {
                            Name        = Localization.GetString("Dismiss.Text"),
                            Description = Localization.GetString("DismissNotification.Text"),
                            Confirm     = "",
                            APICall     = "DesktopModules/InternalServices/API/NotificationsService/Dismiss"
                        });
                    }

                    notificationsViewModel.Notifications.Add(notificationViewModel);
                }

                return(Request.CreateResponse(HttpStatusCode.OK, notificationsViewModel));
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
示例#25
0
        public void SignIn(UserInfo user, bool createPersistentCookie)
        {
            if (PortalController.IsMemberOfPortalGroup(user.PortalID) || createPersistentCookie)
            {
                //Create a custom auth cookie

                //first, create the authentication ticket
                var authenticationTicket = createPersistentCookie
                    ? new FormsAuthenticationTicket(user.Username, true, Config.GetPersistentCookieTimeout())
                    : new FormsAuthenticationTicket(user.Username, false, Config.GetAuthCookieTimeout());

                //encrypt it
                var encryptedAuthTicket = FormsAuthentication.Encrypt(authenticationTicket);

                //Create a new Cookie
                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedAuthTicket)
                {
                    Expires = authenticationTicket.Expiration,
                    Domain  = GetCookieDomain(user.PortalID),
                    Path    = FormsAuthentication.FormsCookiePath,
                    Secure  = FormsAuthentication.RequireSSL
                };

                if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                }

                HttpContext.Current.Response.Cookies.Set(authCookie);
                AuthCookieController.Instance.Update(authCookie.Value, authCookie.Expires.ToUniversalTime(), user.UserID);

                if (PortalController.IsMemberOfPortalGroup(user.PortalID))
                {
                    var domain          = GetCookieDomain(user.PortalID);
                    var siteGroupCookie = new HttpCookie("SiteGroup", domain)
                    {
                        Expires = authenticationTicket.Expiration,
                        Domain  = domain,
                        Path    = FormsAuthentication.FormsCookiePath,
                        Secure  = FormsAuthentication.RequireSSL
                    };

                    HttpContext.Current.Response.Cookies.Set(siteGroupCookie);
                }
            }
            else
            {
                if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                }

                FormsAuthentication.SetAuthCookie(user.Username, false);
                var authCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
                if (!string.IsNullOrEmpty(authCookie?.Value))
                {
                    var t = FormsAuthentication.Decrypt(authCookie.Value);
                    if (t != null)
                    {
                        AuthCookieController.Instance.Update(authCookie.Value, t.Expiration.ToUniversalTime(), user.UserID);
                    }
                }
            }

            if (user.IsSuperUser)
            {
                //save userinfo object in context to ensure Personalization is saved correctly
                HttpContext.Current.Items["UserInfo"] = user;
            }

            //Identity the Login is processed by system.
            HttpContext.Current.Items["DNN_UserSignIn"] = true;
        }
示例#26
0
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <history>
        ///     [cnurse]	9/8/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        protected void Page_Load(Object sender, EventArgs e)
        {
            try
            {
                if ((Request.QueryString["pid"] != null) && (PortalSettings.ActiveTab.ParentId == PortalSettings.SuperTabId || UserInfo.IsSuperUser))
                {
                    intPortalId              = int.Parse(Request.QueryString["pid"]);
                    ctlLogo.ShowUpLoad       = false;
                    ctlBackground.ShowUpLoad = false;
                }
                else
                {
                    intPortalId              = PortalId;
                    ctlLogo.ShowUpLoad       = true;
                    ctlBackground.ShowUpLoad = true;
                }

                //this needs to execute always to the client script code is registred in InvokePopupCal
                cmdExpiryCalendar.NavigateUrl = Calendar.InvokePopupCal(txtExpiryDate);
                ClientAPI.AddButtonConfirm(cmdRestore, Localization.GetString("RestoreCCSMessage", LocalResourceFile));

                // If this is the first visit to the page, populate the site data
                if (Page.IsPostBack == false)
                {
                    ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteMessage", LocalResourceFile));

                    PortalController        objPortalController = new PortalController();
                    ListController          ctlList             = new ListController();
                    ListEntryInfoCollection colProcessor        = ctlList.GetListEntryInfoCollection("Processor");

                    cboProcessor.DataSource = colProcessor;
                    cboProcessor.DataBind();
                    cboProcessor.Items.Insert(0, new ListItem("<" + Localization.GetString("None_Specified") + ">", ""));

                    PortalInfo objPortal = objPortalController.GetPortal(intPortalId);

                    txtPortalName.Text                 = objPortal.PortalName;
                    ctlLogo.Url                        = objPortal.LogoFile;
                    ctlLogo.FileFilter                 = Globals.glbImageFileTypes;
                    txtDescription.Text                = objPortal.Description;
                    txtKeyWords.Text                   = objPortal.KeyWords;
                    ctlBackground.Url                  = objPortal.BackgroundFile;
                    ctlBackground.FileFilter           = Globals.glbImageFileTypes;
                    txtFooterText.Text                 = objPortal.FooterText;
                    optUserRegistration.SelectedIndex  = objPortal.UserRegistration;
                    optBannerAdvertising.SelectedIndex = objPortal.BannerAdvertising;

                    cboSplashTabId.DataSource = Globals.GetPortalTabs(intPortalId, true, true, false, false, false);
                    cboSplashTabId.DataBind();
                    if (cboSplashTabId.Items.FindByValue(objPortal.SplashTabId.ToString()) != null)
                    {
                        cboSplashTabId.Items.FindByValue(objPortal.SplashTabId.ToString()).Selected = true;
                    }
                    cboHomeTabId.DataSource = Globals.GetPortalTabs(intPortalId, true, true, false, false, false);
                    cboHomeTabId.DataBind();
                    if (cboHomeTabId.Items.FindByValue(objPortal.HomeTabId.ToString()) != null)
                    {
                        cboHomeTabId.Items.FindByValue(objPortal.HomeTabId.ToString()).Selected = true;
                    }
                    cboLoginTabId.DataSource = Globals.GetPortalTabs(intPortalId, true, true, false, false, false);
                    cboLoginTabId.DataBind();
                    if (cboLoginTabId.Items.FindByValue(objPortal.LoginTabId.ToString()) != null)
                    {
                        cboLoginTabId.Items.FindByValue(objPortal.LoginTabId.ToString()).Selected = true;
                    }
                    cboUserTabId.DataSource = Globals.GetPortalTabs(intPortalId, true, true, false, false, false);
                    cboUserTabId.DataBind();
                    if (cboUserTabId.Items.FindByValue(objPortal.UserTabId.ToString()) != null)
                    {
                        cboUserTabId.Items.FindByValue(objPortal.UserTabId.ToString()).Selected = true;
                    }

                    ListEntryInfoCollection colList = ctlList.GetListEntryInfoCollection("Currency");

                    cboCurrency.DataSource = colList;
                    cboCurrency.DataBind();
                    if (Null.IsNull(objPortal.Currency) || cboCurrency.Items.FindByValue(objPortal.Currency) == null)
                    {
                        cboCurrency.Items.FindByValue("USD").Selected = true;
                    }
                    else
                    {
                        cboCurrency.Items.FindByValue(objPortal.Currency).Selected = true;
                    }
                    RoleController objRoleController = new RoleController();

                    ArrayList Arr = objRoleController.GetUserRolesByRoleName(intPortalId, objPortal.AdministratorRoleName);
                    int       i;
                    for (i = 0; i <= Arr.Count - 1; i++)
                    {
                        UserRoleInfo objUser = (UserRoleInfo)Arr[i];
                        cboAdministratorId.Items.Add(new ListItem(objUser.FullName, objUser.UserID.ToString()));
                    }
                    if (cboAdministratorId.Items.FindByValue(objPortal.AdministratorId.ToString()) != null)
                    {
                        cboAdministratorId.Items.FindByValue(objPortal.AdministratorId.ToString()).Selected = true;
                    }

                    if (!Null.IsNull(objPortal.ExpiryDate))
                    {
                        txtExpiryDate.Text = objPortal.ExpiryDate.ToShortDateString();
                    }
                    txtHostFee.Text   = objPortal.HostFee.ToString();
                    txtHostSpace.Text = objPortal.HostSpace.ToString();
                    txtPageQuota.Text = objPortal.PageQuota.ToString();
                    txtUserQuota.Text = objPortal.UserQuota.ToString();
                    if (objPortal.SiteLogHistory != 0)
                    {
                        txtSiteLogHistory.Text = objPortal.SiteLogHistory.ToString();
                    }

                    DesktopModuleController objDesktopModules = new DesktopModuleController();
                    ArrayList arrDesktopModules = objDesktopModules.GetDesktopModules();

                    ArrayList arrPremiumModules = new ArrayList();
                    foreach (DesktopModuleInfo objDesktopModule in arrDesktopModules)
                    {
                        if (objDesktopModule.IsPremium)
                        {
                            arrPremiumModules.Add(objDesktopModule);
                        }
                    }

                    ArrayList arrPortalDesktopModules = objDesktopModules.GetPortalDesktopModules(intPortalId, Null.NullInteger);
                    foreach (PortalDesktopModuleInfo objPortalDesktopModule in arrPortalDesktopModules)
                    {
                        foreach (DesktopModuleInfo objDesktopModule in arrPremiumModules)
                        {
                            if (objDesktopModule.DesktopModuleID == objPortalDesktopModule.DesktopModuleID)
                            {
                                arrPremiumModules.Remove(objDesktopModule);
                                break;
                            }
                        }
                    }

                    ctlDesktopModules.Available = arrPremiumModules;
                    ctlDesktopModules.Assigned  = arrPortalDesktopModules;

                    if (!String.IsNullOrEmpty(objPortal.PaymentProcessor))
                    {
                        if (cboProcessor.Items.FindByText(objPortal.PaymentProcessor) != null)
                        {
                            cboProcessor.Items.FindByText(objPortal.PaymentProcessor).Selected = true;
                        }
                        else // default
                        {
                            if (cboProcessor.Items.FindByText("PayPal") != null)
                            {
                                cboProcessor.Items.FindByText("PayPal").Selected = true;
                            }
                        }
                    }
                    else
                    {
                        cboProcessor.Items.FindByValue("").Selected = true;
                    }
                    txtUserId.Text = objPortal.ProcessorUserId;
                    txtPassword.Attributes.Add("value", objPortal.ProcessorPassword);
                    txtHomeDirectory.Text = objPortal.HomeDirectory;

                    //Populate the default language combobox
                    Localization.LoadCultureDropDownList(cboDefaultLanguage, CultureDropDownTypes.NativeName, objPortal.DefaultLanguage);

                    //Populate the timezone combobox (look up timezone translations based on currently set culture)
                    Localization.LoadTimeZoneDropDownList(cboTimeZone, ((PageBase)Page).PageCulture.Name, Convert.ToString(objPortal.TimeZoneOffset));

                    SkinInfo objSkin;

                    ctlPortalSkin.Width    = "275px";
                    ctlPortalSkin.SkinRoot = SkinInfo.RootSkin;
                    objSkin = SkinController.GetSkin(SkinInfo.RootSkin, PortalId, SkinType.Portal);
                    if (objSkin != null)
                    {
                        if (objSkin.PortalId == PortalId)
                        {
                            ctlPortalSkin.SkinSrc = objSkin.SkinSrc;
                        }
                    }
                    ctlPortalContainer.Width    = "275px";
                    ctlPortalContainer.SkinRoot = SkinInfo.RootContainer;
                    objSkin = SkinController.GetSkin(SkinInfo.RootContainer, PortalId, SkinType.Portal);
                    if (objSkin != null)
                    {
                        if (objSkin.PortalId == PortalId)
                        {
                            ctlPortalContainer.SkinSrc = objSkin.SkinSrc;
                        }
                    }

                    ctlAdminSkin.Width    = "275px";
                    ctlAdminSkin.SkinRoot = SkinInfo.RootSkin;
                    objSkin = SkinController.GetSkin(SkinInfo.RootSkin, PortalId, SkinType.Admin);
                    if (objSkin != null)
                    {
                        if (objSkin.PortalId == PortalId)
                        {
                            ctlAdminSkin.SkinSrc = objSkin.SkinSrc;
                        }
                    }
                    ctlAdminContainer.Width    = "275px";
                    ctlAdminContainer.SkinRoot = SkinInfo.RootContainer;
                    objSkin = SkinController.GetSkin(SkinInfo.RootContainer, PortalId, SkinType.Admin);
                    if (objSkin != null)
                    {
                        if (objSkin.PortalId == PortalId)
                        {
                            ctlAdminContainer.SkinSrc = objSkin.SkinSrc;
                        }
                    }

                    LoadStyleSheet();

                    if (Convert.ToString(PortalSettings.HostSettings["SkinUpload"]) == "G" && !UserInfo.IsSuperUser)
                    {
                        lnkUploadSkin.Visible      = false;
                        lnkUploadContainer.Visible = false;
                    }
                    else
                    {
                        ModuleInfo FileManagerModule = (new ModuleController()).GetModuleByDefinition(intPortalId, "File Manager");
                        string[]   parameters        = new string[3];
                        parameters[0]             = "mid=" + FileManagerModule.ModuleID;
                        parameters[1]             = "ftype=" + UploadType.Skin;
                        parameters[2]             = "rtab=" + TabId;
                        lnkUploadSkin.NavigateUrl = Globals.NavigateURL(FileManagerModule.TabID, "Edit", parameters);

                        parameters[1] = "ftype=" + UploadType.Container;
                        lnkUploadContainer.NavigateUrl = Globals.NavigateURL(FileManagerModule.TabID, "Edit", parameters);
                    }

                    if (Request.UrlReferrer != null)
                    {
                        if (Request.UrlReferrer.AbsoluteUri == Request.Url.AbsoluteUri)
                        {
                            ViewState["UrlReferrer"] = "";
                        }
                        else
                        {
                            ViewState["UrlReferrer"] = Convert.ToString(Request.UrlReferrer);
                        }
                    }
                    else
                    {
                        ViewState["UrlReferrer"] = "";
                    }
                }

                if (UserInfo.IsSuperUser)
                {
                    dshHost.Visible   = true;
                    tblHost.Visible   = true;
                    cmdDelete.Visible = true;
                    if (Convert.ToString(ViewState["UrlReferrer"]) == "")
                    {
                        cmdCancel.Visible = false;
                    }
                    else
                    {
                        cmdCancel.Visible = true;
                    }
                }
                else
                {
                    dshHost.Visible   = false;
                    tblHost.Visible   = false;
                    cmdDelete.Visible = false;
                    cmdCancel.Visible = false;
                }
            }
            catch (Exception exc)  //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
示例#27
0
        private static SavedFileDTO SaveFile(
            Stream stream,
            PortalSettings portalSettings,
            UserInfo userInfo,
            string folder,
            string filter,
            string fileName,
            bool overwrite,
            bool isHostMenu,
            bool extract,
            out bool alreadyExists,
            out string errorMessage)
        {
            alreadyExists = false;
            var savedFileDto = new SavedFileDTO();

            try
            {
                var extension = Path.GetExtension(fileName).ValueOrEmpty().Replace(".", "");
                if (!string.IsNullOrEmpty(filter) && !filter.ToLowerInvariant().Contains(extension.ToLowerInvariant()))
                {
                    errorMessage = GetLocalizedString("ExtensionNotAllowed");
                    return(savedFileDto);
                }

                var folderManager = FolderManager.Instance;

                // Check if this is a User Folder
                var effectivePortalId = isHostMenu ? Null.NullInteger : PortalController.GetEffectivePortalId(portalSettings.PortalId);
                int userId;
                var folderInfo = folderManager.GetFolder(effectivePortalId, folder);
                if (IsUserFolder(folder, out userId))
                {
                    var user = UserController.GetUserById(effectivePortalId, userId);
                    if (user != null)
                    {
                        folderInfo = folderManager.GetUserFolder(user);
                    }
                }

                if (!PortalSecurity.IsInRoles(userInfo, portalSettings, folderInfo.FolderPermissions.ToString("WRITE")) &&
                    !PortalSecurity.IsInRoles(userInfo, portalSettings, folderInfo.FolderPermissions.ToString("ADD")))
                {
                    errorMessage = GetLocalizedString("NoPermission");
                    return(savedFileDto);
                }

                if (!overwrite && FileManager.Instance.FileExists(folderInfo, fileName, true))
                {
                    errorMessage          = GetLocalizedString("AlreadyExists");
                    alreadyExists         = true;
                    savedFileDto.FilePath = Path.Combine(folderInfo.PhysicalPath, fileName);
                    return(savedFileDto);
                }

                var contentType = FileContentTypeManager.Instance.GetContentType(Path.GetExtension(fileName));
                var file        = FileManager.Instance.AddFile(folderInfo, fileName, stream, true, false, contentType, userInfo.UserID);

                if (extract && extension.ToLowerInvariant() == "zip")
                {
                    FileManager.Instance.UnzipFile(file);
                    FileManager.Instance.DeleteFile(file);
                }

                errorMessage          = "";
                savedFileDto.FileId   = file.FileId.ToString(CultureInfo.InvariantCulture);
                savedFileDto.FilePath = FileManager.Instance.GetUrl(file);
                return(savedFileDto);
            }
            catch (InvalidFileExtensionException)
            {
                errorMessage = GetLocalizedString("ExtensionNotAllowed");
                return(savedFileDto);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                errorMessage = ex.Message;
                return(savedFileDto);
            }
        }
示例#28
0
        /// <summary>
        /// cmdUpdate_Click runs when the Update LinkButton is clicked.
        /// It saves the current Site Settings
        /// </summary>
        /// <history>
        ///     [cnurse]	9/9/2004	Modified
        /// </history>
        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                string strLogo;
                string strBackground;

                strLogo       = ctlLogo.Url;
                strBackground = ctlBackground.Url;

                double dblHostFee = 0;
                if (!String.IsNullOrEmpty(txtHostFee.Text))
                {
                    dblHostFee = double.Parse(txtHostFee.Text);
                }

                double dblHostSpace = 0;
                if (!String.IsNullOrEmpty(txtHostSpace.Text))
                {
                    dblHostSpace = double.Parse(txtHostSpace.Text);
                }

                int intPageQuota = 0;
                if (txtPageQuota.Text != "")
                {
                    intPageQuota = int.Parse(txtPageQuota.Text);
                }

                double intUserQuota = 0;
                if (txtUserQuota.Text != "")
                {
                    intUserQuota = int.Parse(txtUserQuota.Text);
                }

                int intSiteLogHistory = -1;
                if (!String.IsNullOrEmpty(txtSiteLogHistory.Text))
                {
                    intSiteLogHistory = int.Parse(txtSiteLogHistory.Text);
                }

                DateTime datExpiryDate = Null.NullDate;
                if (!String.IsNullOrEmpty(txtExpiryDate.Text))
                {
                    datExpiryDate = Convert.ToDateTime(txtExpiryDate.Text);
                }

                int intSplashTabId = Null.NullInteger;
                if (cboSplashTabId.SelectedItem != null)
                {
                    intSplashTabId = int.Parse(cboSplashTabId.SelectedItem.Value);
                }

                int intHomeTabId = Null.NullInteger;
                if (cboHomeTabId.SelectedItem != null)
                {
                    intHomeTabId = int.Parse(cboHomeTabId.SelectedItem.Value);
                }

                int intLoginTabId = Null.NullInteger;
                if (cboLoginTabId.SelectedItem != null)
                {
                    intLoginTabId = int.Parse(cboLoginTabId.SelectedItem.Value);
                }

                int intUserTabId = Null.NullInteger;
                if (cboUserTabId.SelectedItem != null)
                {
                    intUserTabId = int.Parse(cboUserTabId.SelectedItem.Value);
                }

                if (txtPassword.Attributes["value"] != null)
                {
                    txtPassword.Attributes["value"] = txtPassword.Text;
                }

                // update Portal info in the database
                PortalController objPortalController = new PortalController();
                //check only relevant fields altered
                if (!UserInfo.IsSuperUser)
                {
                    PortalInfo objPortal   = objPortalController.GetPortal(intPortalId);
                    bool       HostChanged = false;
                    if (dblHostFee != objPortal.HostFee)
                    {
                        HostChanged = true;
                    }
                    if (dblHostSpace != objPortal.HostSpace)
                    {
                        HostChanged = true;
                    }
                    if (intPageQuota != objPortal.PageQuota)
                    {
                        HostChanged = true;
                    }
                    if (intUserQuota != objPortal.UserQuota)
                    {
                        HostChanged = true;
                    }
                    if (intSiteLogHistory != objPortal.SiteLogHistory)
                    {
                        HostChanged = true;
                    }
                    if (datExpiryDate != objPortal.ExpiryDate)
                    {
                        HostChanged = true;
                    }
                    if (HostChanged)
                    {
                        throw new Exception();
                    }
                }

                objPortalController.UpdatePortalInfo(intPortalId, txtPortalName.Text, strLogo, txtFooterText.Text, datExpiryDate, optUserRegistration.SelectedIndex, optBannerAdvertising.SelectedIndex, cboCurrency.SelectedItem.Value, Convert.ToInt32(cboAdministratorId.SelectedItem.Value), dblHostFee, dblHostSpace, intPageQuota, (int)intUserQuota, ((cboProcessor.SelectedValue == "") ? "" : cboProcessor.SelectedItem.Text).ToString(), txtUserId.Text, txtPassword.Text, txtDescription.Text, txtKeyWords.Text, strBackground, intSiteLogHistory, intSplashTabId, intHomeTabId, intLoginTabId, intUserTabId, cboDefaultLanguage.SelectedValue, Convert.ToInt32(cboTimeZone.SelectedValue), txtHomeDirectory.Text);
                bool blnAdminSkinChanged = SkinChanged(SkinInfo.RootSkin, PortalId, SkinType.Admin, ctlAdminSkin.SkinSrc) || SkinChanged(SkinInfo.RootContainer, PortalId, SkinType.Admin, ctlAdminContainer.SkinSrc);

                //Dim objSkins As New UI.Skins.SkinController
                SkinController.SetSkin(SkinInfo.RootSkin, PortalId, SkinType.Portal, ctlPortalSkin.SkinSrc);
                SkinController.SetSkin(SkinInfo.RootContainer, PortalId, SkinType.Portal, ctlPortalContainer.SkinSrc);
                SkinController.SetSkin(SkinInfo.RootSkin, PortalId, SkinType.Admin, ctlAdminSkin.SkinSrc);
                SkinController.SetSkin(SkinInfo.RootContainer, PortalId, SkinType.Admin, ctlAdminContainer.SkinSrc);

                if (UserInfo.IsSuperUser)
                {
                    // delete old portal module assignments
                    DesktopModuleController objDesktopModules = new DesktopModuleController();
                    objDesktopModules.DeletePortalDesktopModules(intPortalId, Null.NullInteger);
                    // add new portal module assignments
                    foreach (ListItem objListItem in ctlDesktopModules.Assigned)
                    {
                        objDesktopModules.AddPortalDesktopModule(intPortalId, int.Parse(objListItem.Value));
                    }
                }

                // Redirect to this site to refresh only if admin skin changed
                if (blnAdminSkinChanged)
                {
                    Response.Redirect(Request.RawUrl, true);
                }
            }
            catch (Exception exc)  //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 public void AddLog(string propertyName, string propertyValue, EventLogType logType)
 {
     AddLog(propertyName, propertyValue, PortalController.GetCurrentPortalSettings(),
            UserController.GetCurrentUserInfo().UserID, logType);
 }
示例#30
0
        protected string SaveFile(Stream stream, PortalSettings portalSettings,
                                  UserInfo userInfo, string folder, string filter, string fileName)
        {
            try
            {
                if (!string.IsNullOrEmpty(fileName))
                {
                    var extension = Path.GetExtension(fileName).Replace(".", "");
                    if (!string.IsNullOrEmpty(filter) && !filter.ToLower().Contains(extension.ToLower()))
                    {
                        // trying to upload a file not allowed for current filter
                        return(string.Empty);
                    }

                    if (!IsAllowedExtension(extension))
                    {
                        return(string.Empty);
                    }

                    var folderManager = FolderManager.Instance;
                    if (string.IsNullOrEmpty(folder))
                    {
                        folder = "";
                    }

                    //Check if this is a User Folder
                    IFolderInfo folderInfo;
                    int         effectivePortalId = PortalController.GetEffectivePortalId(portalSettings.PortalId);
                    if (folder.ToLowerInvariant().StartsWith("users/") &&
                        folder.EndsWith(string.Format("/{0}/", userInfo.UserID)))
                    {
                        //Make sure the user folder exists
                        folderInfo = folderManager.GetFolder(effectivePortalId, folder);
                        if (folderInfo == null)
                        {
                            //Add User folder
                            //fix user's portal id
                            userInfo.PortalID = effectivePortalId;

                            var defaultFolderMapping = FolderMappingController.Instance
                                                       .GetDefaultFolderMapping(portalSettings.PortalId);
                            folderInfo = ((FolderManager)folderManager).AddFolder(defaultFolderMapping, folder);
                        }
                    }
                    else
                    {
                        folderInfo = folderManager.GetFolder(effectivePortalId, folder);
                    }

                    FileManager.Instance.AddFile(folderInfo, fileName, stream, true);
                    return(Path.Combine(folderInfo.PhysicalPath, fileName));
                }

                return(string.Empty);
            }
            catch (Exception exe)
            {
                //Logger.Error(exe.Message);
                Exceptions.LogException(exe);
                return(string.Empty);
            }
        }
示例#31
0
        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (UserInfo.IsSuperUser)
                {
                    //Update Language
                    if (Language == null)
                    {
                        _Language = LocaleController.Instance.GetLocale(languageComboBox.SelectedValue);
                        if (_Language == null)
                        {
                            _Language     = new Locale();
                            Language.Code = languageComboBox.SelectedValue;
                        }
                    }
                    Language.Fallback = fallBackComboBox.SelectedValue;
                    Language.Text     = CultureInfo.CreateSpecificCulture(Language.Code).NativeName;
                    Localization.SaveLanguage(Language);
                }

                if (!IsLanguageEnabled(Language.Code))
                {
                    //Add language to portal
                    Localization.AddLanguageToPortal(PortalId, Language.LanguageId, true);
                }

                string roles = Null.NullString;
                if (IsAddMode)
                {
                    roles = string.Format("Administrators;{0}", string.Format("Translator ({0})", Language.Code));
                }
                else
                {
                    foreach (string role in translatorRoles.SelectedRoleNames)
                    {
                        roles += role + ";";
                    }

                    roles = roles.TrimEnd(';');
                }

                PortalController.UpdatePortalSetting(PortalId, string.Format("DefaultTranslatorRoles-{0}", Language.Code), roles);

                //var tabCtrl = new TabController();
                //TabCollection tabs = tabCtrl.GetTabsByPortal(PortalId).WithCulture(Language.Code, false);
                //if (PortalSettings.ContentLocalizationEnabled && tabs.Count == 0)
                //{
                //    //Create Localized Pages
                //    foreach (TabInfo t in tabCtrl.GetCultureTabList(PortalId))
                //    {
                //        tabCtrl.CreateLocalizedCopy(t, Language, false);
                //    }

                //    var portalCtl = new PortalController();
                //    portalCtl.MapLocalizedSpecialPages(PortalId, Language.Code);

                //    DataCache.ClearPortalCache(PortalId, true);

                //}

                Response.Redirect(Globals.NavigateURL(), true);
                //Module failed to load
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
示例#32
0
        private void SaveFile(object sender, EventArgs e)
        {
            // if file is selected exit
            if (!string.IsNullOrEmpty(this._txtFile.PostedFile.FileName))
            {
                var extension = Path.GetExtension(this._txtFile.PostedFile.FileName).Replace(".", string.Empty);

                if (!string.IsNullOrEmpty(this.FileFilter) && !this.FileFilter.ToLowerInvariant().Contains(extension.ToLowerInvariant()))
                {
                    // trying to upload a file not allowed for current filter
                    var localizedString = Localization.GetString("UploadError", this.LocalResourceFile);
                    if (string.IsNullOrEmpty(localizedString))
                    {
                        localizedString = Utilities.GetLocalizedString("UploadError");
                    }

                    this._lblMessage.Text = string.Format(localizedString, this.FileFilter, extension);
                }
                else
                {
                    var folderManager = FolderManager.Instance;

                    var folderPath = PathUtils.Instance.GetRelativePath(this.PortalId, this.ParentFolder) + this._cboFolders.SelectedItem.Value;

                    // Check if this is a User Folder
                    IFolderInfo folder;
                    if (this.IsUserFolder(this._cboFolders.SelectedItem.Value))
                    {
                        // Make sure the user folder exists
                        folder = folderManager.GetFolder(PortalController.GetEffectivePortalId(this.PortalId), folderPath);
                        if (folder == null)
                        {
                            // Add User folder
                            var user = this.User ?? UserController.Instance.GetCurrentUserInfo();

                            // fix user's portal id
                            user.PortalID = this.PortalId;
                            folder        = ((FolderManager)folderManager).AddUserFolder(user);
                        }
                    }
                    else
                    {
                        folder = folderManager.GetFolder(this.PortalId, folderPath);
                    }

                    var fileName = Path.GetFileName(this._txtFile.PostedFile.FileName);

                    try
                    {
                        FileManager.Instance.AddFile(folder, fileName, this._txtFile.PostedFile.InputStream, true);
                    }
                    catch (PermissionsNotMetException)
                    {
                        this._lblMessage.Text += "<br />" + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath);
                    }
                    catch (NoSpaceAvailableException)
                    {
                        this._lblMessage.Text += "<br />" + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName);
                    }
                    catch (InvalidFileExtensionException)
                    {
                        this._lblMessage.Text += "<br />" + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString());
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex);

                        this._lblMessage.Text += "<br />" + string.Format(Localization.GetString("SaveFileError"), fileName);
                    }
                }

                if (string.IsNullOrEmpty(this._lblMessage.Text))
                {
                    var fileName = this._txtFile.PostedFile.FileName.Substring(this._txtFile.PostedFile.FileName.LastIndexOf("\\") + 1);
                    this.SetFilePath(fileName);
                }
            }

            this.Mode = FileControlMode.Normal;
        }
示例#33
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Exports the selected portal
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// Template will be saved in Portals\_default folder.
        /// An extension of .template will be added to filename if not entered
        /// </remarks>
        /// <history>
        ///     [VMasanas]	23/09/2004	Created
        ///     [cnurse]	11/08/2004	Addition of files to template
        ///     [aprasad]	1/17/2011	New setting AutoAddPortalAlias
        /// </history>
        /// -----------------------------------------------------------------------------
        private void cmdExport_Click(Object sender, EventArgs e)
        {
            try
            {
                ZipOutputStream resourcesFile;
                var             sb       = new StringBuilder();
                var             settings = new XmlWriterSettings();
                settings.ConformanceLevel   = ConformanceLevel.Fragment;
                settings.OmitXmlDeclaration = true;
                settings.Indent             = true;

                if (!Page.IsValid)
                {
                    return;
                }
                string filename;
                filename = Globals.HostMapPath + txtTemplateName.Text;
                if (!filename.EndsWith(".template"))
                {
                    filename += ".template";
                }
                XmlWriter writer = XmlWriter.Create(filename, settings);

                writer.WriteStartElement("portal");
                writer.WriteAttributeString("version", "5.0");

                //Add template description
                writer.WriteElementString("description", Server.HtmlEncode(txtDescription.Text));

                //Serialize portal settings
                PortalInfo objportal;
                var        objportals = new PortalController();
                objportal = objportals.GetPortal(Convert.ToInt32(cboPortals.SelectedValue));

                writer.WriteStartElement("settings");

                writer.WriteElementString("logofile", objportal.LogoFile);
                writer.WriteElementString("footertext", objportal.FooterText);
                writer.WriteElementString("userregistration", objportal.UserRegistration.ToString());
                writer.WriteElementString("banneradvertising", objportal.BannerAdvertising.ToString());
                writer.WriteElementString("defaultlanguage", objportal.DefaultLanguage);

                Dictionary <string, string> settingsDictionary = PortalController.GetPortalSettingsDictionary(objportal.PortalID);

                string setting = "";
                settingsDictionary.TryGetValue("DefaultPortalSkin", out setting);
                if (!string.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("skinsrc", setting);
                }
                settingsDictionary.TryGetValue("DefaultAdminSkin", out setting);
                if (!string.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("skinsrcadmin", setting);
                }
                settingsDictionary.TryGetValue("DefaultPortalContainer", out setting);
                if (!string.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("containersrc", setting);
                }
                settingsDictionary.TryGetValue("DefaultAdminContainer", out setting);
                if (!string.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("containersrcadmin", setting);
                }
                settingsDictionary.TryGetValue("EnableSkinWidgets", out setting);
                if (!string.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("enableskinwidgets", setting);
                }
                settingsDictionary.TryGetValue("portalaliasmapping", out setting);
                if (!String.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("portalaliasmapping", setting);
                }
                settingsDictionary.TryGetValue("ContentLocalizationEnabled", out setting);
                if (!String.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("contentlocalizationenabled", setting);
                }
                settingsDictionary.TryGetValue("TimeZone", out setting);
                if (!string.IsNullOrEmpty(setting))
                {
                    writer.WriteElementString("timezone", setting);
                }

                writer.WriteElementString("hostspace", objportal.HostSpace.ToString());
                writer.WriteElementString("userquota", objportal.UserQuota.ToString());
                writer.WriteElementString("pagequota", objportal.PageQuota.ToString());

                //End Portal Settings
                writer.WriteEndElement();

                //Serialize Profile Definitions
                SerializeProfileDefinitions(writer, objportal);

                //Serialize Portal Desktop Modules
                DesktopModuleController.SerializePortalDesktopModules(writer, objportal.PortalID);

                //Serialize Roles
                RoleController.SerializeRoleGroups(writer, objportal.PortalID);

                //Serialize tabs
                SerializeTabs(writer, objportal);

                if (chkContent.Checked)
                {
                    //Create Zip File to hold files
                    resourcesFile = new ZipOutputStream(File.Create(filename + ".resources"));
                    resourcesFile.SetLevel(6);

                    //Serialize folders (while adding files to zip file)
                    SerializeFolders(writer, objportal, ref resourcesFile);

                    //Finish and Close Zip file
                    resourcesFile.Finish();
                    resourcesFile.Close();
                }
                writer.WriteEndElement();

                writer.Close();

                DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "", string.Format(Localization.GetString("ExportedMessage", LocalResourceFile), filename), ModuleMessage.ModuleMessageType.GreenSuccess);
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
示例#34
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        ///   CreateUserNotifications creates HtmlTextUser records and optionally sends email notifications to participants in a Workflow
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="objHtmlText">An HtmlTextInfo object</param>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        private void CreateUserNotifications(HtmlTextInfo objHtmlText)
        {
            var _htmlTextUserController    = new HtmlTextUserController();
            HtmlTextUserInfo _htmlTextUser = null;
            UserInfo         _user         = null;

            // clean up old user notification records
            _htmlTextUserController.DeleteHtmlTextUsers();

            // ensure we have latest htmltext object loaded
            objHtmlText = GetHtmlText(objHtmlText.ModuleID, objHtmlText.ItemID);

            // build collection of users to notify
            var objWorkflow = new WorkflowStateController();
            var arrUsers    = new ArrayList();

            // if not published
            if (objHtmlText.IsPublished == false)
            {
                arrUsers.Add(objHtmlText.CreatedByUserID); // include content owner
            }

            // if not draft and not published
            if (objHtmlText.StateID != objWorkflow.GetFirstWorkflowStateID(objHtmlText.WorkflowID) && objHtmlText.IsPublished == false)
            {
                // get users from permissions for state
                var objRoles = new RoleController();
                foreach (WorkflowStatePermissionInfo permission in
                         WorkflowStatePermissionController.GetWorkflowStatePermissions(objHtmlText.StateID))
                {
                    if (permission.AllowAccess)
                    {
                        if (Null.IsNull(permission.UserID))
                        {
                            int      roleId  = permission.RoleID;
                            RoleInfo objRole = TestableRoleController.Instance.GetRole(objHtmlText.PortalID, r => r.RoleID == roleId);
                            if ((objRole != null))
                            {
                                foreach (UserRoleInfo objUserRole in objRoles.GetUserRoles(objHtmlText.PortalID, null, objRole.RoleName))
                                {
                                    if (!arrUsers.Contains(objUserRole.UserID))
                                    {
                                        arrUsers.Add(objUserRole.UserID);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (!arrUsers.Contains(permission.UserID))
                            {
                                arrUsers.Add(permission.UserID);
                            }
                        }
                    }
                }
            }

            // process notifications
            if (arrUsers.Count > 0 || (objHtmlText.IsPublished && objHtmlText.Notify))
            {
                // get tabid from module
                var        objModules = new ModuleController();
                ModuleInfo objModule  = objModules.GetModule(objHtmlText.ModuleID);

                PortalSettings objPortalSettings = PortalController.GetCurrentPortalSettings();
                if (objPortalSettings != null)
                {
                    string strResourceFile = string.Format("{0}/DesktopModules/{1}/{2}/{3}",
                                                           Globals.ApplicationPath,
                                                           objModule.DesktopModule.FolderName,
                                                           Localization.LocalResourceDirectory,
                                                           Localization.LocalSharedResourceFile);
                    string strSubject = Localization.GetString("NotificationSubject", strResourceFile);
                    string strBody    = Localization.GetString("NotificationBody", strResourceFile);
                    strBody = strBody.Replace("[URL]", Globals.NavigateURL(objModule.TabID));
                    strBody = strBody.Replace("[STATE]", objHtmlText.StateName);

                    // process user notification collection

                    foreach (int intUserID in arrUsers)
                    {
                        // create user notification record
                        _htmlTextUser          = new HtmlTextUserInfo();
                        _htmlTextUser.ItemID   = objHtmlText.ItemID;
                        _htmlTextUser.StateID  = objHtmlText.StateID;
                        _htmlTextUser.ModuleID = objHtmlText.ModuleID;
                        _htmlTextUser.TabID    = objModule.TabID;
                        _htmlTextUser.UserID   = intUserID;
                        _htmlTextUserController.AddHtmlTextUser(_htmlTextUser);

                        // send an email notification to a user if the state indicates to do so
                        if (objHtmlText.Notify)
                        {
                            _user = UserController.GetUserById(objHtmlText.PortalID, intUserID);
                            if (_user != null)
                            {
                                AddHtmlNotification(strSubject, strBody, _user);
                            }
                        }
                    }

                    // if published and the published state specifies to notify members of the workflow
                    if (objHtmlText.IsPublished && objHtmlText.Notify)
                    {
                        // send email notification to the author
                        _user = UserController.GetUserById(objHtmlText.PortalID, objHtmlText.CreatedByUserID);
                        if (_user != null)
                        {
                            try
                            {
                                Services.Mail.Mail.SendEmail(objPortalSettings.Email, objPortalSettings.Email, strSubject, strBody);
                            }
                            catch (Exception exc)
                            {
                                Exceptions.LogException(exc);
                            }
                        }
                    }
                }
            }
        }
示例#35
0
 public void TearDown()
 {
     PortalController.ClearInstance();
 }
示例#36
0
 /// -----------------------------------------------------------------------------
 /// <summary>
 ///   FormatHtmlText formats HtmlText content for display in the browser
 /// </summary>
 /// <remarks>
 /// </remarks>
 /// <param name="moduleId">The ModuleID</param>
 /// <param name = "content">The HtmlText Content</param>
 /// <param name = "settings">A Hashtable of Module Settings</param>
 /// <history>
 /// </history>
 /// -----------------------------------------------------------------------------
 public static string FormatHtmlText(int moduleId, string content, Hashtable settings)
 {
     return(FormatHtmlText(moduleId, content, settings, PortalController.GetCurrentPortalSettings()));
 }
示例#37
0
	public void setTheOtherPortal(PortalController theOtherPortal)
	{
		this.theOtherPortal = theOtherPortal;
	}
示例#38
0
        /// <summary>
        /// Localize correctly sets up the control for US/Canada/Other Countries
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void Localize()
        {
            var countryCode = cboCountry.SelectedItem.Value;
            var ctlEntry    = new ListController();
            //listKey in format "Country.US:Region"
            var listKey         = "Country." + countryCode;
            var entryCollection = ctlEntry.GetListEntryInfoItems("Region", listKey);

            if (entryCollection.Any())
            {
                cboRegion.Visible = true;
                txtRegion.Visible = false;
                {
                    cboRegion.Items.Clear();
                    cboRegion.DataSource = entryCollection;
                    cboRegion.DataBind();
                    cboRegion.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", ""));
                }
                if (countryCode.Equals("us", StringComparison.InvariantCultureIgnoreCase))
                {
                    valRegion1.Enabled      = true;
                    valRegion2.Enabled      = false;
                    valRegion1.ErrorMessage = Localization.GetString("StateRequired", Localization.GetResourceFile(this, MyFileName));
                    plRegion.Text           = Localization.GetString("plState", Localization.GetResourceFile(this, MyFileName));
                    plRegion.HelpText       = Localization.GetString("plState.Help", Localization.GetResourceFile(this, MyFileName));
                    plPostal.Text           = Localization.GetString("plZip", Localization.GetResourceFile(this, MyFileName));
                    plPostal.HelpText       = Localization.GetString("plZip.Help", Localization.GetResourceFile(this, MyFileName));
                }
                else
                {
                    valRegion1.ErrorMessage = Localization.GetString("ProvinceRequired", Localization.GetResourceFile(this, MyFileName));
                    plRegion.Text           = Localization.GetString("plProvince", Localization.GetResourceFile(this, MyFileName));
                    plRegion.HelpText       = Localization.GetString("plProvince.Help", Localization.GetResourceFile(this, MyFileName));
                    plPostal.Text           = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName));
                    plPostal.HelpText       = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName));
                }
                valRegion1.Enabled = true;
                valRegion2.Enabled = false;
            }
            else
            {
                cboRegion.ClearSelection();
                cboRegion.Visible       = false;
                txtRegion.Visible       = true;
                valRegion1.Enabled      = false;
                valRegion2.Enabled      = true;
                valRegion2.ErrorMessage = Localization.GetString("RegionRequired", Localization.GetResourceFile(this, MyFileName));
                plRegion.Text           = Localization.GetString("plRegion", Localization.GetResourceFile(this, MyFileName));
                plRegion.HelpText       = Localization.GetString("plRegion.Help", Localization.GetResourceFile(this, MyFileName));
                plPostal.Text           = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName));
                plPostal.HelpText       = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName));
            }

            var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", PortalSettings.PortalId, true);

            if (reqRegion)
            {
                valRegion1.Enabled = false;
                valRegion2.Enabled = false;
            }
        }
示例#39
0
        /// <summary>
        /// ShowRequiredFields sets up displaying which fields are required
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void ShowRequiredFields()
        {
            var reqStreet    = PortalController.GetPortalSettingAsBoolean("addressstreet", PortalSettings.PortalId, true);
            var reqCity      = PortalController.GetPortalSettingAsBoolean("addresscity", PortalSettings.PortalId, true);
            var reqCountry   = PortalController.GetPortalSettingAsBoolean("addresscountry", PortalSettings.PortalId, true);
            var reqRegion    = PortalController.GetPortalSettingAsBoolean("addressregion", PortalSettings.PortalId, true);
            var reqPostal    = PortalController.GetPortalSettingAsBoolean("addresspostal", PortalSettings.PortalId, true);
            var reqTelephone = PortalController.GetPortalSettingAsBoolean("addresstelephone", PortalSettings.PortalId, true);
            var reqCell      = PortalController.GetPortalSettingAsBoolean("addresscell", PortalSettings.PortalId, true);
            var reqFax       = PortalController.GetPortalSettingAsBoolean("addressfax", PortalSettings.PortalId, true);

            if (TabPermissionController.CanAdminPage())
            {
                if (reqCountry)
                {
                    chkCountry.Checked  = true;
                    valCountry.Enabled  = true;
                    cboCountry.CssClass = "dnnFormRequired";
                }
                else
                {
                    valCountry.Enabled  = false;
                    cboCountry.CssClass = "";
                }
                if (reqRegion)
                {
                    chkRegion.Checked  = true;
                    txtRegion.CssClass = "dnnFormRequired";
                    cboRegion.CssClass = "dnnFormRequired";

                    if (cboRegion.Visible)
                    {
                        valRegion1.Enabled = true;
                        valRegion2.Enabled = false;
                    }
                    else
                    {
                        valRegion1.Enabled = false;
                        valRegion2.Enabled = true;
                    }
                }
                else
                {
                    valRegion1.Enabled = false;
                    valRegion2.Enabled = false;
                    txtRegion.CssClass = "";
                    cboRegion.CssClass = "";
                }
                if (reqCity)
                {
                    chkCity.Checked  = true;
                    valCity.Enabled  = true;
                    txtCity.CssClass = "dnnFormRequired";
                }
                else
                {
                    valCity.Enabled  = false;
                    txtCity.CssClass = "";
                }
                if (reqStreet)
                {
                    chkStreet.Checked  = true;
                    valStreet.Enabled  = true;
                    txtStreet.CssClass = "dnnFormRequired";
                }
                else
                {
                    valStreet.Enabled  = false;
                    txtStreet.CssClass = "";
                }
                if (reqPostal)
                {
                    chkPostal.Checked  = true;
                    valPostal.Enabled  = true;
                    txtPostal.CssClass = "dnnFormRequired";
                }
                else
                {
                    valPostal.Enabled  = false;
                    txtPostal.CssClass = "";
                }
                if (reqTelephone)
                {
                    chkTelephone.Checked  = true;
                    valTelephone.Enabled  = true;
                    txtTelephone.CssClass = "dnnFormRequired";
                }
                else
                {
                    valTelephone.Enabled  = false;
                    txtTelephone.CssClass = "";
                }
                if (reqCell)
                {
                    chkCell.Checked  = true;
                    valCell.Enabled  = true;
                    txtCell.CssClass = "dnnFormRequired";
                }
                else
                {
                    valCell.Enabled  = false;
                    txtCell.CssClass = "";
                }
                if (reqFax)
                {
                    chkFax.Checked  = true;
                    valFax.Enabled  = true;
                    txtFax.CssClass = "dnnFormRequired";
                }
                else
                {
                    valFax.Enabled  = false;
                    txtFax.CssClass = "";
                }
            }
        }
示例#40
0
	public void SetPortalController( PortalController p ){ portal = p; }