protected void Page_Load(object sender, EventArgs e)
 {
     SPWeb web = SPContext.Current.Web;
     currentUser = web.CurrentUser;
     Response.Write("Current SharePoint user: "******"<BR/>");
     loadList();
 }
 // Gets the login name of the Livelink user that the specified SharePoint user maps to.
 public string GetLoginName(SPUser user) {
     if (user == null)
         throw new ArgumentNullException("user");
     // SPUser.LoginName contains domain\user for web applications with the pure Windows
     // authentication but if the claim-based authentication is used it returns an encoded
     // claim that must be decoded to the actual user login name first.
     var claim = SPClaimProviderManager.Local.ConvertSPUserToClaim(user);
     string login;
     if (SPClaimTypes.Equals(claim.ClaimType, SPClaimTypes.UserLogonName) ||
         SPClaimTypes.Equals(claim.ClaimType,
             "http://schemas.microsoft.com/sharepoint/2009/08/claims/processidentitylogonname")) {
         login = claim.Value;
     } else if (SPClaimTypes.Equals(claim.ClaimType, SPClaimTypes.UserIdentifier) ||
          SPClaimTypes.Equals(claim.ClaimType,
              "http://schemas.microsoft.com/sharepoint/2009/08/claims/processidentitysid") ||
          SPClaimTypes.Equals(claim.ClaimType,
              "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid")) {
         var identifier = new SecurityIdentifier(claim.Value);
         login = identifier.Translate(typeof(NTAccount)).Value;
     } else {
         throw new ApplicationException(
             "No claim with either user name or SID was found to infer the login name from.");
     }
     // Here we assume either plain user name or a combination with the Windows domain.
     var parts = login.Split('\\');
     var name = parts.Length > 1 ? parts[1] : login;
     var domain = parts.Length > 1 ? parts[0] : "";
     return Pattern.ReplaceParameter("login", login).ReplaceParameter("user", name).
         ReplaceParameter("domain", domain);
 }
        private void AddAgendaToMeetingWorkspace(SPWeb boardWeb, string meetingWorkspaceURL, string agendaTitle, SPUser sponsor, int agendaID, string presenterName, int agendaOrder)
        {
            SPFieldUrlValue workspaceURL = new SPFieldUrlValue(meetingWorkspaceURL);

               SPMeeting meetingSites = SPMeeting.GetMeetingInformation(boardWeb);
               SPWebCollection meetingWorkspaces = meetingSites.GetWorkspacesToLinkTo(false);

               SPWeb meetingWeb = null;
               foreach (SPWeb meetingWorkspace in meetingWorkspaces)
               {
               if (workspaceURL.Url.Contains(meetingWorkspace.Url))
               {
                   meetingWeb = meetingWorkspace;
                   break;
               }
               }

               SPList agendaList = meetingWeb.Lists["Agenda"];
               SPListItem newAgenda = agendaList.AddItem();
               boardWeb.EnsureUser(sponsor.LoginName);
               SPUser user = boardWeb.AllUsers[sponsor.LoginName];
               newAgenda["Sponsor"] = user;
               newAgenda["Subject"] = agendaTitle;
               newAgenda["AgendaID"] = agendaID;
               newAgenda["Owner"] = presenterName;
               newAgenda["Item Number"] = agendaOrder;
               newAgenda.Update();
        }
        private void GiveUserPrivelegesToWorkspace(SPUser user, SPItemEventProperties properties)
        {
            InitializeWebAppProperties(properties);
            string workspaceURL = properties.Web.ServerRelativeUrl;
            //workspaceURL = workspaceURL.Remove(0, emisSiteURL.Length);
            workspaceURL = workspaceURL.Substring(workspaceURL.IndexOf("Agenda-"));

            using (SPSite emisSite = new SPSite(emisSiteURL))
            {
                using (SPWeb currentWorkspace = emisSite.OpenWeb(workspaceURL))
                {
                    currentWorkspace.AllowUnsafeUpdates = true;

                    SPRoleAssignment role;

                    role = new SPRoleAssignment(currentWorkspace.EnsureUser(user.LoginName));

                    role.RoleDefinitionBindings.Add(currentWorkspace.RoleDefinitions["Restricted Contribute"]);

                    currentWorkspace.RoleAssignments.Add(role);
                    currentWorkspace.AllowUnsafeUpdates = false;
                    currentWorkspace.Update();
                }
            }
        }
        public void DeleteByAuthor(SPWeb web, SPUser author)
        {
            var item = GetItemByAuthor(web, author);
            if(item == null)
                return;

            item.Delete();
        }
        public void Unsubscribe(SPWeb web, SPUser user)
        {
            var isAlreadySubscribed = _repository.GetByAuthor(web, user) != null;
            if(!isAlreadySubscribed)
                return;

            _repository.DeleteByAuthor(web, user);
        }
Example #7
0
        /// <summary>
        /// Gets the user project leader.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="context">The context.</param>
        /// <returns>The Project Leader SPUser object.</returns>
        public static SPUser GetUserProjectLeader(SPUser user, SPServiceContext serviceContext, SPContext context)
        {
            return context.Web.AllUsers["fp\\fps_pm"];

            UserProfileManager manager = new UserProfileManager(serviceContext);
            var userProfile = manager.GetUserProfile(user.LoginName);
            var projectLeaderProfile = userProfile.GetManager();
            return context.Web.AllUsers[projectLeaderProfile.MultiloginAccounts[0]];
        }
        public EventsCalendarSubscriberEntity GetByAuthor(SPWeb web, SPUser author)
        {
            var item = GetItemByAuthor(web, author);
            if (item == null) 
                return null;

            var subscriber = MapItemToEntity(item);
            return subscriber;
        }
        public void Update(SPWeb web, string email, IEnumerable<string> targets, bool notifyOfNewEvents, SPUser author)
        {
            var subscriber = GetByAuthor(web, author);
            if (subscriber == null)
                throw new InvalidOperationException(string.Format("Cannot find subscription for user '{0} ({1})'.",
                                                                  author.Name, email));

            Update(web, subscriber, email, targets, notifyOfNewEvents, author);
        }
Example #10
0
 private static UserDetail GetUserDetail(SPUser user, UserProfile profile)
 {
     UserDetail userDetail = new UserDetail();
     userDetail.Email = GetPropertyValue(profile, "WorkEmail");
     userDetail.LoginName = user.LoginName;
     userDetail.FirstName = GetPropertyValue(profile, "FirstName");
     userDetail.LastName = GetPropertyValue(profile, "LastName");
     userDetail.Name = user.Name;
     return userDetail;
 }
