/// <summary>
        /// Returns an XML structure containing all the audience details.
        /// </summary>
        /// <param name="audienceName">Name of the audience.</param>
        /// <param name="includeAllAttributes">if set to <c>true</c> [include all attributes].</param>
        /// <returns></returns>
        internal static string Export(SPServiceContext context, string audienceName, bool includeAllAttributes)
        {
            AudienceManager manager = new AudienceManager(context);

            if (!string.IsNullOrEmpty(audienceName) && !manager.Audiences.AudienceExist(audienceName))
            {
                throw new SPException("Audience name does not exist");
            }

            StringBuilder sb = new StringBuilder();
            XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
            xmlWriter.Formatting = Formatting.Indented;

            xmlWriter.WriteStartElement("Audiences");

            if (!string.IsNullOrEmpty(audienceName))
            {
                Audience audience = manager.Audiences[audienceName];
                ExportAudience(xmlWriter, audience, includeAllAttributes);
            }
            else
            {
                foreach (Audience audience in manager.Audiences)
                    ExportAudience(xmlWriter, audience, includeAllAttributes);
            }

            xmlWriter.WriteEndElement(); // Audiences
            xmlWriter.Flush();
            return sb.ToString();
        }
        /// <summary>
        /// Deletes the specified audience or all audience rules for the specified audience.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="audienceName">Name of the audience.</param>
        /// <param name="deleteRulesOnly">if set to <c>true</c> [delete rules only].</param>
        internal static void Delete(SPServiceContext context, string audienceName, bool deleteRulesOnly)
        {
            AudienceManager manager = new AudienceManager(context);

            if (!manager.Audiences.AudienceExist(audienceName))
            {
                throw new SPException("Audience name does not exist");
            }

            Audience audience = manager.Audiences[audienceName];

            if (audience.AudienceRules != null && deleteRulesOnly)
            {
                audience.AudienceRules = new ArrayList();
                if (audience.GroupOperation == AudienceGroupOperation.AUDIENCE_MIX_OPERATION)
                {
                    // You can't change from mixed mode using the property without setting some internal fields.
                    object audienceInfo = Utilities.GetFieldValue(audience, "m_AudienceInfo");
                    Utilities.SetPropertyValue(audienceInfo, "NewGroupOperation", AudienceGroupOperation.AUDIENCE_OR_OPERATION);
                    Utilities.SetFieldValue(audience, typeof (Audience), "m_AuidenceGroupOperationChanged", true);
                }
                audience.Commit();
                return;
            }
            if (!deleteRulesOnly)
                manager.Audiences.Remove(audience.AudienceID);
        }
Esempio n. 3
0
        public NodeServiceClient(string callingUrl)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                _site = new SPSite(callingUrl);

                _serviceContext = SPServiceContext.GetContext(_site);
            });
        }
Esempio n. 4
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]];
        }
Esempio n. 5
0
 static void InitUsers(SPServiceContext context) {
     UserProfileManager manager = new UserProfileManager(context);
     using (var db = new CMSMIPEntities()) {
         var users = db.CMS_SA_USER_INFO_V;
         foreach (var user in users) {
             if (!manager.UserExists(user.SP账号)) {
                 UserProfile userProfile = manager.CreateUserProfile(user.SP账号);
             }
         }
     }
 }
        /// <summary>
        /// Returns an XML structure containing all the rules associated with the audience.
        /// </summary>
        /// <param name="audienceName">Name of the audience.</param>
        /// <param name="includeAllAttributes">if set to <c>true</c> [include all attributes].</param>
        /// <returns></returns>
        internal static string EnumRules(SPServiceContext context, string audienceName, bool includeAllAttributes)
        {
            AudienceManager manager = new AudienceManager(context);

            if (!manager.Audiences.AudienceExist(audienceName))
            {
                throw new SPException("Audience name does not exist");
            }

            Audience audience = manager.Audiences[audienceName];

            ArrayList audienceRules = audience.AudienceRules;

            if (audienceRules == null || audienceRules.Count == 0)
                return "The audience contains no rules.";

            string rulesXml = "<rules>\r\n";
            foreach (AudienceRuleComponent rule in audienceRules)
            {
                if (includeAllAttributes)
                {
                    rulesXml += string.Format("\t<rule field=\"{1}\" op=\"{0}\" value=\"{2}\" />\r\n", rule.Operator, rule.LeftContent, rule.RightContent);
                }
                else
                {
                    switch (rule.Operator.ToLowerInvariant())
                    {
                        case "=":
                        case ">":
                        case ">=":
                        case "<":
                        case "<=":
                        case "contains":
                        case "<>":
                        case "not contains":
                            rulesXml += string.Format("\t<rule field=\"{1}\" op=\"{0}\" value=\"{2}\" />\r\n", rule.Operator, rule.LeftContent, rule.RightContent);
                            break;
                        case "reports under":
                        case "member of":
                            rulesXml += string.Format("\t<rule op=\"{0}\" value=\"{1}\" />\r\n", rule.Operator, rule.RightContent);
                            break;
                        case "and":
                        case "or":
                        case "(":
                        case ")":
                            rulesXml += string.Format("\t<rule op=\"{0}\" />\r\n", rule.Operator);
                            break;
                    }
                }
            }
            rulesXml += "</rules>";
            return rulesXml;
        }
        /// <summary>
        /// Creates the specified audience.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="audienceName">Name of the audience.</param>
        /// <param name="description">The description.</param>
        /// <param name="rule">The rule.</param>
        /// <param name="owner">The owner.</param>
        /// <param name="update">if set to <c>true</c> [update].</param>
        /// <returns></returns>
        internal static Audience Create(SPServiceContext context, string audienceName, string description, RuleEnum? rule, string owner, bool update)
        {
            AudienceManager manager = new AudienceManager(context);
            AudienceCollection auds = manager.Audiences;

            Audience audience;
            if (auds.AudienceExist(audienceName))
            {
                if (update)
                {
                    audience = auds[audienceName];
                    audience.AudienceDescription = description ?? "";
                }
                else
                    throw new SPException("Audience name already exists");
            }
            else
                audience = auds.Create(audienceName, description??"");// IMPORTANT: the create method does not do a null check but the methods that load the resultant collection assume not null.

            if (update && rule.HasValue && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_MIX_OPERATION)
            {
                if (rule.Value == RuleEnum.Any && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_OR_OPERATION)
                    audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION;
                else if (rule.Value == RuleEnum.All && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_AND_OPERATION)
                    audience.GroupOperation = AudienceGroupOperation.AUDIENCE_AND_OPERATION;
            }
            else
            {
                if (audience.GroupOperation != AudienceGroupOperation.AUDIENCE_MIX_OPERATION)
                {
                    if (rule.HasValue)
                    {
                        if (rule == RuleEnum.Any)
                            audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION;
                        else if (rule == RuleEnum.All)
                            audience.GroupOperation = AudienceGroupOperation.AUDIENCE_AND_OPERATION;
                    }
                    else
                        audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION;
                }
            }
            if (!string.IsNullOrEmpty(owner))
            {
                audience.OwnerAccountName = owner;
            }
            else
            {
                audience.OwnerAccountName = string.Empty;
            }
            audience.Commit();
            return audience;
        }
Esempio n. 8
0
        private DataTable FullQuery(string txtFrom, string txtTo)
        {
            SPServiceContext context           = SPServiceContext.Current;
            SearchServiceApplicationProxy ssap = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site));

            using (KeywordQuery qry = new KeywordQuery(ssap))
            {
                qry.EnableStemming = true;
                qry.TrimDuplicates = true;
                qry.RowLimit       = 10000;
                string queryText = GetFullQueryString();
                string txtTime   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                txtTime       = txtTime.Substring(txtTime.IndexOf(" "));
                qry.QueryText = "Created:" + txtFrom + ".." + txtTo + " " + queryText;
                qry.SelectProperties.AddRange(new string[] { "WorkId", "Title", "Author", "Created", "Path", "ContentClass", "FileExtension" });
                qry.SortList.Add("Created", Microsoft.Office.Server.Search.Query.SortDirection.Descending);
                SearchExecutor            searchExecutor        = new SearchExecutor();
                ResultTableCollection     resultTableCollection = searchExecutor.ExecuteQuery(qry);
                IEnumerator <ResultTable> iResult = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).GetEnumerator();
                iResult.MoveNext();
                ResultTable resultTable    = iResult.Current;
                DataTable   queryDataTable = resultTable.Table;
                if (queryDataTable.Rows.Count > 0)
                {
                    foreach (DataRow dr in queryDataTable.Rows)
                    {
                        //小时加8
                        dr["Created"] = ((DateTime)dr["Created"]).AddHours(8);
                        string author = dr["Author"].ToString();
                        if (author.IndexOf(";") > 0)//多个作者,修改者也加到了里面
                        {
                            dr["Author"] = author.Substring(0, author.IndexOf(";"));
                        }
                    }
                    queryDataTable.AcceptChanges();
                    //当天查询减去24小时
                    if (dateFrom.SelectedDate == DateTime.Today.AddDays(-1) && DateTo.SelectedDate == DateTime.Today)
                    {
                        DataRow[] drs = queryDataTable.Select("Created>='" + txtFrom + txtTime + "' and Created<='" + DateTo.SelectedDate.ToString("yyyy-MM-dd") + txtTime + "'", "Created desc");
                        DataSet   ds  = new DataSet();
                        DataTable dt  = queryDataTable.Clone();
                        ds.Tables.Add(dt);
                        ds.Merge(drs);
                        queryDataTable = ds.Tables[0];
                    }
                }
                return(queryDataTable);
            }
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            int userCount = 1;

            try
            {
                if (Convert.ToBoolean(ConfigurationManager.AppSettings["TESTRUN"]))
                {
                    LogMessage(string.Format("******** RUNNING IN TEST RUN MODE **********"), LogLevel.Debug);
                }

                LogMessage(string.Format("Connecting to My Site Host: '{0}'...", ConfigurationManager.AppSettings["MYSITEHOSTURL"]), LogLevel.Info);
                using (SPSite mySite = new SPSite(ConfigurationManager.AppSettings["MYSITEHOSTURL"]))
                {
                    LogMessage(string.Format("Connecting to My Site Host: '{0}'...Done!", ConfigurationManager.AppSettings["MYSITEHOSTURL"]), LogLevel.Info);

                    LogMessage(string.Format("getting Service Context..."), LogLevel.Info);
                    SPServiceContext svcContext = SPServiceContext.GetContext(mySite);
                    LogMessage(string.Format("getting Service Context...Done!"), LogLevel.Info);

                    LogMessage(string.Format("Connecting to Profile Manager..."), LogLevel.Info);
                    UserProfileManager profileManager = new UserProfileManager(svcContext);
                    LogMessage(string.Format("Connecting to Profile Manager...Done!"), LogLevel.Info);

                    // Presize List with Number of Profiles...
                    List <UserProfileData> pData = new List <UserProfileData>(Convert.ToInt32(profileManager.Count));

                    // Initialize Serialization Class...
                    UserProfileCollection ups = new UserProfileCollection();

                    foreach (UserProfile spUser in profileManager)
                    {
                        // Get Profile Information
                        LogMessage(string.Format("processing user '{0}' of {1}...", userCount, profileManager.Count), LogLevel.Info);
                        UserProfileData userData = new UserProfileData();

                        userData.UserName = GetSingleValuedProperty(spUser, "WorkEmail");

                        if (userData.UserName != string.Empty)
                        {
                            userData.AboutMe    = GetSingleValuedProperty(spUser, "AboutMe");
                            userData.AskMeAbout = GetMultiValuedProperty(spUser, "SPS-Responsibility");
                            pData.Add(userData);
                            // Add to Serilization Class List of Profiles
                            ups.ProfileData = pData;
                        }

                        LogMessage(string.Format("processing user '{0}' of {1}...Done!", userCount++, profileManager.Count), LogLevel.Info);

                        // Only processing the First item if we are in test mode...
                        if (Convert.ToBoolean(ConfigurationManager.AppSettings["TESTRUN"]))
                        {
                            break;
                        }
                    }

                    // Serialize profiles to disk...
                    ups.Save();
                }
            }
            catch (Exception ex)
            {
                LogMessage("Exception trying to get profile properties:\n" + ex.Message, LogLevel.Error);
            }
        }
Esempio n. 10
0
        protected void UpdateCustomer_Click(object sender, EventArgs e)
        {
            // Make sure we have values for the entity namespace and name.
            if (!EntityValuesAreSet)
            {
                DisplaySetPropertyValuePrompt(true);
                return;
            }
            else
            {
                DisplaySetPropertyValuePrompt(false);
            }

            // Do simple validation of the customer ID. Make sure it is
            // an integer.
            int customerID = -1;

            if (!ValidateCustomerID(CustomerID.Text, ref customerID))
            {
                StatusLabel.ForeColor = Color.Red;
                StatusLabel.Text      =
                    "Please enter an integer for the Customer ID value.";
                return;
            }

            try
            {
                using (new Microsoft.SharePoint.SPServiceContextScope(
                           SPServiceContext.GetContext(SPContext.Current.Site)))
                {
                    // Get the BDC service and metadata catalog.
                    BdcService service =
                        SPFarm.Local.Services.GetValue <BdcService>(String.Empty);
                    IMetadataCatalog catalog =
                        service.GetDatabaseBackedMetadataCatalog(
                            SPServiceContext.Current);

                    // Get the entity using the specified name and namespace.
                    IEntity entity =
                        catalog.GetEntity(EntityNamespace, EntityName);
                    ILobSystemInstance LobSysteminstance =
                        entity.GetLobSystem().GetLobSystemInstances()[0].Value;

                    // Create an Identity based on the specified Customer ID.
                    Identity identity = new Identity(customerID);

                    // Get a method instance for the Updater method.
                    IMethodInstance method =
                        entity.GetMethodInstance("UpdateCustomer",
                                                 MethodInstanceType.Updater);

                    // The UpdateCustomer method of the external content type
                    // maps to the UpdateCustomer method in the AdventureWorks
                    // web service. Looking at the source for the web service
                    // shows that the UpdateCustomer method has the following
                    // signature:
                    //
                    // public void UpdateCustomer(SalesCustomer customer)
                    //
                    // The SalesCustomer type has the following layout:
                    //
                    // public class SalesCustomer
                    // {
                    //     public int CustomerId { get; set; }
                    //     public String Title { get; set; }
                    //     public String FirstName { get; set; }
                    //     public String MiddleName { get; set; }
                    //     public String LastName   { get; set; }
                    //     public String EmailAddress { get; set; }
                    //     public String Phone { get; set; }
                    //     public DateTime ModifiedDate { get; set; }
                    // }

                    // Get the collection of parameters for the method.
                    // In this case there is only one.
                    IParameterCollection parameters =
                        method.GetMethod().GetParameters();

                    // Use type reflection to get an instance of a
                    // SalesCustomer object to pass as a parameter.
                    ITypeReflector  reflector          = parameters[0].TypeReflector;
                    ITypeDescriptor rootTypeDescriptor =
                        parameters[0].GetRootTypeDescriptor();

                    object[] methodParamInstances =
                        method.GetMethod().CreateDefaultParameterInstances(
                            method);
                    Object instance = methodParamInstances[0];

                    // Get type descriptors for each of the SalesCustomer
                    // members.
                    ITypeDescriptor customerIDTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[0];
                    ITypeDescriptor titleTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[1];
                    ITypeDescriptor firstNameTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[2];
                    ITypeDescriptor middleNameTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[3];
                    ITypeDescriptor lastNameTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[4];
                    ITypeDescriptor emailAddressTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[5];
                    ITypeDescriptor phoneTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[6];
                    ITypeDescriptor modifiedDateTypeDescriptor =
                        rootTypeDescriptor.GetChildTypeDescriptors()[7];

                    // Set the values of the SalesCustomer object members
                    // with the values specified by the user.
                    reflector.Set(customerIDTypeDescriptor,
                                  rootTypeDescriptor,
                                  ref instance, customerID);
                    reflector.Set(titleTypeDescriptor, rootTypeDescriptor,
                                  ref instance, Title.Text);
                    reflector.Set(firstNameTypeDescriptor, rootTypeDescriptor,
                                  ref instance, FirstName.Text);
                    reflector.Set(middleNameTypeDescriptor,
                                  rootTypeDescriptor,
                                  ref instance, MiddleName.Text);
                    reflector.Set(lastNameTypeDescriptor, rootTypeDescriptor,
                                  ref instance, LastName.Text);
                    reflector.Set(emailAddressTypeDescriptor,
                                  rootTypeDescriptor,
                                  ref instance, Email.Text);
                    reflector.Set(phoneTypeDescriptor, rootTypeDescriptor,
                                  ref instance, Phone.Text);
                    reflector.Set(modifiedDateTypeDescriptor,
                                  rootTypeDescriptor,
                                  ref instance, DateTime.Now);

                    // Execute the updater method, passing the parameter.
                    entity.Execute(method, LobSysteminstance,
                                   ref methodParamInstances);

                    StatusLabel.ForeColor = Color.Green;
                    StatusLabel.Text      = "Customer successfully updated.";
                }
            }
            catch (Exception ex)
            {
                StatusLabel.ForeColor = Color.Red;
                StatusLabel.Text      = "Unable to find customer with ID = " +
                                        CustomerID.Text + ". " + ex.Message;
            }
        }
