Example #1
0
        public static string GetUserProfilePictureURL(string UserName)
        {
            string             url            = string.Empty;
            SPServiceContext   serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);
            UserProfileManager upm            = new UserProfileManager(serviceContext);

            if (upm.UserExists(UserName))
            {
                Microsoft.Office.Server.UserProfiles.UserProfile profile = upm.GetUserProfile(UserName);
                if (profile != null)
                {
                    url = profile["PictureURL"].Value.ToString().Replace("MThumb", "LThumb");
                    //Action.Write(profile.ID.ToString(), UserName);
                    //Action.Write(profile.PersonalUrl.ToString().ToString(), UserName);
                    //Action.Write(profile.PersonalUrl.ToString().ToString(), UserName);
                    //Action.Write(profile.PublicUrl.ToString().ToString(), UserName);
                    //Action.Write(profile.RecordId.ToString().ToString(), UserName);
                    //Action.Write(profile.DisplayName.ToString().ToString(), UserName);
                }
                else
                {
                    //Action.Write("profile is null", UserName);
                }
            }
            // change to default if user does not have an image specified
            if (string.IsNullOrEmpty(url))
            {
                url = "/_layouts/15/images/spa/PHOTO-NOT-AVAILABLE.png";
            }
            return(url);
        }
Example #2
0
        public void ReadSPProfiles(Guid currentSiteId)
        {
            this.Clear();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(currentSiteId))
                {
                    SPServiceContext sc    = SPServiceContext.GetContext(site);
                    UserProfileManager upm = new UserProfileManager(sc);
                    foreach (UserProfile profile in upm)
                    {
                        // TODO: Figure out how to filter the list and skill all service accounts
                        if (profile["AccountName"].Value != null &&
                            (profile["AccountName"].Value.ToString().ToUpper().IndexOf("\\SM_") >= 0 ||
                             profile["AccountName"].Value.ToString().ToUpper().IndexOf("\\SP_") >= 0))
                        {
                            continue;
                        }
                        if (profile["AccountName"].Value != null &&
                            profile["AccountName"].Value.ToString() == profile.DisplayName)
                        {
                            continue;
                        }

                        Add(profile);
                    }
                }
            });
            this._bEmpty = false;
        }
Example #3
0
        public UserProfileManager GetProfileManager()
        {
            UserProfileManager profileManager = null;

            try
            {
                using (SPSite siteCollection = GetSiteCollection())
                {
                    if (siteCollection == null)
                    {
                        return(null);
                    }

                    var context = SPServiceContext.GetContext(siteCollection);
                    profileManager = new UserProfileManager(context);
                }
            }
            catch (Exception ex)
            {
                var log = new AppEventLog(AppException.ExceptionMessage(ex, "GetProfileManager", "ClsHelperParent"));
                log.WriteToLog();
            }

            return(profileManager);
        }
Example #4
0
        public Scope EnsureSiteScope(SPSite site, string scopeName, string displayGroupName, string searchPagePath)
        {
            // remotescopes class retrieves information via search web service so we run this as the search service account
            RemoteScopes remoteScopes = new RemoteScopes(SPServiceContext.GetContext(site));

            // see if there is an existing scope
            Scope scope = remoteScopes.GetScopesForSite(new Uri(site.Url)).Cast <Scope>().FirstOrDefault(s => s.Name == scopeName);

            // only add if the scope doesn\"t exist already
            if (scope == null)
            {
                scope = remoteScopes.AllScopes.Create(scopeName, string.Empty, new Uri(site.Url), true, searchPagePath, ScopeCompilationType.AlwaysCompile);
            }

            // see if there is an existing display group
            ScopeDisplayGroup displayGroup = remoteScopes.GetDisplayGroupsForSite(new Uri(site.Url)).Cast <ScopeDisplayGroup>().FirstOrDefault(d => d.Name == displayGroupName);

            // add if the display group doesn\"t exist
            if (displayGroup == null)
            {
                displayGroup = remoteScopes.AllDisplayGroups.Create(displayGroupName, string.Empty, new Uri(site.Url), true);
            }

            // add scope to display group if not already added
            if (!displayGroup.Contains(scope))
            {
                displayGroup.Add(scope);
                displayGroup.Update();
            }

            // optionally force a scope compilation so this is available immediately
            remoteScopes.StartCompilation();

            return(scope);
        }
