Ejemplo n.º 1
0
        internal static void WriteToLog(SPContext context, Exception exception)
        {
            ASCIIEncoding enc = new ASCIIEncoding();
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            string errors = exception.Source + " " + exception.Message + " " + exception.StackTrace;

            SPFile files = context.Web.GetFile("/" + DocumentLibraryName + "/" + LogFileName);

            if (files.Exists)
            {
                byte[] fileContents = files.OpenBinary();
                string newContents = enc.GetString(fileContents) + Environment.NewLine + errors;
                files.SaveBinary(enc.GetBytes(newContents));
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter sw = new StreamWriter(ms, uniEncoding))
                    {
                        sw.Write(errors);
                    }

                    SPFolder LogLibraryFolder = SPContext.Current.Web.Folders[DocumentLibraryName];
                    LogLibraryFolder.Files.Add(LogFileName, ms.ToArray(), false);
                }
            }

            SPContext.Current.Web.Update();
        }
Ejemplo n.º 2
0
        internal static void WriteToLog(SPContext context, string message)
        {
            context.Web.AllowUnsafeUpdates = true;

            ASCIIEncoding enc = new ASCIIEncoding();
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            SPFile files = context.Web.GetFile("/" + DocumentLibraryName + "/" + LogFileName);

            if (files.Exists)
            {
                byte[] fileContents = files.OpenBinary();
                string newContents = enc.GetString(fileContents) + Environment.NewLine + message;
                files.SaveBinary(enc.GetBytes(newContents));
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter sw = new StreamWriter(ms, uniEncoding))
                    {
                        sw.Write(message);
                    }

                    SPFolder LogLibraryFolder = SPContext.Current.Web.Folders[DocumentLibraryName];
                    LogLibraryFolder.Files.Add(LogFileName, ms.ToArray(), false);
                }
            }

            files.Update();

            context.Web.AllowUnsafeUpdates = false;
        }
        public static string getSiteURL(SPContext Context)
        {
            if (Context != null)
                return Context.Site.Url;

            return "http://epm2007demo/pwa04"; // for developement
        }
 public static string GetDataBaseName(SPContext Context)
 {
     if (Context != null)
         return Utilities.GetProjectServerSQLDatabaseName(Context.Site.Url, Utilities.DatabaseType.ReportingDatabase);
     // For Development
     return "";
 }