Esempio n. 11
0
        public static void Create(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber)
        {
            foreach (SearchResult user in users)
            {
                DirectoryEntry de2  = user.GetDirectoryEntry();
                SPSite         site = null;
                try
                {
                    site = new SPSite(WebApplication.GetResponseUri(SPUrlZone.Default).AbsoluteUri);

                    SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(SPUrlZone.Default);

                    foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders)
                    {
                        if (provider.GetType() == typeof(SPFormsAuthenticationProvider))
                        {
                            SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider;
                            SPServiceContext   serviceContext           = SPServiceContext.GetContext(site);
                            UserProfileManager uPM = new UserProfileManager(serviceContext);

                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                if (de2.Properties[loginAttribute].Value != null)
                                {
                                    if (!uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                        de2.Properties[loginAttribute].Value.ToString()))
                                    {
                                        Department = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty :
                                                     de2.Properties[DepartmentAttrib].Value.ToString();
                                        DistinguishedName = de2.Properties[DistinguishedNameAttrib].Value.ToString();
                                        FirstName         = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty :
                                                            de2.Properties[FirstNameAttrib].Value.ToString();
                                        LastName = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty :
                                                   de2.Properties[LastNameAttrib].Value.ToString();
                                        Office = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty :
                                                 de2.Properties[OfficeAttrib].Value.ToString();
                                        PreferredName = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty :
                                                        de2.Properties[PreferredNameAttrib].Value.ToString();
                                        UserTitle = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty :
                                                    de2.Properties[UserTitleAttrib].Value.ToString();
                                        WebSite = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty :
                                                  de2.Properties[WebSiteAttrib].Value.ToString();
                                        WorkEmail = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty :
                                                    de2.Properties[WorkEmailAttrib].Value.ToString();
                                        WorkPhone = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty :
                                                    de2.Properties[WorkPhoneAttrib].Value.ToString();

                                        UserProfile newProfile = uPM.CreateUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                                                       de2.Properties[loginAttribute].Value.ToString(), PreferredName);

                                        newProfile[PropertyConstants.Department].Add(Department);
                                        newProfile[PropertyConstants.DistinguishedName].Add(DistinguishedName);
                                        newProfile[PropertyConstants.FirstName].Add(FirstName);
                                        newProfile[PropertyConstants.LastName].Add(LastName);
                                        newProfile[PropertyConstants.Office].Add(Office);
                                        newProfile[PropertyConstants.Title].Add(UserTitle);
                                        newProfile[PropertyConstants.WebSite].Add(WebSite);
                                        newProfile[PropertyConstants.WorkEmail].Add(WorkEmail);
                                        newProfile[PropertyConstants.WorkPhone].Add(WorkPhone);

                                        try
                                        {
                                            newProfile.Commit();
                                            Logging.LogMessage(210, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Created profile " +
                                                               DistinguishedName);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logging.LogMessage(510, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to create profile " +
                                                               DistinguishedName + " " + ex.Message);
                                        }
                                    }
                                    else if (uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                            de2.Properties[loginAttribute].Value.ToString()))
                                    {
                                        UserProfile updateProfile = uPM.GetUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                                                       de2.Properties[loginAttribute].Value.ToString());

                                        updateProfile[PropertyConstants.Department].Value = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty :
                                                                                            de2.Properties[DepartmentAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.DistinguishedName].Value = de2.Properties[DistinguishedNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.FirstName].Value         = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty :
                                                                                                   de2.Properties[FirstNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.LastName].Value = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty :
                                                                                          de2.Properties[LastNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.Office].Value = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty :
                                                                                        de2.Properties[OfficeAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.PreferredName].Value = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty :
                                                                                               de2.Properties[PreferredNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.Title].Value = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty :
                                                                                       de2.Properties[UserTitleAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.WebSite].Value = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty :
                                                                                         de2.Properties[WebSiteAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.WorkEmail].Value = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty :
                                                                                           de2.Properties[WorkEmailAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.WorkPhone].Value = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty :
                                                                                           de2.Properties[WorkPhoneAttrib].Value.ToString();

                                        try
                                        {
                                            updateProfile.Commit();
                                            Logging.LogMessage(211, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Updated profile " +
                                                               updateProfile[PropertyConstants.DistinguishedName].Value);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logging.LogMessage(511, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to update profile " +
                                                               updateProfile[PropertyConstants.DistinguishedName].Value + " " + ex.Message);
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message);
                }

                finally
                {
                    if (site != null)
                    {
                        site.Dispose();
                    }
                }
            }
        }
        /// <summary>
        ///统计不同时间的个人用户和团队的新闻源
        /// </summary>
        /// MaxThreadCount最大值是100,即最多只能返回100,默认值是20,
        /// <returns>返回一维数组,0-个人总数,1-团队总数,2-当日更新,3-本周更新</returns>
        private int[] GetPublishdNews()
        {
            SPSocialFeedOptions socialOptions = new SPSocialFeedOptions();

            socialOptions.MaxThreadCount = int.MaxValue;
            int i = 0;
            int j = 0;

            int[] totalTimes = new int[4];

            try
            {
                string acountName = GetAccountName();
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        //this.Controls.Add(new LiteralControl("site:" + site.Url + "<br/>"));
                        using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                        {
                            //this.Controls.Add(new LiteralControl("web:"+web.Url + "<br/>"));
                            SPServiceContext serviceContext = SPServiceContext.GetContext(site);
                            UserProfileManager upm          = new UserProfileManager(serviceContext);
                            string accountName = GetAccountName();
                            //this.Controls.Add(new LiteralControl("name:" + accountName + "<br/>"));
                            UserProfile u = upm.GetUserProfile(accountName);
                            SPSocialFeedManager feedManager = new SPSocialFeedManager(u, serviceContext);
                            SPSocialFeed feed        = feedManager.GetFeedFor(web.Url, socialOptions);
                            SPSocialThread[] threads = feed.Threads;
                            //this.Controls.Add(new LiteralControl("count:" + threads.Length + "<br/>"));
                            foreach (SPSocialThread thread in threads)
                            {
                                //只统计用户发布的新闻源,thread.Attributes.ToString() == "None"表示用户关注了哪些内容,这部分没有统计
                                if (thread.Attributes.ToString() != "None")
                                {
                                    string actorAccount;

                                    if (thread.Actors.Length == 1)
                                    {
                                        actorAccount = thread.Actors[0].AccountName;
                                    }
                                    else
                                    {
                                        actorAccount = thread.Actors[1].AccountName;
                                    }
                                    //string temp = "";
                                    //for (int k = 0; k < thread.Actors.Length; k++)
                                    //{
                                    //    temp += thread.Actors[k].AccountName+" 、 ";
                                    //}
                                    //this.Controls.Add(new LiteralControl("actorlength:" + thread.Actors.Length + ";actorAccount:" + temp + "<br/>"));
                                    //当前用户
                                    if (actorAccount.ToLower() == accountName.ToLower())
                                    {
                                        i = i + 1;
                                    }

                                    j = j + 1;
                                }
                            }
                            totalTimes[0] = i; //个人总数
                            //this.Controls.Add(new LiteralControl("my:" + i + "<br/>"));
                            totalTimes[1] = j; //团队总数
                            //this.Controls.Add(new LiteralControl("all:" + j + "<br/>"));

                            socialOptions = new SPSocialFeedOptions();
                            socialOptions.MaxThreadCount = int.MaxValue;
                            //this.Controls.Add(new LiteralControl("Now:" + DateTime.Now + "<br/>24小时前:" + DateTime.Now.AddHours(-24) + "<br/>一天前:" + DateTime.Now.AddDays(-1)));
                            socialOptions.NewerThan = DateTime.Now.AddHours(-32);//.Date.AddDays(-1).AddHours(8);
                            feed          = feedManager.GetFeedFor(web.Url, socialOptions);
                            threads       = feed.Threads;
                            totalTimes[2] = threads.Length;//当日更新

                            socialOptions = new SPSocialFeedOptions();
                            socialOptions.MaxThreadCount = int.MaxValue;
                            socialOptions.NewerThan      = DateTime.Now.Date.AddDays(-6).AddHours(-8);//.AddHours(8);
                            feed          = feedManager.GetFeedFor(web.Url, socialOptions);
                            threads       = feed.Threads;
                            totalTimes[3] = threads.Length;//本周更新
                            //this.Controls.Add(new LiteralControl("week:" + threads.Length + "<br/>"));
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                this.Controls.Add(new LiteralControl(ex.Message));
            }
            return(totalTimes);
        }
 public static void Main(string[] args)
 {
     if (args.Length == 0)
     {
         PrintHelp();
     }
     else
     {
         site = args[1];
         sc = SPServiceContext.GetContext(new SPSite(site));
         switch (args[0])
         {
             case "1f":
                 AddSyncFile(args[2], args[3], args[4]);
                 break;
             case "1s":
                 AddSyncStream(args[2], args[3], args[4], args[5]);
                 break;
             case "1b":
                 AddSyncByte(args[2], args[3], args[4], args[5]);
                 break;
             case "2f":
                 if (args.Length == 6)
                 {
                     AddAsyncFile(args[2], args[3], args[4], args[5]);
                 }
                 else
                 {
                     AddAsyncFile(args[2], args[3], args[4], null);
                 }
                 break;
             case "2o":
                 AddAsyncFolder(args[2], args[3], args[4]);
                 break;
             case "2l":
                 AddAsyncLibrary(args[2], args[3], args[4]);
                 break;
             case "3":
                 GetJobStatus();
                 break;
             case "4":
                 GetJobItems(args[2]);
                 break;
             case "5":
                 GetSupportedLanguages();
                 break;
             case "6":
                 GetSupportedFileExtensions();
                 break;
             case "7":
                 GetMaximumFileSize();
                 break;
             case "8":
                 CancelJob(args[2]);
                 break;
             default:
                 Console.WriteLine("incorrect option");
                 break;
         }
     }
 }
Esempio n. 14
0
 /// <summary>
 /// When using this constructor, the default search service application is used to create the service context.
 /// </summary>
 public SearchAdminUtility()
 {
     // Get the default service context
     _context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
 }
Esempio n. 15
0
        private static void RebuildMetadataProperties(XNode config, SPServiceContext context)
        {
            // Get the search service application proxy
            var searchProxy = SearchServiceApplicationProxy.GetProxy(context);
            // Another alternative is the following line ;)
            // * var searchProxy =
            //   context.GetDefaultProxy(typeof (SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;

            if (searchProxy == null)
                throw new InvalidOperationException("Search Service Application was not found.");

            // Get the search service application info object so we can find the Id of
            // our Search Service Application.
            var ssai = searchProxy.GetSearchServiceApplicationInfo();

            // Get the application itself
            var searchApp = SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(ssai.SearchServiceApplicationId);

            // Get the schema of our Search Service Application
            var schema = new Schema(searchApp);

            var crawledPropsCache = new List<CrawledProperty>();
            var categories = schema.AllCategories;

            // Remove Managed Properties
            var managedPropsRemove = config.XPathSelectElements("/SearchConfiguration/ManagedProperties/remove");
            RemoveManagedProperties(schema, managedPropsRemove);

            var loadedCategories = new HashSet<string>();

            // Add / update crawled properties under different categories
            // SearchConfiguration > CrawledProperties > Category
            foreach (var categoryCfg in config.XPathSelectElements("/SearchConfiguration/CrawledProperties/Category"))
            {
                // If crawled properties in this category are not loaded
                // load them and add category name to the list.
                var categoryName = TryGetAttributeValue(categoryCfg, "Name");
                if (string.IsNullOrEmpty(categoryName))
                {
                    Logger.LogMessage(SeverityLevels.Critical, LogCategory,
                        string.Format(CategoryAttributeMissingLogFormat, "Name"));
                    continue;
                }
                var cat = categories[categoryName];
                if (!loadedCategories.Contains(categoryName))
                {
                    crawledPropsCache.AddRange(categories[categoryName].GetAllCrawledProperties().Cast<CrawledProperty>());
                    loadedCategories.Add(categoryName);
                }

                // SearchConfiguration > CrawledProperties > Category > * (clear | CrawledProperty)
                foreach (var crawledPropCfg in categoryCfg.Elements())
                {
                    if (crawledPropCfg.Name == "clear")
                    {
                        ClearCrawledPropertiesInCategory(crawledPropsCache, cat, categoryCfg);
                    }
                    else if (crawledPropCfg.Name == "CrawledProperty")
                    {
                        // Create the crawled property if it doesn't exist
                        CreateCrawledPropertyIfDoesNotExist(crawledPropsCache, cat, crawledPropCfg);
                    }
                }

            }
            // Get all the managed properties
            // Create all required managed properties
            // SearchConfiguration > ManagedProperties > ManagedProperty
            // foreach (var managedPropCfg in config.Element("SearchConfiguration").Element("ManagedProperties").Elements("ManagedProperty"))
            foreach (var managedPropCfg in config.XPathSelectElements("/SearchConfiguration/ManagedProperties/ManagedProperty"))
            {
                var managedPropName = TryGetAttributeValue(managedPropCfg, "Name");
                if (string.IsNullOrEmpty(managedPropName))
                {
                    Logger.LogMessage(SeverityLevels.Critical, LogCategory,
                        string.Format(UnknownManagedPropertyAttributeMissingLogFormat, "Name"));
                    continue;
                }
                var managedPropType = TryGetAttributeValue(managedPropCfg, "Type");
                if (string.IsNullOrEmpty(managedPropType))
                {
                    Logger.LogMessage(SeverityLevels.Critical, LogCategory,
                        string.Format(KnownManagedPropertyAttributeMissingLogFormat, managedPropName, "Type"));
                    continue;
                }
                var managedProp = CreateOrGetManagedProperty(schema, managedPropName, managedPropType);

                // Create all the required mappings for the current Managed Property
                var isMappingChanged = false;
                MappingCollection mappings = null;
                foreach (var mapCfg in managedPropCfg.Elements())
                {
                    if (mapCfg.Name == "clear")
                    {
                        // Clear all mappings of this ManagedProperty
                        managedProp.DeleteAllMappings();
                        isMappingChanged = true;
                    }
                    else if (mapCfg.Name == "Map")
                    {
                        // Add new mappings
                        mappings = managedProp.GetMappings();
                        var crawledPropName = mapCfg.Value;
                        var mappingCategoryName = TryGetAttributeValue(mapCfg, "Category");
                        var crawledProp = FindCrawledProperty(schema, crawledPropName, mappingCategoryName,
                            crawledPropsCache, loadedCategories);

                        // Map the managed property to the crawled property (if found)
                        if (crawledProp != null)
                        {
                            var mapping = new Mapping(
                                crawledProp.Propset,
                                crawledPropName,
                                crawledProp.VariantType,
                                managedProp.PID);
                            if (!mappings.Contains(mapping))
                            {
                                mappings.Add(mapping);
                                isMappingChanged = true;
                            }
                        }
                        else
                        {
                            Logger.LogMessage(SeverityLevels.Critical, LogCategory,
                                string.Format(PropertyMappingFailedExceptionFormat, managedPropName));
                        }
                    }
                }

                if (isMappingChanged) managedProp.SetMappings(mappings);
            }
        }
Esempio n. 16
0
        private static bool ProcessWorkMatterDocuments()
        {
            inProgress = true;
            bool success = false;
            try
            {
                foreach(string libraryName in Settings.Default.LibrariesToProcess)
                {
                    using (SPSite site = new SPSite(ConfigurationManager.AppSettings["SiteUrl"], SPUserToken.SystemAccount))
                    {
                        Console.WriteLine("Successfully connected to site at " + site.Url);
                        using (SPWeb web = site.OpenWeb())
                        {
                            Console.WriteLine("Successfully opened SPWeb at " + web.Url);
                            SPList workMatterDocumentLibrary = web.Lists[libraryName];
                            SPQuery query = new SPQuery();
                            query.ViewXml = Util.GetViewQuery();
                            query.QueryThrottleMode = SPQueryThrottleOption.Override;
                            do
                            {
                                SPListItemCollection items = workMatterDocumentLibrary.GetItems(query);
                                int totalItems = items.Count;
                                Console.WriteLine("Processing items " + (query.ListItemCollectionPosition != null ? query.ListItemCollectionPosition.ToString() : "0") + " to " + query.ListItemCollectionPosition + totalItems);
                                query.ListItemCollectionPosition = items.ListItemCollectionPosition;
                                for (int i = 0; i < items.Count; i++)
                                {
                                    SPListItem item = items[i];

                                    try
                                    {
                                        web.AllowUnsafeUpdates = true;
                                        Records.BypassLocks(item, delegate (SPListItem delegateItem)
                                        {
                                            using (DisabledEventsScope scope = new DisabledEventsScope())
                                            {

                                                SPBusinessDataField field = delegateItem.Fields[Resource.FieldBCSWorkMatterDocument] as SPBusinessDataField;
                                                string documentId = Util.GetDocumentId(delegateItem);
                                                using (SPServiceContextScope ctxScope = new SPServiceContextScope(SPServiceContext.GetContext(site)))
                                                {
                                                    try
                                                    {
                                                        Util.SetBCSField(delegateItem, field, documentId, "GetWorkMatterDocumentBySPID");
                                                        Util.ClearFields(item);
                                                        if (delegateItem.Fields.ContainsField(Resource.FieldBCSWorkMatterDocumentStatus) && delegateItem[Resource.FieldBCSWorkMatterDocumentStatus] != null && delegateItem[Resource.FieldBCSWorkMatterDocumentStatus].ToString() == "Final")
                                                        {
                                                            Util.LockItem(delegateItem);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        // Swallow the error at this level
                                                    }
                                                }

                                                Console.WriteLine("Document updated. ItemId=" + delegateItem.ID);
                                            }
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        Util.LogError("Error updating document: " + ex.Message);
                                        Console.WriteLine("Error updating document: " + ex.Message);
                                    }
                                    finally
                                    {
                                        web.AllowUnsafeUpdates = false;
                                    }
                                }
                            }
                            while (query.ListItemCollectionPosition != null);
                        }
                    }
                }
                success = true;
            }
            catch (Exception ex)
            {
                success = false;
                Util.LogError("Error in ProcessWorkMatterDocuments(): " + ex.Message);
                Console.WriteLine("Error in ProcessWorkMatterDocuments(): " + ex.Message);
            }
            inProgress = false;
            return success;
        }
Esempio n. 17
0
        private void generateTableOfAllInvolved()
        {
            WBAction inviteIndividualsAction = WorkBox.GetAction(WBAction.ACTION_KEY__INVITE_INDIVIDUALS);

            if (inviteIndividualsAction.IsEnabled)
            {
                currentUserCanRemoveIndividuals = true;
            }

            WBAction inviteTeamsAction = WorkBox.GetAction(WBAction.ACTION_KEY__INVITE_TEAMS);

            if (inviteTeamsAction.IsEnabled)
            {
                currentUserCanRemoveTeams = true;
            }

            SPServiceContext   serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);
            UserProfileManager profileManager = new UserProfileManager(serviceContext);

            Dictionary <String, String> headers = new Dictionary <String, String>();

            headers.Add("body", "\n\nWork Box Title: " + WorkBox.Title + "\nWork Box URL: " + WorkBox.Url);

            string html = "<p>Users Involved with <b>" + WorkBox.Title + "</b></p>\n";

            html += "<table class=\"wbf-dialog-form\">\n";

            if (WorkBox.OwningTeam != null)
            {
                html += "<tr><td class=\"wbf-field-name-panel wbf-wider\"><b>Owning Team:</b><ul><li>";

                html += WBUtils.GenerateLinkToEmailGroup("Email work box owners", WorkBox.GetAllOwners(SPContext.Current.Site).WBxToEmails(), headers);

                html += "</li></ul></td><td class=\"wbf-field-value-panel\">\n";

                html += renderTeamAsFieldSet(profileManager, SPContext.Current.Site, WorkBox.OwningTeam);

                html += "</td></tr>\n";
            }


            html += "<tr><td class=\"wbf-field-name-panel wbf-wider\"><b>Involved Teams:</b><ul><li>";

            html += WBUtils.GenerateLinkToEmailGroup("Email all involved with work box", WorkBox.GetAllInvolved(SPContext.Current.Site).WBxToEmails(), headers);

            html += "</li></ul></td><td class=\"wbf-field-value-panel\">\n";

            if (WorkBox.InvolvedTeams != null && WorkBox.OwningTeam != null)
            {
                foreach (WBTeam involved in WorkBox.InvolvedTeams)
                {
                    if (involved.Id.Equals(WorkBox.OwningTeam.Id))
                    {
                        continue;
                    }

                    html += renderTeamAsFieldSet(profileManager, SPContext.Current.Site, involved, "Involved");
                }
            }

            html += "</td></tr>\n";

            html += "<tr><td class=\"wbf-field-name-panel wbf-wider\"><b>Involved Individuals:</b></td><td class=\"wbf-field-value-panel\"><ul>\n";

            if (WorkBox.InvolvedIndividuals != null)
            {
                foreach (SPUser user in WorkBox.InvolvedIndividuals)
                {
                    html += "<li>" + renderUser(profileManager, user, "Involved") + "</li>";
                }
            }

            html += "</ul>";
            html += "</td></tr>\n";


            html += "<tr><td class=\"wbf-field-name-panel wbf-wider\"><b>Visiting Teams:</b><ul><li>";

            html += WBUtils.GenerateLinkToEmailGroup("Email everyone who can visit the work box", WorkBox.GetAllWhoCanVisit(SPContext.Current.Site).WBxToEmails(), headers);

            html += "</li></ul></td><td class=\"wbf-field-value-panel\">\n";

            if (WorkBox.VisitingTeams != null)
            {
                foreach (WBTeam visiting in WorkBox.VisitingTeams)
                {
                    html += renderTeamAsFieldSet(profileManager, SPContext.Current.Site, visiting, "Visiting");
                }
            }

            html += "</td></tr>\n";

            html += "<tr><td class=\"wbf-field-name-panel wbf-wider\"><b>Visiting Individuals:</b></td><td class=\"wbf-field-value-panel\"><ul>\n";

            if (WorkBox.VisitingIndividuals != null)
            {
                foreach (SPUser user in WorkBox.VisitingIndividuals)
                {
                    html += "<li>" + renderUser(profileManager, user, "Visiting") + "</li>";
                }
            }

            html += "</ul>";
            html += "</td></tr>\n";


            html += "</table>\n";

            GeneratedViewOfAllInvolved.Text = html;
        }
Esempio n. 18
0
        public string GetSearchResult(string messageInput)
        {
            string k   = GetSearchKeyWord(messageInput);
            string ret = string.Empty;

            using (SPMonitoredScope scope = new SPMonitoredScope("MyCustomMessageHandler.GetSearchResult"))
            {
                //KeywordQuery keywordquery = new KeywordQuery(SPContext.Current.Site);
                //keywordquery.ResultTypes = ResultType.RelevantResults;
                //keywordquery.QueryText = string.Concat("ContentSource=", contentSourceName, " ", AppearInWeChat, "=True");
                //keywordquery.SelectProperties.Add(WeChatResult);
                //keywordquery.TrimDuplicates = false;
                //keywordquery.RowsPerPage = 0;
                //keywordquery.RowLimit = 10;
                //keywordquery.Timeout = 5000;

                //SearchExecutor searchexecutor = new SearchExecutor();
                //2013 foundation 里面的SearchExecutor这里没有
                //ResultTableCollection resulttablecollection = searchexecutor.ExecuteQuery(keywordquery);
                //ResultTable resulttable = resulttablecollection.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault();

                //https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ms493601(v=office.14)
                SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site));
                KeywordQuery query = new KeywordQuery(proxy);
                query.ResultsProvider = Microsoft.Office.Server.Search.Query.SearchProvider.Default;
                query.QueryText       = string.Concat("ContentSource=", contentSourceName, " ", AppearInWeChat, "=True");
                query.ResultTypes    |= ResultType.RelevantResults;
                ResultTableCollection searchResults = query.Execute();
                if (searchResults.Exists(ResultType.RelevantResults))
                {
                    ResultTable searchResult = searchResults[ResultType.RelevantResults];
                    DataTable   result       = new DataTable();
                    result.TableName = "Result";
                    result.Load(searchResult, LoadOption.OverwriteChanges);

                    StringBuilder sb = new StringBuilder();
                    foreach (DataRow r in result.Rows)
                    {
                        sb.Append(r[WeChatResult]);
                        sb.Append(System.Environment.NewLine);
                    }
                    ret = sb.ToString();
                }
            }

            return(ret);
        }
        private DataTable GetItems()
        {
            DataTable resultsDataTable = new DataTable();

            if (tags.Length > 0)
            {
                SPSite site = new SPSite(SPContext.Current.Site.Url);

                /*
                 * FullTextSqlQuery query = new FullTextSqlQuery(site);
                 * query.Hint = QueryHint.OptimizeWithPropertyStore;
                 * // inserito per prendere tutto. BUG della search
                 * query.TrimDuplicates = false;
                 * query.QueryText = "SELECT Path, title, Created, Tags, TipoContenuto, SiteTitle, SiteName FROM scope() WHERE \"scope\"='All Sites' AND (CONTAINS(Tags,'\"" + tags[0] + "\"')";
                 * if (tags.Length > 1)
                 * {
                 *  for (int i = 1; i < tags.Length; i++)
                 *  {
                 *      query.QueryText += " OR CONTAINS(Tags,'\"" + tags[i] + "\"')";
                 *  }
                 * }
                 * query.QueryText += ") ORDER BY LastModifiedTime Desc";
                 * query.SiteContext = new Uri(site.Url);
                 * query.ResultTypes = ResultType.RelevantResults;
                 * */
                SearchServiceApplicationProxy proxy =
                    (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site));
                KeywordQuery query = new KeywordQuery(proxy);
                //query.EnableFQL = true;
                query.QueryText = propertyName + ":\"" + tags[0] + "\"";
                if (tags.Length > 1)
                {
                    for (int i = 1; i < tags.Length; i++)
                    {
                        query.QueryText += " OR " + propertyName + ":\"" + tags[i] + "\"";
                    }
                }
                query.ResultsProvider = SearchProvider.Default;
                query.ResultTypes     = ResultType.RelevantResults;
                query.StartRow        = 0;
                query.RowLimit        = 5000;
                query.TrimDuplicates  = false;
                query.SelectProperties.Add("Path");
                query.SelectProperties.Add("title");
                query.SelectProperties.Add("Descrizione");
                query.SelectProperties.Add(propertyName);
                query.SelectProperties.Add("TipoContenuto");
                query.SelectProperties.Add("Created");
                query.SelectProperties.Add("SiteTitle");
                query.SelectProperties.Add("SiteName");
                query.SortList.Add("Rank", Microsoft.Office.Server.Search.Query.SortDirection.Descending);
                //
                ResultTableCollection resultTables    = query.Execute();
                ResultTable           relevantResults = resultTables[ResultType.RelevantResults];
                resultsDataTable.Load(relevantResults, LoadOption.OverwriteChanges);
            }
            return(resultsDataTable);
        }
