Esempio n. 1
0
        public static void PopulateGuidData(
            string webId,
            string listId,
            string siteId,
            Action <SPList> updateProjectList,
            ref Guid siteGuid,
            ref SPWeb iWeb,
            ref SPSite iSite,
            ref Guid webGuid,
            ref Guid listGuid,
            ref SPList iList)
        {
            var wGuid = new Guid(webId);
            var lGuid = new Guid(listId);
            var sGuid = new Guid(siteId);

            if (siteGuid != sGuid)
            {
                if (iWeb != null)
                {
                    iWeb.Close();
                    iWeb = null;
                    iSite.Close();
                }
                iSite    = new SPSite(sGuid);
                siteGuid = iSite.ID;
            }
            if (webGuid != wGuid)
            {
                if (iWeb != null)
                {
                    iWeb.Close();
                    iWeb = iSite.OpenWeb(wGuid);
                }
                else
                {
                    iWeb = iSite.OpenWeb(wGuid);
                }
                webGuid = iWeb.ID;
            }
            if (listGuid != lGuid)
            {
                iList = iWeb.Lists[lGuid];
                updateProjectList?.Invoke(iList);
                listGuid = iList.ID;
            }
        }
Esempio n. 2
0
        public void HandleWSSUpdate(Microsoft.Office.Project.Server.Library.PSContextInfo contextInfo, string acceptdecline, Guid assnid, Guid projectid)
        {
            try
            {
                string thenotes = "";

                SPSite site = new SPSite(contextInfo.SiteGuid);

                Guid   trackingGuid = Guid.NewGuid();
                string lcid         = "1033";
                StatusingDerived.SetImpersonationContext(true, contextInfo.UserName, contextInfo.UserGuid, trackingGuid, contextInfo.SiteGuid, lcid);
                StatusingDerived statusing = new StatusingDerived();
                statusing.Url = site.Url + "/_vti_bin/psi/statusing.asmx";

                WebSvcStatusing.StatusingDataSet ds = statusing.ReadStatus(assnid, DateTime.MinValue, DateTime.MaxValue);

                //Guid userguid = new Guid(ds.Tables[0].Rows[0]["RES_UID"].ToString());

                DataTable dt     = ds.Tables["Tasks"];
                string    taskid = "";
                foreach (DataRow dr in dt.Rows)
                {
                    taskid = dr["Task_Published_UID"].ToString();
                    break;
                }

                WebSvcStatusing.StatusApprovalDataSet statusingDs2 = statusing.ReadStatusApprovalsInProcess(contextInfo.UserGuid);
                WebSvcStatusing.StatusApprovalDataSet.StatusApprovalsRow[] statusingRow = (WebSvcStatusing.StatusApprovalDataSet.StatusApprovalsRow[])statusingDs2.Tables[0].Select("ASSN_UID = '" + assnid + "'");

                if (statusingRow.Length > 0)
                {
                    string impersonateuser = GetWindowsAccountByResGUID(statusingRow[0].RES_UID.ToString(), contextInfo, site.Url);

                    //impersonate
                    Guid   trackingGuid2 = Guid.NewGuid();
                    string lcid2         = "1033";
                    StatusingDerived.SetImpersonationContext(true, impersonateuser, statusingRow[0].RES_UID, trackingGuid2, contextInfo.SiteGuid, lcid2);
                    //StatusingDerived statusing2 = new StatusingDerived();
                    //statusing2.Url = site.Url + "/_vti_bin/psi/statusing.asmx";
                    WebSvcStatusing.AssnHistoryDataSet statusingDs4             = statusing.ReadAssignmentHistory(statusingRow[0].ASSN_TRANS_UID, WebSvcStatusing.AssnHistoryItemType.SingleTransaction);
                    WebSvcStatusing.AssnHistoryDataSet.HistoryRow[] historyRows = (WebSvcStatusing.AssnHistoryDataSet.HistoryRow[])statusingDs4.Tables[0].Select("ASSN_TRANS_UID = '" + statusingRow[0].ASSN_TRANS_UID + "'");

                    foreach (WebSvcStatusing.AssnHistoryDataSet.HistoryRow row in historyRows)
                    {
                        if ((int)row.ASSN_TRANS_COMMENT_TYPE_ENUM == 1 || (int)row.ASSN_TRANS_COMMENT_TYPE_ENUM == 2) //1=Accepted, 2=Rejected
                        {
                            thenotes = row.ASSN_TRANS_COMMENT.ToString();

                            string publishSiteUrl = RetrieveWebURL(projectid.ToString(), contextInfo.SiteGuid);

                            SPSite mySite = new SPSite(contextInfo.SiteGuid);

                            int indSlash = publishSiteUrl.IndexOf("/", 9);
                            publishSiteUrl = publishSiteUrl.Substring(indSlash);

                            SPWeb myWeb = mySite.OpenWeb(publishSiteUrl);
                            //Impersonate the Project Manager
                            SPUser user = myWeb.AllUsers[getResourceUsername(mySite.Url, getProjectOwner(mySite.Url, projectid))];

                            SPUserToken token = user.UserToken;
                            //reopen the web with the new user credentials
                            mySite = new SPSite(mySite.ID, token);

                            myWeb = mySite.OpenWeb(publishSiteUrl);

                            myWeb.AllowUnsafeUpdates = true;
                            SPList  taskList    = myWeb.Lists["Task Center"];
                            SPQuery queryFilter = new SPQuery();

                            queryFilter.Query = "<Where><Eq><FieldRef Name='taskuid'/><Value Type='Text'><![CDATA[" + taskid + "." + assnid.ToString() + "]]></Value></Eq></Where>";

                            Guid CommentsFieldId = taskList.Fields.GetFieldByInternalName("Publisher_x0020_Approval_x0020_C").Id;
                            Guid StatusFieldId   = taskList.Fields.GetFieldByInternalName("Publisher_x0020_Approval_x0020_S").Id;

                            foreach (SPListItem item in taskList.GetItems(queryFilter))
                            {
                                item[CommentsFieldId] = thenotes;
                                item[StatusFieldId]   = acceptdecline;
                                item.Update();
                            }

                            myWeb.Close();
                            mySite.Close();
                        }
                    }
                }
            }
            catch (System.Web.Services.Protocols.SoapException ex1)
            {
                string logEntry = "Soap Error: " + ex1.Message + ex1.Detail;
                ErrorTrap(3001, logEntry);
            }
            catch (Exception ex)
            {
                string logEntry = "Error: " + ex.Message + ex.StackTrace;
                ErrorTrap(3000, logEntry);
            }
        }