Example #5
0
        //获取用户头像
        private string GetPhotoUrlByUserProfile(string loginName)
        {
            string photoUrl = "";

            if (SPContext.Current.Site.OpenWeb().CurrentUser == null)
            {
                photoUrl = "/_layouts/15/images/PersonPlaceholder.200x150x32.png";
                return(photoUrl);
            }
            string accountName = loginName.Substring(loginName.LastIndexOf("|") + 1);

            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                SPServiceContext   serviceContext = SPServiceContext.GetContext(site);
                UserProfileManager upm            = new UserProfileManager(serviceContext);
                if (upm.UserExists(accountName))
                {
                    UserProfile u = upm.GetUserProfile(accountName);
                    if (u[PropertyConstants.PictureUrl].Value == null)
                    {
                        photoUrl = "/_layouts/15/images/PersonPlaceholder.200x150x32.png";
                    }
                    else
                    {
                        photoUrl = u[PropertyConstants.PictureUrl].Value.ToString();
                    }
                }
            }
            return(photoUrl);
        }
Example #6
0
        public static string GetPersonalPageUserName()
        {
            string userName;

            SPWeb web = SPControl.GetContextWeb(HttpContext.Current);

            SPServiceContext   spServiceContext   = SPServiceContext.GetContext(web.Site);
            UserProfileManager userProfileManager = new UserProfileManager(spServiceContext);

            string accountname = HttpContext.Current.Request.Params.Get("accountname");

            if (accountname == null)
            {
                userName = web.CurrentUser.Name;
            }
            else
            {
                if (userProfileManager.UserExists(accountname))
                {
                    UserProfile userProfile = userProfileManager.GetUserProfile(accountname);
                    userName = userProfile.DisplayName;
                }
                else
                {
                    userName = "";
                }
            }

            return(userName);
        }
        protected override void UpdateDataObject()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }

            Common.Audiences.CreateAudience.Create(context, Identity, Description, Membership, Owner, true);
        }
        private String generateTable(WBTeam team, String groupName, String groupType, String title, List <String> groupEmails)
        {
            string html = "";

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

            SPGroup group = SPContext.Current.Site.RootWeb.WBxGetGroupOrNull(groupName);

            if (group == null)
            {
                // Then either the owners group name has not been defined for this team, or the group doesn’t exist for some reason!
                html += "<i>(The " + groupType + " group name has not been defined for this team, or the group doesn’t exist for some reason)</i>";
            }
            else
            {
                // If the current user is not allowed to see the members then we'll return blank:
                if (group.OnlyAllowMembersViewMembership && !group.ContainsCurrentUser)
                {
                    return("");
                }

                html += "<h3>" + title + ":</h3>\n";

                // OK so now we have the SPGroup for the team’s owners group.
                // Now we can iterate through the SPUser-s in this group … or whatever else we want to do with it, e.g.:

                html += "<table cellpadding='5'><tr><td><ul>";
                foreach (SPUser user in group.Users)
                {
                    html += "<li>" + user.WBxToHTML(profileManager); //renderUser(user, SPContext.Current.Site.RootWeb);

                    if (team.IsUserTeamManager(user))
                    {
                        html += " (manager)";
                    }
                    else
                    {
                        if (userIsTeamOwnerOrSystemAdmin)
                        {
                            string actionURL = "RemoveFromTeam.aspx?userLogin="******"\\", "\\\\") + "&role=" + groupType;

                            html += " <a href=\"javascript: WorkBoxFramework_relativeCommandAction('" + actionURL + "', 0, 0); \">(remove)</a>";
                        }
                    }

                    html += "</li>";

                    if (profileManager.UserExists(user.LoginName) && !String.IsNullOrEmpty(user.Email) && !groupEmails.Contains(user.Email))
                    {
                        groupEmails.Add(user.Email);
                    }
                }

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

            return(html);
        }
Example #9
0
        /// <summary>
        ///     Update a particular user profile property field
        /// </summary>
        /// <param name="acctName"></param>
        /// <param name="fieldName"></param>
        /// <param name="fieldValue"></param>
        public void updateProfileDetails(string acctName, string fieldName, string fieldValue, SPWeb currentWeb)
        {
            try
            {
                SPSite             site                  = SPContext.Current.Site;
                SPServiceContext   ospServerContext      = SPServiceContext.GetContext(site);
                UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);

                UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(acctName);
                Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection;

                if (ospUserProfile != null && propColl != null)
                {
                    foreach (Property prop in propColl)
                    {
                        if (fieldName == prop.Name)
                        {
                            ospUserProfile[prop.Name].Value = fieldValue;
                        }
                    }
                    ospUserProfile.Commit();
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at getUserProfileDetails function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }
        }
