Example #1
0
        public ActionResult UpdateAlias(int id, int?entryNodeId)
        {
            Site      currentSite = CuyahogaContext.CurrentSite;
            SiteAlias siteAlias   = this._siteService.GetSiteAliasById(id);

            try
            {
                if (entryNodeId.HasValue)
                {
                    siteAlias.EntryNode = this._nodeService.GetNodeById(entryNodeId.Value);
                }
                else
                {
                    siteAlias.EntryNode = null;
                }
                if (TryUpdateModel(siteAlias, new [] { "Url" }) && ValidateModel(siteAlias, this._siteAliasValidator, new[] { "Site", "Url" }))
                {
                    this._siteService.SaveSiteAlias(siteAlias);
                    Messages.AddFlashMessageWithParams("SiteAliasUpdatedMessage", siteAlias.Url);
                    return(RedirectToAction("Aliases"));
                }
            }
            catch (Exception ex)
            {
                Messages.AddException(ex);
            }
            ViewData["Site"]       = currentSite;
            ViewData["EntryNodes"] = new SelectList(GetDisplayRootNodes(currentSite), "Key", "Value", siteAlias.EntryNode != null ? siteAlias.EntryNode.Id : -1);
            return(View("NewAlias", currentSite));
        }
Example #2
0
        public ActionResult CreateAlias([Bind(Exclude = "Id")] SiteAlias siteAlias, int?entryNodeId)
        {
            Site currentSite = CuyahogaContext.CurrentSite;

            try
            {
                siteAlias.Site = currentSite;
                if (entryNodeId.HasValue)
                {
                    siteAlias.EntryNode = this._nodeService.GetNodeById(entryNodeId.Value);
                }
                if (ValidateModel(siteAlias, this._siteAliasValidator, new[] { "Site", "Url" }))
                {
                    this._siteService.SaveSiteAlias(siteAlias);
                    Messages.AddFlashMessageWithParams("SiteAliasCreatedMessage", siteAlias.Url);
                    return(RedirectToAction("Aliases"));
                }
            }
            catch (Exception ex)
            {
                Messages.AddException(ex);
            }
            ViewData["Site"]       = currentSite;
            ViewData["EntryNodes"] = new SelectList(GetDisplayRootNodes(currentSite), "Key", "Value", entryNodeId.HasValue ? entryNodeId.Value : -1);
            return(View("NewAlias", siteAlias));
        }
Example #3
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            base.Title = "Sửa site alias";

            if (Context.Request.QueryString["SiteAliasId"] != null)
            {
                if (Int32.Parse(Context.Request.QueryString["SiteAliasId"]) == -1)
                {
                    // Create a new site alias instance
                    this._activeSiteAlias = new SiteAlias();
                    if (Context.Request.QueryString["SiteId"] != null)
                    {
                        this._activeSiteAlias.Site = base.SiteService.GetSiteById(Int32.Parse(Request.QueryString["SiteId"]));
                    }
                    else
                    {
                        throw new Exception("Không có trang cho tên này.");
                    }
                    this.btnDelete.Visible = false;
                }
                else
                {
                    // Get site alias data
                    this._activeSiteAlias  = base.SiteService.GetSiteAliasById(Int32.Parse(Request.QueryString["SiteAliasId"]));
                    this.btnDelete.Visible = true;
                    this.btnDelete.Attributes.Add("onclick", "return confirm('Bạn có chắc chắn?')");
                }
                if (!this.IsPostBack)
                {
                    BindSiteAliasControls();
                    BindAvailableNodes();
                }
            }
        }