Example #11
0
        public UserNode(object parent, SPUser user)
        {
            this.Tag = user;
            this.SPParent = parent;
            //this.ContextMenuStrip = new SiteMenuStrip();

            Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
        private SPListItem GetItemByAuthor(SPWeb web, SPUser author)
        {
            Expression<Func<SPListItem, bool>> authorCondition =
                item => item[EventsCalendarSubscriberFields.Author] == (DataTypes.UserId) (author.ID.ToString());
            var items = Query(web, authorCondition);

            if (items.Count == 0)
                return null;

            return items[0];
        }
        public IEnumerable<TaskListItemViewModel> GetLastTasksForUser(SPSite rootOfSearch, SPUser user, int count)
        {
            DataTable dataTable = new SPSiteDataQueryExecutor(
                                "<Lists ServerTemplate=\"107\" />",
                                @"<FieldRef Name=""ID"" /><FieldRef Name=""Title"" /><FieldRef Name=""Status"" /><FieldRef Name=""GUID"" /><FieldRef Name=""DueDate"" /><FieldRef Name=""StartDate"" /><FieldRef Name=""Priority"" />",
                                string.Format(@"<OrderBy><FieldRef Name=""Created"" Ascending=""false"" /></OrderBy><Where><Eq><FieldRef Name='AssignedTo' /><Value Type='Text'>{0}</Value></Eq></Where>", user.Name),
                                "<Webs Scope='SiteCollection'>",
                                count).ExecuteQuery(rootOfSearch.RootWeb);

            var result = _resultMapper.Map(dataTable);
            return result;
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserValue"/> class.
        /// </summary>
        /// <param name="user">The user.</param>
        public UserValue(SPUser user)
            : base(user)
        {
            this.Email = user.Email;
            this.IsDomainGroup = user.IsDomainGroup;
            this.IsSiteAdmin = user.IsSiteAdmin;
            this.IsSiteAuditor = user.IsSiteAuditor;
            this.Notes = user.Notes;
            this.Sid = user.Sid;

            // If the user doesn't have any regional settings of his own, that means he's defaulting to the current Web's settings
            this.RegionalSettings = new RegionalSettings(user.RegionalSettings ?? user.ParentWeb.RegionalSettings);
        }
        public void Subscribe(SPWeb web, string email, IEnumerable<string> targets, bool notifyOfNewEvents, SPUser author)
        {
            var subscriber = _repository.GetByAuthor(web, author);

            var isAlreadySubscribed = subscriber != null;
            if (isAlreadySubscribed)
            {
                Update(web, subscriber, email, targets, notifyOfNewEvents, author);
                return;
            }

            subscriber = MapToEntity(email, targets, notifyOfNewEvents, author);
            _repository.Create(web, subscriber);
        }
Example #16
0
        /// <summary>
        /// Determines whether The specified user is part of the specified SharePoint user group.
        /// This method will also check users in the active directory groups if any are in the SharePoint group.
        /// </summary>
        /// <param name="user">The SharePoint user.</param>
        /// <param name="group">The SharePoint group.</param>
        /// <returns>True if the user is part of the specified group.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// user or group is null
        /// </exception>
        public bool IsUserInGroup(SPUser user, SPGroup group)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (group == null)
            {
                throw new ArgumentNullException("group");
            }

            var usersInGroup = this.GetUsersInPrincipal(group);
            return HasUserInList(usersInGroup, user);
        }
Example #17
0
        public static List<EmailVariable> GetAndSetVariablesFromTemplate(string strInput, SPListItem sourceListItem, SPListItem taskItem, SPUser user)
        {
            List<EmailVariable> list = new List<EmailVariable>();
            List<string> variables = new List<string>();
            variables = extractVariables(strInput);

            foreach (string variable in variables)
            {
                EmailVariable var = new EmailVariable(variable);
                SetVariableValuesFromItem(var, sourceListItem, taskItem, user);
                list.Add(var);
            }

            return list;
        }
Example #18
0
 /// <summary>
 /// This method is used to check for the Administrator and then enable/disable the controls accordingly
 /// </summary>
 private void ConfigureControls()
 {
     currentUser = Web.CurrentUser;
     if (!currentUser.IsSiteAdmin)
     {
         dropdownList.Enabled = false;
         btnUpdate.Enabled = false;
     }
     else
     {
         dropdownList.Enabled = true;
         btnUpdate.Enabled = true;
     }
     if (!Page.IsPostBack)
     {
         var propertyValue = Web.Properties[IsBlankSiteProperty];
         dropdownList.SelectedValue = string.Equals(propertyValue ?? "0", "1") ? "1" : "0";
     }
 }
        public static bool IsUserMemberOfGroup(SPUser user, string groupName)
        {
            bool result = false;

            if (!String.IsNullOrEmpty(groupName) && user != null)
            {
                foreach (SPGroup group in user.Groups)
                {
                    if (group.Name == groupName)
                    {
                        // found it
                        result = true;
                        break;
                    }
                }
            }

            return result;
        }
        public static SPFieldUserValue Convert2Account(string userId)
        {
            SPFieldUserValue uservalue = null;

            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPUser requireduser = web.EnsureUser(userId);
                        uservalue = new SPFieldUserValue(web, requireduser.ID, requireduser.LoginName);
                    }
                }
            }
            catch (Exception ex)
            {
                LogMessage(ex, string.Format("Unable to resolve the user with ID {0} in Methods.Convert2Account", userId));
            }
            return(uservalue);
        }
Example #21
0
        private static bool WhereUser(string condition, string group)
        {
            SPUser            user       = SPContext.Current.Web.CurrentUser;
            SPGroupCollection userGroups = user.Groups;
            bool userInGroup             = false;

            foreach (SPGroup groupItem in userGroups)
            {
                if (groupItem.Name.Equals(group))
                {
                    userInGroup = true;
                    continue;
                }
            }

            if (condition.Equals("IsInGroup"))
            {
                return(userInGroup);
            }
            return(!userInGroup);
        }
        public void TestAddUserToSPSite()
        {
            SPSite site = new SPSite(_newSPSiteUrl);

            // verify that this user is not already part of the site.
            try {
                SPUser user1 = site.RootWeb.AllUsers[_newUserLogin];
                Assertion.Fail("The user should not be found in the new site");
            }
            catch (Exception ignored) {
                // this is the exptected response
            }

            string result = result = RunBuild(String.Format(CultureInfo.InvariantCulture,
                                                            _xmlProjectTemplate, _newSPSiteUrl, "true", _newUserLogin, _validRole));

            // Verify that the user was added.
            SPUser user2 = site.RootWeb.AllUsers[_newUserLogin];

            Assertion.AssertNotNull(user2);
        }