Example #10
0
        public FullTextSqlQueryInstance Construct(object siteOrProxy)
        {
            var instance = siteOrProxy as SPSiteInstance;

            if (instance != null)
            {
                return(new FullTextSqlQueryInstance(this.Engine, new FullTextSqlQuery(instance.Site)));
            }

            var proxy = siteOrProxy as SearchServiceApplicationProxyInstance;

            if (proxy != null)
            {
                return(new FullTextSqlQueryInstance(this.Engine, new FullTextSqlQuery(proxy.SearchServiceApplicationProxy)));
            }

            var context      = SPServiceContext.GetContext(SPBaristaContext.Current.Site);
            var currentProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy));

            if (currentProxy == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "Could not locate a SearchServiceApplicationProxy for the current context. Ensure that A Search Service Application has been created.");
            }

            var searchAppProxy = currentProxy as SearchServiceApplicationProxy;

            return(new FullTextSqlQueryInstance(this.Engine, new FullTextSqlQuery(searchAppProxy)));
        }
        protected override void InternalProcessRecord()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }

            Common.Audiences.AddAudienceRule.AddRules(context, Identity, Rules.OuterXml, Clear.IsPresent, Compile.IsPresent, GroupExisting.IsPresent, AppendOperator.Value);
        }
Example #12
0
        /// <summary>
        /// Get Credential from SSS
        /// </summary>
        /// <param name="appId">Application Id</param>
        /// <param name="adminSiteUrl">Admin Site Url</param>
        /// <returns>Credential as Dictionary string and string</returns>
        public static Dictionary <string, string> GetCredentialsFromSSS(string appId, string adminSiteUrl)
        {
            var result = new Dictionary <string, string>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    var siteAdmin = new SPSite(adminSiteUrl);

                    // Get the default Secure Store Service provider.
                    var provider = SecureStoreProviderFactory.Create();
                    if (provider == null)
                    {
                        throw new InvalidOperationException("Unable to get an ISecureStoreProvider");
                    }

                    var providerContext = provider as ISecureStoreServiceContext;
                    if (providerContext == null)
                    {
                        return;
                    }

                    providerContext.Context = SPServiceContext.GetContext(siteAdmin);

                    var secureStoreProvider = new SecureStoreProvider {
                        Context = providerContext.Context
                    };

                    // Create the variables to hold the credentials.
                    using (var creds = provider.GetCredentials(appId))
                    {
                        if (creds == null)
                        {
                            return;
                        }

                        var fields = secureStoreProvider.GetTargetApplicationFields(appId);
                        if (fields.Count <= 0)
                        {
                            return;
                        }

                        for (var i = 0; i < fields.Count; i++)
                        {
                            var field               = fields[i];
                            var credential          = creds[i];
                            var decryptedCredential = GetStringFromSecureString(credential.Credential);
                            result.Add(field.Name, decryptedCredential);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ULSLogging.LogError(ex);
            }

            return(result);
        }
        protected override IEnumerable <AudienceManager> RetrieveDataObjects()
        {
            List <AudienceManager> audienceManagers = new List <AudienceManager>();

            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }
            AudienceManager manager = new AudienceManager(context);

            audienceManagers.Add(manager);
            return(audienceManagers);
        }
        /// <summary>
        /// Get the instance of a Business Data Connectivity entity
        /// </summary>
        /// <param name="site"></param>
        /// <param name="nameSpace"></param>
        /// <param name="entityName"></param>
        /// <param name="entityId"></param>
        /// <returns></returns>
        private static IEntityInstance GetEntityInstance(SPSite site, string nameSpace, string entityName, string entityId)
        {
            //Use the scope of the currently opened site
            SPServiceContext      ctx   = SPServiceContext.GetContext(site);
            SPServiceContextScope scope = new SPServiceContextScope(ctx);

            //Get the BDC service of the local SP farm
            BdcService         service           = SPFarm.Local.Services.GetValue <BdcService>();
            IMetadataCatalog   catalog           = service.GetDatabaseBackedMetadataCatalog(ctx);
            IEntity            entity            = catalog.GetEntity(nameSpace, entityName);
            ILobSystemInstance LobSysteminstance = entity.GetLobSystem().GetLobSystemInstances()[0].Value;
            IEntityInstance    entInstance       = null;

            //Loop through the methods defined in the LOB
            foreach (KeyValuePair <string, IMethod> method in entity.GetMethods())
            {
                IMethodInstance methodInstance = method.Value.GetMethodInstances()[method.Key];
                //Get the Specific Finder method of the LOB
                if (methodInstance.MethodInstanceType == MethodInstanceType.SpecificFinder)
                {
                    //Find the record with the ID from the datasource
                    Microsoft.BusinessData.Runtime.Identity id = new Microsoft.BusinessData.Runtime.Identity(entityId);
                    entInstance = entity.FindSpecific(id, entity.GetLobSystem().GetLobSystemInstances()[0].Value);
                }
            }

            return(entInstance);
        }