Example #4
0
        public override bool Update(SiteAlias site)
        {
            if (site != null && !site.Identity.IsNullOrEmpty() && !site.AliasSchemeIdentity.IsNullOrEmpty() && CanUpdate(site))
            {
                if (SiteUtils.IsDirty(site))
                {
                    try
                    {
                        NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
                        cmd.CommandText = Db.UpdateAlias;
                        cmd.Parameters.AddWithValue("sid", site.Identity.DataStoreIdentity);
                        cmd.Parameters.AddWithValue("id", site.Identity.Identity);
                        cmd.Parameters.AddWithValue("ssid", site.AliasSchemeIdentity.DataStoreIdentity);
                        cmd.Parameters.AddWithValue("scid", site.AliasSchemeIdentity.Identity);
                        cmd.Parameters.AddWithValue("name", site.Name);
                        cmd.Parameters.AddWithValue("oldName", SiteUtils.OriginalName(site));
                        cmd.Parameters.AddWithValue("start", DateTime.UtcNow);

                        Db.ExecuteNonQuery(cmd);

                        return(true);
                    }
                    catch
                    { }
                }
                else
                {
                    return(true); //no change to the alias
                }
            }
            return(false);
        }
Example #5
0
        static SiteAlias MakeOrg(SiteAliasProviderBase prov, SiteAliasScheme scheme, Site org, string orgName)
        {
            SiteAlias sch = null;

            if (!prov.Exists(scheme, orgName))
            {
                sch = prov.Create(scheme, org, orgName);
                if (sch != null)
                {
                    Console.WriteLine("Created Alias: For: " + org.Name + " Alias: " + sch.Name + " In: " + scheme.Name);
                }
                else
                {
                    Console.WriteLine("Failed to create org alias");
                }
            }
            else
            {
                IEnumerable <SiteAlias> orgs = prov.Get(scheme, orgName);
                if (orgs != null)
                {
                    foreach (SiteAlias o in orgs)
                    {
                        if (o.SiteEquals(org))
                        {
                            sch = o;
                            Console.WriteLine("Fetched Alias: For: " + org.Name + " Alias: " + sch.Name + " In: " + scheme.Name);
                            break;
                        }
                    }
                }
            }
            return(sch);
        }
Example #6
0
        public void DeleteSiteAlias(SiteAlias siteAlias)
        {
            ISession session = this._sessionManager.OpenSession();

            // Clear query cache first
            session.SessionFactory.EvictQueries("Sites");

            // Delete site
            session.Delete(siteAlias);
        }
Example #7
0
 public static JObject ToJson(SiteAlias alias)
 {
     if (alias != null)
     {
         JObject o = new JObject();
         o.Add(JsonUtils.Id, JsonUtils.ToJson(alias.Identity));
         o.Add(JsonUtils.SchemeId, JsonUtils.ToJson(alias.AliasSchemeIdentity));
         o.Add(JsonUtils.Name, alias.Name);
         return(o);
     }
     return(null);
 }
 public void SaveSiteAlias(SiteAlias siteAlias)
 {
     try
     {
         // We need to use a specific DAO to also enable clearing the query cache.
         _siteStructureDao.SaveSiteAlias(siteAlias);
     }
     catch (Exception ex)
     {
         log.Error("Error saving site alias", ex);
         throw;
     }
 }
Example #9
0
 public virtual void DeleteSiteAlias(SiteAlias siteAlias)
 {
     try
     {
         // We need to use a specific DAO to also enable clearing the query cache.
         this._siteStructureDao.DeleteSiteAlias(siteAlias);
     }
     catch (Exception ex)
     {
         log.Error("Error deleting site alias", ex);
         throw;
     }
 }
Example #10
0
 public override IEnumerable <SiteAlias> Get(SiteAliasScheme scheme, string name, StringComparison comparisonOption)
 {
     if (!string.IsNullOrEmpty(name) && this.CanGet())
     {
         string where = Db.SelectAliasByScheme;
         if (comparisonOption == StringComparison.CurrentCultureIgnoreCase || comparisonOption == StringComparison.OrdinalIgnoreCase)
         {
             where += " AND lower(\"Name\")=lower(:name)";
         }
         else
         {
             where += " AND \"Name\"=:name";
         }
         NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
         cmd.CommandText = Db.SelectAlias + where + " AND" + Db.WhereCurrent;
         cmd.Parameters.AddWithValue("ssid", scheme.Identity.DataStoreIdentity);
         cmd.Parameters.AddWithValue("scid", scheme.Identity.Identity);
         cmd.Parameters.AddWithValue("name", name);
         NpgsqlDataReader rdr     = Db.ExecuteReader(cmd);
         List <SiteAlias> schemes = new List <SiteAlias>();
         SiteAlias        o       = null;
         if (rdr != null)
         {
             try
             {
                 while (rdr.Read())
                 {
                     o = SiteAliasBuilder.Instance.Build(rdr);
                     if (o != null)
                     {
                         schemes.Add(o);
                     }
                 }
                 if (cmd.Connection.State == System.Data.ConnectionState.Open)
                 {
                     cmd.Connection.Close();
                 }
             }
             catch
             { }
             finally
             {
                 cmd.Dispose();
             }
         }
         return(schemes);
     }
     return(null);
 }