Example #23
0
        private void AssignPermissionLevelsToNonSharePointGroup(SPWeb web, string name, IList <string> levels)
        {
            foreach (string level in levels)
            {
                if (level == "Limited Access")
                {
                    continue;
                }

                try
                {
                    SPUser           user           = web.EnsureUser(name);
                    SPRoleAssignment roleAssignment = new SPRoleAssignment(user);
                    roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[level]);
                    web.RoleAssignments.Add(roleAssignment);
                }
                catch
                {
                }
            }
        }
Example #24
0
        private SPUser GetProfileUser(SPSite site, bool revertSystemAccount, SPUser user)
        {
            string loginName   = user.LoginName;
            SPUser ensuredUser = user;

            if (!IsSharePointSystemAccount(loginName) || !revertSystemAccount)
            {
                return(ensuredUser);
            }

            bool originalAllowUnsafeUpdatesFlag = site.RootWeb.AllowUnsafeUpdates;

            site.RootWeb.AllowUnsafeUpdates = true;

            loginName   = site.WebApplication.ApplicationPool.Username;
            ensuredUser = site.RootWeb.EnsureUser(loginName);

            site.RootWeb.AllowUnsafeUpdates = originalAllowUnsafeUpdatesFlag;

            return(ensuredUser);
        }
Example #25
0
        private void SetPermissionsForWeb(string loginName, e.Permission p, SPWeb web)
        {
            using (SPSite esite = new SPSite(web.Site.ID))
            {
                using (SPWeb eweb = esite.OpenWeb(web.ID))
                {
                    eweb.AllowUnsafeUpdates = true;

                    SPUser user = eweb.EnsureUser(loginName);
                    if (p.SharePointGroup == null)
                    {
                        SPRoleAssignment ra = new SPRoleAssignment(user);

                        foreach (string level in p.PermissionLevels.Split(';'))
                        {
                            if (level == "Limited Access")
                            {
                                SkippedPermissions = true;
                            }
                            else
                            {
                                ra.RoleDefinitionBindings.Add(eweb.RoleDefinitions[level.Trim()]);
                            }
                        }

                        if (ra.RoleDefinitionBindings.Count > 0)
                        {
                            eweb.RoleAssignments.Add(ra);
                        }
                    }
                    else
                    {
                        eweb.Groups[p.SharePointGroup.Name].AddUser(user);
                    }

                    eweb.AllowUnsafeUpdates = false;
                    eweb.Update();
                }
            }
        }