Esempio n. 20
0
        //按时间显示开始的十条
        /// <summary>
        /// 1为博文,2为汇总
        /// </summary>
        /// <param name="queryState"></param>
        /// <returns></returns>
        private DataTable FullQuery(int queryState)
        {
            DataTable queryDataTable = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPServiceContext context           = SPServiceContext.Current;// ServerContext.Current;//ServerContext.GetContext
                SearchServiceApplicationProxy ssap = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site));
                using (KeywordQuery qry = new KeywordQuery(ssap))
                {
                    qry.EnableStemming = true;
                    qry.TrimDuplicates = true;
                    if (queryState == 1)
                    {
                        qry.RowLimit = totalCount;
                    }
                    else
                    {
                        qry.RowLimit = 5000;
                    }
                    string queryText = "-author:系统帐户 -author:administrator ContentClass:STS_ListItem_Posts";
                    if (queryState > 1)
                    {
                        double dValue = -30;
                        //if (queryState == 3)
                        //    dValue = -60;
                        queryText = queryText + " Created:" + DateTime.Now.AddDays(dValue).ToString("yyyy-MM-dd") + ".." + DateTime.Now.ToString("yyyy-MM-dd");
                    }
                    qry.QueryText = queryText;//
                    qry.SelectProperties.AddRange(new string[] { "WorkId", "Title", "Author", "AuthorOWSUSER", "Created", "Path", "EditorOWSUSER", "HitHighlightedSummary", "ParentLink" });
                    qry.SortList.Add("Created", Microsoft.Office.Server.Search.Query.SortDirection.Descending);
                    SearchExecutor searchExecutor = new SearchExecutor();
                    ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(qry);
                    IEnumerator <ResultTable> iResult           = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults).GetEnumerator();
                    iResult.MoveNext();
                    ResultTable resultTable = iResult.Current;
                    queryDataTable          = resultTable.Table;
                    foreach (DataRow dr in queryDataTable.Rows)
                    {
                        string author = dr["Author"].ToString();
                        if (author.IndexOf(";") > 0)//多个作者
                        {
                            dr["Author"] = author.Substring(0, author.IndexOf(";"));
                        }
                    }
                    queryDataTable.AcceptChanges();
                }
            });
            return(queryDataTable);
        }