Example #11
0
        public Site GetSiteBySiteUrl(string siteUrl)
        {
            Site site = this._siteStructureDao.GetSiteBySiteUrl(siteUrl);

            // Try to resolve the site via SiteAlias
            if (site == null)
            {
                SiteAlias sa = this._siteStructureDao.GetSiteAliasByUrl(siteUrl);
                if (sa != null)
                {
                    site = sa.Site;
                }
            }
            return(site);
        }
Example #12
0
 public override IEnumerable <SiteAlias> Get(CompoundIdentity id, SiteAliasScheme scheme)
 {
     if (!id.IsNullOrEmpty() && scheme != null && !scheme.Identity.IsNullOrEmpty() && this.CanGet())
     {
         NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
         cmd.CommandText = Db.SelectAlias + Db.SelectAliasById + " AND" + Db.WhereCurrent;
         cmd.Parameters.AddWithValue("sid", id.DataStoreIdentity);
         cmd.Parameters.AddWithValue("id", id.Identity);
         cmd.Parameters.AddWithValue("ssid", scheme.Identity.DataStoreIdentity);
         cmd.Parameters.AddWithValue("scid", scheme.Identity.Identity);
         NpgsqlDataReader rdr     = Db.ExecuteReader(cmd);
         List <SiteAlias> schemes = new List <SiteAlias>();
         SiteAlias        o       = null;
         if (rdr != null)
         {
             try
             {
                 while (rdr.Read())
                 {
                     o = SiteAliasBuilder.Instance.Build(rdr);
                     if (o != null)
                     {
                         schemes.Add(o);
                     }
                 }
                 if (cmd.Connection.State == System.Data.ConnectionState.Open)
                 {
                     cmd.Connection.Close();
                 }
             }
             catch
             { }
             finally
             {
                 cmd.Dispose();
             }
         }
         return(schemes);
     }
     return(null);
 }
Example #13
0
        private void rptAliases_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            SiteAlias sa      = (SiteAlias)e.Item.DataItem;
            HyperLink hplEdit = e.Item.FindControl("hplEdit") as HyperLink;

            if (hplEdit != null)
            {
                hplEdit.NavigateUrl = String.Format("~/Admin/SiteAliasEdit.aspx?SiteId={0}&SiteAliasId={1}", this._activeSite.Id, sa.Id);
            }
            Label lblEntryNode = e.Item.FindControl("lblEntryNode") as Label;

            if (lblEntryNode != null)
            {
                if (sa.EntryNode == null)
                {
                    lblEntryNode.Text = "Được thừa kế từ trang";
                }
                else
                {
                    lblEntryNode.Text = sa.EntryNode.Title + " (" + sa.EntryNode.Culture + ")";
                }
            }
        }
Example #14
0
        public override bool Delete(SiteAlias alias)
        {
            if (alias != null && this.CanDelete())
            {
                try
                {
                    NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
                    cmd.CommandText = Db.DeleteAlias + "\"SystemId\"=:sid AND \"Id\"=:id AND \"SchemeSystemId\"=:ssid AND \"SchemeId\"=:scid AND \"Name\"=:n AND" + Db.WhereCurrent;
                    cmd.Parameters.AddWithValue("sid", alias.Identity.DataStoreIdentity);
                    cmd.Parameters.AddWithValue("id", alias.Identity.Identity);
                    cmd.Parameters.AddWithValue("ssid", alias.AliasSchemeIdentity.DataStoreIdentity);
                    cmd.Parameters.AddWithValue("scid", alias.AliasSchemeIdentity.Identity);
                    cmd.Parameters.AddWithValue("n", alias.Name);
                    cmd.Parameters.AddWithValue("end", DateTime.UtcNow);

                    Db.ExecuteNonQuery(cmd);

                    return(true);
                }
                catch
                { }
            }
            return(false);
        }