Example #26
0
        /// <summary>
        ///   Get multiple people information from people editor control
        /// </summary>
        /// <remarks>
        ///     References: http://kancharla-sharepoint.blogspot.com.au/2012/10/sometimes-we-need-to-get-all-people-or.html
        /// </remarks>
        /// <param name="people"></param>
        /// <param name="web"></param>
        /// <returns></returns>
        public SPFieldUserValueCollection GetPeopleFromPickerControl(PeopleEditor people, SPWeb web)
        {
            SPFieldUserValueCollection values = new SPFieldUserValueCollection();

            try
            {
                if (people.ResolvedEntities.Count > 0)
                {
                    for (int i = 0; i < people.ResolvedEntities.Count; i++)
                    {
                        PickerEntity user = (PickerEntity)people.ResolvedEntities[i];

                        switch ((string)user.EntityData["PrincipalType"])
                        {
                        case "User":
                            SPUser           webUser   = web.EnsureUser(user.Key);
                            SPFieldUserValue userValue = new SPFieldUserValue(web, webUser.ID, webUser.Name);
                            values.Add(userValue);
                            break;

                        case "SharePointGroup":
                            SPGroup          siteGroup  = web.SiteGroups[user.EntityData["AccountName"].ToString()];
                            SPFieldUserValue groupValue = new SPFieldUserValue(web, siteGroup.ID, siteGroup.Name);
                            values.Add(groupValue);
                            break;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, web);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at GetPeopleFromPickerControl function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }

            return(values);
        }
Example #27
0
        /// <summary>Enumerates a domain group.</summary>
        public override DomainGroupEnumeratorResults EnumerateGroup(SPUser domainGroup, SPWeb web, TimeSpan timeRemaining, bool hideDisabledUsers)
        {
            DomainGroupEnumeratorResults results     = new DomainGroupEnumeratorResults();
            ICollection <SPUserInfo>     spUserInfos = new List <SPUserInfo>();

            try
            {
                DomainGroupUtilities enumerateDomainGroups = new DomainGroupUtilities(timeRemaining, hideDisabledUsers);
                spUserInfos = enumerateDomainGroups.EnumerateDomainGroup(domainGroup);

                foreach (string error in enumerateDomainGroups.Errors)
                {
                    results.Errors.Add(error);
                }
            }
            catch (DomainGroupEnumerationException exception)
            {
                results.Errors.Add(exception.Message);
                if (exception.InnerException != null)
                {
                    results.DetailedExceptions.Add(exception.InnerException);
                }
            }

            foreach (SPUserInfo spUserInfo in spUserInfos)
            {
                try
                {
                    SPUser spUserInGroup = web.EnsureUser(spUserInfo.LoginName);
                    results.Users.Add(spUserInGroup);
                }
                catch (SPException exception)
                {
                    SlkCulture culture = new SlkCulture();
                    results.Errors.Add(string.Format(culture.Culture, culture.Resources.ErrorCreatingSPSiteUser, web.Site.Url, exception));
                }
            }

            return(results);
        }
Example #28
0
        //返回新建项目的Id
        private void WritePerform(float intRadio, PickerEntity picker)
        {
            string siteUrl      = SPContext.Current.Site.Url;
            SPUser appraiseUser = SPContext.Current.Web.CurrentUser;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(siteUrl)) //找到网站集
                {
                    using (SPWeb spWeb = spSite.OpenWeb(SPContext.Current.Web.ID))
                    {
                        SPList spList = spWeb.Lists.TryGetList(webObj.ResultList);

                        if (spList != null)
                        {
                            spWeb.AllowUnsafeUpdates = true;
                            SPListItem listItem;
                            if (ViewState["id"] == null)
                            {
                                string ID = Page.Request.QueryString["ID"];
                                listItem  = spList.AddItem();
                                listItem[GetTitleDispName] = ID;// + ";#" + strPerformance;
                            }

                            else
                            {
                                int id   = int.Parse(ViewState["id"].ToString());
                                listItem = spList.Items.GetItemById(id);
                            }
                            listItem[GetAuthorDispName] = GetUserValue(spWeb, picker); //用户填写的
                            listItem [GetRadioDispName] = intRadio;                    //系数
                            listItem["动作"]  = webObj.CurrentAction;
                            listItem["创建者"] = appraiseUser.ID;                         // + ";#" + appraiseUser.Name;//当前用户
                            listItem.Update();
                            spWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }
Example #29
0
        private int GetSiteFollowedCount()
        {
            SPUser user    = SPContext.Current.Web.CurrentUser;
            string siteUrl = SPContext.Current.Web.Url;
            int    i       = 0;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.Url))
                {
                    SPServiceContext contexto = SPServiceContext.GetContext(currentSite);

                    UserProfileManager perfiles = new UserProfileManager(contexto);

                    foreach (UserProfile userProfile in perfiles)
                    {
                        try
                        {
                            //Check if the user profile is already created
                            if (userProfile.PersonalSiteInstantiationState == PersonalSiteInstantiationState.Created)
                            {
                                SPSocialFollowingManager followingManager = new SPSocialFollowingManager(userProfile, contexto);

                                SPSocialActor[] followedUserSites = followingManager.GetFollowed(SPSocialActorTypes.Sites);

                                SPSocialActor matchSite = followedUserSites.Where(st => st.Uri.AbsoluteUri.Contains(siteUrl)).SingleOrDefault();
                                if (matchSite != null)
                                {
                                    i = i + 1;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            });
            return(i);
        }
Example #30
0
        protected void btnIncluir_Click(object sender, EventArgs e)
        {
            if (pppAdd.ResolvedEntities.Count <= 0)
            {
                return;                                     //nenhum usuario selecionado
            }
            foreach (Microsoft.SharePoint.WebControls.PickerEntity Pessoa in pppAdd.ResolvedEntities)
            {
                //verifica se o usuario já foi adicionado na reunião
                if ((from SPListItem u in objWrapper.RetornaLista("ParticipantesReuniao", new string[] { "id_usuario", "Title" }, SPContext.Current.Web.ID)
                     where
                     u.Title == this.cboReunioes.SelectedItem.Value.ToString() &&
                     u["id_usuario"].ToString() == Pessoa.Key
                     select u).Count() == 0)
                {
                    //monta o dicionario de valores
                    Dictionary <string, object> dicItem = new Dictionary <string, object>();

                    dicItem.Add("id_usuario", Pessoa.Key);
                    dicItem.Add("Title", this.cboReunioes.SelectedItem.Value.ToString());

                    //Carrega a pessoa
                    SPUser usrP =
                        SPContext.Current.Web.EnsureUser(Pessoa.Key);


                    // dicItem.Add("Participante",  (new SPFieldUserValue(SPContext.Current.Web, Convert.ToInt32(Pessoa.EntityData["SPUserID"]), Pessoa.Key))  );
                    dicItem.Add("Participante", (new SPFieldUserValue(SPContext.Current.Web, usrP.ID, Pessoa.Key)));

                    objWrapper.AdicionaItemLista("ParticipantesReuniao", dicItem);
                }
            }


            //Limpa o epp
            pppAdd.ResolvedEntities.Clear();

            //força a atualização do grid
            grid.DataBind();
        }
Example #31
0
        private void RemoveAlerts(XmlNode siteNode, string url)
        {
            using (SPWeb web = new SPSite(url).OpenWeb())
            {
                SPClaimProviderManager cpm = SPClaimProviderManager.Local;
                SPClaim userClaim          = cpm.ConvertIdentifierToClaim("emirates\\s717981", SPIdentifierTypes.WindowsSamAccountName);
                SPUser  tempUser           = web.EnsureUser(userClaim.ToEncodedString());

                web.AllowUnsafeUpdates = true;
                try
                {
                    SPAlertCollection allAlerts = web.Alerts;

                    List <Guid> alertsToDelete = new List <Guid>();

                    foreach (SPAlert spAlert in allAlerts)
                    {
                        alertsToDelete.Add(spAlert.ID);
                    }

                    Guid [] alerts = alertsToDelete.ToArray();
                    for (int i = 0; i < alerts.Length; i++)
                    {
                        SPAlert alert = allAlerts[alerts[i]];
                        alert.User   = tempUser;
                        alert.Status = SPAlertStatus.Off;
                        alert.Update();
                    }

                    foreach (Guid alertGuid in alertsToDelete)
                    {
                        allAlerts.Delete(alertGuid);
                    }

                    web.Update();
                }
                catch (Exception ex) { Console.WriteLine(ex.Message); }
                web.AllowUnsafeUpdates = false;
            }
        }
Example #32
0
        public static void CreateSiteBySiteTemplate(string url, string webName, string webDescription, string templateName)
        {
            string loginName = GetLoginAccountWithDomain;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site            = new SPSite(SPContext.Current.Site.Url);
                SPWeb web              = site.OpenWeb();
                web.AllowUnsafeUpdates = true;
                //= "subsite1";//创建后的站点是:http://moss:5001/subsite1
                if (!web.Webs[webName].Exists)
                {
                    //1.根据网站模版,创建网站
                    //= "SubSiteTemplate";//网站模版定义
                    SPWebTemplate CustomTemplate           = null;
                    SPWebTemplateCollection subWebTemplate = web.GetAvailableWebTemplates((uint)web.Locale.LCID);
                    foreach (SPWebTemplate template in subWebTemplate)
                    {
                        if (template.Title == templateName)
                        {
                            CustomTemplate = template;
                            break;
                        }
                    }
                    SPWeb NewWeb = web.Webs.Add(url, webName, webDescription, (uint)2052, CustomTemplate, true, false);
                    NewWeb.AllowUnsafeUpdates = true;
                    //2.给创建好的网站分配权限,
                    //2.1断开网站权限
                    NewWeb.BreakRoleInheritance(false);
                    //2.2添加网站的"完全控制"权限.
                    SPUser user = web.EnsureUser(loginName);
                    SPRoleAssignment MyRoleAssignment = new SPRoleAssignment(user);
                    MyRoleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Administrator));
                    NewWeb.RoleAssignments.Add(MyRoleAssignment);
                    NewWeb.Update();
                }
                web.Update();
                web.Dispose();
            });
        }
Example #33
0
        public static bool canUserImpersonate(string curuser, string iuser, SPWeb web, out string resName)
        {
            resName = "";
            bool   impersonate = false;
            string resUrl      = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL", true, false);

            //using (SPSite site = new SPSite(resUrl))
            using (SPSite site = new SPSite(resUrl))
            {
                //using (SPWeb rweb = site.OpenWeb())
                using (SPWeb rweb = site.OpenWeb())
                {
                    SPList rlist = rweb.Lists["Resources"];
                    SPUser u     = rweb.SiteUsers[curuser];

                    SPQuery query = new SPQuery();
                    query.Query = "<Where><Eq><FieldRef Name=\"TimesheetDelegates\" LookupId='True'/><Value Type=\"User\">" + u.ID + "</Value></Eq></Where><OrderBy><FieldRef Name=\"Title\"/></OrderBy>";

                    SPListItemCollection lic = rlist.GetItems(query);

                    if (lic.Count > 0)
                    {
                        foreach (SPListItem li in lic)
                        {
                            try
                            {
                                SPFieldUserValue uv = new SPFieldUserValue(web, li["SharePointAccount"].ToString());
                                if (System.Web.HttpUtility.UrlDecode(iuser).ToLower() == uv.User.LoginName.ToLower())
                                {
                                    impersonate = true;
                                    resName     = uv.User.Name;
                                }
                            }
                            catch { }
                        }
                    }
                }
            }
            return(impersonate);
        }
Example #34
0
        //最新的关注的网站和取消的网站
        private void FollowingAndStopFollowing()
        {
            SPUser us = SPContext.Current.Web.CurrentUser;
            SPSocialFollowingManager _followManager = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSite = new SPSite(SPContext.Current.Web.Url))
                {
                    SPServiceContext serverContext    = SPServiceContext.GetContext(SPContext.Current.Site);
                    UserProfileManager profileManager = new UserProfileManager(serverContext);
                    UserProfile profile = profileManager.GetUserProfile(us.LoginName);
                    if (profile != null)
                    {
                        //Create a Social Manager profile
                        _followManager = new SPSocialFollowingManager(profile);
                        SPSocialActorInfo actorInfo = null;
                        //SPSocialActor[] actors = _followManager.GetFollowers();
                        SPSocialActor[] ifollow = _followManager.GetFollowed(SPSocialActorTypes.Sites);
                        foreach (SPSocialActor follower in ifollow)
                        {
                            actorInfo            = new SPSocialActorInfo();
                            actorInfo.ContentUri = follower.Uri;
                            actorInfo.ActorType  = SPSocialActorType.Site;
                            if (!_followManager.IsFollowed(actorInfo))
                            {
                                _followManager.Follow(actorInfo);
                                des.Text = "follow:OK";
                            }
                            else
                            {
                                _followManager.StopFollowing(actorInfo);
                                des.Text = "stoppFollowing OK";
                            }
                        }
                    }
                }
            });
        }