Esempio n. 3
0
        private void InsertRowIntoPublisherCheck(Guid projectGuid)
        {
            // prepare command string
            string insertString = @"INSERT INTO [PUBLISHERCHECK] 
                ([projectguid]
                           ,[webguid]                           
                           ,[checkbit]
                           ,[weburl])
                     VALUES
                           (@projectguid,
                            @webguid,  
                            @checkbit,                        
                            @weburl)";

            SPSecurity.RunWithElevatedPrivileges(
                delegate()
            {
                // Get Site ID
                SPSite site = null;
                Guid siteID;
                try
                {
                    site   = new SPSite(ViewState["siteURL"].ToString());
                    siteID = site.ID;
                }
                finally
                {
                    if (site != null)
                    {
                        site.Close();
                    }
                }

                // Instantiate the connection
                SqlConnection conn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(SPContext.Current.Site.WebApplication.Id));

                try
                {
                    // Open the connection
                    conn.Open();

                    // Instantiate a new command with a query and connection
                    SqlCommand cmd = new SqlCommand(insertString, conn);

                    // Add Parameters
                    cmd.Parameters.Add("@projectguid", SqlDbType.UniqueIdentifier, 16);
                    cmd.Parameters.Add("@webguid", SqlDbType.UniqueIdentifier, 16);
                    cmd.Parameters.Add("@weburl", SqlDbType.VarChar, 255);
                    cmd.Parameters.Add("@checkbit", SqlDbType.Bit, 1);

                    // Set Parameter values
                    cmd.Parameters["@projectguid"].Value = projectGuid;
                    cmd.Parameters["@webguid"].Value     = siteID;
                    cmd.Parameters["@weburl"].Value      = SPContext.Current.Web.Url;
                    cmd.Parameters["@checkbit"].Value    = false;

                    // Call ExecuteNonQuery to send command
                    cmd.ExecuteNonQuery();
                }
                finally
                {
                    // Close the connection
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
            });
        }
        public override void RunTask(CancellationToken token)
        {
            try
            {
                SPWebApplicationCollection _webapplication = GetWebApplications();
                foreach (SPWebApplication webApp in _webapplication)
                {
                    SPSite  site  = null;
                    SPWeb   web   = null;
                    DataSet ds    = new DataSet();
                    string  sConn = EPMLiveCore.CoreFunctions.getConnectionString(webApp.Id);
                    if (sConn != "")
                    {
                        using (SqlConnection cn = new SqlConnection(sConn))
                        {
                            try
                            {
                                cn.Open();

                                using (SqlCommand cmd = new SqlCommand("delete from PERSONALIZATIONS where FK in (select ID from NOTIFICATIONS where DATEADD(mm, 1, CreatedAt) < GETDATE())", cn))
                                {
                                    cmd.ExecuteNonQuery();
                                }

                                using (SqlCommand cmd1 = new SqlCommand("delete from NOTIFICATIONS where DATEADD(mm, 1, CreatedAt) < GETDATE()", cn))
                                {
                                    cmd1.ExecuteNonQuery();
                                }

                                using (var cmd2 = new SqlCommand("spNotificationGetQueue", cn))
                                {
                                    cmd2.CommandType = CommandType.StoredProcedure;
                                    cmd2.Parameters.AddWithValue("@servername", System.Environment.MachineName);

                                    using (SqlDataAdapter da = new SqlDataAdapter(cmd2))
                                    {
                                        da.Fill(ds);

                                        Guid siteid    = Guid.Empty;;
                                        int  processed = 0;
                                        foreach (DataRow dr in ds.Tables[0].Rows)
                                        {
                                            try
                                            {
                                                Guid newsiteid = new Guid(dr["siteid"].ToString());

                                                if (newsiteid != siteid)
                                                {
                                                    if (site != null)
                                                    {
                                                        web.Close();
                                                        site.Close();
                                                    }
                                                    site = new SPSite(newsiteid);
                                                    web  = site.OpenWeb();
                                                }

                                                string body    = dr["Message"].ToString();
                                                string subject = dr["Title"].ToString();

                                                SPUser fromUser = web.SiteUsers.GetByID(int.Parse(dr["createdby"].ToString()));
                                                SPUser toUser   = web.SiteUsers.GetByID(int.Parse(dr["userid"].ToString()));

                                                if (toUser.Email != "")
                                                {
                                                    if (dr["createdby"].ToString() == "1073741823")
                                                    {
                                                        EmailSystem.SendFullEmail(body, subject, true, fromUser, toUser);
                                                    }
                                                    else
                                                    {
                                                        EmailSystem.SendFullEmail(body, subject, false, fromUser, toUser);
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                logMessage("ERR", "NOTIFICATIONS", ex.Message);
                                            }

                                            using (SqlCommand cmd3 = new SqlCommand("spNSetBit", cn))
                                            {
                                                cmd3.CommandType = CommandType.StoredProcedure;
                                                cmd3.Parameters.AddWithValue("@FK", dr["FK"].ToString());
                                                cmd3.Parameters.AddWithValue("@userid", dr["userid"].ToString());
                                                cmd3.Parameters.AddWithValue("@index", 1);
                                                cmd3.Parameters.AddWithValue("@val", 1);
                                                cmd3.ExecuteNonQuery();
                                            }
                                            processed++;
                                            token.ThrowIfCancellationRequested();
                                        }
                                        if (processed > 0)
                                        {
                                            logMessage("HTBT", "PRCS", "Processed " + processed + " jobs");
                                        }
                                    }
                                }
                            }
                            catch (Exception ex) when(!(ex is OperationCanceledException))
                            {
                                logMessage("ERR", "RUNT", ex.Message);
                            }
                            finally
                            {
                                if (site != null)
                                {
                                    web.Close();
                                    site.Close();
                                }
                                ds.Dispose();
                            }
                        }
                    }
                }
            }
            catch (Exception ex) when(!(ex is OperationCanceledException))
            {
                logMessage("ERR", "RUNT", ex.Message);
            }
        }
        /// <summary>
        /// Fixes the pages page layout url so that it points to the page layout in the container site collections master page gallery.
        /// </summary>
        /// <param name="publishingWeb">The target publishing web.</param>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="pageLayoutUrl">The page layout URL.</param>
        /// <param name="searchRegex">The search regex.</param>
        /// <param name="replaceString">The replace string.</param>
        /// <param name="fixContact">if set to <c>true</c> [fix contact].</param>
        /// <param name="test">if set to <c>true</c> [test].</param>
        public static void FixPages(PublishingWeb publishingWeb, string pageName, string pageLayoutUrl, Regex searchRegex, string replaceString, bool fixContact, bool test)
        {
            if (!PublishingWeb.IsPublishingWeb(publishingWeb.Web))
            {
                return;
            }

            PublishingPageCollection pages;
            int tryCount = 0;

            while (true)
            {
                try
                {
                    tryCount++;
                    pages = publishingWeb.GetPublishingPages();
                    break;
                }
                catch (InvalidPublishingWebException)
                {
                    // The following is meant to deal with a timing issue when using this method in conjuction with other commands.  When
                    // used independently this should be unnecessary.
                    if (tryCount > 4)
                    {
                        throw;
                    }
                    Thread.Sleep(10000);
                    SPWeb  web  = publishingWeb.Web;
                    SPSite site = web.Site;
                    string url  = site.MakeFullUrl(web.ServerRelativeUrl);
                    site.Close();
                    site.Dispose();
                    web.Close();
                    web.Dispose();
                    publishingWeb.Close();
                    site          = new SPSite(url);
                    web           = site.OpenWeb(Utilities.GetServerRelUrlFromFullUrl(url));
                    publishingWeb = PublishingWeb.GetPublishingWeb(web);
                }
            }

            foreach (PublishingPage page in pages)
            {
                if (!(string.IsNullOrEmpty(pageName) || page.Name.ToLower() == pageName.ToLower()))
                {
                    continue;
                }

                if (page.ListItem[FieldId.PageLayout] == null)
                {
                    continue;
                }

                Logger.Write("Progress: Begin processing {0}.", page.Url);
                Logger.Write("Progress: Current layout set to {0}.", page.ListItem[FieldId.PageLayout].ToString());

                // Can't edit items that are checked out.
                if (Utilities.IsCheckedOut(page.ListItem) && !Utilities.IsCheckedOutByCurrentUser(page.ListItem))
                {
                    Logger.WriteWarning("WARNING: Page is already checked out by another user - skipping.");
                    continue;
                }

                SPFieldUrlValue url;
                if (string.IsNullOrEmpty(pageLayoutUrl))
                {
                    if (searchRegex == null)
                    {
                        if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim()))
                        {
                            Logger.WriteWarning("WARNING: Current page layout is empty - skipping.  Use the 'pagelayout' parameter to set a page layout.");

                            continue;
                        }

                        // We didn't get a layout url passed in or a regular expression so try and fix the existing url
                        url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString());
                        if (string.IsNullOrEmpty(url.Url) ||
                            url.Url.IndexOf("/_catalogs/") < 0)
                        {
                            Logger.WriteWarning("WARNING: Current page layout does not point to a _catalogs folder or is empty - skipping.  Use the 'pagelayout' parameter to set a page layout  Layout Url: {0}", url.ToString());
                            continue;
                        }


                        string newUrl = publishingWeb.Web.Site.ServerRelativeUrl.TrimEnd('/') +
                                        url.Url.Substring(url.Url.IndexOf("/_catalogs/"));

                        string newDesc = publishingWeb.Web.Site.MakeFullUrl(newUrl);

                        if (url.Url.ToLowerInvariant() == newUrl.ToLowerInvariant())
                        {
                            Logger.Write("Progress: Current layout matches new evaluated layout - skipping.");
                            continue;
                        }
                        url.Url         = newUrl;
                        url.Description = newDesc;
                    }
                    else
                    {
                        if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim()))
                        {
                            Logger.Write("Progress: Current page layout is empty - skipping.  Use the pagelayout parameter to set a page layout.");
                        }

                        // A regular expression was passed in so use it to fix the page layout url if we find a match.
                        if (searchRegex.IsMatch((string)page.ListItem[FieldId.PageLayout]))
                        {
                            url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString());
                            string newUrl = searchRegex.Replace((string)page.ListItem[FieldId.PageLayout], replaceString);
                            if (url.ToString().ToLowerInvariant() == newUrl.ToLowerInvariant())
                            {
                                Logger.Write("Progress: Current layout matches new evaluated layout - skipping.");
                                continue;
                            }
                            url = new SPFieldUrlValue(newUrl);
                        }
                        else
                        {
                            Logger.Write("Progress: Existing page layout url does not match provided regular expression - skipping.");
                            continue;
                        }
                    }
                }
                else
                {
                    // The user passed in an url string so use it.
                    if (pageLayoutUrl.ToLowerInvariant() == (string)page.ListItem[FieldId.PageLayout])
                    {
                        Logger.Write("Progress: Current layout matches provided layout - skipping.");
                        continue;
                    }

                    url = new SPFieldUrlValue(pageLayoutUrl);
                }

                string fileName = url.Url.Substring(url.Url.LastIndexOf('/'));
                // Make sure that the URLs are server relative instead of absolute.
                //if (url.Description.ToLowerInvariant().StartsWith("http"))
                //    url.Description = Utilities.GetServerRelUrlFromFullUrl(url.Description) + fileName;
                //if (url.Url.ToLowerInvariant().StartsWith("http"))
                //    url.Url = Utilities.GetServerRelUrlFromFullUrl(url.Url) + fileName;

                if (page.ListItem[FieldId.PageLayout] != null && url.ToString().ToLowerInvariant() == page.ListItem[FieldId.PageLayout].ToString().ToLowerInvariant())
                {
                    continue; // No difference detected so move on.
                }
                Logger.Write("Progress: Changing layout url from \"{0}\" to \"{1}\"", page.ListItem[FieldId.PageLayout].ToString(), url.ToString());


                if (fixContact)
                {
                    SPUser contact = null;
                    try
                    {
                        contact = page.Contact;
                    }
                    catch (SPException)
                    {
                    }
                    if (contact == null)
                    {
                        Logger.Write("Progress: Page contact ('{0}') does not exist - assigning current user as contact.", page.ListItem[FieldId.Contact].ToString());
                        page.Contact = publishingWeb.Web.CurrentUser;

                        if (!test)
                        {
                            page.ListItem.SystemUpdate();
                        }
                    }
                }

                if (test)
                {
                    continue;
                }

                try
                {
                    bool publish = false;
                    if (!Utilities.IsCheckedOut(page.ListItem))
                    {
                        page.CheckOut();
                        publish = true;
                    }
                    page.ListItem[FieldId.PageLayout] = url;
                    page.ListItem.UpdateOverwriteVersion();

                    if (publish)
                    {
                        Common.Lists.PublishItems itemPublisher = new Common.Lists.PublishItems();
                        itemPublisher.PublishListItem(page.ListItem, page.ListItem.ParentList, false, "Automated fix of publishing pages page layout URL.", null, null);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteException(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, page));
                }
            }
        }