Example #15
0
        public static List <SPPrincipal> GetUserManagers(this SPUser user)
        {
            List <SPPrincipal> userManagers = new List <SPPrincipal>();

            UserProfile[] userManagersProfiles;

            SPServiceContext   spServiceContext   = SPServiceContext.GetContext(user.ParentWeb.Site);
            UserProfileManager userProfileManager = new UserProfileManager(spServiceContext);

            if (userProfileManager.UserExists(user.LoginName))
            {
                UserProfile userProfile = userProfileManager.GetUserProfile(user.LoginName);
                userManagersProfiles = userProfile.GetManagers();
            }
            else
            {
                return(userManagers);
            }

            foreach (UserProfile managerProfile in userManagersProfiles)
            {
                SPUser manager = user.ParentWeb.EnsureUser(managerProfile.AccountName);
                userManagers.Add(manager);
            }

            return(userManagers);
        }
Example #16
0
        /// <summary>
        /// Get the localized label of User Profile Properties
        /// Option 1 => Get the specific property to find the label (much better performance)
        /// </summary>
        /// <param name="userProfilePropertyName"></param>
        /// <reference>
        ///       1. http://nikpatel.net/2013/12/26/code-snippet-programmatically-retrieve-localized-user-profile-properties-label/
        /// </reference>
        /// <returns></returns>
        public string getLocalizedUserProfilePropertiesLabel(string userProfilePropertyName, SPWeb currentWeb)
        {
            string localizedLabel = string.Empty;

            try
            {
                //Get the handle of User Profile Service Application for current site (web application)
                SPSite                   site    = SPContext.Current.Site;
                SPServiceContext         context = SPServiceContext.GetContext(site);
                UserProfileConfigManager upcm    = new UserProfileConfigManager(context);

                //Access the User Profile Property manager core properties
                ProfilePropertyManager ppm = upcm.ProfilePropertyManager;
                CorePropertyManager    cpm = ppm.GetCoreProperties();

                //Get the core property for user profile property and get the localized value
                CoreProperty cp = cpm.GetPropertyByName(userProfilePropertyName);
                if (cp != null)
                {
                    localizedLabel = cp.DisplayNameLocalized[System.Globalization.CultureInfo.CurrentUICulture.LCID];
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at getLocalizedUserProfilePropertiesLabel function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
                return(string.Empty);
            }
            return(localizedLabel);
        }
Example #17
0
        protected void UploadPicture_OnClick(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(FileToLoad.Text))
            {
                return;
            }


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

                string filename = FileToLoad.Text;
                if (File.Exists(filename))
                {
                    FileStream   fileStream = File.OpenRead(filename);
                    BinaryReader reader     = new BinaryReader(fileStream);

                    int    length    = (int)new FileInfo(filename).Length;
                    byte[] byteArray = reader.ReadBytes(length);

//                    profile.
                }
            }
            catch (Exception error)
            {
                WBLogging.Debug("An error occurred: " + error.Message);
            }
        }
        internal static ISecureStore GetSecureStore()
        {
            var context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
            var ssp     = new SecureStoreServiceProxy();

            return(ssp.GetSecureStore(context));
        }