Example #35
0
        public void getDataFromparentlist(int itemId, Guid listguid)
        {
            using (SPSite spSite = SPContext.Current.Site) //找到网站集
            {
                using (SPWeb spweb = spSite.OpenWeb(SPContext.Current.Web.ID))
                {
                    SPUser user = spweb.CurrentUser;
                    if (user != null)//已登录
                    {
                        SPListCollection colllists = spweb.Lists;
                        SPList           spList    = colllists[listguid];
                        //SPList spList = colllists.TryGetList("任务");
                        if (spList != null)
                        {
                            SPListItem item   = spList.GetItemById(itemId);
                            string     action = item["操作"].ToString();
                            if (action == "所有")
                            {
                                AppAction.InnerHtml = "该任务不是原子任务,无法进行日程分配!";
                            }
                            else
                            {
                                lbItemTitle.Text = item.Title;
                                tbName.CommaSeparatedAccounts = user.LoginName;
                            }
                        }

                        else
                        {
                            AppAction.InnerHtml = "你尚未指定分配日程的任务!";
                        }
                    }
                    else
                    {
                        AppAction.InnerHtml = "你尚未登录!";
                    }
                }
            }
        }
Example #36
0
        public void Register(SPWeb web, string loginName)
        {
            int courseId;

            TrainingCourse course       = null;
            Registration   registration = null;
            bool           success      = false;
            SPUser         user         = null;

            if (this._view.QueryString.AllKeys.Contains("ID"))
            {
                success = Int32.TryParse(this._view.QueryString["ID"], out courseId);
            }
            else
            {
                success = Int32.TryParse(this._view.SelectedCourse, out courseId);
            }

            this._view.HeaderTitle = "Course Registration";
            this._view.SiteLink    = web.Url;

            if (!success)
            {
                return;
            }

            success = GetCourseUserRegistration(web, courseId, out course, out registration, out user, loginName);

            if (success)
            {
                PerformRegistration(web, course, user);

                this._view.PageTitle                   = string.Format("Course Registration - {0}", course.Code);
                this._view.HeaderSubtitle              = course.Code;
                this._view.ContentMessage              = string.Format("Your registration request for {0} has been submitted.", course.Code);
                this._view.ShowConfirmationControls    = false;
                this._view.ShowCourseSelectionControls = false;
            }
        }
Example #37
0
        /// <summary>
        /// 根据组名获取SPGroup对象
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public static SPGroup GetSPGroupByName(string siteUrl, string groupName, SPUser groupUser)
        {
            SPGroup group = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteUrl))
                    {
                        using (SPWeb web = site.RootWeb)
                        {
                            web.AllowUnsafeUpdates = true;

                            if (!IsExistGroup(web, groupName))
                            {
                                web.SiteGroups.Add(groupName, groupUser, null, groupName);//新建组

                                if (IsExistGroup(web, groupName))
                                {
                                    group = web.SiteGroups.GetByName(groupName);
                                }
                            }
                            else
                            {
                                group = web.SiteGroups.GetByName(groupName);
                            }

                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });
                return(group);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Gets the regional date time.
        /// </summary>
        /// <param name="dateTime">The date time.</param>
        /// <param name="spWeb">The sp web.</param>
        /// <returns></returns>
        private static string GetRegionalDateTime(DateTime dateTime, SPWeb spWeb)
        {
            string result = string.Empty;

            using (var spSite = new SPSite(spWeb.Site.ID))
            {
                using (SPWeb web = spSite.OpenWeb(spWeb.ID))
                {
                    SPUser user = web.CurrentUser;

                    SPRegionalSettings spRegionalSettings = user.RegionalSettings ?? web.RegionalSettings;

                    if (dateTime != DateTime.MinValue)
                    {
                        DateTime utcToLocalTime = spRegionalSettings.TimeZone.UTCToLocalTime(dateTime.ToUniversalTime());
                        result = utcToLocalTime.ToString("M/d/yyyy HH:mm:ss").Replace('-', '/').Replace('.', '/');
                    }
                }
            }

            return(result);
        }