Esempio n. 21
0
 /// <summary>
 /// When using this constructor, the given site collection is used to create the service context.
 /// </summary>
 /// <param name="site">SPSite object to be used when constructing service context</param>
 public SearchAdminUtility(SPSite site)
 {
     // Get the service context related to the given site
     _site = site;
     _context = SPServiceContext.GetContext(site);
 }
        /// <summary>
        /// Imports the specified XML.
        /// </summary>
        /// <param name="xml">The XML.</param>
        /// <param name="context">The context.</param>
        /// <param name="deleteExisting">if set to <c>true</c> [delete existing].</param>
        /// <param name="compile">if set to <c>true</c> [compile].</param>
        /// <param name="mapFile">The map file.</param>
        internal static void Import(string xml, SPServiceContext context, bool deleteExisting, bool compile, string mapFile)
        {
            AudienceManager manager = new AudienceManager(context);

            XmlDocument audiencesDoc = new XmlDocument();
            audiencesDoc.LoadXml(xml);

            XmlNodeList audienceElements = audiencesDoc.SelectNodes("//Audience");
            if (audienceElements == null)
                throw new ArgumentException("The input file does not contain any audience elements.");

            StringBuilder sb = new StringBuilder();
            XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
            xmlWriter.Formatting = Formatting.Indented;
            xmlWriter.WriteStartElement("Replacements");

            Dictionary<Guid, string> ids = new Dictionary<Guid, string>();
            if (deleteExisting)
            {
                Logger.Write("Progrss: Deleting existing audiences.");
                foreach (Audience au in manager.Audiences)
                    ids.Add(au.AudienceID, au.AudienceName);

                foreach (Guid id in ids.Keys)
                {
                    if (id == Guid.Empty)
                        continue;

                    string name = manager.Audiences[id].AudienceName;
                    manager.Audiences.Remove(id);
                }
            }

            foreach (XmlElement audienceElement in audienceElements)
            {
                string audienceName = audienceElement.GetAttribute("AudienceName");
                string audienceDesc = audienceElement.GetAttribute("AudienceDescription");

                Audience audience;
                bool updatedAudience = false;
                if (manager.Audiences.AudienceExist(audienceName))
                {
                    Logger.Write("Progress: Updating audience {0}.", audienceName);
                    audience = manager.Audiences[audienceName];
                    audience.AudienceDescription = audienceDesc ?? "";
                    updatedAudience = true;
                }
                else
                {
                    // IMPORTANT: the create method does not do a null check but the methods that load the resultant collection assume not null.
                    Logger.Write("Progress: Creating audience {0}.", audienceName);
                    audience = manager.Audiences.Create(audienceName, audienceDesc ?? "");
                }

                audience.GroupOperation = (AudienceGroupOperation)Enum.Parse(typeof (AudienceGroupOperation),
                                                     audienceElement.GetAttribute("GroupOperation"));

                audience.OwnerAccountName = audienceElement.GetAttribute("OwnerAccountName");

                audience.Commit();

                if (updatedAudience && audience.AudienceID != Guid.Empty)
                {
                    // We've updated an existing audience.
                    xmlWriter.WriteStartElement("Replacement");
                    xmlWriter.WriteElementString("SearchString", string.Format("(?i:{0})", (new Guid(audienceElement.GetAttribute("AudienceID")).ToString().ToUpper())));
                    xmlWriter.WriteElementString("ReplaceString", audience.AudienceID.ToString().ToUpper());
                    xmlWriter.WriteEndElement(); // Replacement
                }
                else if (!updatedAudience && audience.AudienceID != Guid.Empty && ids.ContainsValue(audience.AudienceName))
                {
                    // We've added a new audience which we just previously deleted.
                    xmlWriter.WriteStartElement("Replacement");
                    foreach (Guid id in ids.Keys)
                    {
                        if (ids[id] == audience.AudienceName)
                        {
                            xmlWriter.WriteElementString("SearchString", string.Format("(?i:{0})", id.ToString().ToUpper()));
                            break;
                        }
                    }
                    xmlWriter.WriteElementString("ReplaceString", audience.AudienceID.ToString().ToUpper());
                    xmlWriter.WriteEndElement(); // Replacement
                }

                XmlElement rulesElement = (XmlElement)audienceElement.SelectSingleNode("rules");
                if (rulesElement == null || rulesElement.ChildNodes.Count == 0)
                {
                    audience.AudienceRules = new ArrayList();
                    audience.Commit();
                    continue;
                }

                string rules = rulesElement.OuterXml;
                Logger.Write("Progress: Adding rules to audience {0}.", audienceName);
                AddAudienceRule.AddRules(context, audienceName, rules, true, compile, false, AppendOp.AND);
            }

            xmlWriter.WriteEndElement(); // Replacements

            if (!string.IsNullOrEmpty(mapFile))
            {
                xmlWriter.Flush();
                File.WriteAllText(mapFile, sb.ToString());
            }
        }
        /// <summary>
        /// Adds the rules.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="audienceName">Name of the audience.</param>
        /// <param name="rules">The rules.</param>
        /// <param name="clearExistingRules">if set to <c>true</c> [clear existing rules].</param>
        /// <param name="compile">if set to <c>true</c> [compile].</param>
        /// <param name="groupExisting">if set to <c>true</c> [group existing].</param>
        /// <param name="appendOp">The append op.</param>
        /// <returns></returns>
        internal static ArrayList AddRules(SPServiceContext context, string audienceName, string rules, bool clearExistingRules, bool compile, bool groupExisting, AppendOp appendOp)
        {
            AudienceManager manager = new AudienceManager(context);

            if (!manager.Audiences.AudienceExist(audienceName))
            {
                throw new SPException("Audience name does not exist");
            }

            Audience audience = manager.Audiences[audienceName];
            /*
            Operator        Need left and right operands (not a group operator)
            =               Yes
            >               Yes
            >=              Yes
            <               Yes
            <=              Yes
            Contains        Yes
            Reports Under   Yes (Left operand must be 'Everyone')
            <>              Yes
            Not contains    Yes
            AND             No
            OR              No
            (               No
            )               No
            Member Of       Yes (Left operand must be 'DL')
            */
            XmlDocument rulesDoc = new XmlDocument();
            rulesDoc.LoadXml(rules);

            ArrayList audienceRules = audience.AudienceRules;
            bool ruleListNotEmpty = false;

            if (audienceRules == null || clearExistingRules)
                audienceRules = new ArrayList();
            else
                ruleListNotEmpty = true;

            //if the rule is not emply, start with a group operator 'AND' to append
            if (ruleListNotEmpty)
            {
                if (groupExisting)
                {
                    audienceRules.Insert(0, new AudienceRuleComponent(null, "(", null));
                    audienceRules.Add(new AudienceRuleComponent(null, ")", null));
                }

                audienceRules.Add(new AudienceRuleComponent(null, appendOp.ToString(), null));
            }

            if (rulesDoc.SelectNodes("//rule") == null || rulesDoc.SelectNodes("//rule").Count == 0)
                throw new ArgumentException("No rules were supplied.");

            foreach (XmlElement rule in rulesDoc.SelectNodes("//rule"))
            {
                string op = rule.GetAttribute("op").ToLowerInvariant();
                string field = null;
                string val = null;
                bool valIsRequired = true;
                bool fieldIsRequired = false;

                switch (op)
                {
                    case "=":
                    case ">":
                    case ">=":
                    case "<":
                    case "<=":
                    case "contains":
                    case "<>":
                    case "not contains":
                        field = rule.GetAttribute("field");
                        val = rule.GetAttribute("value");
                        fieldIsRequired = true;
                        break;
                    case "reports under":
                        field = "Everyone";
                        val = rule.GetAttribute("value");
                        break;
                    case "member of":
                        field = "DL";
                        val = rule.GetAttribute("value");
                        break;
                    case "and":
                    case "or":
                    case "(":
                    case ")":
                        valIsRequired = false;
                        break;
                    default:
                        throw new ArgumentException(string.Format("Rule operator is invalid: {0}", rule.GetAttribute("op")));
                }
                if (valIsRequired && string.IsNullOrEmpty(val))
                    throw new ArgumentNullException(string.Format("Rule value attribute is missing or invalid: {0}", rule.GetAttribute("value")));

                if (fieldIsRequired && string.IsNullOrEmpty(field))
                    throw new ArgumentNullException(string.Format("Rule field attribute is missing or invalid: {0}", rule.GetAttribute("field")));

                AudienceRuleComponent r0 = new AudienceRuleComponent(field, op, val);
                audienceRules.Add(r0);
            }

            audience.AudienceRules = audienceRules;
            audience.Commit();

            if (compile)
            {
                SPServiceApplication svcApp = Utilities.GetUserProfileServiceApplication(context);
                if (svcApp != null)
                    CompileAudience(svcApp.Id, audience.AudienceName);
            }

            return audienceRules;
        }
Esempio n. 24
0
        public static bool ConvertLibrary(SPList list, string fileFormat, bool isWorkflow, ActivityExecutionContext executionContext)
        {
            ISharePointService wfService = null;

            if (executionContext != null)
            {
                wfService = executionContext.GetService <ISharePointService>();
            }

            using (SPSite spSite = new SPSite(list.ParentWeb.Site.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    try
                    {
                        var proxies =
                            SPServiceContext.GetContext(spSite).GetProxies(typeof(WordServiceApplicationProxy));

                        if (proxies.Any())
                        {
                            _proxy = proxies.First();
                        }
                        else
                        {
                            var exception = new SPException();
                            throw exception;
                        }

                        var job = new ConversionJob(_proxy.DisplayName)
                        {
                            UserToken = spSite.UserToken
                        };

                        if (spSite.SiteSubscription != null)
                        {
                            job.SubscriptionId = spSite.SiteSubscription.Id;
                        }

                        job.Settings.OutputFormat = DeriveFileFormat(fileFormat);
                        job.Name = list.Title + "-" + Guid.NewGuid();
                        job.AddLibrary(list, list);
                        job.Start();

                        if (wfService != null)
                        {
                            wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowCompleted,
                                                       0, TimeSpan.Zero, "Information", "Conversion job queued for " + list.Title, string.Empty);
                        }

                        return(true);
                    }
                    catch (SPException exception)
                    {
                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus",
                                                                                           TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected,
                                                              "An unexpected error has occurred attempting to find the Word Automation Services Proxy", exception.StackTrace);

                        if (wfService != null)
                        {
                            wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError,
                                                       0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to find the" +
                                                       "Word Automation Services Proxy for " + list.Title, exception.StackTrace);
                        }

                        return(false);
                    }
                    catch (InvalidOperationException exception2)
                    {
                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus",
                                                                                           TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected,
                                                              "An unexpected error has occurred attempting to contact the Word Automation Services. Validate that the" +
                                                              "Word Automation Service is Started.", exception2.StackTrace);

                        if (wfService != null)
                        {
                            wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError,
                                                       0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to contact the " +
                                                       "Word Automation Services. Validate that the Word Automation Service is Started. Attempted to process file " +
                                                       list.Title, exception2.StackTrace);
                        }

                        return(false);
                    }
                }
            }
        }
Esempio n. 25
0
        //获取当前用户发布的新闻源
        /// <summary>
        ///统计不同时间的用户和总的新闻源
        /// </summary>
        /// <param name="typeID">0-个人总数,1-团队总数,2-当日更新,3-本周更新</param>
        /// <returns></returns>
        private int[] GetPublishdNews( )
        {
            SPSocialFeedOptions socialOptions = new SPSocialFeedOptions();

            socialOptions.MaxThreadCount = int.MaxValue;
            int i = 0;
            int j = 0;

            int[] totalTimes = new int[4];

            try
            {
                string acountName = GetAccountName();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                        {
                            SPServiceContext serviceContext = SPServiceContext.GetContext(site);
                            UserProfileManager upm          = new UserProfileManager(serviceContext);
                            string accountName = GetAccountName();
                            UserProfile u      = upm.GetUserProfile(accountName);
                            SPSocialFeedManager feedManager = new SPSocialFeedManager(u, serviceContext);
                            //this.Controls.Add(new LiteralControl(accountName + "<br>"));
                            //SPSocialFeed feed = feedManager.GetFeedFor(accountName, socialOptions);//.GetFeed
                            SPSocialFeed feed        = feedManager.GetFeedFor(web.Url, socialOptions);//.GetFeed(SPSocialFeedType.Personal,  socialOptions);
                            SPSocialThread[] threads = feed.Threads;
                            foreach (SPSocialThread thread in threads)
                            {
                                if (thread.Attributes.ToString() != "None")
                                {
                                    //if (thread.RootPost.Text != null)
                                    //    this.Controls.Add(new LiteralControl("Text  " + thread.RootPost.Text + ""));
                                    //else if (thread.RootPost.Attachment != null)
                                    //    this.Controls.Add(new LiteralControl( thread.RootPost.Attachment.AttachmentKind.ToString () + "<img src='" + thread.RootPost.Attachment.Uri.ToString() + "'/><br>"));
                                    ////if (thread.RootPost.Text == "http://xqx2012/_layouts/15/studentlist/studentlist.aspx")
                                    ////    Console.WriteLine(thread.RootPost.Text );
                                    string actorAccount;
                                    if (thread.Actors.Length == 2)
                                    {
                                        actorAccount = thread.Actors[1].AccountName;
                                    }
                                    //this.Controls.Add(new LiteralControl("AccountName  " + thread.Actors[1].AccountName + "<br>"));
                                    else
                                    {
                                        actorAccount = thread.Actors[0].AccountName;
                                    }
                                    //this.Controls.Add(new LiteralControl("AccountName  " + thread.Actors[0].AccountName + "<br>"));
                                    //当前用户
                                    if (actorAccount.ToLower() == accountName.ToLower())
                                    {
                                        i = i + 1;
                                    }
                                    j = j + 1;
                                }
                            }
                            totalTimes[0] = i; //个人总数
                            totalTimes[1] = j; //团队总数

                            socialOptions = new SPSocialFeedOptions();
                            socialOptions.MaxThreadCount = int.MaxValue;
                            socialOptions.NewerThan      = DateTime.Now.Date.AddDays(-1).AddHours(8);
                            feed          = feedManager.GetFeedFor(accountName, socialOptions);
                            threads       = feed.Threads;
                            totalTimes[2] = threads.Length;//当日更新

                            socialOptions = new SPSocialFeedOptions();
                            socialOptions.MaxThreadCount = int.MaxValue;

                            socialOptions.NewerThan = DateTime.Now.Date.AddDays(-7).AddHours(8);
                            feed          = feedManager.GetFeedFor(accountName, socialOptions);
                            threads       = feed.Threads;
                            totalTimes[3] = threads.Length;//本周更新
                        }
                    }
                });
            }
            catch
            {
            }
            return(totalTimes);
        }