Example #19
0
        private void CheckListItemField(SPWeb web, SPList list, SPListItem listItem, Guid fieldId, JChemMetaFieldCollector metaData, WebStructureOutput webZipOutput)
        {
            try
            {
                JChemContextInfo ctx = new JChemContextInfo(
                    SPSecurity.AuthenticationMode != System.Web.Configuration.AuthenticationMode.Windows,
                    web.CurrentUser.LoginName,
                    Convert.ToBase64String(web.CurrentUser.UserToken.BinaryToken),
                    Guid.NewGuid(),
                    web.Site.ID,
                    web.ID,
                    web.Locale,
                    web.Locale,
                    Guid.NewGuid());
                StructureServiceClient client = new StructureServiceClient(ctx, SPServiceContext.GetContext(web.Site));

                var fieldContent = listItem[fieldId] as string;
                if (!string.IsNullOrEmpty(fieldContent))
                {
                    var fieldContentDocument = new HtmlDocument();
                    fieldContentDocument.LoadHtml(fieldContent);

                    HtmlNodeCollection structureHtmlNodesWithIdOrURL =
                        fieldContentDocument.DocumentNode.SelectNodes("//img[contains(@src,'/_vti_bin/JChem/CxnWebGet.svc/GetStructureImageFromSession')]");
                    if (structureHtmlNodesWithIdOrURL != null)
                    {
                        ConsoleEx.WriteLine(ConsoleColor.DarkRed, "\tEmpty structure found in '{0}/{1}/{2}'", web.Title, list.Title, listItem.Name);
                        foreach (var entry in metaData)
                        {
                            var structures = JChemMetaFieldDataProvider.GetStructures(entry.Value[FieldPropertyCollector.SructuresProperty]);
                            foreach (var structure in structures)
                            {
                                if (!structure.StructureString.StartsWith("error", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    try
                                    {
                                        var image = client.GetStructureImage(structure.StructureString, structure.Format.ToString(), 200, 200, false);
                                        using (var imageStream = new MemoryStream())
                                        {
                                            image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png);
                                            imageStream.Position = 0;
                                            webZipOutput.AddStructure(list.Title, listItem.Name, listItem.ID, structure.Id.ToString(), imageStream.ToArray());
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ConsoleEx.WriteLine(ConsoleColor.Red, "\tCannot render structure: {0}", ex.Message);
                                        Environment.Exit(1);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ConsoleEx.WriteLine("\tCannot determine content of column '{0}'. Reason: {1}", list.Fields[fieldId].Title, ex.Message);
            }
        }
Example #20
0
        ////// <summary>
        ////// The list received a context event.
        ////// </summary>
        //public override void ContextEvent(SPItemEventProperties properties)
        //{
        //  base.ContextEvent(properties);
        //}

        /// <summary>
        /// Executes the Barista Script in response to an item event.
        /// </summary>
        /// <param name="properties">The properties.</param>
        private static void ExecuteBaristaScript(SPItemEventProperties properties)
        {
            BrewRequest request;

            using (var web = properties.OpenWeb())
            {
                var list = web.Lists[properties.ListId];
                var item = list.GetItemById(properties.ListItemId);

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

                request = new BrewRequest
                {
                    Headers             = new BrewRequestHeaders(headers),
                    Code                = properties.ReceiverData,
                    ScriptEngineFactory =
                        "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52"
                };

                request.SetExtendedPropertiesFromSPItemEventProperties(web, list, item, properties);
            }

            var serviceContext = SPServiceContext.Current ??
                                 SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default,
                                                             new SPSiteSubscriptionIdentifier(Guid.Empty));

            var client = new BaristaServiceClient(serviceContext);

            client.Exec(request);
            //TODO: Allow for Syncronous events that expect to return an object with which to update the properties object with.
        }
Example #21
0
        internal static Collection <Microsoft.Office.Server.ActivityFeed.ActivityType> GetInstalledActivityTypes(OutputManager outputManager)
        {
            SPSite           site    = null;
            SPServiceContext context = null;

            try
            {
                site    = SPWebService.AdministrationService.WebApplications.First().Sites.First();
                context = SPServiceContext.GetContext(site);

                var am            = new Microsoft.Office.Server.ActivityFeed.ActivityManager(null, context);
                var activityTypes = am.ActivityTypes;

                return(activityTypes.ToCollection());
            }
            catch (Exception exception)
            {
                if (outputManager != null)
                {
                    outputManager.WriteError(string.Format(CultureInfo.CurrentCulture, Exceptions.ErrorGettingActivityTypes, exception.Message), exception);
                }
            }
            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }
            }

            return(null);
        }
    /// <summary>
    /// submit an async job to translate folder(s)
    /// </summary>
    /// <param name="culture">target langauge</param>
    /// <param name="inputFolder">Full URL of the input folder on SharePoint</param>
    /// <param name="outputFolder">Full URL of the output folder on SharePoint</param>
    static void AddAsyncFolder(string culture, string inputFolder, string outputFolder)
    {
        SPServiceContext sc  = SPServiceContext.GetContext(new SPSite(site));
        TranslationJob   job = new TranslationJob(sc, CultureInfo.GetCultureInfo(culture));

        using (SPSite siteIn = new SPSite(inputFolder))
        {
            Console.WriteLine("In site: {0}", siteIn);
            using (SPWeb webIn = siteIn.OpenWeb())
            {
                Console.WriteLine("In web: {0}", webIn);
                using (SPSite siteOut = new SPSite(outputFolder))
                {
                    Console.WriteLine("Out site: {0}", siteOut);
                    using (SPWeb webOut = siteOut.OpenWeb())
                    {
                        Console.WriteLine("Out web: {0}", webOut);
                        SPFolder folderIn  = webIn.GetFolder(inputFolder);
                        SPFolder folderOut = webOut.GetFolder(outputFolder);
                        Console.WriteLine("Input: " + folderIn);
                        Console.WriteLine("Output: " + folderOut);
                        //true means to recursive all the sub folders
                        job.AddFolder(folderIn, folderOut, true);
                        Console.WriteLine("Submitting the job");
                        job.Start();
                        ListJobItemInfo(job);
                    }
                }
            }
        }
    }
Example #23
0
        public static void ProcessUserProfile(this SPSite site, Action <UserProfileManager> action, bool ignoreUserPrivacy = false)
        {
            HttpContext currentContext = HttpContext.Current;

            try
            {
                HttpContext.Current = null;
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    site.RunAsSystem(elevSite =>
                    {
                        SPServiceContext serviceContext = SPServiceContext.GetContext(elevSite);
                        UserProfileManager upm          = new UserProfileManager(serviceContext, ignoreUserPrivacy);

                        if (action != null)
                        {
                            action(upm);
                        }
                    });
                });
            }
            finally
            {
                HttpContext.Current = currentContext;
            }
        }
    /// <summary>
    /// submit an async job to translate a document library
    /// </summary>
    /// <param name="culture">target langauge</param>
    /// <param name="inputList">Full URL of the input document library on SharePoint</param>
    /// <param name="outputList">Full URL of the output document library on SharePoint</param>
    static void AddAsyncLibrary(string culture, string inputList, string outputList)
    {
        SPServiceContext sc  = SPServiceContext.GetContext(new SPSite(site));
        TranslationJob   job = new TranslationJob(sc, CultureInfo.GetCultureInfo(culture));

        using (SPSite siteIn = new SPSite(inputList))
        {
            Console.WriteLine("In site: {0}", siteIn);
            using (SPWeb webIn = siteIn.OpenWeb())
            {
                Console.WriteLine("In web: {0}", webIn);
                using (SPSite siteOut = new SPSite(outputList))
                {
                    Console.WriteLine("Out site: {0}", siteOut);
                    using (SPWeb webOut = siteOut.OpenWeb())
                    {
                        Console.WriteLine("Out web: {0}", webOut);
                        SPDocumentLibrary listIn  = (SPDocumentLibrary)webIn.GetList(inputList);
                        SPDocumentLibrary listOut = (SPDocumentLibrary)webOut.GetList(outputList);
                        Console.WriteLine("Input: " + listIn);
                        Console.WriteLine("Output: " + listOut);
                        job.AddLibrary(listIn, listOut);
                        Console.WriteLine("Submitting the job");
                        job.Start();
                        ListJobItemInfo(job);
                    }
                }
            }
        }
    }
        /// <summary>
        /// Executes the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            output = string.Empty;

#if !MOSS
            output = NOT_VALID_FOR_FOUNDATION;
            return((int)ErrorCodes.GeneralError);
#endif

            SPServiceContext context = null;
            if (Params["serviceappname"].UserTypedIn)
            {
                SPSiteSubscriptionIdentifier subId  = Utilities.GetSiteSubscriptionId(new Guid(Params["sitesubscriptionid"].Value));
                SPServiceApplication         svcApp = Utilities.GetUserProfileServiceApplication(Params["serviceappname"].Value);
                Utilities.GetServiceContext(svcApp, subId);
            }
            else
            {
                using (SPSite site = new SPSite(Params["contextsite"].Value))
                    context = SPServiceContext.GetContext(site);
            }
            Console.WriteLine(Common.Audiences.EnumAudienceRules.EnumRules(context, Params["name"].Value, Params["explicit"].UserTypedIn));


            return((int)ErrorCodes.NoError);
        }
        protected ManagedProperty GetCurrentObject(object modelHost, ManagedPropertyDefinition definition,
                                                   out ManagedPropertyCollection properties,
                                                   out List <CrawledPropertyInfo> crawledProps)
        {
            if (modelHost is FarmModelHost)
            {
                var context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default,
                                                          SPSiteSubscriptionIdentifier.Default);
                var searchProxy =
                    context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;

                var ssai        = searchProxy.GetSearchServiceApplicationInfo();
                var application = SearchService.Service.SearchApplications.GetValue <SearchServiceApplication>(ssai.SearchServiceApplicationId);

                SearchObjectOwner searchOwner = new SearchObjectOwner(SearchObjectLevel.Ssa);

                if (cachedCrawledProps == null)
                {
                    cachedCrawledProps = application.GetAllCrawledProperties(string.Empty, string.Empty, 0, searchOwner);
                }

                crawledProps = cachedCrawledProps;

                var schema = new Schema(application);

                properties = schema.AllManagedProperties;
                return(properties.FirstOrDefault(p => p.Name.ToUpper() == definition.Name.ToUpper()));
            }

            throw new NotImplementedException();
        }