Example #39
0
        /// <summary>Returns all files for an assignment grouped by learner.</summary>
        /// <param name="assignmentKey">The key of the assignment.</param>
        public Dictionary <string, List <SPFile> > AllFiles(long assignmentKey)
        {
            string queryXml = @"<Where>
                                <And>
                                    <Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq>
                                    <Eq><FieldRef Name='{2}'/><Value Type='Boolean'>1</Value></Eq>
                                </And>
                             </Where>";

            queryXml = string.Format(CultureInfo.InvariantCulture, queryXml, ColumnAssignmentId, assignmentKey, ColumnIsLatest);
            SPQuery query = new SPQuery();

            query.ViewAttributes = "Scope=\"Recursive\"";
            query.Query          = queryXml;
            SPListItemCollection items = DropBoxList.GetItems(query);

            SPFieldUser learnerField = (SPFieldUser)DropBoxList.Fields[ColumnLearner];

            Dictionary <string, List <SPFile> > files = new Dictionary <string, List <SPFile> >();

            foreach (SPListItem item in items)
            {
                SPFile           file         = item.File;
                SPFieldUserValue learnerValue = (SPFieldUserValue)learnerField.GetFieldValue(item[ColumnLearner].ToString());
                SPUser           learner      = learnerValue.User;

                List <SPFile> learnerFiles;
                string        learnerAccount = learner.LoginName.Replace("\\", "-");
                if (files.TryGetValue(learnerAccount, out learnerFiles) == false)
                {
                    learnerFiles = new List <SPFile>();
                    files.Add(learnerAccount, learnerFiles);
                }

                learnerFiles.Add(item.File);
            }

            return(files);
        }
Example #40
0
        // Private Methods (1) 

        private void AddGroup(SPWeb spWeb, SPGroup owner, SPUser user, string groupName)
        {
            LogMessage(groupName, 3);

            try
            {
                SPGroup spGroup = null;

                try
                {
                    spGroup = spWeb.SiteGroups.GetByName(groupName);
                }
                catch { }

                if (spGroup == null)
                {
                    spWeb.SiteGroups.Add(groupName, owner, user, null);
                    SPRole roll = spWeb.Roles["Read"];
                    roll.AddGroup(spWeb.SiteGroups[groupName]);

                    try
                    {
                        SPList spList = spWeb.Lists["User Information List"];
                        spList.Items.GetItemById(spWeb.SiteGroups[groupName].ID).SystemUpdate();
                    }
                    catch { }

                    LogMessage(null, MessageKind.SUCCESS, 4);
                }
                else
                {
                    LogMessage("Group already exists.", MessageKind.SKIPPED, 4);
                }
            }
            catch (Exception exception)
            {
                LogMessage(exception.Message, MessageKind.FAILURE, 4);
            }
        }
Example #41
0
        private string GetUserName()
        {
            string userName = "";

            SPWeb  web  = SPContext.Current.Web;
            SPUser user = web.CurrentUser;
            SPRoleDefinitionBindingCollection usersRoles         = web.AllRolesForCurrentUser;
            SPRoleDefinitionCollection        siteRoleCollection = web.RoleDefinitions;
            SPRoleDefinition roleDefinition = siteRoleCollection["完全控制"];

            SPRoleDefinition roleDefinition2 = siteRoleCollection["参与讨论"];

            if (user != null)//当前有用户登录
            {
                //if (usersRoles.Contains(roleDefinition) && Page.Request.QueryString["Code"] != null)
                //{
                //    //具有完全控制权限
                //    userName = Page.Request.QueryString["Code"];
                //}
                if ((GetGroupofUser("辽宁省数学建模竞赛组委会") || usersRoles.Contains(roleDefinition) || usersRoles.Contains(roleDefinition2)) && Page.Request.QueryString["Code"] != null)
                //已登录的用户是组委会成员且url中传递了EnrollCode,则查看制定EnrollCode的报名信息
                {
                    userName = Page.Request.QueryString["Code"];
                }
                else
                {
                    userName = user.LoginName;
                    if (userName.Contains("|"))
                    {
                        userName = userName.Substring(userName.IndexOf("|") + 1);
                    }
                    if (userName.Contains("\\"))
                    {
                        userName = userName.Substring(userName.IndexOf("\\") + 1);
                    }
                }
            }
            return(userName);
        }
Example #42
0
        protected void removeButton_OnClick(object sender, EventArgs e)
        {
            AreYouSureText.Text = "Something went wrong when trying to remove the user from the team";

            SPUser userToRemove = SPContext.Current.Web.WBxEnsureUserOrNull(LoginNameOfUserToRemove.Value);

            if (userToRemove == null)
            {
                return;
            }

            if (RoleToRemove.Value == "Owner")
            {
                team.RemoveOwner(SPContext.Current.Site, userToRemove);
            }
            else
            {
                team.RemoveMember(SPContext.Current.Site, userToRemove);
            }

            CloseDialogAndRefresh("?panel=TeamDetails");
        }
Example #43
0
 public static int GetUserID(string loginName, bool dominio, out string mensaje)
 {
     mensaje = "";
     try
     {
         SPUser user = null;
         if (dominio)
         {
             user = SPContext.Current.Web.EnsureUser(BIT.UDLA.FLUJOS.PASANTIAS.Comun.Properties.Parametros.Default.Dominio + loginName);
         }
         else
         {
             user = SPContext.Current.Web.EnsureUser(loginName);
         }
         return(user.ID);
     }
     catch (Exception ex)
     {
         mensaje = Mensajes.Default.ObtenerMOSSID;
         return(-1);
     }
 }
Example #44
0
        public static bool CheckForEditing(string SPUrl, string SPListURLDir, SPUser currentUser)
        {
            var canEdit = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList docLibrary = web.GetList(SPListURLDir);
                        try
                        {
                            SPRoleAssignment userRoles = docLibrary.RoleAssignments.GetAssignmentByPrincipal(currentUser);
                            canEdit = CheckRolesForEditing(userRoles);
                        }
                        catch (Exception)
                        {
                            SPGroupCollection groupColl = web.Groups;

                            foreach (SPGroup group in groupColl)
                            {
                                try
                                {
                                    SPRoleAssignment groupsRoles = docLibrary.RoleAssignments.GetAssignmentByPrincipal(group);
                                    canEdit = CheckRolesForEditing(groupsRoles);
                                    if (canEdit)
                                    {
                                        break;
                                    }
                                }
                                catch (Exception) { }
                            }
                        }
                    }
                }
            });
            return(canEdit);
        }