Esempio n. 26
0
 public OceanikServiceClient(SPServiceContext serviceContext)
 {
     _serviceContext = serviceContext;
 }
Esempio n. 27
0
        private void RecreateContentSources(XNode config, SPServiceContext context)
        {
            // Get the search service application proxy
            var searchProxy = SearchServiceApplicationProxy.GetProxy(context);

            if (searchProxy == null)
                throw new Exception(DefaultSsaProxyNotFoundExceptionMessage);

            var ssaInfo = searchProxy.GetSearchServiceApplicationInfo();
            var searchApp = SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(ssaInfo.SearchServiceApplicationId);
            var content = new Content(searchApp);

            // Remove content sources specified by remove tag in configuration XML.
            var removeContentSourceElements = config.XPathSelectElements("/SearchConfiguration/ContentSources/remove");
            foreach (var removeContentSourceElement in removeContentSourceElements)
            {
                var contentSourceName = TryGetAttributeValue(removeContentSourceElement, "Name");
                if (content.ContentSources.Exists(contentSourceName))
                {
                    var contentSource = content.ContentSources[contentSourceName];
                    contentSource.Delete();
                }
                else
                {
                    Logger.LogMessage(
                        SeverityLevels.Warning,
                        LogCategory,
                        string.Format(ContentSourceNotFoundRemovalFailedLogFormat,
                            contentSourceName));
                }
            }

            // Create new Content Sources (if they don't exist)
            var contentSourceElements = config.XPathSelectElements("/SearchConfiguration/ContentSources/ContentSource");
            foreach (var contentSourceElement in contentSourceElements)
            {
                var contentSourceName = TryGetAttributeValue(contentSourceElement,"Name");
                var contentSourceExists = content.ContentSources.Exists(contentSourceName);
                if (contentSourceExists)
                {
                    Logger.LogMessage(
                        SeverityLevels.Information,
                        LogCategory,
                        string.Format(ContentSourceExistsLogFormat,
                            contentSourceName));
                    var recreateAttr = contentSourceElement.Attribute("RecreateIfExists");
                    if (recreateAttr != null && bool.Parse(recreateAttr.Value))
                    {
                        var contentSource = content.ContentSources[contentSourceName];
                        if (contentSource.StartAddresses.Count > 0)
                        {
                            contentSource.StartAddresses.Clear();
                            contentSource.Update();
                        }
                        contentSource.Delete();
                        contentSourceExists = false;
                    }
                }
                if (!contentSourceExists)
                {
                    var contentSourceTypeName = TryGetAttributeValue(contentSourceElement,"Type");
                    var startFullCrawl = bool.Parse(contentSourceElement.AttributeOrDefault("StartFullCrawl", "false"));
                    var contentSourceType = GetContentSourceTypeFromString(contentSourceTypeName);
                    var contentSource = content.ContentSources.Create(contentSourceType, contentSourceName);
                    ConstructStartAddresses(contentSource, contentSourceElement.Elements("StartAddress"));
                    contentSource.Update();
                    if (startFullCrawl)
                        contentSource.StartFullCrawl();
                }
            }
        }
Esempio n. 28
0
        private void SyncAddMembers(SPGroup fromGroup, List <SPUser> newUsers)
        {
            WBFarm farm      = WBFarm.Local;
            String groupName = fromGroup.Name;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(farm.TimerJobsManagementSiteUrl))
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPServiceContext serviceContext   = SPServiceContext.GetContext(site);
                        UserProfileManager profileManager = new UserProfileManager(serviceContext);

                        SPList dailyJobs        = web.Lists[WBTimerTasksJob.DAILY_TIMER_TASKS__LIST_NAME];
                        SPView inOrderToExecute = dailyJobs.Views[WBTimerTasksJob.DAILY_TIMER_TASKS__ORDERED_VIEW_NAME];

                        foreach (SPListItem task in dailyJobs.GetItems(inOrderToExecute))
                        {
                            string command   = task.WBxGetColumnAsString(WBTimerTask.COLUMN_NAME__COMMAND);
                            string targetUrl = task.WBxGetColumnAsString(WBTimerTask.COLUMN_NAME__TARGET_URL);
                            string argument1 = task.WBxGetColumnAsString(WBTimerTask.COLUMN_NAME__ARGUMENT_1);

                            if (command == WBTimerTask.COMMAND__SYNCHRONISE_ALL_TEAMS)
                            {
                                try
                                {
                                    using (SPSite toSite = new SPSite(targetUrl))
                                    {
                                        SPGroup toGroup = toSite.RootWeb.WBxGetGroupOrNull(groupName);

                                        toSite.AllowUnsafeUpdates         = true;
                                        toSite.RootWeb.AllowUnsafeUpdates = true;

                                        if (toGroup == null)
                                        {
                                            SPUser defaultUser = WBUtils.GetLocalUserFromGroupOrSystemAccount(toSite, fromGroup);
                                            SPUser systemUser  = toSite.SystemAccount;

                                            WBLogging.Teams.Verbose("Found the user - about to create new group");
                                            toSite.RootWeb.SiteGroups.Add(groupName, systemUser, defaultUser, fromGroup.Description);

                                            WBLogging.Teams.Verbose("Created new group.");

                                            toGroup = toSite.RootWeb.SiteGroups[groupName];
                                        }

                                        foreach (SPUser fromUser in newUsers)
                                        {
                                            // If the user doesn't exist in the user profile - then we assume that they've been disabled:
                                            if (!profileManager.UserExists(fromUser.LoginName))
                                            {
                                                WBLogging.Teams.Monitorable("Ignoring user as they appear to be disabled: " + fromUser.LoginName);
                                                continue;
                                            }

                                            WBLogging.Teams.Verbose("Copying across a user: "******"Something went wrong when trying to add " + fromUser.LoginName + " to " + groupName + " on site collection " + targetUrl, exception);
                                                }
                                            }
                                        }

                                        toGroup.OnlyAllowMembersViewMembership = false;

                                        toGroup.Update();
                                    }
                                }
                                catch (Exception exception)
                                {
                                    WBLogging.Teams.Unexpected("Something went wrong when trying to add a set of users to " + groupName + " on site collection " + targetUrl, exception);
                                }
                            }
                        }
                    }
            });
        }
Esempio n. 29
0
        protected void saveButton_OnClick(object sender, EventArgs e)
        {
            try
            {
                bool digestOK = WorkBox.Web.ValidateFormDigest();

                if (digestOK)
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(WorkBox.Site.ID))
                            using (SPWeb elevatedWorkBoxWeb = elevatedSite.OpenWeb(WorkBox.Web.ID))
                            {
                                elevatedSite.AllowUnsafeUpdates       = true;
                                elevatedWorkBoxWeb.AllowUnsafeUpdates = true;

                                WorkBox elevatedWorkBox    = new WorkBox(elevatedSite, elevatedWorkBoxWeb);
                                elevatedWorkBox.ShortTitle = WorkBoxShortTitle.Text;
                                elevatedWorkBox.Web.Title  = WorkBoxPrettyTitle.Text;
                                elevatedWorkBox.GenerateTitle();

                                if (showReferenceID)
                                {
                                    elevatedWorkBox.ReferenceID = ReferenceID.Text;
                                }

                                if (showReferenceDate)
                                {
                                    if (!ReferenceDate.IsDateEmpty)
                                    {
                                        elevatedWorkBox.ReferenceDate = ReferenceDate.SelectedDate;
                                    }
                                }

                                elevatedWorkBox.Update();
                            }
                    });
                }
            }
            catch (Exception exception)
            {
                WBUtils.SendErrorReport(SPContext.Current.Web, "Exception in EditWorkBoxPropertise.saveButton_OnClick()", "Something went wrong when saving: " + exception.Message + " ... " + exception.StackTrace);
                throw new NotImplementedException("Something went wrong when saving the properties changes");
            }

            WBFarm farm = WBFarm.Local;
            String cachedDetailsListUrl = farm.OpenWorkBoxesCachedDetailsListUrl;

            if (!String.IsNullOrEmpty(cachedDetailsListUrl))
            {
                using (SPSite cacheSite = new SPSite(cachedDetailsListUrl))
                    using (SPWeb cacheWeb = cacheSite.OpenWeb())
                    {
                        SPList cacheList = cacheWeb.GetList(cachedDetailsListUrl);

                        SPServiceContext   serviceContext = SPServiceContext.GetContext(cacheSite);
                        UserProfileManager profileManager = new UserProfileManager(serviceContext);

                        // Get the current user's user profile:
                        UserProfile profile = profileManager.GetUserProfile(true);

                        // We're using the 'now' plus one hour ticks as we're not really looking to update the last modified dates of other work boxes.
                        WBUser.CheckLastModifiedDatesAndTitlesOfRecentWorkBoxes(cacheSite, cacheList, profile, DateTime.Now.AddHours(1).Ticks);

                        WBUser.CheckTitlesOfFavouriteWorkBoxes(cacheSite, cacheList, profile);
                    }
            }

            returnFromDialogOK("");
        }
    public static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            PrintHelp();
        }
        else
        {
            site = args[1];
            sc   = SPServiceContext.GetContext(new SPSite(site));
            switch (args[0])
            {
            case "1f":
                AddSyncFile(args[2], args[3], args[4]);
                break;

            case "1s":
                AddSyncStream(args[2], args[3], args[4], args[5]);
                break;

            case "1b":
                AddSyncByte(args[2], args[3], args[4], args[5]);
                break;

            case "2f":
                if (args.Length == 6)
                {
                    AddAsyncFile(args[2], args[3], args[4], args[5]);
                }
                else
                {
                    AddAsyncFile(args[2], args[3], args[4], null);
                }
                break;

            case "2o":
                AddAsyncFolder(args[2], args[3], args[4]);
                break;

            case "2l":
                AddAsyncLibrary(args[2], args[3], args[4]);
                break;

            case "3":
                GetJobStatus();
                break;

            case "4":
                GetJobItems(args[2]);
                break;

            case "5":
                GetSupportedLanguages();
                break;

            case "6":
                GetSupportedFileExtensions();
                break;

            case "7":
                GetMaximumFileSize();
                break;

            case "8":
                CancelJob(args[2]);
                break;

            default:
                Console.WriteLine("incorrect option");
                break;
            }
        }
    }