Ejemplo n.º 5
0
 public SharePointContext(SPContext context, ILanguage language, Console console)
 {
     _language = language;
       _console = console;
       language.SetVar("Console", _console);
       language.SetVar("__site__", context.Site);
       language.SetVar("__web__", context.Web);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the user project leader.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="context">The context.</param>
        /// <returns>The Project Leader SPUser object.</returns>
        public static SPUser GetUserProjectLeader(SPUser user, SPServiceContext serviceContext, SPContext context)
        {
            return context.Web.AllUsers["fp\\fps_pm"];

            UserProfileManager manager = new UserProfileManager(serviceContext);
            var userProfile = manager.GetUserProfile(user.LoginName);
            var projectLeaderProfile = userProfile.GetManager();
            return context.Web.AllUsers[projectLeaderProfile.MultiloginAccounts[0]];
        }
        public static SPList getListUID(SPContext Context)
        {
            if (Context != null)
                return SPContext.Current.List;

            using (var Site = new SPSite(getSiteURL(Context)))
            {
                return Site.RootWeb.Lists["Shared Documents"];
            }
        }
Ejemplo n.º 8
0
        public bool IsCheckedOut(SPList list, SPListItem listItem)
        {
            var cacheId      = string.Format("SharePointFile:{0}_{1}", list.Id, listItem.Id);
            var isCheckedOut = (bool?)cacheService.Get(cacheId, CacheScope.Context | CacheScope.Process);

            if (isCheckedOut == null)
            {
                using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
                {
                    var spfile = clientContext.ToFile(list.Id, listItem.Id);
                    clientContext.Load(spfile, item => item.CheckedOutByUser);
                    clientContext.ExecuteQuery();
                    isCheckedOut = !(spfile.CheckedOutByUser.ServerObjectIsNull ?? true);
                    cacheService.Put(cacheId, isCheckedOut, CacheScope.Context | CacheScope.Process, new string[0], CacheTimeOut);
                }
            }
            return(isCheckedOut.Value);
        }
        public Dictionary <int, string> UserCollection(SPList currentList)
        {
            var _userCollection = new Dictionary <int, string>();

            using (var clientContext = new SPContext(currentList.SPWebUrl, credentials.Get(currentList.SPWebUrl)))
            {
                SP.Web web       = clientContext.Web;
                var    usersList = web.SiteUserInfoList.GetItems(SP.CamlQuery.CreateAllItemsQuery());
                clientContext.Load(usersList, _users => _users
                                   .Include(_user => _user["Name"], _user => _user.Id));
                clientContext.ExecuteQuery();
                for (int i = 0, len = usersList.Count; i < len; i++)
                {
                    _userCollection.Add(usersList[i].Id, usersList[i]["Name"].ToString());
                }
                return(_userCollection);
            }
        }
Ejemplo n.º 10
0
        internal static void InstallPackageInWeb(StorePackage package, string targetWebURL)
        {
            SPContext context = SPContext.Current;

            using (SPSite site = new SPSite(targetWebURL))
            {
                using (SPWeb activationWeb = site.OpenWeb())
                {
                    WebClient wc               = new WebClient();
                    string    tempFileName     = Path.GetTempFileName();
                    string    solutionFileName = package.SolutionFileName;
                    tempFileName             = tempFileName.Replace(Path.GetFileName(tempFileName), solutionFileName);
                    wc.UseDefaultCredentials = true;
                    wc.DownloadFile(package.PackageURL, tempFileName);

                    AddPackageContext packageContext = new AddPackageContext();
                    packageContext.HttpContext      = HttpContext.Current;
                    packageContext.SolutionFilePath = tempFileName;
                    packageContext.SPContext        = SPContext.Current;
                    packageContext.StorePackage     = package;
                    packageContext.TargetWeb        = activationWeb;


                    if (package.SolutionType == SolutionType.Farm)
                    {
                        if (SPSINStorePackageUtilities.CanAddFarmSolutions(context, activationWeb))
                        {
                            SPSINStorePackageUtilities.AddFarmSolution(packageContext);
                        }
                    }
                    else if (package.SolutionType == SolutionType.Sandbox)
                    {
                        if (SPSINStorePackageUtilities.CanAddSandboxSolutions(SPContext.Current, activationWeb))
                        {
                            SPSINStorePackageUtilities.AddSandboxSolution(packageContext);
                        }
                    }
                    else
                    {
                        // use App type loader
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public List <Folder> UpToParent(string url, Guid libraryId, string folderPath)
        {
            var folderList = new List <Folder>();

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var list       = clientContext.Web.Lists.GetById(libraryId);
                    var rootFolder = list.RootFolder;
                    clientContext.Load(rootFolder, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount);
                    clientContext.ExecuteQuery();

                    bool pathIsNotEmpty  = !String.IsNullOrEmpty(folderPath.Trim('/'));
                    bool isARootFolder   = rootFolder.ServerRelativeUrl.Trim('/').Equals(folderPath.Trim('/'));
                    bool hasParentFolder = pathIsNotEmpty && !isARootFolder;
                    while (hasParentFolder)
                    {
                        var spfolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                        clientContext.Load(spfolder, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount);
                        clientContext.Load(spfolder.ParentFolder, p => p.ServerRelativeUrl);
                        clientContext.ExecuteQuery();

                        folderList.Add(new Folder(spfolder.Name, spfolder.ServerRelativeUrl, spfolder.ItemCount, libraryId));

                        folderPath = spfolder.ParentFolder.ServerRelativeUrl;

                        pathIsNotEmpty  = !String.IsNullOrEmpty(folderPath.Trim('/'));
                        isARootFolder   = rootFolder.ServerRelativeUrl.Trim('/').Equals(folderPath.Trim('/'));
                        hasParentFolder = pathIsNotEmpty && !isARootFolder;
                    }
                    folderList.Add(new Folder(rootFolder.Name, rootFolder.ServerRelativeUrl, rootFolder.ItemCount, libraryId));
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.UpToParent() method LibraryId: {1} ServerRelativeUrl: '{2}' SPWebUrl: '{3}'. The exception message is: {4}", ex.GetType(), libraryId, folderPath, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
            return(folderList);
        }
Ejemplo n.º 12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SPContext spContext = SPContext.Current;

            _spWeb = spContext.Web;

            WebUrl = _spWeb.SafeServerRelativeUrl();

            try
            {
                UplandInsightId = CoreFunctions.getConfigSetting(_spWeb.Site.RootWeb, "UplandInsightId");
            }
            catch (Exception ex)
            {
                //TODO handle exception
            }

            Scheme = Request.Url.Scheme;
        }
Ejemplo n.º 13
0
        private void LoadSubProviders(List <IntegrationProvider> collection, IntegrationProvider current)
        {
            using (var clientContext = new SPContext(current.SPSiteURL, current.Authentication))
            {
                var site = clientContext.Site;
                clientContext.Load(site, s => s.Id, s => s.Url);

                var webs = clientContext.Web.Webs;
                clientContext.Load(webs, ws => ws.Include(w => w.Id, w => w.ServerRelativeUrl, w => w.Title, w => w.Webs));

                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception)
                {
                    return;
                }

                Parallel.ForEach(webs, new ParallelOptions {
                    MaxDegreeOfParallelism = 5
                }, website =>
                {
                    var provider = new IntegrationProvider
                    {
                        SPSiteURL      = SPSite.MergeUrl(current.SPSiteURL, website.ServerRelativeUrl),
                        TEGroupId      = current.TEGroupId,
                        TEGroupName    = current.TEGroupName,
                        Authentication = current.Authentication,
                        SPSiteName     = website.Title,
                        SPWebID        = website.Id,
                        SPSiteID       = site.Id
                    };

                    collection.Add(provider);

                    if (website.Webs.Count > 0)
                    {
                        LoadSubProviders(collection, provider);
                    }
                });
            }
        }
 public SPUser Get(string url, int lookupId)
 {
     using (var clientContext = new SPContext(url, credentials.Get(url)))
     {
         try
         {
             var userProfile = clientContext.Web.SiteUserInfoList.GetItemById(lookupId);
             clientContext.Load(userProfile, SPUser.InstanceQuery);
             clientContext.ExecuteQuery();
             return(new SPUser(userProfile));
         }
         catch (Exception ex)
         {
             string message = string.Format("An exception of type {0} occurred in the InternalApi.UserProfileService.Get() method URL: {1}, LookupId: {2}. The exception message is: {4}", ex.GetType(), url, lookupId, ex.Message);
             SPLog.RoleOperationUnavailable(ex, message);
         }
     }
     return(null);
 }
Ejemplo n.º 15
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var db   = new SPContext();
                var user = new ApplicationUser {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var profile = new UserProfiles();
                    profile.UserID    = user.Id;
                    profile.FirstName = "..";
                    profile.LastName  = "..";
                    profile.Created   = DateTime.UtcNow.Ticks;

                    db.UserProfiles.Add(profile);
                    await db.SaveChangesAsync();


                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    await UserManager.AddToRoleAsync(user.Id, model.Roles);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }

                ViewBag.Roles = new SelectList(db.Roles.Where(a => !a.Name.Contains("Admin")).ToList(), "Name", "Name");

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 16
0
        public List <SPBaseUser> UserList(string url, Authentication authentication)
        {
            try
            {
                using (var clientContext = new SPContext(url, authentication ?? credentials.Get(url)))
                {
                    var userInfoList = clientContext.Web.SiteUserInfoList;
                    var users        = userInfoList.GetItems(CamlQuery.CreateAllItemsQuery());
                    clientContext.Load(users, userCollection => userCollection.Include(
                                           u => u.Id,
                                           u => u["Name"],
                                           u => u.DisplayName));
                    clientContext.ExecuteQuery();

                    var userList = new List <SPBaseUser>();

                    foreach (var user in users)
                    {
                        try
                        {
                            if (user.FieldValues["Name"] != null)
                            {
                                userList.Add(new SPBaseUser(user.Id, user.FieldValues["Name"].ToString())
                                {
                                    Name = user.DisplayName
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            SPLog.UnKnownError(ex, ex.Message);
                        }
                    }
                    return(userList);
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the WidgetApi.V1.SharePointPermissions.GroupList() method for URL: {1}. The exception message is: {2}", ex.GetType(), url, ex.Message);
                SPLog.UnKnownError(ex, message);
            }
            return(null);
        }
Ejemplo n.º 17
0
        protected override void CreateChildControls()
        {
            buildParams();

            if (SPContext.Current.ViewContext.View != null)
            {
                try
                {
                    typeof(ListTitleViewSelectorMenu).GetField("m_wpSingleInit", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Page.FindControl("ctl00$PlaceHolderPageTitleInTitleArea$ctl01$ctl00").Controls[1], true);
                }
                catch { }
                try
                {
                    typeof(ListTitleViewSelectorMenu).GetField("m_wpSingle", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Page.FindControl("ctl00$PlaceHolderPageTitleInTitleArea$ctl01$ctl00").Controls[1], true);
                }
                catch { }
            }

            EnsureChildControls();

            EPMLiveCore.Act act = new EPMLiveCore.Act(web);
            activation = act.CheckFeatureLicense(EPMLiveCore.ActFeature.WebParts);
            if (activation != 0)
            {
                return;
            }

            try
            {
                toolbar = new ViewToolBar();
                toolbar.EnableViewState = false;

                list = SPContext.Current.List;
                view = SPContext.Current.ViewContext.View;

                SPContext context = SPContext.GetContext(this.Context, view.ID, list.ID, web);
                toolbar.RenderContext = context;

                Controls.Add(toolbar);
            }
            catch { }
        }
 public SPListItem Update(SPList list, SPListItem item)
 {
     using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
     {
         SP.List     splist   = clientContext.ToList(list.Id);
         SP.ListItem listItem = clientContext.ToList(list.Id).GetItemById(item.Id);
         clientContext.Load(listItem);
         foreach (var field in item.Fields)
         {
             listItem[field.Key] = field.Value;
         }
         clientContext.ValidateOnClient = true;
         listItem.Update();
         clientContext.Load(listItem);
         var fieldsQuery = clientContext.LoadQuery(splist.Fields.Where(field => !field.Hidden && field.Group != "_Hidden"));
         clientContext.ExecuteQuery();
         cacheService.RemoveByTags(new[] { GetTag(list.Id) }, CacheScope.Context | CacheScope.Process);
         return(new SPListItem(listItem, fieldsQuery.ToList()));
     }
 }
Ejemplo n.º 19
0
        public void CheckOut(string url, Guid libraryId, int itemId)
        {
            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var spfile = clientContext.Web.Lists.GetById(libraryId).GetItemById(itemId).File;
                    spfile.CheckOut();

                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFileService.CheckOut() method for URL: {1}, LibraryId: {2}, ItemId: {3}. The exception message is: {4}", ex.GetType(), url, libraryId, itemId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message);
            }
        }
Ejemplo n.º 20
0
        public FarmUserProfileService(SPProfileSyncProvider settings)
        {
            syncSettings = settings;

            farmUserProfileService = new UserProfileService
            {
                UseDefaultCredentials = false,
                Credentials           = syncSettings.Authentication.Credentials(),
                Url = syncSettings.SPSiteURL.TrimEnd('/') + UserProfileServiceUrl
            };

            farmUserProfileChangeService = new UserProfileChangeService
            {
                UseDefaultCredentials = false,
                Credentials           = syncSettings.Authentication.Credentials(),
                Url = syncSettings.SPSiteURL.TrimEnd('/') + UserProfileChangeServiceUrl
            };

            spcontext = new SPContext(syncSettings.SPSiteURL, syncSettings.Authentication);
        }
Ejemplo n.º 21
0
        internal static string GetFolderPath(SPContext ctx, HttpContext context, SPList list)
        {
#if SP12
            string rootFolder = context.Request.QueryString ["RootFolder"];
#else
            string rootFolder = ((ctx == null) ? context.Request.QueryString ["RootFolder"] : ctx.RootFolderUrl);
#endif
            if ((rootFolder == null) || "*".Equals(rootFolder))
            {
                rootFolder = string.Empty;
            }
            if (rootFolder.StartsWith(SPContext.Current.Web.Url, StringComparison.InvariantCultureIgnoreCase))
            {
                rootFolder = rootFolder.Substring(SPContext.Current.Web.Url.Length);
            }
            if (rootFolder.StartsWith(SPContext.Current.Web.ServerRelativeUrl, StringComparison.InvariantCultureIgnoreCase))
            {
                rootFolder = rootFolder.Substring(SPContext.Current.Web.ServerRelativeUrl.Length);
            }
            return((rootFolder.Trim('/').StartsWith(list.RootFolder.Url.Trim('/'), StringComparison.InvariantCultureIgnoreCase) ? rootFolder.Trim('/').Substring(list.RootFolder.Url.Trim('/').Length) : rootFolder).Trim('/'));
        }
        public Dictionary <string, string> GetValues(SPList currentList, object splistItem, SP.Field field, bool removeSelected)
        {
            SPListItem listItem = splistItem as SPListItem;

            SP.FieldLookup lookupField = field as SP.FieldLookup;
            if (lookupField == null)
            {
                return(new Dictionary <string, string>());
            }
            using (var clientContext = new SPContext(currentList.SPWebUrl, credentials.Get(currentList.SPWebUrl)))
            {
                SP.Web lookupWeb = clientContext.Site.OpenWebById(lookupField.LookupWebId);
                clientContext.Load(lookupWeb);
                SP.List list = lookupWeb.Lists.GetById(new Guid(lookupField.LookupList));
                clientContext.Load(list);
                SP.ListItemCollection items = list.GetItems(SP.CamlQuery.CreateAllItemsQuery());
                clientContext.Load(items);
                clientContext.ExecuteQuery();
                SP.FieldLookupValue[] selectedValues = null;
                if (removeSelected)
                {
                    selectedValues = GetSelectedValues(listItem, field);
                }
                Dictionary <string, string> values = new Dictionary <string, string>();
                foreach (SP.ListItem item in items)
                {
                    if (removeSelected && selectedValues.Any(v => v.LookupId == item.Id))
                    {
                        continue;
                    }
                    object lookupVal = item[lookupField.LookupField];
                    if (lookupVal != null)
                    {
                        values.Add(item.Id.ToString(), (string)lookupVal);
                    }
                }
                return(values);
            }
        }
Ejemplo n.º 23
0
        private void GetImageFile()
        {
            if (ImageFile == null)
            {
                SPContext currentContext = SPContext.Current;

                if (currentContext != null)
                {
                    SPSite currentSite = currentContext.Site;

                    using (SPWeb fileWeb = currentSite.OpenWeb(Source, false)) {
                        string fullUrl = currentSite.MakeFullUrl(Source);
                        ImageFile = fileWeb.GetFile(fullUrl);
                    }
                }

                if (ImageFile != null || !ImageFile.Exists)
                {
                    throw new FileNotFoundException(FileNotFoundErrorMessage, Source);
                }
            }
        }
Ejemplo n.º 24
0
        public SPWeb OpenWeb()
        {
            try
            {
                using (var clientContext = new SPContext(siteUrl, auth, runAsServiceAccount: true))
                {
                    var web  = clientContext.Web;
                    var site = clientContext.Site;

                    clientContext.Load(web, w => w.Title, w => w.Id);
                    clientContext.Load(site, s => s.Id);

                    clientContext.ExecuteQuery();

                    return(new SPWeb(clientContext.Url, site.Id, web.Id, web.Title));
                }
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Recycle Folder
        /// </summary>
        /// <param name="url">SPWeb Url</param>
        /// <param name="folderPath"></param>
        /// <returns>A Guid that represents the transaction ID of the delete transaction.</returns>
        public Guid Recycle(string url, string folderPath)
        {
            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var spfolder     = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    var removedItems = spfolder.Recycle();

                    clientContext.ExecuteQuery();

                    return(removedItems.Value);
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Recycle() method ServerRelativeUrl: '{1}' in SPWebUrl: '{2}'. The exception message is: {3}", ex.GetType(), folderPath, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
        }
Ejemplo n.º 26
0
        private ClaimsContext(SPContext context)
        {
            SPWebApplication webApplication = context.Site.WebApplication;

            foreach (SPAlternateUrl mapping in webApplication.AlternateUrls)
            {
                SPIisSettings settings = webApplication.GetIisSettingsWithFallback(mapping.UrlZone);
                if (settings.UseFormsClaimsAuthenticationProvider)
                {
                    this.FormsMembershipProvider = Membership.Providers[settings.FormsClaimsAuthenticationProvider.MembershipProvider];
                    this.FormsRoleProvider       = Roles.Providers[settings.FormsClaimsAuthenticationProvider.RoleProvider];
                    break;
                }
            }

            SPUser currentUser = context.Web.CurrentUser;

            if (currentUser != null && SPClaimProviderManager.IsEncodedClaim(currentUser.LoginName))
            {
                SPClaim claim = SPClaimProviderManager.Local.DecodeClaim(currentUser.LoginName);
                this.IsWindowsUser = claim.OriginalIssuer == "Windows";

                if (claim.OriginalIssuer.StartsWith("Forms:"))
                {
                    if (this.FormsMembershipProvider != null && this.FormsMembershipProvider.Name.Equals(claim.OriginalIssuer.Substring(6), StringComparison.OrdinalIgnoreCase))
                    {
                        this.FormsUser = this.FormsMembershipProvider.GetUser(claim.Value, false);
                        if (this.FormsUser != null)
                        {
                            this.IsFormsUser      = true;
                            this.FormsUserId      = claim.Value;
                            this.FormsUserProfile = ProfileBase.Create(this.FormsUser.UserName);
                        }
                    }
                }
            }
            this.IsAnonymous = !this.IsFormsUser && !this.IsWindowsUser;
        }
Ejemplo n.º 27
0
        public PagedList <SPPermissions> List(PermissionsListQuery options)
        {
            var spwebUrl = EnsureUrl(options.Url, options.ListId);

            try
            {
                using (var clientContext = new SPContext(spwebUrl, credentials.Get(spwebUrl)))
                {
                    List splist = clientContext.Web.Lists.GetById(options.ListId);
                    var  splistItemCollection = splist.GetItems(options.Id.HasValue ?
                                                                CAMLQueryBuilder.GetItem(options.Id.Value, new string[] { }) :
                                                                CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));

                    var lazyListItems = clientContext.LoadQuery(splistItemCollection.Include(item => item.HasUniqueRoleAssignments, item => item.Id));
                    clientContext.ExecuteQuery();

                    var splistItem = lazyListItems.First();
                    IEnumerable <RoleAssignment> lazyRoleAssignmentList = RoleAssignmentsLoadQuery(splistItem, clientContext);
                    clientContext.ExecuteQuery();

                    var roleAssignmentList = lazyRoleAssignmentList.ToList();
                    return(new PagedList <SPPermissions>(roleAssignmentList.Skip(options.PageSize * options.PageIndex).Take(options.PageSize).Select(ra => ra.ToPermission()))
                    {
                        PageSize = options.PageSize,
                        PageIndex = options.PageIndex,
                        TotalCount = roleAssignmentList.Count
                    });
                }
            }
            catch (Exception ex)
            {
                string listItemId = options.Id.HasValue ? options.Id.Value.ToString(CultureInfo.InvariantCulture) : options.ContentId.ToString();
                string message    = string.Format("An exception of type {0} occurred in the SPPermissionsService.List() method for ListId: {1} ItemId: {2}. The exception message is: {3}", ex.GetType(), options.ListId, listItemId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
        }
        public SPListItem Get(SPList list, string listItemId,
                              [Documentation(Name = "ViewFields", Type = typeof(List <string>))]
                              IDictionary options)
        {
            int id;

            if (!int.TryParse(listItemId, out id))
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                var splist = clientContext.ToList(list.Id);
                IEnumerable <ListItem> itemQuery;
                if (options != null && options["ViewFields"] != null)
                {
                    var viewFields = (List <string>)options["ViewFields"];
                    itemQuery = clientContext.LoadQuery(splist.GetItems(CamlQuery.CreateAllItemsQuery())
                                                        .Where(item => item.Id == id)
                                                        .Include(CreateListItemLoadExpressions(viewFields)));
                }
                else
                {
                    itemQuery = clientContext.LoadQuery(splist.GetItems(CamlQuery.CreateAllItemsQuery())
                                                        .Where(item => item.Id == id)
                                                        .IncludeWithDefaultProperties(SPItemService.InstanceQuery));
                }
                var fieldsQuery = clientContext.LoadQuery(splist.Fields.Where(field => !field.Hidden && field.Group != "_Hidden"));
                clientContext.ExecuteQuery();
                var listItem = itemQuery.FirstOrDefault();
                if (listItem != null)
                {
                    return(new SPListItem(listItem, fieldsQuery.ToList()));
                }
                return(null);
            }
        }
        /// <summary>
        /// Tries get config store list from context.
        /// Without launch exceptions
        /// </summary>
        /// <returns>The list</returns>
        private static SPList TryGetConfigStoreListFromContext()
        {
            SPList    configList     = null;
            SPContext currentContext = SPContext.Current;

            if (currentContext != null)
            {
                SPSite currentSite = currentContext.Site;
                SPWeb  configWeb   = TryGetConfigStoreWeb(currentSite, false);

                if (configWeb != null)
                {
                    configList = TryGetConfigStoreList(configWeb, false);
                }

                {
                    // we're not in the same site collection as the config web. Exit without disposing any references since
                    // we haven't created any objects..
                }
            }

            return(configList);
        }
Ejemplo n.º 30
0
        public Stream GetResumeDetails(Int32 candidateId)
        {
            String foldername = this.LobSystemInstance.GetProperties()["FolderName"] as string;

            if (foldername == null)
            {
                throw new LobBusinessErrorException("the folder information is missing to retrive the resume file");
            }

            SPContext context = GetSPContext();

            if (context == null)
            {
                throw new LobBusinessErrorException("The SPServiceContext is null to get the resume file");
            }

            SPWeb site = context.Web;


            string   fileName     = "Candidate" + candidateId + ".docx";
            SPFolder resumeFolder = site.GetFolder(foldername);

            if (resumeFolder == null)
            {
                throw new LobBusinessErrorException("The folder cannot be found. Hence exiting....");
            }

            SPFile file         = resumeFolder.Files[fileName];
            Stream resumeStream = file.OpenBinaryStream(SPOpenBinaryOptions.SkipVirusScan);

            if (!resumeStream.CanRead)
            {
                throw new LobBusinessErrorException("The resume file cannot be read");
            }

            return(resumeStream);
        }
Ejemplo n.º 31
0
        public void Remove(int[] userOrGroupIds, PermissionsGetQuery options)
        {
            if (userOrGroupIds != null && userOrGroupIds.Length > 0)
            {
                var spwebUrl = EnsureUrl(options.Url, options.ListId);

                try
                {
                    using (var clientContext = new SPContext(spwebUrl, credentials.Get(spwebUrl)))
                    {
                        List splist = clientContext.Web.Lists.GetById(options.ListId);
                        var  splistItemCollection = splist.GetItems(options.Id.HasValue ?
                                                                    CAMLQueryBuilder.GetItem(options.Id.Value, new string[] { }) :
                                                                    CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));

                        var lazyListItems = clientContext.LoadQuery(splistItemCollection.Include(item => item.HasUniqueRoleAssignments, item => item.Id));
                        clientContext.ExecuteQuery();

                        var splistItem = lazyListItems.First();
                        foreach (int userOrGroupId in userOrGroupIds)
                        {
                            splistItem.RoleAssignments.GetByPrincipalId(userOrGroupId).DeleteObject();
                        }
                        clientContext.ExecuteQuery();
                    }
                }
                catch (Exception ex)
                {
                    string listItemId           = options.Id.HasValue ? options.Id.Value.ToString(CultureInfo.InvariantCulture) : options.ContentId.ToString();
                    string userOrGroupIdsString = string.Join(", ", userOrGroupIds);
                    string message = string.Format("An exception of type {0} occurred in the SPPermissionsService.Remove() method for Users or Groups with Ids: {1} ListId: {2} ItemId: {3}. The exception message is: {4}", ex.GetType(), userOrGroupIdsString, options.ListId, listItemId, ex.Message);
                    SPLog.RoleOperationUnavailable(ex, message);

                    throw new SPInternalException(message, ex);
                }
            }
        }
Ejemplo n.º 32
0
        public List <SPGroup> GroupList(string url, Authentication authentication)
        {
            try
            {
                using (var clientContext = new SPContext(url, authentication ?? credentials.Get(url)))
                {
                    SP.Web web = clientContext.Web;
                    IEnumerable <SP.Group> groups = clientContext.LoadQuery(web.SiteGroups);
                    clientContext.ExecuteQuery();

                    return((from g in groups
                            select new SPGroup(g.Id, g.LoginName)
                    {
                        Description = g.Description
                    }).ToList());
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the WidgetApi.V1.SharePointPermissions.GroupList() method for URL: {1}. The exception message is: {2}", ex.GetType(), url, ex.Message);
                SPLog.UnKnownError(ex, message);
            }
            return(null);
        }
Ejemplo n.º 33
0
        public VideoSettings Load()
        {
            if (SPContext.Current != null)
            {
                _context = SPContext.Current;
                Load(SPContext.Current.Site);
            }
            else
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    if (_context != null)
                    {
                        _context = SPContext.GetContext(context);
                    }

                    SPSite site = Context.Site;// (context.Request.Url.ToString());
                    Load(site);
                }
            }

            return(this);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Register the specified type (class) for the current page. This will also add the common JavaScript file.
        /// </summary>
        /// <param name="type">The tpye to register i.e. RegisterTypeForAjax(typeof(WebApplication1.WebForm1));</param>
        /// <param name="page">The Page the script should rendered on.</param>
        public static void RegisterTypeForAjax(Type type, System.Web.UI.Page page)
        {
            RegisterCommonAjax(page);

            string path = type.FullName + "," + type.Assembly.FullName.Substring(0, type.Assembly.FullName.IndexOf(","));

#if (NET20)
            if (!Settings.OldStyle.Contains("appCodeQualifiedFullName") && type.Assembly.FullName.StartsWith("App_Code."))
            {
                path = type.FullName + ",App_Code";
            }
#endif

            if (Utility.Settings.UseAssemblyQualifiedName)
            {
                path = type.AssemblyQualifiedName;
            }

            if (Utility.Settings != null && Utility.Settings.UrlNamespaceMappings.ContainsValue(path))
            {
                foreach (string key in Utility.Settings.UrlNamespaceMappings.Keys)
                {
                    if (Utility.Settings.UrlNamespaceMappings[key].ToString() == path)
                    {
                        path = key;
                        break;
                    }
                }
            }

            //iiunknown added @16:06 2013/11/9 增加AjaxPro客户端请求对SharePoint的SPContext.Current的支持,方便服务器端Ajax方法能正确定位到当前真正的SharePoint路径下的SPContext.Current,而不需要传递过多的参数去自己构造SharePoint上下文环境。
            SPContext c           = SPContext.Current;
            string    queryString = string.Format("siteid={0}&webid={1}&listid={2}&itemid={3}&lcid={4}&formmode={5}", c.Site.ID, c.Web.ID, c.ListId, c.ItemId, System.Threading.Thread.CurrentThread.CurrentUICulture.LCID, (int)c.FormContext.FormMode);
            RegisterClientScriptBlock(page, "AjaxType." + type.FullName,
                                      "<script type=\"text/javascript\" src=\"" + System.Web.HttpContext.Current.Request.ApplicationPath + (System.Web.HttpContext.Current.Request.ApplicationPath.EndsWith("/") ? "" : "/") + Utility.HandlerPath + "/" + Utility.GetSessionUri() + path + Utility.HandlerExtension + "?" + queryString + "\"></script>");
        }
Ejemplo n.º 35
0
        public SPDocumentInfo GetDetails(string url, Guid libraryId, int itemId)
        {
            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var spList = clientContext.Web.Lists.GetById(libraryId);
                    var spFile = spList.GetItemById(itemId).File;
                    clientContext.Load(spList);
                    clientContext.Load(spFile);
                    clientContext.Load(spFile, f => f.CheckedOutByUser);
                    clientContext.ExecuteQuery();

                    return(new SPDocumentInfo(spList, spFile, spFile.CheckedOutByUser));
                }
            }
            catch (Exception ex)
            {
                var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFileService.GetDetails() method for URL: {1}, LibraryId: {2}, ItemId: {3}. The exception message is: {4}", ex.GetType(), url, libraryId, itemId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message);
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Sends the email to user on print.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <param name="parentSiteURL">The parent site URL.</param>
        /// <param name="strAddress">The STR address.</param>
        /// <param name="contextForMail">The context for mail.</param>
        public void SendEmailToUserOnPrint(string results, string parentSiteURL, string strAddress, SPContext contextForMail)
        {
            DataTable dtPrintChapterDetails = null;
            ActiveDirectoryService objADS = null;
            try
            {
                try
                {
                    objADS = new ActiveDirectoryService();
                }
                catch (Exception)
                {
                    objADS = new ActiveDirectoryService(contextForMail);
                }
                dtPrintChapterDetails = new DataTable();
                CommonUtility objUtility = new CommonUtility();
                objCommonDAL = new CommonDAL();
                string strToMailID = string.Empty;
                string strAccessLink = string.Empty;
                string strMessage = string.Empty;

                string strCamlQuery = @"<Where><Eq><FieldRef Name='RequestID' /><Value Type='Text'>" + results + "</Value></Eq></Where>";
                dtPrintChapterDetails = objCommonDAL.GetChapterPrintDetails(strCamlQuery, parentSiteURL, "DWB Chapter Print Details");

                if (dtPrintChapterDetails != null && dtPrintChapterDetails.Rows.Count > 0)
                {
                    /// Loop through the values in Chapter Print Details list.
                    foreach (DataRow dtRow in dtPrintChapterDetails.Rows)
                    {
                        try
                        {
                            strToMailID = objADS.GetEmailID(dtRow["UserName"].ToString());
                        }
                        catch (Exception)
                        {
                        }
                        strAccessLink = parentSiteURL + "/Pages/eWBPDFViewer.aspx?mode=chapter&requestID=" + results;

                        objUtility.SendMailforPrintUpdate(strToMailID, strAccessLink, parentSiteURL, strAddress, contextForMail);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (dtPrintChapterDetails != null)
                    dtPrintChapterDetails.Dispose();
            }
        }
 public static string GetSiteURL(SPContext Context)
 {
     if (Context != null)
         return Utilities.GetDefaultZoneUri(SPContext.Current.Site);
     return "http://jump/cimb";
 }
 public static string ProjectServerInstanceURL(SPContext context)
 {
     if (context != null)
         return context.Site.Url;
     return "http://epm2007demo/pwa04";
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Sends the mailfor print update.
        /// </summary>
        /// <param name="strToMailID">The STR to mail ID.</param>
        /// <param name="message">The message.</param>
        /// <param name="parentSiteURL">The parent site URL.</param>
        /// <param name="address">The address.</param>
        /// <param name="contextForMail">The context for mail.</param>
        public void SendMailforPrintUpdate(string strToMailID, string message, string parentSiteURL, string address, SPContext contextForMail)
        {
            try
            {
                StringBuilder strMessageBody = new StringBuilder();
                StringBuilder strAdminMailIDs = new StringBuilder();

                string strSubject = string.Empty;
                string strSignature = string.Empty;
                StringDictionary objHeaders = null;
                DataTable objDtListValue = null;
                DataRow objListRow;

                objDtListValue = new DataTable();
                objMossController = objFactory.GetServiceManager("MossService");
                objHeaders = new StringDictionary();
                string strCamlQuery = "<FieldRef Name=\"Title\"/><Where><Eq><FieldRef Name=\"Category\" /><Value Type=\"Choice\">"
                                + "eWB2 Printing</Value></Eq></Where>";

                objDtListValue = ((MOSSServiceManager)objMossController).ReadList(parentSiteURL, EMAILTEMPLATELIST, strCamlQuery);
                if(objDtListValue.Rows.Count > 0)
                {
                    objListRow = objDtListValue.Rows[0];
                    strSubject = objListRow["Subject"].ToString();
                    strMessageBody.Append(objListRow["BodyLine1"].ToString());
                    strMessageBody.Append("<BR><BR>" + objListRow["BodyLine2"].ToString());
                    strMessageBody = strMessageBody.Replace("{DREAM portal}", "<a href='" + parentSiteURL + "' >DREAM Portal</a>");
                    strSignature = objListRow["Signature"].ToString();
                    strSignature = strSignature.Replace("{Region}", "EPE");
                }
                strMessageBody.Append("<a href='" + message + "'>Click here</a> to access the PDF file.<BR>");
                strMessageBody.Append("<BR><BR>" + strSignature);

                //build String Dictionary Object
                objHeaders.Add("from", GetSenderEmailId());
                objHeaders.Add("to", strToMailID.ToString());
                objHeaders.Add("subject", strSubject);
                SendAlertMail(objHeaders, strMessageBody.ToString(), contextForMail);
            }
            catch(Exception Ex)
            {
                throw Ex;
            }
        }
Ejemplo n.º 40
0
 /// <summary>
 /// Sends the alert mail.
 /// </summary>
 /// <param name="header">The header.</param>
 /// <param name="messageBody">The message body.</param>
 /// <param name="contextForMail">The context for mail.</param>
 private void SendAlertMail(StringDictionary header, string messageBody, SPContext contextForMail)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             SPUtility.SendEmail(contextForMail.Site.OpenWeb(), header, messageBody.ToString());
         });
     }
     catch(Exception Ex)
     {
         throw Ex;
     }
 }
Ejemplo n.º 41
0
        void EnsureFormContext()
        {
            if ((this.m_itemContext == null) && (this.Context != null))
            {
                if (base.List == null)
                {
                    throw new SPException(SPResource.GetString("ListWithTitleDoesNotExist", new object[] { base.ListName }));
                }

                if (Page.Request.QueryString["ID"] != null)
                {
                    //if (this.CurListItemId <= 0)
                    this.CurListItemId = Convert.ToInt32(Page.Request.QueryString["ID"]);

                    if (this.FormMode == SPControlMode.Invalid)
                        this.FormMode = SPControlMode.Display ;
                }
                else
                {
                    if (this.FormMode == SPControlMode.Invalid)
                        this.FormMode = SPControlMode.New ;
                }

                this.m_itemContext = SPContext.GetContext(this.Context, this.CurListItemId, this.List.ID, base.Web);

                if (this._FormMode == SPControlMode.Invalid)
                {
                    this._FormMode = this.m_itemContext.FormContext.FormMode;
                }
                else
                {
                    this.m_itemContext.FormContext.FormMode = this.FormMode;
                    //this.m_itemContext.FormContext.DisableInitialFocus = this.DisableInitialFocus;
                    this.m_itemContext.FormContext.SetFormMode(this.FormMode, true);
                }
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Gets the print document URL.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <param name="parentSiteURL">The parent site URL.</param>
        /// <param name="strAddress">The STR address.</param>
        /// <param name="contextForMail">The context for mail.</param>
        /// <param name="listName">Name of the list.</param>
        /// <returns></returns>
        public string GetPrintDocumentURL(string results, string parentSiteURL, string strAddress, SPContext contextForMail, string listName)
        {
            string strDocumentURL = string.Empty;
            DataTable dtPrintChapterDetails = null;
            try
            {
                string strCamlQuery = @"<Where><Eq><FieldRef Name='RequestID' /><Value Type='Text'>" + results + "</Value></Eq></Where>";
                dtPrintChapterDetails = objCommonDAL.GetChapterPrintDetails(strCamlQuery, parentSiteURL, listName);

                if (dtPrintChapterDetails != null && dtPrintChapterDetails.Rows.Count > 0)
                {
                    /// Loop through the values in Chapter Print Details list.
                    foreach (DataRow dtRow in dtPrintChapterDetails.Rows)
                    {
                        strDocumentURL = dtRow["DocumentURL"].ToString();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (dtPrintChapterDetails != null)
                    dtPrintChapterDetails.Dispose();
            }
            return strDocumentURL;
        }
Ejemplo n.º 43
0
 public PowerWebEventReceiver()
 {
     httpContext = HttpContext.Current;
     spContext   = SPContext.Current;
 }
Ejemplo n.º 44
0
        protected override void CreateChildControls()
        {
            try
            {
                foreach (SINCycleReceiver receiver in SINCycleReceivers)
                {
                    SINCycleContext scContext = new SINCycleContext();
                    receiver.BeforeContextLoad(scContext);
                }

                SPContext   currentcontext = SPContext.Current;
                HttpContext httpContext    = HttpContext.Current;

                foreach (SINCycleReceiver receiver in SINCycleReceivers)
                {
                    SINCycleContext scContext = new SINCycleContext();
                    scContext.SPContext   = currentcontext;
                    scContext.HttpContext = httpContext;
                    receiver.AfterContextLoad(scContext);
                }

                foreach (SINCycleReceiver receiver in SINCycleReceivers)
                {
                    SINCycleContext scContext = new SINCycleContext();
                    scContext.SPContext   = currentcontext;
                    scContext.HttpContext = httpContext;
                    receiver.BeforeResourceItemsLoad(scContext);
                }

                List <SPListItem> allItems = Utilities.GetAllItemsForContext(currentcontext, SINCycleReceivers);

                foreach (SINCycleReceiver receiver in SINCycleReceivers)
                {
                    SINCycleContext scContext = new SINCycleContext();
                    scContext.SPContext   = currentcontext;
                    scContext.HttpContext = httpContext;
                    receiver.AfterResourceItemsLoad(scContext, allItems);
                }

                StringBuilder sb = new StringBuilder();

                foreach (SPListItem item in allItems)
                {
                    SPContentType ct = item.ContentType;
                    string        ctResourceConfiguration = ct.XmlDocuments["http://schemas.spsin.com/Resource"];
                    XmlDocument   xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(ctResourceConfiguration);
                    string               receiverAssembly = xmlDoc["ScriptResourceReceiver"]["ReceiverAssembly"].InnerText;
                    string               receiverClass    = xmlDoc["ScriptResourceReceiver"]["ReceiverClass"].InnerText;
                    Assembly             assembly         = Assembly.Load(receiverAssembly);
                    SPSINResourceHandler resourceItem     = (SPSINResourceHandler)assembly.CreateInstance(receiverClass);
                    SPSINContext         context          = new SPSINContext();
                    context.Context     = currentcontext;
                    context.Item        = item;
                    context.HttpContext = httpContext;

                    string resourceString = "";

                    foreach (SINCycleReceiver receiver in SINCycleReceivers)
                    {
                        SINCycleContext scContext = new SINCycleContext();
                        scContext.SPContext           = currentcontext;
                        scContext.HttpContext         = httpContext;
                        scContext.AllResourceItems    = allItems;
                        scContext.CurrentResourceItem = item;
                        resourceString += receiver.BeforeResourceItemGetResourceStringEvaluation(scContext, item);
                    }

                    resourceString += resourceItem.GetResourceString(context);

                    foreach (SINCycleReceiver receiver in SINCycleReceivers)
                    {
                        SINCycleContext scContext = new SINCycleContext();
                        scContext.SPContext           = currentcontext;
                        scContext.HttpContext         = httpContext;
                        scContext.AllResourceItems    = allItems;
                        scContext.CurrentResourceItem = item;
                        resourceString = receiver.AfterResourceItemGetResourceStringEvaluation(scContext, item, resourceString);
                    }

                    sb.Append(resourceString);
                    sb.Append(Environment.NewLine);
                }

                string output = sb.ToString();
                foreach (SINCycleReceiver receiver in SINCycleReceivers)
                {
                    SINCycleContext scContext = new SINCycleContext();
                    scContext.SPContext        = currentcontext;
                    scContext.HttpContext      = httpContext;
                    scContext.AllResourceItems = allItems;
                    output = receiver.AfterProcessingComplete(scContext, output);
                }

                Controls.Add(new LiteralControl(output));
            }
            catch (Exception e)
            {
                Controls.Add(new LiteralControl(string.Format(@"<!-- SP SIN Encountered an exception while processing: {0} -->", e.ToString())));
            }
        }
Ejemplo n.º 45
0
 public BackOffice(SPContext spContext)
 {
     this._spweb = spContext.Web;
     this._isWebFromSPContext = true;
     this._userGroups = spContext.Web.CurrentUser.Groups.Cast<SPGroup>().Select<SPGroup, string>(g => g.Name).ToList<string>();
 }
 public static DataTable GetProjectTasks(SPContext context, Guid ProjectUID)
 {
     var ResultTaskTable = new DataTable();
     try
     {
         string SiteUrl = ProjectServerInstanceURL(context);
         SPSecurity.RunWithElevatedPrivileges(delegate
                                                  {
                                                      using (var site = new SPSite(SiteUrl))
                                                      {
                                                          SiteUrl = Utilities.GetDefaultZoneUri(site);
                                                      }
                                                  }
             );
         var Project_Svc = new Project
         {
             UseDefaultCredentials =
                 true,
             Url = (SiteUrl +
                    "/_vti_bin/psi/project.asmx"),
             AllowAutoRedirect = true
         };
         var projectDataSet = Project_Svc.ReadProjectEntities(ProjectUID, 2, DataStoreEnum.WorkingStore);
         ResultTaskTable.Columns.Add("ID");
         ResultTaskTable.Columns.Add("Task");
         ResultTaskTable.Columns.Add("UID");
         ResultTaskTable.Columns.Add("start date");
         ResultTaskTable.Columns.Add("end date");
         foreach (ProjectDataSet.TaskRow taskRow in projectDataSet.Task.Rows)
         {
             DataRow NewRow = ResultTaskTable.NewRow();
             NewRow["ID"] = taskRow.TASK_ID;
             NewRow["Task"] = taskRow.TASK_NAME;
             NewRow["UID"] = taskRow.TASK_UID;
             if (!taskRow.IsTASK_START_DATENull())
                 NewRow["start date"] = taskRow.TASK_START_DATE.ToString("dd/MM/yy");
             else
                 NewRow["start date"] = " -- ";
             if (!taskRow.IsTASK_FINISH_DATENull())
                 NewRow["end date"] = taskRow.TASK_FINISH_DATE.ToString("dd/MM/yy");
             else
                 NewRow["end date"] = " -- ";
             ResultTaskTable.Rows.Add(NewRow);
         }
     }
     catch (Exception ex)
     {
         ErrorLog("Error at getting project tasks due to " + ex.Message, EventLogEntryType.Error);
     }
     return ResultTaskTable;
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ActiveDirectoryService"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public ActiveDirectoryService(SPContext context)
 {
     try
     {
         strADFullPathName = PortalConfiguration.GetInstance().GetKey("ADFullPathName", context.Web.Url.ToString());
         strADServerName = PortalConfiguration.GetInstance().GetKey("ADServerName", context.Web.Url.ToString());
         strADUserName = PortalConfiguration.GetInstance().GetKey("ADUserName", context.Web.Url.ToString());
         strADPassword = PortalConfiguration.GetInstance().GetKey("ADPassword", context.Web.Url.ToString());
     }
     catch(Exception)
     {
         throw;
     }
 }
Ejemplo n.º 48
0
 internal CustomViewSelectorMenu(SPContext renderContext)
 {
     base.RenderContext = renderContext;
 }