Example #45
0
        public static SPUser UserExists(SPUserCollection users, string name)
        {
            SPUser result = null;

            /*if (string.IsNullOrEmpty(name) ||
             *  (name.Length > 255) ||
             *  (users == null) ||
             *  (users.Count == 0))
             *  return false;
             * else
             * {*/
            foreach (SPUser user in users)
            {
                if ((user.Name == name) | (user.LoginName == name))
                {
                    result = user;
                }
            }

            //  }
            return(result);
        }
        public static List <RoleSetup> GetRoleSetup(SPUser user)
        {
            List <RoleSetup> roleSetups = new List <RoleSetup>();

            List <int> groups = user.Groups.Cast <SPGroup>().Select(g => g.ID).ToList();

            groups.Add(user.ID);

            ArchiveCacheCRUD crud = new ArchiveCacheCRUD(user.ParentWeb.Site);

            foreach (int griupOrUserId in groups)
            {
                StatusValuePair <List <RoleSetupDb> > result = crud.GetRoleSetup(griupOrUserId);
                if (!result.HasValue || result.ErrorCode != ErrorCode.NoError)
                {
                    continue;
                }

                IEnumerable <RoleSetup> setups = result.Value.Select(v =>
                {
                    RoleSetup rs = new RoleSetup();

                    if (!string.IsNullOrEmpty(v.Lists))
                    {
                        rs.Lists = v.Lists.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    }
                    rs.ListRight     = v.ListsRights;
                    rs.Services      = new SPFieldLookupValueCollection(v.Service);
                    rs.ServicesRight = v.ServiceRights;
                    rs.Legals        = new SPFieldLookupValueCollection(v.Legals);
                    rs.LegalsRight   = v.LegalsRights;
                    return(rs);
                });

                roleSetups.AddRange(setups);
            }

            return(roleSetups);
        }
Example #47
0
        public void TestRemoveUserFromSPSite()
        {
            SPSite site = new SPSite(_newSPSiteUrl);


            // verify that this user is registered in the site.
            SPUser user2 = site.RootWeb.AllUsers[_newUserLogin];

            Assertion.AssertNotNull(user2);

            string result = result = RunBuild(String.Format(CultureInfo.InvariantCulture,
                                                            _xmlProjectTemplate, _newSPSiteUrl, "true", _newUserLogin));

            // Verify that the user was removed.
            try {
                SPUser user1 = site.RootWeb.AllUsers[_newUserLogin];
                Assertion.Fail("The user should not be found after it was removed from the site.");
            }
            catch (Exception ignored) {
                // this is the exptected response
            }
        }