Esempio n. 31
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            Result = String.Empty;

            // get all of the information we currently have about the item
            // that this workflow is running on
            var listGuid = new Guid(__ListId);
            var web      = __Context.Web;
            var myList   = __Context.Web.Lists[listGuid];
            var myItem   = __Context.GetListItem(myList, __ListItem);

            var serviceContext = SPServiceContext.GetContext(__Context.Site);
            var client         = new BaristaServiceClient(serviceContext);

            var headers = new Dictionary <string, IEnumerable <string> >
            {
                { "Content-Type", new[] { "application/json" } }
            };

            var request = new BrewRequest
            {
                Code                = Code,
                Headers             = new BrewRequestHeaders(headers),
                Body                = Encoding.UTF8.GetBytes(Body),
                ScriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52",
                ExtendedProperties  = new Dictionary <string, string> {
                    { "SPSiteId", __Context.Site.ID.ToString() },
                    { "SPUrlZone", __Context.Site.Zone.ToString() },
                    { "SPUserToken", Convert.ToBase64String(__Context.Site.UserToken.BinaryToken) },
                    { "SPWebId", web.ID.ToString() },
                    { "SPListId", __ListId },
                    { "SPListItemUrl", myItem.Url },
                    { "SPWorkflowAssociationTitle", __Context.AssociationTitle },
                    { "SPWorkflowInstanceId", __Context.WorkflowInstanceId.ToString() },
                    { "SPWorkflowCurrentItemUrl", __Context.CurrentItemUrl },
                    { "SPWorkflowCurrentWebUrl", __Context.CurrentWebUrl },
                    { "SPWorkflowItemName", __Context.ItemName },
                    { "SPWorkflowTaskListGuid", __Context.TaskListGuid },
                    { "SPWorkflowStatusUrl", __Context.WorkflowStatusUrl },
                    { "SPWorkflowAssociatorUserLoginName", __Context.AssociatorUser.LoginName },
                    { "SPWorkflowInitiatorUserLoginName", __Context.InitiatorUser.LoginName },
                    { "SPWorkflowItemId", __Context.ItemId.ToString(CultureInfo.InvariantCulture) },
                    { "SPWorkflowStartedDateTime", __Context.StartedDateTime.ToUniversalTime().ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz") },
                    { "SPWorkflowLastRunDateTime", __Context.LastRunDateTime.ToUniversalTime().ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz") }
                }
            };

            var response = client.Eval(request);

            if (response.StatusCode == HttpStatusCode.BadRequest && response.ExtendedProperties.ContainsKey("Exception_Message"))
            {
                var wfService = executionContext.GetService <ISharePointService>();

                wfService.LogToHistoryList(executionContext.ContextGuid,
                                           SPWorkflowHistoryEventType.WorkflowError,
                                           0,
                                           TimeSpan.Zero,
                                           "Message",
                                           response.ExtendedProperties["Exception_Message"],
                                           "");

                wfService.LogToHistoryList(executionContext.ContextGuid,
                                           SPWorkflowHistoryEventType.WorkflowError,
                                           0,
                                           TimeSpan.Zero,
                                           "Name",
                                           response.ExtendedProperties["Exception_Name"],
                                           "");

                wfService.LogToHistoryList(executionContext.ContextGuid,
                                           SPWorkflowHistoryEventType.WorkflowError,
                                           0,
                                           TimeSpan.Zero,
                                           "Function Name",
                                           response.ExtendedProperties["Exception_FunctionName"],
                                           "");

                wfService.LogToHistoryList(executionContext.ContextGuid,
                                           SPWorkflowHistoryEventType.WorkflowError,
                                           0,
                                           TimeSpan.Zero,
                                           "Line Number",
                                           response.ExtendedProperties["Exception_LineNumber"],
                                           "");

                wfService.LogToHistoryList(executionContext.ContextGuid,
                                           SPWorkflowHistoryEventType.WorkflowError,
                                           0,
                                           TimeSpan.Zero,
                                           "Source Path",
                                           response.ExtendedProperties["Exception_SourcePath"],
                                           "");

                wfService.LogToHistoryList(executionContext.ContextGuid,
                                           SPWorkflowHistoryEventType.WorkflowError,
                                           0,
                                           TimeSpan.Zero,
                                           "Stack Trace",
                                           response.ExtendedProperties["Exception_StackTrace"],
                                           "");

                return(ActivityExecutionStatus.Faulting);
            }

            Result = Encoding.UTF8.GetString(response.Content);


            return(ActivityExecutionStatus.Closed);
        }
 public UserProfileHelper(SPServiceContext context, ILogger logger)
 {
     spContext = context;
     spLogger = logger;
 }
 public CvrServiceClient(SPServiceContext serviceContext) : base(serviceContext)
 {
 }
Esempio n. 34
0
 static void InitOrganizations(SPServiceContext context, SPSite site) {
     ProfileSubtypeManager subtypeManager = ProfileSubtypeManager.Get(context);
     string subtypeName = ProfileSubtypeManager.GetDefaultProfileName(ProfileType.Organization);
     ProfileSubtype subtype = subtypeManager.GetProfileSubtype(subtypeName);
     OrganizationProfileManager manager = new OrganizationProfileManager(context);
     OrganizationProfile rootProfile = manager.RootOrganization;
     using (var db = new CMSMIPEntities()) {
         var root = db.CMS_BA_IN_DEPT_INFO_V.Where(o => o.组织机构上级ID == 0).FirstOrDefault();
         CreateOrganization(root.组织机构名称, root.机构ID, rootProfile, subtype, manager, site);
     }
 }
Esempio n. 35
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string html      = "";
            string userValue = "";
            UserProfileValueCollection valueCollection = null;
            object valueObject = null;

            _site                     = SPContext.Current.Site;
            _serviceContext           = SPServiceContext.GetContext(_site);
            _userProfileConfigManager = new UserProfileConfigManager(_serviceContext);
            _profilePropertyManager   = _userProfileConfigManager.ProfilePropertyManager;

            _profileManager = new UserProfileManager(_serviceContext);
            _profileSubtypePropertyManager = _profileManager.DefaultProfileSubtypeProperties;

            // if you need another profile subtype
            //_profileSubtypePropertyManager = _profilePropertyManager.GetProfileSubtypeProperties("ProfileSubtypeName");

            _corePropertyManager        = _profilePropertyManager.GetCoreProperties();
            _profileTypePropertyManager = _profilePropertyManager.GetProfileTypeProperties(ProfileType.User);

            UserProfile profile = _profileManager.GetUserProfile(true);

            html += "<h1>First listing out all of the property types themselves</h1>";

            html += "<h2>ProfileSubtypeProperty list</h2>";

            html += "<table cellspacing='2' border='1'>";

            html += "<tr><th>Section/Property</th><th>Name</th><th>Display Name</th><th>Type Property Name</th><th>Core Property Name</th><th>Display Order</th><th>Current User's Value</th></tr>";

            foreach (ProfileSubtypeProperty profileSubtypeProperty in _profileSubtypePropertyManager.PropertiesWithSection)
            {
                userValue = "";
                if (!profileSubtypeProperty.IsSection)
                {
                    userValue       = "<i>(none)</i>";
                    valueCollection = profile[profileSubtypeProperty.Name];
                    if (valueCollection != null)
                    {
                        valueObject = valueCollection.Value;
                        if (valueObject != null)
                        {
                            userValue = valueObject.ToString();
                        }
                    }
                }


                html += string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td></tr>",
                                      profileSubtypeProperty.IsSection ? "Section" : "Property",
                                      profileSubtypeProperty.Name,
                                      profileSubtypeProperty.DisplayName,
                                      profileSubtypeProperty.TypeProperty.Name,
                                      profileSubtypeProperty.CoreProperty.Name,
                                      profileSubtypeProperty.DisplayOrder,
                                      userValue);
            }

            html += "</table>";

            html += "<h2>ProfileTypeProperty list</h2>";

            html += "<table cellspacing='2' border='1'>";

            html += "<tr><th>Section/Property</th><th>Name</th><th>Core Property Name</th></tr>";

            foreach (ProfileTypeProperty profileTypeProperty in _profileTypePropertyManager.PropertiesWithSection)
            {
                html += string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
                                      profileTypeProperty.IsSection ? "Section" : "Property",
                                      profileTypeProperty.Name,
                                      profileTypeProperty.CoreProperty.Name);
            }

            html += "</table>";

            html += "<h2>CoreProperty list</h2>";
            html += "<table cellspacing='2' border='1'>";

            html += "<tr><th>Section/Property</th><th>(Core Property) Name</th><th>Display Name</th><th>Type</th></tr>";

            foreach (CoreProperty coreProperty in _corePropertyManager.PropertiesWithSection)
            {
                html += string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>",
                                      coreProperty.IsSection ? "Section" : "Property",
                                      coreProperty.Name,
                                      coreProperty.DisplayName,
                                      coreProperty.Type); //,
                //coreProperty.UseCount
                //"BUG!" );
            }

            html += "</table>";

            UserProfileValueCollection values = profile[PropertyConstants.PictureUrl];

            if (values.Count > 0)
            {
                // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}

                SPFieldUrlValue urlValue = new SPFieldUrlValue(values.Value.ToString());

                html += "<p><b>PictureUrl = " + urlValue.Url + "</b></p>";
            }

            html += "<p><b>User account = " + profile[PropertyConstants.AccountName].Value.ToString() + "</b></p>";


            Content.Text = html;
        }
Esempio n. 36
0
        protected override void CreateChildControls()
        {
            Literal literal = new Literal();
            string  html    = "<style type=\"text/css\">\n tr.wbf-extra-recent-items {display:none;}\n</style>\n\n";

            try
            {
                // Now let's check or set the last visited Guid:
                SPSite             _site           = SPContext.Current.Site;
                SPServiceContext   _serviceContext = SPServiceContext.GetContext(_site);
                UserProfileManager _profileManager = new UserProfileManager(_serviceContext);
                UserProfile        profile         = _profileManager.GetUserProfile(true);

                UserProfileValueCollection workBoxesRecentlyVisited = profile[WorkBox.USER_PROFILE_PROPERTY__MY_RECENTLY_VISITED_WORK_BOXES];

                // If the NumberToShow value isn't set or is set zero or negative then fix the web part to show 5 items:
                if (NumberToShow <= 0)
                {
                    NumberToShow = 5;
                }

                if (workBoxesRecentlyVisited.Value != null)
                {
                    string[] recentWorkBoxes = workBoxesRecentlyVisited.Value.ToString().Split(';');

                    if (recentWorkBoxes.Length > 0)
                    {
                        html += "<table cellpadding='5' width='100%'>";
                        int    count         = 0;
                        bool   hasExtraItems = false;
                        String cssClass      = "";

                        foreach (string workBoxLinkDetails in recentWorkBoxes)
                        {
                            WBLink workBoxLink = new WBLink(workBoxLinkDetails);
                            if (!workBoxLink.IsOK)
                            {
                                continue;
                            }

                            //string[] details = workBoxLinkDetails.Split('|');

                            //String workBoxTitle = details[0];
                            //String workBoxUrl = details[1];
                            //String workBoxUniqueID = details[2];

                            // We're going to skip any work box whose title matches the unique prefix being filtered:
                            if (!String.IsNullOrEmpty(UniquePrefixToFilter))
                            {
                                if (workBoxLink.UniqueID.StartsWith(UniquePrefixToFilter))
                                {
                                    continue;
                                }
                            }

                            count++;
                            if (count > NumberToShow)
                            {
                                cssClass      = " class='wbf-extra-recent-items'";
                                hasExtraItems = true;
                            }

                            html += "<tr" + cssClass + "><td><img src='/_layouts/images/WorkBoxFramework/work-box-16.png'/></td><td><a href='";
                            html += workBoxLink.URL;
                            html += "'>" + workBoxLink.Title + "</a></td></tr>";
                        }

                        if (hasExtraItems)
                        {
                            html += "<tr class=\"wbf-show-more-recent-link\"><td colspan='2' align='right'><a href='#' onclick='javascript: $(\".wbf-extra-recent-items\").show(); $(\".wbf-show-more-recent-link\").hide(); '>More recent work boxes ...</a></td></tr>";
                            html += "<tr class=\"wbf-extra-recent-items\"><td colspan='2' align='right'><a href='#' onclick='javascript: $(\".wbf-extra-recent-items\").hide(); $(\".wbf-show-more-recent-link\").show(); '>Fewer recent work boxes</a></td></tr>";
                        }

                        html += "</table>";
                    }
                    else
                    {
                        html += "<i>(No recently visited work boxes)</i>";
                    }
                }
                else
                {
                    html += "<i>(No recently visited work boxes)</i>";
                }
            }
            catch (Exception e)
            {
                html += "<i>(An error occurred)</i> \n\n <!-- \n Exception was: " + e.WBxFlatten() + " \n\n -->";
            }

            literal.Text = html;

            this.Controls.Add(literal);
        }
Esempio n. 37
0
        public List <User> getUsersBySearchString(string searchString)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getUsersBySearchString invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"searchString: {searchString}");

            List <User> usersToReturn = new List <User>();

            if (searchString.Length < 3)
            {
                return(null);
            }


            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    // Save the original HttpContext and set it to null
                    // solution to enable impersonated access to UPS from here:
                    // https://weblogs.asp.net/sreejukg/access-denied-error-when-retrieving-user-profiles-count-from-sharepoint
                    HttpContext savedHttpContext = HttpContext.Current;
                    HttpContext.Current          = null;

                    // Access the User Profile Service
                    try
                    {
                        SPServiceContext serviceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to SPServiceContext obtained");
                        UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to UserProfileManager obtained");
                        ProfileBase[] searchResults = userProfileManager.Search(searchString);

                        foreach (ProfileBase profile in searchResults)
                        {
                            UserProfile userProfile = (UserProfile)profile;
                            UPSBrowserLogger.LogDebug(loggingCategory, $"Profile found - AccountName: {userProfile.AccountName}, DisplayName: {userProfile.DisplayName}");

                            User user           = UserProfileToUser(userProfile);
                            string outputString = $"Retrieved user properties - Email: {user.WorkEmail}, Username: {user.AccountName}, DisplayName: {user.DisplayName}, Department: {user.Department}, JobTitle: {user.JobTitle}";
                            UPSBrowserLogger.LogDebug(loggingCategory, outputString);
                            usersToReturn.Add(user);
                        }
                        ;
                    }
                    catch (System.Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    }
                    finally
                    {
                        // Restore HttpContext
                        HttpContext.Current = savedHttpContext;
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };


            UPSBrowserLogger.LogDebug(loggingCategory, $"usersToReturn.Count: {usersToReturn.Count}");
            return(usersToReturn);
        }
Esempio n. 38
0
        public static void Delete(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber)
        {
            SPSite site = null;

            try
            {
                site = new SPSite(WebApplication.GetResponseUri(SPUrlZone.Default).AbsoluteUri);

                SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(SPUrlZone.Default);

                foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders)
                {
                    if (provider.GetType() == typeof(SPFormsAuthenticationProvider))
                    {
                        SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider;

                        SPServiceContext   serviceContext = SPServiceContext.GetContext(site);
                        UserProfileManager uPM            = new UserProfileManager(serviceContext);

                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            string search = ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|";

                            List <UserProfile> uPAResults = uPM.Search(search).Cast <UserProfile>().ToList();
                            List <SearchResult> usersList = users.Cast <SearchResult>().ToList();

                            var query = usersList.Select(sr => sr.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString());

                            HashSet <string> paths = new HashSet <string>(query);

                            var profiles = uPAResults.Select(profile => new
                            {
                                ShouldKeep = paths.Contains(profile[PropertyConstants.DistinguishedName].Value.ToString()),
                                Profile    = profile
                            });

                            foreach (var profile in profiles.Where(result => !result.ShouldKeep))
                            {
                                try
                                {
                                    uPM.RemoveProfile(profile.Profile);
                                    Logging.LogMessage(212, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Removed profile " +
                                                       profile.Profile[PropertyConstants.DistinguishedName].Value);
                                }
                                catch (Exception ex)
                                {
                                    Logging.LogMessage(502, Logging.LogCategories.Profiles,
                                                       TraceSeverity.Unexpected,
                                                       "Failed to delete profile " + profile.Profile[PropertyConstants.DistinguishedName].Value +
                                                       " " + ex.Message);
                                }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message);
            }

            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }
            }
        }
Esempio n. 39
0
        public User createUser(User newUser, string identityProviderName)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "createUser invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"newUser.AccountName: {newUser.AccountName}, newUser.WorkEmail: {newUser.WorkEmail}, newUser.DisplayName: {newUser.DisplayName}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"identityProviderName: {identityProviderName}");

            User   userToReturn         = null;
            string accountNameForLogger = newUser.WorkEmail;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    // Save the original HttpContext and set it to null
                    // solution to enable impersonated access to UPS from here:
                    // https://weblogs.asp.net/sreejukg/access-denied-error-when-retrieving-user-profiles-count-from-sharepoint
                    HttpContext savedHttpContext = HttpContext.Current;
                    HttpContext.Current          = null;

                    // Access the User Profile Service
                    try
                    {
                        SPServiceContext serviceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to SPServiceContext obtained");
                        UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to UserProfileManager obtained");

                        string accountName   = identityProvidersHelper.getAccountNameForEmail(newUser.WorkEmail, identityProviderName);
                        accountNameForLogger = accountName;

                        UserProfile userProfile = userProfileManager.CreateUserProfile(accountName, newUser.DisplayName);
                        if (userProfile == null)
                        {
                            UPSBrowserLogger.LogError(loggingCategory, $"Failed to create user profile with AccountName {accountName}");
                            ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Error);
                            return; //exit delegate block
                        }
                        ;

                        userProfile[PropertyConstants.WorkEmail].Value  = newUser.WorkEmail;
                        userProfile[PropertyConstants.FirstName].Value  = newUser.FirstName;
                        userProfile[PropertyConstants.LastName].Value   = newUser.LastName;
                        userProfile[PropertyConstants.Department].Value = newUser.Department;
                        userProfile[PropertyConstants.JobTitle].Value   = newUser.JobTitle;
                        userProfile[PropertyConstants.Title].Value      = newUser.JobTitle; // Title is synced from UPS to User Information List!
                        userProfile[PropertyConstants.WorkPhone].Value  = newUser.WorkPhone;
                        userProfile[PropertyConstants.CellPhone].Value  = newUser.CellPhone;
                        userProfile.Commit();



                        UPSBrowserLogger.LogDebug(loggingCategory, $"userProfile.AccountName: {userProfile.AccountName}, userProfile.DisplayName: {userProfile.DisplayName}, userProfile.AccountName: {userProfile[PropertyConstants.UserGuid]}");

                        userToReturn = UserProfileToUser(userProfile);

                        string outputString = $"Retrieved user properties - Email: {userToReturn.WorkEmail}, AccountName: {userToReturn.AccountName}, DisplayName: {userToReturn.DisplayName}, UserGuid: {userToReturn.UserGuid}, Department: {userToReturn.Department}, JobTitle: {userToReturn.JobTitle}";
                        UPSBrowserLogger.LogDebug(loggingCategory, outputString);
                    }
                    catch (System.Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                        ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Error);
                    }
                    finally
                    {
                        // Restore HttpContext
                        HttpContext.Current = savedHttpContext;
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
                ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Error);
            };


            if (userToReturn != null)
            {
                ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Success);
            }
            ;

            return(userToReturn);
        }
