Monday, April 23, 2012

Hide links pointing to other site collections

We know that "Global navigation" and "Current navigation" hide links if the current user doesn't have access rights.  However, this only happens if the "links" in part of the current site collection. So what we should do if need to hide links which pointing to other site collections?

My solutions is checking the "HttpWebResponse" of that link. Below is the sample code:


private bool GetHttpStatus(string strUrl)
        {
            HttpWebRequest request = null;
            bool returnStatus = false;


            try
            {
                if (strUrl != null && strUrl != string.Empty)
                {
                    Uri uri = new Uri(strUrl);
                    request = (HttpWebRequest)HttpWebRequest.Create(uri);
                    request.Method = "GET";
                    request.KeepAlive = true;
                    request.Accept = @"*/*";
                    request.AllowAutoRedirect = true;


                    request.UseDefaultCredentials = true;
                    request.PreAuthenticate = true;
                    request.Credentials = CredentialCache.DefaultCredentials;


                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        returnStatus = true;
                    }
                }
            }
            //401 status codes with throw an exception in this code
            catch (System.Net.WebException ex)
            {
                returnStatus = false;
            }
            catch (System.Exception ex)
            {
                returnStatus = false;
            }


            return returnStatus;
        }

Then we can alter the SPView to display proper items in a list view web part.


if (CheckPermission)
                            {
                                strOriginalQuery = objSPView.Query;
                                strPermissionQuery = GetNewQueryBasedOnAccessPermissions(objSPView);
                                strFinalQuery = GetFinalQuery(strOriginalQuery, strPermissionQuery);
                                objSPView.Query = strFinalQuery;
                            }


                            strHtml = objSPView.RenderAsHtml(false, false, ListViewUrl);


I have added this feature to an open source web part, and you are welcome to have a look.

http://efspwebparts.codeplex.com/releases/view/86485

No comments:

Post a Comment