Example #15
0
        /// <summary>
        /// Load the content and the template as early as possible, so everything is in place before
        /// modules handle their own ASP.NET lifecycle events.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // Set context
            this._currentContext = Container.Resolve <ICuyahogaContext>();

            // Load the current site
            string currentSiteUrl = UrlUtil.GetSiteUrl();

            if (this.CurrentSite == null)
            {
                throw new SiteNullException("No site found at " + currentSiteUrl);
            }

            // Check if we're browsing via an alias. If so get the optional entry node.
            Node entryNode = null;

            if (currentSiteUrl != this.CurrentSite.SiteUrl.ToLower())
            {
                SiteAlias siteAlias = this._siteService.GetSiteAliasByUrl(currentSiteUrl);
                if (siteAlias != null)
                {
                    entryNode = siteAlias.EntryNode;
                }
            }

            // Load the active node
            // Query the cache by SectionId, ShortDescription and NodeId.
            if (Context.Request.QueryString["SectionId"] != null)
            {
                try
                {
                    this._activeSection = this._sectionService.GetSectionById(Int32.Parse(Context.Request.QueryString["SectionId"]));
                    this._activeNode    = this._activeSection.Node;
                }
                catch
                {
                    throw new SectionNullException("Section not found: " + Context.Request.QueryString["SectionId"]);
                }
            }
            else if (Context.Request.QueryString["ShortDescription"] != null)
            {
                this._activeNode = this._nodeService.GetNodeByShortDescriptionAndSite(Context.Request.QueryString["ShortDescription"], this.CurrentSite);
            }
            else if (Context.Request.QueryString["NodeId"] != null)
            {
                this._activeNode = this._nodeService.GetNodeById(Int32.Parse(Context.Request.QueryString["NodeId"]));
            }
            else if (entryNode != null)
            {
                this._activeNode = entryNode;
            }
            else
            {
                // Can't load a particular node, so the root node has to be the active node
                // Maybe we have culture information stored in a cookie, so we might need a different
                // root Node.
                string currentCulture = this.CurrentSite.DefaultCulture;
                if (Context.Request.Cookies["CuyahogaCulture"] != null)
                {
                    currentCulture = Context.Request.Cookies["CuyahogaCulture"].Value;
                }
                this._activeNode = this._nodeService.GetRootNodeByCultureAndSite(currentCulture, this.CurrentSite);
            }
            // Raise an exception when there is no Node found. It will be handled by the global error handler
            // and translated into a proper 404.
            if (this._activeNode == null)
            {
                throw new NodeNullException(String.Format(@"No node found with the following parameters: 
					NodeId: {0},
					ShortDescription: {1},
					SectionId: {2}"
                                                          , Context.Request.QueryString["NodeId"]
                                                          , Context.Request.QueryString["ShortDescription"]
                                                          , Context.Request.QueryString["SectionId"]));
            }
            this._rootNode = this._activeNode.NodePath[0];

            // Set culture
            // TODO: fix this because ASP.NET pages are not guaranteed to run in 1 thread (how?).
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(this._activeNode.Culture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(this._activeNode.Culture);

            // Check node-level security
            if (!this._activeNode.ViewAllowed(this.User.Identity))
            {
                throw new AccessForbiddenException("You are not allowed to view this page.");
            }

            // Check if the active node is a link. If so, redirect to the link
            if (this._activeNode.IsExternalLink)
            {
                Response.Redirect(this._activeNode.LinkUrl);
            }
            else
            {
                if (this._shouldLoadContent)
                {
                    LoadContent();
                    LoadMenus();
                }
            }

            // Check if the current user has access to the manager. If so, add manager toolbar to the template.
            if (this._templateControl != null && CuyahogaContext.Current.CurrentUser != null)
            {
                if (CuyahogaContext.Current.CurrentUser.HasRight(Rights.AccessAdmin))
                {
                    this._templateControl.Form.Controls.AddAt(0, LoadControl("~/Controls/ManagerToolbar.ascx"));
                }
                if (CuyahogaContext.Current.CurrentUser.CanEdit(this.ActiveNode))
                {
                    this._templateControl.Form.Controls.Add(LoadControl("~/Controls/InlineEditing.ascx"));
                }
            }
        }