Example #27
0
        public void ReadSPProfiles(string strSiteUrl)
        {
            this.Clear();
            using (SPSite site2 = new SPSite(strSiteUrl))
            {
                using (SPWeb web = site2.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPServiceContext   sc  = SPServiceContext.GetContext(site2);
                    UserProfileManager upm = new UserProfileManager(sc);
                    foreach (UserProfile profile in upm)
                    {
                        // TODO: Figure out how to filter the list and skill all service accounts
                        if (profile["AccountName"].Value != null &&
                            (profile["AccountName"].Value.ToString().ToUpper().IndexOf("\\SM_") >= 0 ||
                             profile["AccountName"].Value.ToString().ToUpper().IndexOf("\\SP_") >= 0))
                        {
                            continue;
                        }
                        if (profile["AccountName"].Value != null &&
                            profile["AccountName"].Value.ToString() == profile.DisplayName)
                        {
                            continue;
                        }

                        Add(profile);
                    }
                }
            }
            this._bEmpty = false;
        }
        private OASResponse ConvertPPTImmediately(OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    byte[]       input     = Convert.FromBase64String(settings.Content);
                    MemoryStream outstream = new MemoryStream();

                    try
                    {
                        Microsoft.Office.Server.PowerPoint.Conversion.FixedFormatSettings ppsettings = FillPowerPointConversionOptions(settings.Options);

                        PdfRequest request = new PdfRequest(new MemoryStream(input), ".pptx", ppsettings, outstream);

                        IAsyncResult result = request.BeginConvert(SPServiceContext.GetContext(site), null, null);

                        // Use the EndConvert method to get the result.
                        request.EndConvert(result);

                        oasResponse.Content   = Convert.ToBase64String(outstream.ToArray());
                        oasResponse.ErrorCode = OASErrorCodes.Success;
                    }
                    catch (Exception ex)
                    {
                        oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                        oasResponse.Message   = ex.Message;
                    }
                }
            }

            return(oasResponse);
        }
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Please specify file and web-service url to convert...");
                return;
            }

            // read file content
            string filename = args[0];
            Stream fs       = File.OpenRead(filename);

            string url = args[1];

            MemoryStream outstream = new MemoryStream();
            PdfRequest   request   = new PdfRequest(fs, ".pptx", outstream);

            SPSite site = new SPSite(url);

            IAsyncResult result = request.BeginConvert(SPServiceContext.GetContext(site), null, null);

            // Use the EndConvert method to get the result.
            request.EndConvert(result);

            string result_file = Path.GetDirectoryName(filename) + "\\" + Path.GetFileNameWithoutExtension(filename) + ".pdf";

            using (FileStream fs1 = new FileStream(result_file, FileMode.Create))
            {
                outstream.Position = 0;
                outstream.CopyTo(fs1);
                fs1.Flush();
            }
            fs.Close();
        }
        protected override void InternalProcessRecord()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }

            string xml = File.ReadAllText(InputFile);

            Common.Audiences.ImportAudiences.Import(xml, context, DeleteExisting.IsPresent, Compile.IsPresent, MapFile);
        }