Example #48
0
        /// <summary>
        /// 获取任务根节点的文档,项目和例行
        /// </summary>
        /// <returns></returns>
        private SPUser GetSPUser(string sLoginName)
        {
            SPUser oUser = null;

            try
            {
                if (!string.IsNullOrEmpty(sLoginName))
                {
                    if (web.AllUsers.Count > 0)
                    {
                        string domainName = web.AllUsers[0].LoginName;
                        domainName = domainName.Substring(0, domainName.IndexOf(@"\") + 1);
                        sLoginName = domainName + sLoginName;
                        oUser      = web.AllUsers[sLoginName];
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(oUser);
        }
        internal static SPFieldUserValue ToUserValue(User user, SPWeb web)
        {
            if (user is Person)
            {
                var person = (Person)user;

                SPUser spUser = null;
                try
                {
                    spUser = web.SiteUsers[person.Login];
                }
                catch (SPException)
                {
                    throw new SharepointCommonException(string.Format("User {0} not found.", user.Id));
                }


                return(new SPFieldUserValue {
                    LookupId = spUser.ID,
                });
            }
            else
            {   // sharepoint group
                SPGroup spUser = null;
                try
                {
                    spUser = web.SiteGroups[user.Name];
                }
                catch (SPException)
                {
                    throw new SharepointCommonException(string.Format("Group {0} not found.", user.Name));
                }

                return(new SPFieldUserValue {
                    LookupId = spUser.ID,
                });
            }
        }
Example #50
0
        public GroupCollectionNode(SPUser user)
        {
            this.Text = SPMLocalization.GetString("GroupCollection_Text");
            this.ToolTipText = SPMLocalization.GetString("GroupCollection_ToolTip");
            this.Name = "OwnedGroups";
            this.Tag = user.OwnedGroups;
            this.SPParent = user;
            //this.WebNode = webNode;

            int index = Program.Window.Explorer.AddImage(this.ImageUrl());
            this.ImageIndex = index;
            this.SelectedImageIndex = index;

            //this.ContextMenuStrip = SPMMenu.Strips.Refresh;
            if (user.OwnedGroups.Count > 0)
            {
                this.Nodes.Add(new ExplorerNodeBase("Dummy"));
            }
            else
            {
                this.HasChildrenLoaded = true;
            }
        }
        /// <summary>
        /// This method is used to prefill the values in the dropdowns after fetching existing values of properties 
        /// </summary>
        private void ConfiguringControls()
        {
            if (!Page.IsPostBack)
            {
                var propertyValue = Web.Properties[ShowOnBreadcrumbProperty];
                ddBreadcrumb.SelectedValue = string.Equals(propertyValue, "1") ? "1" : "0";

                var leftNavPropertyValue = Web.Properties[ShowOnLeftMenuProperty];
                ddLeftNav.SelectedValue = string.Equals(leftNavPropertyValue, "1") ? "1" : "0";
            }
            ddBreadcrumb.Enabled = false;
            btnUpdate.Enabled = false;
            ddLeftNav.Enabled = false;
            currentUser = Web.CurrentUser;
            if (currentUser.IsSiteAdmin)
            {
                if (IsValidWebLevel())
                {
                    ddBreadcrumb.Enabled = true;
                    btnUpdate.Enabled = true;
                    ddLeftNav.Enabled = true;
                }
            }
        }
        private bool isUserinGroup(Guid siteid, Guid webid, int groupid, SPUser oUser)
        {
            Boolean bUserIsInGroup = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteid))
                    {
                        using (SPWeb web = site.OpenWeb(webid))
                        {
                            SPGroup isgroup = web.Groups.GetByID(groupid);
                            if (oUser != null)
                            {
                                foreach (SPUser item in isgroup.Users)
                                {
                                    if (item.LoginName == oUser.LoginName)
                                    {
                                        bUserIsInGroup = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                });
            }
            catch
            {
            }
            return bUserIsInGroup;
        }
        private bool IsValidMSA(string msaDate,
                                string accompaniedBy,
                                string designation,
                                SPUser auditedBy_SPUser,
                                string areaAuditedListItem,
                                string startTimeStr,
                                string endTimeStr,
                                string noOfUnsafeActs,
                                string noOfUnsafeConditions,
                                string noOfFatalityInjury,
                                string noOfSeriousInjury,
                                string positivePoints,
                                string areaOfImprovement,
                                string msaQualityScore)
        {
            try
            {
                if (auditedBy_SPUser != null && !String.IsNullOrEmpty(auditedBy_SPUser.Email))
                {
                    if (!String.IsNullOrEmpty(endTimeStr) && !String.IsNullOrEmpty(startTimeStr))
                    {
                        if (Convert.ToDateTime(endTimeStr) != null && Convert.ToDateTime(startTimeStr) != null)
                        {
                            DateTime date;
                            bool bValid = DateTime.TryParse(msaDate, new CultureInfo("en-GB"), DateTimeStyles.AssumeLocal, out date);

                            if (!bValid)
                            {
                                Convert.ToDateTime(msaDate);
                            }

                            if (this.fileUploadControl.HasFiles)
                            {
                                int maxFileLimit = 20971520;

                                foreach (var uploadedFile in fileUploadControl.PostedFiles)
                                {
                                    if (uploadedFile.ContentLength > maxFileLimit)
                                    {
                                        message_div.InnerHtml = "Attachment file size limit is 20MB. Please reattach files.";
                                        return false;
                                    }
                                }
                            }
                            return true;
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSAForm->IsValidMSA)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                DisableControls();
            }
            return false;
        }
Example #54
0
        public static bool DoesUserHavePermissions(SPList list, SPUser user, string permissionLevel)
        {
            var roleDefinition = GetRoleDefinition(list.ParentWeb, permissionLevel);
            if (roleDefinition == null)
            {
                return false;
            }

            return list.DoesUserHavePermissions(user, roleDefinition.BasePermissions);
        }
        /// <summary>
        /// Synchronizes the taxonomy fields from specified mappings
        /// The source property will build the destination property taxonomy tree.
        /// </summary>
        /// <param name="site">The site for the service context.</param>
        /// <param name="user">The user for which to sync the profile properties.</param>
        /// <param name="mappings">The taxonomy property mappings.  The key is the source property name. The value is the destination property name.</param>
        public void SyncTaxonomyFieldsForUser(SPSite site, SPUser user, IDictionary<string, string> mappings)
        {
            using (new SPMonitoredScope(string.Format(CultureInfo.InvariantCulture, "{0}::{1}", MonitoredScopePrefix, "SyncTaxonomyFieldsForUser")))
            {
                // Get user profile objects
                var context = SPServiceContext.GetContext(site);
                var userProfileManager = new UserProfileManager(context);
                var profileSubtypeProperties = this.userProfilePropertyHelper.GetProfileSubtypePropertyManager(site);
                var userProfile = userProfileManager.GetUserProfile(user.LoginName);

                // For each property, update mapping
                foreach (var mapping in mappings)
                {
                    var targetPropertyName = mapping.Value;
                    var targetSubtypeProp = profileSubtypeProperties.GetPropertyByName(targetPropertyName);
                    this.SyncTaxonomyFields(
                        site,
                        userProfile,
                        mapping,
                        targetSubtypeProp.CoreProperty.TermSet.TermStore.Id,
                        targetSubtypeProp.CoreProperty.TermSet.Id,
                        user.ParentWeb);
                }
            }
        }
 private bool IsValidUser(SPUser spUser, SPGroup spGroup)
 {
     return spUser.Groups.Cast<SPGroup>()
       .Any(g => g.ID == spGroup.ID);
 }
 public FakeCurrentUserAccesor(SPUser user)
 {
     _user = user;
 }
        private static IWindsorContainer ConfigureKernelForTest(SPSite site, SPUser user)
        {
            IWindsorContainer kernel = new WindsorContainer();

            kernel.Register(Component.For<ICurrentSiteAccesor>()
                                        .UsingFactoryMethod(() => new FakeCurrentSiteAccesor(site))
                                        .LifeStyle.Transient);

            kernel.Register(Component.For<ICurrentUserAccesor>()
                                        .UsingFactoryMethod(() => new FakeCurrentUserAccesor(user))
                                        .LifeStyle.Transient);

            kernel.Install(FromAssembly.Containing<ICurrentSiteAccesor>());
            return kernel;
        }
Example #59
0
        private static string GetQueryForCurrentUserReplies(SPList discussionBoard, SPUser currentUser, DateTime recentDate)
        {
            string query = null;

            if (discussionBoard != null)
            {
                SPQuery qry = new SPQuery();
                qry.Query = string.Format(@"<Where>
                                        <And>
                                            <And>
                                                <Eq>
                                                    <FieldRef Name='ContentType' />
                                                    <Value Type='Computed'>Message</Value>
                                                </Eq>
                                                <Eq>
                                                    <FieldRef Name='Author' LookupId='True' />
                                                    <Value Type='Integer'>{0}</Value>
                                                </Eq>
                                            </And>
                                            <Geq>
                                                <FieldRef Name = 'Modified' />
                                                <Value Type ='DateTime'>{1}</Value>
                                            </Geq>
                                        </And>
                                   </Where>", currentUser.ID, Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(recentDate));
                //qry.ViewFields = @"<FieldRef Name='ReplyNoGif' />";
                qry.ViewAttributes = "Scope='RecursiveAll'";
                SPListItemCollection listItems = discussionBoard.GetItems(qry);
                if (listItems.Count > 0)
                {
                    string queryText = @"<Eq>
                                             <FieldRef Name='ContentType' />
                                             <Value Type='Computed'>Discussion</Value>
                                          </Eq>";
                    List<string> threads = new List<string>();
                    foreach (SPListItem message in listItems)
                    {
                        string thread = Convert.ToString(message["ReplyNoGif"]);
                        //thread = thread.Substring(0, 46);
                        if (!threads.Contains(thread))
                        {
                            threads.Add(thread);

                        }
                    }

                    if (threads.Count == 1)
                    {
                        queryText = "<And>" + queryText + "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + "/" + threads[0] + "</Value></Eq></And>";
                    }
                    else
                    {
                        string tempQuery = "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + "/" + threads[0] + "</Value></Eq>";
                        for (int i = 1; i < threads.Count; i++)
                        {
                            tempQuery = "<Or>" +
                                                "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + "/" + threads[i] + "</Value></Eq>" +
                                                tempQuery +
                                        "</Or>";
                        }
                        queryText = "<And>" + tempQuery + "</And>";
                    }
                    queryText = "<Where>" + queryText + "</Where>";
                    query = queryText;
                }
            }
            return query;
        }
        internal void UpdatedExcessLeaves(string empId, SPUser empname, string leaveType, decimal value)
        {
            var list = SPContext.Current.Web.Lists.TryGetList("Employee Excess Leaves");
            var newItem = list.Items.Add();

            newItem["Employee Id"] = empId;
            newItem["Employee Name"] = empname;
            newItem["Leave Type"] = leaveType;
            newItem["Leave Excess"] = value;
            newItem["Year"] = DateTime.Now.Year + "-" + DateTime.Now.AddYears(1).Year;
            newItem.Update();
        }