Esempio n. 6
0
        // Get resource manager
        //private ResourceManager rm = new ResourceManager("LearningPortalUtilities.Strings", Assembly.GetExecutingAssembly());

        protected void Page_Load(object sender, System.EventArgs e)
        {
            //            ltlPageTitle.Text = GetLocalResourceObject("X").ToString();
            ltlLBTitle.Text     = GetLocalResourceObject("Title").ToString();
            ltlBegin.Text       = GetLocalResourceObject("Begin").ToString();          // Resources.Strings.Begin;
            ltlEnd.Text         = GetLocalResourceObject("End").ToString();            // Resources.Strings.End;
            ltlDescription.Text = GetLocalResourceObject("Description").ToString();    // Resources.Strings.Description;
            ltlLocation.Text    = GetLocalResourceObject("Location").ToString();       //Resources.Strings.Location;
            ltlCreatedAt.Text   = GetLocalResourceObject("CreatedAt").ToString();      //Resources.Strings.CreatedAt;
            ltlModifiedAt.Text  = GetLocalResourceObject("LastModifiedAt").ToString(); //Resources.Strings.LastModifiedAt;
            //ltlBy1.Text = GetLocalResourceObject ("By").ToString();//Resources.Strings.By;
            //ltlBy2.Text = GetLocalResourceObject ("By").ToString();//Resources.Strings.By;



            HtmlTableRow  rw;
            HtmlTableCell cell;

            string NewsURL;
            int    NewsID;

            NewsURL = Request.QueryString.GetValues("URL")[0];

            // Add the terminating slash if not present
            if (!NewsURL.EndsWith("/"))
            {
                NewsURL += "/";
            }

            NewsID = int.Parse(Request.QueryString.GetValues("ID")[0]);

            // Open the site, and the default web
            SPSite mysite = new SPSite(NewsURL);
            SPWeb  myWeb  = mysite.OpenWeb();

            // Get the view of this list, and from that the reference to the list itself
            SPView view = myWeb.GetViewFromUrl(NewsURL + "allitems.aspx");
            SPList list = myWeb.Lists[view.ParentList.Title];

            ltlListName.Text = list.Title;

            // Get the Item from the list
            SPListItem myItem = list.GetItemById(NewsID);

            ltlTitle.Text     = myItem["ows_Title"].ToString();
            ltlItemTitle.Text = myItem["ows_Title"].ToString();

            // Begin (mandatory)
            ltlItemBegin.Text = ((DateTime)myItem["ows_EventDate"]).ToString();

            // End (not mandatory)
            if (myItem["ows_EndDate"] != null)
            {
                ltlItemEnd.Text = ((DateTime)myItem["ows_EndDate"]).ToString();
            }
            else
            {
                ltlItemEnd.Text = "--";
            }

            // Description (not mandatory)
            if (myItem["ows_Description"] != null)
            {
                ltlItemDescription.Text = myItem["ows_Description"].ToString();
            }
            else
            {
                ltlItemDescription.Text = "--";
            }

            // Location (not mandatory)
            if (myItem["ows_Location"] != null)
            {
                ltlItemLocation.Text = myItem["ows_Location"].ToString();
            }
            else
            {
                ltlItemLocation.Text = "--";
            }

            // Created
            ltlItemCreated.Text = ((DateTime)myItem["ows_Created"]).ToString();
            //ltlItemCreatedBy.Text = myItem["ows_Author"].ToString().Split('#')[1];

            // Modified
            ltlItemLastModified.Text = ((DateTime)myItem["ows_Modified"]).ToString();
            //ltlItemLastModifiedBy.Text = myItem["ows_Editor"].ToString().Split('#')[1];
            try
            {
                //Issue #9 - Sometimes the instant messenger icon doesn't appear
                //myWeb.SiteUsers.GetByID(UserID) is used to get the user object with id = UserID
                int AuthorID = int.Parse(myItem["ows_Author"].ToString().Split('#')[0].Replace(";", ""));
                int EditorID = int.Parse(myItem["ows_Editor"].ToString().Split('#')[0].Replace(";", ""));

                //if (myWeb.SiteUsers.GetByID(AuthorID).Email.Length > 0)
                //    imn0.Attributes.Add("onload", "IMNRC('" + myWeb.SiteUsers.GetByID(AuthorID).Email + "')");
                //if (myWeb.SiteUsers.GetByID(EditorID).Email.Length > 0)
                //    imn1.Attributes.Add("onload", "IMNRC('" + myWeb.SiteUsers.GetByID(EditorID).Email + "')");
            }
            catch
            {
            }
            //Clean up
            myWeb.Close();
            mysite.Close();
        }