Esempio n. 40
0
        public static UserProfileInfo GetCurrent()
        {
            try
            {
                var query = ContextFactory.GetContextWeb();

                if (query.IsClient)
                {
                    var context = (ClientContext)query.Context;

                    var peopleManager = new Microsoft.SharePoint.Client.UserProfiles.PeopleManager(context);

                    Microsoft.SharePoint.Client.UserProfiles.PersonProperties personDetails =
                        peopleManager.GetMyProperties();

                    context.Load(personDetails,
                                 personsD => personsD.AccountName,
                                 personsD => personsD.Email,
                                 personsD => personsD.Title,
                                 personsD => personsD.PictureUrl,
                                 personsD => personsD.UserProfileProperties,
                                 personsD => personsD.DisplayName);

                    context.ExecuteQuery();

                    return(new UserProfileInfo
                    {
                        Department = personDetails.UserProfileProperties["Department"],
                        DisplayName = personDetails.DisplayName,
                        Email = personDetails.Email,
                        PictureUrl = personDetails.PictureUrl,
                        Title = personDetails.Title,
                        AccountName = personDetails.AccountName,
                        Properties = personDetails.UserProfileProperties
                    });
                }
                else
                {
                    //string currentUser = SPContext.Current.Web.CurrentUser.LoginName;
                    //SPSite spSite = SPContext.Current.Site;

                    var context = (SPWeb)query.Context;

                    SPServiceContext serviceContext = SPServiceContext.GetContext(context.Site);

                    var profileManager = new UserProfileManager(serviceContext);
                    var userProfile    = profileManager.GetUserProfile(context.CurrentUser.LoginName);

                    return(new UserProfileInfo
                    {
                        AccountName = userProfile.AccountName,
                        DisplayName = userProfile.DisplayName,
                        Department = userProfile["Department"].Value.ToString(),
                        Email = userProfile["Email"].Value.ToString(),
                        PictureUrl = userProfile["PictureUrl"].Value.ToString(),
                        Title = userProfile["Title"].Value.ToString(),
                        Properties = userProfile.Properties.ToDictionary(p => p.Name, p => p.Name)
                    });
                }
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Esempio n. 41
0
        public bool deleteUserByGuid(string guid)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "deleteUserByGuid invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"guid: {guid}");

            bool   result = false;
            string accountNameForLogger = guid;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    // Save the original HttpContext and set it to null
                    // solution to enable impersonated access to UPS from here:
                    // https://weblogs.asp.net/sreejukg/access-denied-error-when-retrieving-user-profiles-count-from-sharepoint
                    HttpContext savedHttpContext = HttpContext.Current;
                    HttpContext.Current          = null;


                    // Access the User Profile Service
                    try
                    {
                        SPServiceContext serviceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to SPServiceContext obtained");
                        UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to UserProfileManager obtained");

                        UserProfile userProfile = userProfileManager.GetUserProfile(new Guid(guid));
                        if (userProfile == null)
                        {
                            UPSBrowserLogger.LogError(loggingCategory, $"User profile with guid {guid} not found in User Profile Service");
                            ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Error);
                            return; //exit delegate block
                        }
                        ;

                        UPSBrowserLogger.LogDebug(loggingCategory, $"userProfile.AccountName: {userProfile.AccountName}, userProfile.DisplayName: {userProfile.DisplayName}");
                        accountNameForLogger = userProfile.AccountName;

                        userProfileManager.RemoveUserProfile(new Guid(guid));
                        string outputString = $"User profile with guid {guid} deleted";
                        UPSBrowserLogger.LogDebug(loggingCategory, outputString);
                        result = true;
                    }
                    catch (System.Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                        ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Error);
                    }
                    finally
                    {
                        // Restore HttpContext
                        HttpContext.Current = savedHttpContext;
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
                ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Error);
            };

            if (result)
            {
                ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Success);
            }
            ;

            return(result);
        }
Esempio n. 42
0
        protected void FindCustomerByID_Click(
            object sender, EventArgs e)
        {
            // Make sure we have values for the entity namespace and name.
            if (!EntityValuesAreSet)
            {
                DisplaySetPropertyValuePrompt(true);
                return;
            }
            else
            {
                DisplaySetPropertyValuePrompt(false);
            }

            // Do simple validation of the customer ID. Make sure it is
            // an integer.
            int customerID = -1;

            if (!ValidateCustomerID(CustomerID.Text, ref customerID))
            {
                ClearFields(false);
                StatusLabel.ForeColor = Color.Red;
                StatusLabel.Text      =
                    "Please enter an integer for the Customer ID value.";
                return;
            }

            try
            {
                using (new Microsoft.SharePoint.SPServiceContextScope(
                           SPServiceContext.GetContext(SPContext.Current.Site)))
                {
                    // Get the BDC service and metadata catalog.
                    BdcService service =
                        SPFarm.Local.Services.GetValue <BdcService>(String.Empty);
                    IMetadataCatalog catalog =
                        service.GetDatabaseBackedMetadataCatalog(
                            SPServiceContext.Current);

                    // Get the entity using the specified name and namespace.
                    IEntity entity =
                        catalog.GetEntity(EntityNamespace, EntityName);
                    ILobSystemInstance LobSysteminstance =
                        entity.GetLobSystem().GetLobSystemInstances()[0].Value;

                    // Create an Identity based on the specified Customer ID.
                    Identity identity = new Identity(customerID);

                    // Get a method instance for the SpecificFinder method.
                    IMethodInstance method =
                        entity.GetMethodInstance("GetCustomerById",
                                                 MethodInstanceType.SpecificFinder);

                    // Execute the Specific Finder method to return the
                    // customer data.
                    IEntityInstance iei =
                        entity.FindSpecific(identity, LobSysteminstance);

                    // Display the data for the returned customer in the UI.
                    Title.Text = iei["Title"] != null ?
                                 iei["Title"].ToString() : string.Empty;
                    FirstName.Text = iei["FirstName"] != null ?
                                     iei["FirstName"].ToString() : string.Empty;
                    MiddleName.Text = iei["MiddleName"] != null ?
                                      iei["MiddleName"].ToString() : string.Empty;
                    LastName.Text = iei["LastName"] != null ?
                                    iei["LastName"].ToString() : string.Empty;
                    Email.Text = iei["EmailAddress"] != null ?
                                 iei["EmailAddress"].ToString() : string.Empty;
                    Phone.Text = iei["Phone"] != null ?
                                 iei["Phone"].ToString() : string.Empty;
                }
            }
            catch (Exception ex)
            {
                ClearFields(false);

                StatusLabel.ForeColor = Color.Red;
                StatusLabel.Text      = "Unable to find customer with ID = " +
                                        CustomerID.Text + ". " + ex.Message;
            }
        }
        private void getEmps()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite oSite                      = new SPSite(SPContext.Current.Web.Url);
                    SPWeb spWeb                       = oSite.OpenWeb();
                    SPPrincipalInfo pinfo             = SPUtility.ResolvePrincipal(spWeb, strEmpDisplayName, SPPrincipalType.User, SPPrincipalSource.All, null, false);
                    SPServiceContext serviceContext   = SPServiceContext.GetContext(oSite);
                    UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
                    UserProfile cUserProfile          = userProfileMgr.GetUserProfile(pinfo.LoginName);

                    List <UserProfile> directReports = new List <UserProfile>(cUserProfile.GetDirectReports());
                    foreach (UserProfile up in directReports)
                    {
                        DataRow row = tblEmps.NewRow();

                        if (up.GetProfileValueCollection("AboutMe")[0] != null && up.GetProfileValueCollection("AboutMe")[0].ToString() != string.Empty)
                        {
                            row["EmpName"] = up.GetProfileValueCollection("AboutMe")[0].ToString();
                        }
                        else
                        {
                            row["EmpName"] = up.DisplayName;
                        }

                        row["EnglishName"] = up.DisplayName;


                        row["EmpJob"] = up.GetProfileValueCollection("Title")[0].ToString();

                        string Active_Set_Goals_Year = EnableYear_DAL.get_Active_Set_Goals_Year();
                        string empEmail = up.GetProfileValueCollection("WorkEmail")[0].ToString();
                        SPUser sp       = spWeb.SiteUsers.GetByEmail(empEmail);
                        string Emp_Application_Status    = Dashboard_DAL.get_Emp_Application_Status(sp, Active_Set_Goals_Year)[0];
                        string Emp_Application_Status_Ar = string.Empty;

                        if (Emp_Application_Status == "Objectives not set")
                        {
                            Emp_Application_Status_Ar = "لم يتم وضع الأهداف بعد";
                        }
                        else if (Emp_Application_Status == "Objectives_set_by_Emp")
                        {
                            Emp_Application_Status_Ar = "تم وضع الأهداف - بإنتظار اعتماد المدير المباشر";
                        }
                        else if (Emp_Application_Status == "Objectives_approved_by_DM")
                        {
                            Emp_Application_Status_Ar = "اعتمد المدير المباشر الأهداف";
                        }
                        else if (Emp_Application_Status == "Objectives_approved_by_Dept_Head")
                        {
                            Emp_Application_Status_Ar = "اعتمد مدير الإدارة الأهداف";
                        }

                        row["Emp_Application_Status"] = Emp_Application_Status_Ar;

                        tblEmps.Rows.Add(row);
                    }
                });
            }
            catch (Exception)
            {
            }
        }
Esempio n. 44
0
        protected void CreateNewCustomer_Click(object sender,
                                               EventArgs e)
        {
            // Make sure we have values for the entity namespace and name.
            if (!EntityValuesAreSet)
            {
                DisplaySetPropertyValuePrompt(true);
                return;
            }
            else
            {
                DisplaySetPropertyValuePrompt(false);
            }

            try
            {
                using (new Microsoft.SharePoint.SPServiceContextScope(
                           SPServiceContext.GetContext(SPContext.Current.Site)))
                {
                    // Get the BDC service and metadata catalog.
                    BdcService service =
                        SPFarm.Local.Services.GetValue <BdcService>(String.Empty);
                    IMetadataCatalog catalog =
                        service.GetDatabaseBackedMetadataCatalog(
                            SPServiceContext.Current);

                    // Get the entity using the specified name and namespace.
                    IEntity entity =
                        catalog.GetEntity(EntityNamespace, EntityName);
                    ILobSystemInstance LobSysteminstance =
                        entity.GetLobSystem().GetLobSystemInstances()[0].Value;

                    // Get the fields on the entity.
                    IView createView =
                        entity.GetCreatorView("CreateCustomer");
                    IFieldValueDictionary valueDictionary =
                        createView.GetDefaultValues();

                    // Set the values of the entity fields.
                    valueDictionary["EmailAddress"] = Email.Text;
                    valueDictionary["FirstName"]    = FirstName.Text;
                    valueDictionary["LastName"]     = LastName.Text;
                    valueDictionary["MiddleName"]   = MiddleName.Text;
                    valueDictionary["Phone"]        = Phone.Text;
                    valueDictionary["Title"]        = Title.Text;

                    // Call the creator method and display the returned
                    // Customer ID.
                    Identity id = entity.Create(valueDictionary,
                                                LobSysteminstance);

                    CustomerID.Text =
                        id.GetIdentifierValues().GetValue(0).ToString();

                    StatusLabel.ForeColor = Color.Green;
                    StatusLabel.Text      = "Customer successfully created.";
                }
            }
            catch (Exception ex)
            {
                StatusLabel.ForeColor = Color.Red;
                StatusLabel.Text      = "Unable to create customer." +
                                        ex.Message;
            }
        }