Example #16
0
        /// <summary>
        /// Load the content and the template as early as possible, so everything is in place before
        /// modules handle their own ASP.NET lifecycle events.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreInit(EventArgs e)
        {
            // Load the current site
            Node      entryNode        = null;
            string    siteUrl          = UrlHelper.GetSiteUrl();
            SiteAlias currentSiteAlias = _siteService.GetSiteAliasByUrl(siteUrl);

            if (currentSiteAlias != null)
            {
                _currentSite = currentSiteAlias.Site;
                entryNode    = currentSiteAlias.EntryNode;
            }
            else
            {
                _currentSite = _siteService.GetSiteBySiteUrl(siteUrl);
            }
            if (_currentSite == null)
            {
                throw new SiteNullException("No site found at " + siteUrl);
            }

            // Load the active node
            // Query the cache by SectionId, ShortDescription and NodeId.
            if (Context.Request.QueryString["SectionId"] != null)
            {
                try
                {
                    _activeSection =
                        _sectionService.GetSectionById(Int32.Parse(Context.Request.QueryString["SectionId"]));
                    _activeNode = _activeSection.Node;
                }
                catch
                {
                    throw new SectionNullException("Section not found: " + Context.Request.QueryString["SectionId"]);
                }
            }
            else if (Context.Request.QueryString["ShortDescription"] != null)
            {
                _activeNode =
                    _nodeService.GetNodeByShortDescriptionAndSite(Context.Request.QueryString["ShortDescription"],
                                                                  _currentSite);
            }
            else if (Context.Request.QueryString["NodeId"] != null)
            {
                _activeNode = _nodeService.GetNodeById(Int32.Parse(Context.Request.QueryString["NodeId"]));
            }
            else if (entryNode != null)
            {
                _activeNode = entryNode;
            }
            else
            {
                // Can't load a particular node, so the root node has to be the active node
                // Maybe we have culture information stored in a cookie, so we might need a different
                // root Node.
                string currentCulture = _currentSite.DefaultCulture;
                if (Context.Request.Cookies["CuyahogaCulture"] != null)
                {
// ReSharper disable PossibleNullReferenceException
                    currentCulture = Context.Request.Cookies["CuyahogaCulture"].Value;
// ReSharper restore PossibleNullReferenceException
                }
                _activeNode = _nodeService.GetRootNodeByCultureAndSite(currentCulture, _currentSite);
            }
            // Raise an exception when there is no Node found. It will be handled by the global error handler
            // and translated into a proper 404.
            if (_activeNode == null)
            {
                throw new NodeNullException(
                          String.Format(
                              @"No node found with the following parameters: 
					NodeId: {0},
					ShortDescription: {1},
					SectionId: {2}"
                              , Context.Request.QueryString["NodeId"]
                              , Context.Request.QueryString["ShortDescription"]
                              , Context.Request.QueryString["SectionId"]));
            }
            _rootNode = _activeNode.NodePath[0];

            // Set culture
            // TODO: fix this because ASP.NET pages are not guaranteed to run in 1 thread (how?).
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(_activeNode.Culture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(_activeNode.Culture);

            // Check node-level security
            if (!_activeNode.ViewAllowed(User.Identity))
            {
                throw new AccessForbiddenException("You are not allowed to view this page.");
            }

            if (_shouldLoadContent)
            {
                LoadContent();
                LoadMenus();
            }
            base.OnPreInit(e);
        }
Example #17
0
        public static void Handle(UserSecurityContext user, string method, HttpContext context, CancellationToken cancel)
        {
            if (context.Request.Method == "POST")
            {
                if (method.Equals("all", StringComparison.OrdinalIgnoreCase))
                {
                    Get(user, context, cancel);
                    return;
                }
                else if (method.Equals("find", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        JToken token = JsonUtils.GetDataPayload(context.Request);
                        if (token != null)
                        {
                            if (token["id"] != null && token["schemeid"] != null)
                            {
                                GetBySiteAndScheme(JsonUtils.ToId(token["id"]), JsonUtils.ToId(token["schemeid"]), user, context, cancel);
                                return;
                            }
                            else if (token["id"] != null && token["name"] != null)
                            {
                                GetBySiteAndName(JsonUtils.ToId(token["id"]), token["name"].ToString(), user, context, cancel);
                                return;
                            }
                            else if (token["schemeid"] != null && token["name"] != null)
                            {
                                GetBySchemeAndName(JsonUtils.ToId(token["schemeid"]), token["name"].ToString(), user, context, cancel);
                                return;
                            }
                            else if (token["schemeid"] != null)
                            {
                                GetByScheme(JsonUtils.ToId(token["schemeid"]), user, context, cancel);
                                return;
                            }
                            else if (token["id"] != null)
                            {
                                GetBySite(JsonUtils.ToId(token["id"]), user, context, cancel);
                                return;
                            }
                            else if (token["name"] != null)
                            {
                                GetByName(token["name"].ToString(), user, context, cancel);
                                return;
                            }
                        }

                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                    }
                    catch
                    {
                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                        return;
                    }
                }
                else if (method.Equals("create", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        //token and providers
                        JToken token = JsonUtils.GetDataPayload(context.Request);
                        SiteAliasProviderBase       alias_provider  = SiteManager.Instance.GetSiteAliasProvider(user);
                        SiteProviderBase            site_provider   = SiteManager.Instance.GetSiteProvider(user);
                        SiteAliasSchemeProviderBase scheme_provider = SiteManager.Instance.GetSiteAliasSchemeProvider(user);
                        if (alias_provider != null && scheme_provider != null && site_provider != null && token != null)
                        {
                            //required
                            string          name   = token["name"].ToString();
                            SiteAliasScheme scheme = scheme_provider.Get(JsonUtils.ToId(token["schemeid"]));
                            Site            site   = site_provider.Get(JsonUtils.ToId(token["id"]));
                            if (site != null && scheme != null && !string.IsNullOrEmpty(name))
                            {
                                //create object
                                SiteAlias alias = alias_provider.Create(scheme, site, name);
                                if (alias != null)
                                {
                                    JObject jalias = Jsonifier.ToJson(alias);
                                    if (jalias != null)
                                    {
                                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok, jalias.ToString()));
                                    }
                                    else
                                    {
                                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    }
                                    return;
                                }
                            }
                        }

                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                    }
                    catch
                    {
                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                        return;
                    }
                }
                else if (method.Equals("update", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        //token and providers
                        JToken token = JsonUtils.GetDataPayload(context.Request);
                        SiteAliasProviderBase       alias_provider  = SiteManager.Instance.GetSiteAliasProvider(user);
                        SiteProviderBase            site_provider   = SiteManager.Instance.GetSiteProvider(user);
                        SiteAliasSchemeProviderBase scheme_provider = SiteManager.Instance.GetSiteAliasSchemeProvider(user);
                        if (alias_provider != null && scheme_provider != null && site_provider != null && token != null)
                        {
                            //required fields
                            CompoundIdentity site_id   = JsonUtils.ToId(token["id"]);
                            Site             site      = site_provider.Get(site_id);
                            CompoundIdentity scheme_id = JsonUtils.ToId(token["schemeid"]);
                            SiteAliasScheme  scheme    = scheme_provider.Get(scheme_id);
                            string           old_name  = token["name"].ToString();
                            string           new_name  = token["newname"].ToString();
                            if (site != null && scheme == null && !string.IsNullOrEmpty(old_name) && !string.IsNullOrEmpty(new_name))
                            {
                                //retrieve by site, scheme
                                IEnumerable <SiteAlias> aliases = alias_provider.Get(site_id, scheme);
                                if (aliases == null)
                                {
                                    //match alias by name (an org could have multiple aliases in the same scheme, but they must be unique)
                                    SiteAlias alias = null;
                                    foreach (SiteAlias a in aliases)
                                    {
                                        if (a.Name == old_name)
                                        {
                                            alias = a;
                                        }
                                    }
                                    alias.Name = new_name;
                                    bool result = alias_provider.Update(alias);
                                    if (result == true)
                                    {
                                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok));
                                        return;
                                    }
                                }
                            }
                        }

                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                    }
                    catch
                    {
                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                        return;
                    }
                }
                else if (method.Equals("delete", StringComparison.OrdinalIgnoreCase))
                {
                    CompoundIdentity scheme_id = null;
                    CompoundIdentity site_id   = null;
                    SiteAliasScheme  scheme    = null;
                    Site             site      = null;
                    string           name      = null;

                    try
                    {
                        //token and providers
                        JToken token = JsonUtils.GetDataPayload(context.Request);
                        SiteAliasProviderBase       alias_provider  = SiteManager.Instance.GetSiteAliasProvider(user);
                        SiteProviderBase            site_provider   = SiteManager.Instance.GetSiteProvider(user);
                        SiteAliasSchemeProviderBase scheme_provider = SiteManager.Instance.GetSiteAliasSchemeProvider(user);
                        if (alias_provider != null && scheme_provider != null && site_provider != null && token != null)
                        {
                            //If a token is provided, it cannot be null
                            //Checking values against intent avoids firing a degenerate delete override

                            //schemeid
                            if (token.SelectToken("schemeid") != null)
                            {
                                if (token["schemeid"] == null)
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                                else
                                {
                                    scheme_id = JsonUtils.ToId(token["schemeid"]);
                                    scheme    = scheme_provider.Get(scheme_id);
                                }
                            }

                            //id
                            if (token.SelectToken("id") != null)
                            {
                                if (token["id"] == null)
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                                else
                                {
                                    site_id = JsonUtils.ToId(token["id"]);
                                    site    = site_provider.Get(site_id);
                                }
                            }

                            //name
                            if (token.SelectToken("name") != null)
                            {
                                if (token["name"] == null)
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                                else
                                {
                                    name = token["name"].ToString();
                                }
                            }

                            //determine override
                            bool result = false;
                            if (scheme != null && site != null && name != null)    //delete specific alias
                            {
                                //don't have a provider method that returns specific alias, so get by site, scheme and match alias by name (most of the time a single alias will be returned)
                                IEnumerable <SiteAlias> aliases = alias_provider.Get(site_id, scheme);
                                if (aliases != null)
                                {
                                    foreach (SiteAlias alias in aliases)
                                    {
                                        if (alias.Name == name)
                                        {
                                            result = alias_provider.Delete(alias);
                                            break;                                          //aliases should be unique for a given site in a given scheme
                                        }
                                    }
                                }
                            }
                            else if (scheme != null && site_id != null)
                            {
                                result = alias_provider.Delete(site_id, scheme);       //delete * for given site in a given scheme (could be multiple)
                            }
                            else if (scheme != null)
                            {
                                result = alias_provider.Delete(scheme);                //delete * for a given scheme (across orgs)
                            }
                            else if (site_id != null)
                            {
                                result = alias_provider.Delete(site_id);               //delete * for a given org (across schemes)
                            }
                            if (result == true)
                            {
                                RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok));
                                return;
                            }
                        }

                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                    }
                    catch
                    {
                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                        return;
                    }
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Example #18
0
 public override bool CanUpdate(SiteAlias alias)
 {
     return(this.CanUpdate()); //TODO -- add fine grained security
 }
Example #19
0
 public override bool CanDelete(SiteAlias scheme)
 {
     return(this.CanDelete()); //TODO -- add fine grained security
 }