Esempio n. 45
0
        public static bool ConvertDocument(SPListItem listItem, string fileFormat, string newFileName, bool isWorkflow,
                                           ActivityExecutionContext executionContext, WorkflowContext __Context, SPFolder folder, string settings, bool isImmediate)
        {
            ISharePointService wfService = null;

            if (executionContext != null)
            {
                wfService = executionContext.GetService <ISharePointService>();
            }

            using (SPSite spSite = new SPSite(listItem.ParentList.ParentWeb.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    int i       = listItem.Url.IndexOf("/");
                    var listUrl = listItem.Url.Remove(i + 1);

                    var listItemUri        = new Uri(listItem.Web.Url + "/" + listItem.Url);
                    var listItemLibraryUri = new Uri(listItem.Web.Url + "/" + listUrl);

                    var fileName = listItem.Name;
                    var idx      = fileName.LastIndexOf(".", StringComparison.Ordinal);

                    if (string.IsNullOrEmpty(newFileName))
                    {
                        newFileName = fileName.Replace(fileName.Substring(idx, fileName.Length - idx),
                                                       "." + fileFormat);
                    }
                    else
                    {
                        if (isWorkflow)
                        {
                            newFileName = newFileName + fileName.Replace(fileName.Substring(idx, fileName.Length - idx),
                                                                         "." + fileFormat);
                        }
                    }

                    try
                    {
                        var proxies = SPServiceContext.GetContext(spSite).GetProxies(typeof(WordServiceApplicationProxy));

                        if (proxies.Any())
                        {
                            _proxy = proxies.First();
                        }
                        else
                        {
                            var exception = new SPException();
                            throw exception;
                        }

                        #region ImmediateJob
                        if (isImmediate)
                        {
                            SyncConverter immJob;

                            if (isWorkflow)
                            {
                                immJob = new SyncConverter(_proxy.DisplayName)
                                {
                                    UserToken = __Context.InitiatorUser.UserToken
                                };
                            }
                            else
                            {
                                immJob = new SyncConverter(_proxy.DisplayName)
                                {
                                    UserToken = spSite.UserToken
                                };
                            }

                            if (spSite.SiteSubscription != null)
                            {
                                immJob.SubscriptionId = spSite.SiteSubscription.Id;
                            }

                            immJob.Settings.OutputFormat = DeriveFileFormat(fileFormat);

                            if (!string.IsNullOrEmpty(settings))
                            {
                                var splitSettings = settings.Split(';');

                                if (fileFormat.ToLower(CultureInfo.InvariantCulture) == splitSettings[0].Remove(0, 2).ToLower(CultureInfo.InvariantCulture))
                                {
                                    switch (fileFormat)
                                    {
                                    case "xps":
                                    case "pdf":
                                    {
                                        immJob.Settings.FixedFormatSettings.Bookmarks =
                                            (FixedFormatBookmark)
                                            Enum.Parse(typeof(FixedFormatBookmark),
                                                       splitSettings[1].Remove(0, 2));
                                        immJob.Settings.FixedFormatSettings.BalloonState =
                                            (BalloonState)
                                            Enum.Parse(typeof(BalloonState), splitSettings[2].Remove(0, 2));

                                        if (splitSettings.Contains("BitmapEmbeddedFonts"))
                                        {
                                            immJob.Settings.FixedFormatSettings.BitmapEmbeddedFonts = true;
                                        }

                                        if (splitSettings.Contains("IncludeDocumentProperties"))
                                        {
                                            immJob.Settings.FixedFormatSettings.IncludeDocumentProperties = true;
                                        }

                                        if (splitSettings.Contains("IncludeDocumentStructure"))
                                        {
                                            immJob.Settings.FixedFormatSettings.IncludeDocumentStructure = true;
                                        }

                                        if (splitSettings.Contains("OptimizeForMinimumSize"))
                                        {
                                            immJob.Settings.FixedFormatSettings.OutputQuality =
                                                FixedFormatQuality.Minimum;
                                        }

                                        if (splitSettings.Contains("UsePdfA"))
                                        {
                                            immJob.Settings.FixedFormatSettings.UsePDFA = true;
                                        }

                                        break;
                                    }

                                    case "doc":
                                    case "docx":
                                    case "docm":
                                    case "dot":
                                    case "dotx":
                                    case "dotm":
                                    {
                                        immJob.Settings.CompatibilityMode = (CompatibilityMode)
                                                                            Enum.Parse(typeof(CompatibilityMode),
                                                                                       splitSettings[1].Remove(0, 2));

                                        if (splitSettings.Contains("AddThumbnail"))
                                        {
                                            immJob.Settings.AddThumbnail = true;
                                        }

                                        if (splitSettings.Contains("EmbedFonts"))
                                        {
                                            immJob.Settings.AddThumbnail = true;
                                        }

                                        if (splitSettings.Contains("UpdateFields"))
                                        {
                                            immJob.Settings.UpdateFields = true;
                                        }

                                        break;
                                    }
                                    }
                                }
                            }
                            var sStream     = new SPFileStream(spWeb, 0x1000);
                            var inputStream = listItem.File.OpenBinaryStream();

                            immJob.Convert(inputStream, sStream);

                            try
                            {
                                if (folder == null)
                                {
                                    listItem.Folder.Files.Add(newFileName, sStream);
                                }
                                else
                                {
                                    if (spWeb.Url != folder.ParentWeb.Url)
                                    {
                                        using (SPWeb web2 = spSite.OpenWeb(folder.ParentWeb.Url))
                                        {
                                            folder.Files.Add(newFileName, sStream);
                                        }
                                    }
                                    folder.Files.Add(newFileName, sStream);
                                }
                            }
                            catch (Exception exception)
                            {
                                if (wfService != null)
                                {
                                    Exceptions.CheckedOutException(exception, listItem, wfService, executionContext);
                                    return(false);
                                }
                                Exceptions.CheckedOutException(exception, listItem, null, null);
                                return(false);
                            }

                            return(true);
                        }
                        #endregion

                        #region Timer Conversion Job
                        else
                        {
                            ConversionJob job;

                            if (isWorkflow)
                            {
                                job = new ConversionJob(_proxy.DisplayName)
                                {
                                    UserToken = __Context.InitiatorUser.UserToken
                                };
                            }
                            else
                            {
                                job = new ConversionJob(_proxy.DisplayName)
                                {
                                    UserToken = spSite.UserToken
                                };
                            }

                            if (spSite.SiteSubscription != null)
                            {
                                job.SubscriptionId = spSite.SiteSubscription.Id;
                            }

                            job.Settings.OutputFormat = DeriveFileFormat(fileFormat);
                            job.Name = listItem.Name + "-" + Guid.NewGuid();

                            if (!string.IsNullOrEmpty(settings))
                            {
                                var splitSettings = settings.Split(';');

                                if (fileFormat.ToLower(CultureInfo.InvariantCulture) == splitSettings[0].Remove(0, 2).ToLower(CultureInfo.InvariantCulture))
                                {
                                    switch (fileFormat)
                                    {
                                    case "xps":
                                    case "pdf":
                                    {
                                        job.Settings.FixedFormatSettings.Bookmarks =
                                            (FixedFormatBookmark)
                                            Enum.Parse(typeof(FixedFormatBookmark), splitSettings[1].Remove(0, 2));
                                        job.Settings.FixedFormatSettings.BalloonState =
                                            (BalloonState)
                                            Enum.Parse(typeof(BalloonState), splitSettings[2].Remove(0, 2));

                                        if (splitSettings.Contains("BitmapEmbeddedFonts"))
                                        {
                                            job.Settings.FixedFormatSettings.BitmapEmbeddedFonts = true;
                                        }

                                        if (splitSettings.Contains("IncludeDocumentProperties"))
                                        {
                                            job.Settings.FixedFormatSettings.IncludeDocumentProperties = true;
                                        }

                                        if (splitSettings.Contains("IncludeDocumentStructure"))
                                        {
                                            job.Settings.FixedFormatSettings.IncludeDocumentStructure = true;
                                        }

                                        if (splitSettings.Contains("OptimizeForMinimumSize"))
                                        {
                                            job.Settings.FixedFormatSettings.OutputQuality = FixedFormatQuality.Minimum;
                                        }

                                        if (splitSettings.Contains("UsePdfA"))
                                        {
                                            job.Settings.FixedFormatSettings.UsePDFA = true;
                                        }
                                        break;
                                    }

                                    case "doc":
                                    case "docx":
                                    case "docm":
                                    case "dot":
                                    case "dotx":
                                    case "dotm":
                                    {
                                        job.Settings.CompatibilityMode = (CompatibilityMode)
                                                                         Enum.Parse(typeof(CompatibilityMode),
                                                                                    splitSettings[1].Remove(0, 2));

                                        if (splitSettings.Contains("AddThumbnail"))
                                        {
                                            job.Settings.AddThumbnail = true;
                                        }

                                        if (splitSettings.Contains("EmbedFonts"))
                                        {
                                            job.Settings.EmbedFonts = true;
                                        }

                                        if (splitSettings.Contains("UpdateFields"))
                                        {
                                            job.Settings.UpdateFields = true;
                                        }

                                        break;
                                    }
                                    }
                                }
                            }

                            try
                            {
                                if (folder == null)
                                {
                                    job.AddFile(listItemUri.ToString(), listItemLibraryUri + newFileName);
                                }
                                else
                                {
                                    job.AddFile(listItemUri.ToString(),
                                                string.Format("{0}/{1}/{2}", folder.ParentWeb.Url, folder.Url, newFileName));
                                }
                            }
                            catch (Exception exception)
                            {
                                if (wfService != null)
                                {
                                    Exceptions.CheckedOutException(exception, listItem, wfService, executionContext);
                                    return(false);
                                }
                                Exceptions.CheckedOutException(exception, listItem, null, null);
                                return(false);
                            }

                            job.Start();

                            if (wfService != null)
                            {
                                wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowCompleted,
                                                           0, TimeSpan.Zero, "Information", "Conversion job queued for " + listItem.DisplayName, string.Empty);
                            }

                            return(true);

                            #endregion
                        }
                    }
                    catch (SPException exception)
                    {
                        if (wfService != null)
                        {
                            Exceptions.SharePointException(exception, listItem, wfService, executionContext);
                            return(false);
                        }
                        Exceptions.SharePointException(exception, listItem, null, null);
                        return(false);
                    }
                    catch (InvalidOperationException exception)
                    {
                        if (wfService != null)
                        {
                            Exceptions.InvalidOperationException(exception, listItem, wfService, executionContext);
                            return(false);
                        }
                        Exceptions.InvalidOperationException(exception, listItem, null, null);
                        return(false);
                    }
                }
            }
        }
Esempio n. 46
0
        protected override void CreateChildControls()
        {
            Literal literal = new Literal();
            string  html    = "";


            try
            {
                html += "<style type=\"text/css\">\n tr.wbf-extra-favourites-items {display:none;}\n</style>\n\n" + getScriptCode();

                SPSite             _site           = SPContext.Current.Site;
                SPServiceContext   _serviceContext = SPServiceContext.GetContext(_site);
                UserProfileManager _profileManager = new UserProfileManager(_serviceContext);
                UserProfile        profile         = _profileManager.GetUserProfile(true);

                UserProfileValueCollection myFavouriteWorkBoxesPropertyValue = profile[WorkBox.USER_PROFILE_PROPERTY__MY_FAVOURITE_WORK_BOXES];

                // If the NumberToShow value isn't set or is set zero or negative then fix the web part to show 5 items:
                if (NumberToShow <= 0)
                {
                    NumberToShow = 5;
                }

                if (myFavouriteWorkBoxesPropertyValue.Value != null)
                {
                    string[] myFavouriteWorkBoxes = myFavouriteWorkBoxesPropertyValue.Value.ToString().Split(';');

                    // We actually want to display the most recently added favourite first even though it'll be last in the list so:
                    Array.Reverse(myFavouriteWorkBoxes);

                    if (myFavouriteWorkBoxes.Length > 0)
                    {
                        html += "<table cellpadding='5' width='100%'>";
                        int    count         = 0;
                        bool   hasExtraItems = false;
                        String cssClass      = "";

                        foreach (string workBoxLinkDetails in myFavouriteWorkBoxes)
                        {
                            WBLink workBoxLink = new WBLink(workBoxLinkDetails);
                            if (!workBoxLink.IsOK)
                            {
                                continue;
                            }

                            count++;

                            if (count > NumberToShow)
                            {
                                cssClass      = " class='wbf-extra-favourites-items'";
                                hasExtraItems = true;
                            }

                            /*
                             * string[] details = recentWorkBoxDetails.Split('|');
                             *
                             * string guidString = details[2];
                             * if (details.Length == 4)
                             *  guidString = details[3];
                             *
                             * html += "<tr" + cssClass + "><td><img src='/_layouts/images/WorkBoxFramework/work-box-16.png'/></td><td><a href='";
                             * html += details[1];
                             * html += "'>" + details[0] + "</a></td>";
                             *
                             * String command = "RemoveWorkBoxFromFavourites.aspx?workBoxTitle=" + HttpUtility.UrlEncode(details[0]) + "&workBoxGuid=" + guidString;
                             *
                             * html += "<td><a href='#' onclick='javascript: WorkBoxFramework_relativeCommandAction(\"" + command + "\", 0, 0);'>remove</a></td>";
                             * html += "</tr>";
                             */

                            html += "<tr" + cssClass + "><td><img src='/_layouts/images/WorkBoxFramework/work-box-16.png'/></td><td><a href='";
                            html += workBoxLink.URL;
                            html += "'>" + workBoxLink.Title + "</a></td>";

                            String command = "RemoveWorkBoxFromFavourites.aspx?workBoxTitle=" + HttpUtility.UrlEncode(workBoxLink.Title) + "&workBoxGuid=" + workBoxLink.SPWebGUID;

                            html += "<td><a href='#' onclick='javascript: WorkBoxFramework_relativeCommandAction(\"" + command + "\", 0, 0);'>remove</a></td>";
                            html += "</tr>";
                        }

                        if (hasExtraItems)
                        {
                            html += "<tr class=\"wbf-show-more-favourites-link\"><td colspan='3' align='right'><a href='#' onclick='javascript: $(\".wbf-extra-favourites-items\").show(); $(\".wbf-show-more-favourites-link\").hide(); '>More favourite work boxes ...</a></td></tr>";
                            html += "<tr class=\"wbf-extra-favourites-items\"><td colspan='3' align='right'><a href='#' onclick='javascript: $(\".wbf-extra-favourites-items\").hide(); $(\".wbf-show-more-favourites-link\").show(); '>Fewer favourite work boxes</a></td></tr>";
                        }

                        html += "</table>";
                    }
                    else
                    {
                        html += "<i>(No favourite work boxes)</i>";
                    }
                }
                else
                {
                    html += "<i>(No favourite work boxes)</i>";
                }
            }
            catch (Exception e)
            {
                html += "<i>(An error occurred)</i> \n\n <!-- \n Exception was: " + e.WBxFlatten() + " \n\n -->";
            }

            literal.Text = html;

            this.Controls.Add(literal);
        }
Esempio n. 47
0
        public static bool ConvertFolder(SPFolder folderItem, string fileFormat, string location, bool isWorkflow, ActivityExecutionContext executionContext)
        {
            ISharePointService wfService = null;

            if (executionContext != null)
            {
                wfService = executionContext.GetService <ISharePointService>();
            }

            if (string.IsNullOrEmpty(location))
            {
                location = null;
            }

            using (SPSite spSite = new SPSite(location ?? SPContext.Current.Web.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    try
                    {
                        var proxies =
                            SPServiceContext.GetContext(spSite).GetProxies(typeof(WordServiceApplicationProxy));

                        if (proxies.Any())
                        {
                            _proxy = proxies.First();
                        }
                        else
                        {
                            var exception = new SPException();
                            throw exception;
                        }

                        var job = new ConversionJob(_proxy.DisplayName)
                        {
                            UserToken = spSite.UserToken
                        };

                        if (spSite.SiteSubscription != null)
                        {
                            job.SubscriptionId = spSite.SiteSubscription.Id;
                        }

                        job.Settings.OutputFormat = DeriveFileFormat(fileFormat);
                        job.Name = folderItem.Name + "-" + Guid.NewGuid();

                        if (string.IsNullOrEmpty(location))
                        {
                            job.AddFolder(folderItem, folderItem, true);
                        }
                        else
                        {
                            if (location.ToLower().Contains("http://"))
                            {
                                location = location.Remove(0, 7);
                            }
                            else if (location.ToLower().Contains("https://"))
                            {
                                location = location.Remove(0, 8);
                            }

                            var index = location.IndexOf('/');

                            if (index > 0)
                            {
                                location = location.Substring(index);
                            }

                            var list = spWeb.GetList(location);

                            try
                            {
                                var folder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder,
                                                            folderItem.Name);

                                folder["Title"] = folderItem.Name;
                                folder.Update();
                            }
                            catch (SPException)
                            {
                                //Folder already exists
                            }

                            var folder2 = list.RootFolder.SubFolders[folderItem.Name];

                            job.AddFolder(folderItem, folder2, true);
                        }

                        job.Start();

                        if (wfService != null)
                        {
                            wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowCompleted,
                                                       0, TimeSpan.Zero, "Information", "Conversion job queued for " + folderItem.Name, string.Empty);
                        }

                        return(true);
                    }
                    catch (SPException exception)
                    {
                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus",
                                                                                           TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected,
                                                              "An unexpected error has occurred attempting to find the Word Automation Services Proxy", exception.StackTrace);

                        if (wfService != null)
                        {
                            wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError,
                                                       0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to find the" +
                                                       "Word Automation Services Proxy for " + folderItem.Name, exception.StackTrace);
                        }

                        return(false);
                    }
                    catch (InvalidOperationException exception2)
                    {
                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("NaupliusWASStatus",
                                                                                           TraceSeverity.High, EventSeverity.Error), TraceSeverity.Unexpected,
                                                              "An unexpected error has occurred attempting to contact the Word Automation Services. Validate that the" +
                                                              "Word Automation Service is Started.", exception2.StackTrace);

                        if (wfService != null)
                        {
                            wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError,
                                                       0, TimeSpan.Zero, "Information", "An unexpected error has occurred attempting to contact the " +
                                                       "Word Automation Services. Validate that the Word Automation Service is Started. Attempted to process file " +
                                                       folderItem.Name, exception2.StackTrace);
                        }

                        return(false);
                    }
                }
            }
        }