private void DoSubsite(SPWeb web) { try { string webServerRelativeUrl = web.ServerRelativeUrl.TrimEnd(new char[] { '/' }); if (webServerRelativeUrl != "" && !webServerRelativeUrl.Contains("QuoteMigration") && !webServerRelativeUrl.Contains("OfferMigration") && !webServerRelativeUrl.Contains("ContractMigration")) { string resultText = "\"" + web.Url + "\""; WriteResult(resultText); } foreach (SPWeb subWeb in web.Webs) { DoSubsite(subWeb); } } catch (Exception ex) { WriteErrorLog("write Url error for web:" + web.Url + ". Exception:" + ex.ToString()); } finally { web.Dispose(); web.Close(); web = null; } }
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; } }
public PanelInfo[] FetchPanelsInformationByUrl(string pageLayoutUrl, string cultureName) { //CommonUtilities.ConfirmNotNullOrEmptyString(pageLayoutUrl, "pageLayoutUrl"); //CommonUtilities.ConfirmNotNull(cultureName, "cultureName"); //ULS.SendTraceTag(0x3670356b, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.Medium, "SharepointPublishingToolboxService.FetchPanelsInformationByUrl({0}, {1})", new object[] { pageLayoutUrl, cultureName }); PanelInfo[] infoArray = null; SPSite site = SPContext.Current.Site; SPUtility.EnsureAuthentication(); Uri uri = new Uri(pageLayoutUrl); string url = ConvertToAbsoluteUrl(uri.PathAndQuery, site); SPWeb web = null; try { web = site.OpenWeb(); SPFile fileFromUrl = GetFileFromUrl(url, web); if ((fileFromUrl != null) && fileFromUrl.Exists) { ContentTypeIdFieldValue value2; SPListItem item = fileFromUrl.Item; SPContentTypeCollection contentTypes = this.GetContentTypes(); try { value2 = (ContentTypeIdFieldValue)item[BuildFieldId.PublishingAssociatedContentType]; } catch (ArgumentException) { SPContentType contentType = item.ContentType; while ((contentTypes[contentType.Id] == null) && (contentType.Parent != null)) { contentType = contentType.Parent; } value2 = new ContentTypeIdFieldValue(contentType); } string contentTypeId = value2.Id.ToString(); SPContentType type2 = this.GetContentTypes()[value2.Id]; if ((type2 == null) || !type2.Id.IsChildOf(ContentTypeId.PageTemplate)) { CultureInfo culture = new CultureInfo(cultureName); // throw new SoapException(Resources.GetFormattedStringEx("ErrorInvalidAssociatedContentTypeId", culture, new object[] { contentTypeId, value2.StoredName, pageLayoutUrl }), SoapException.ServerFaultCode); } infoArray = this.FetchPanelsInformation(contentTypeId, cultureName); } } finally { if (web != null) { web.Close(); } } //ULS.SendTraceTag(0x3670356c, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.Medium, "SharepointPublishingToolboxService.FetchPanelsInformationByUrl ends"); return(infoArray); }
/// <summary> /// Run find&replace process on root of the specified site (or site collection) /// </summary> /// <param name="sharePointSiteURL"></param> public void FindReplace(string sharePointSiteURL) { SPSite site = null; SPWeb web = null; m_IsCanceled = false; m_IsCanceling = false; try { site = new SPSite(sharePointSiteURL); web = site.OpenWeb(); web.AllowUnsafeUpdates = true; if (web.WebTemplate == "SPS") { if (m_Parameters.IncludeSubSites) { SPGlobalAdmin gAdm = new SPGlobalAdmin(); SPVirtualServer vSrv = gAdm.OpenVirtualServer(new Uri(sharePointSiteURL)); foreach (SPSite Site in vSrv.Sites) { web = Site.OpenWeb(); FindReplaceWebs(web); } } else { FindReplaceWebs(web); } } else { FindReplaceWebs(web); } } catch (Exception ex) { OnError(ex, "FindReplaceComponent.FindReplace"); } finally { if (web != null) { web.Close(); web.Dispose(); web = null; } } }
private static void DeleteAllWebParts(string destinationPageUrlServerRelative, SPWeb destinationPageWeb, string sourcePageUrlServerRelative, SPWeb sourcePageWeb, bool shouldOverwriteDestinationWebParts) { SPWeb web = null; SPWeb web2 = null; try { SPLimitedWebPartManager limitedWebPartManager = destinationPageWeb.GetLimitedWebPartManager(destinationPageUrlServerRelative, PersonalizationScope.Shared); SPLimitedWebPartManager manager2 = sourcePageWeb.GetLimitedWebPartManager(sourcePageUrlServerRelative, PersonalizationScope.Shared); web2 = limitedWebPartManager.Web; web = manager2.Web; SPLimitedWebPartCollection webParts = manager2.WebParts; SPLimitedWebPartCollection parts2 = limitedWebPartManager.WebParts; if (shouldOverwriteDestinationWebParts && (parts2 != null)) { while (parts2.Count > 0) { try { limitedWebPartManager.DeleteWebPart(parts2[0]); continue; } catch (WebPartPageUserException) { } } } } catch (Exception e) { if (HttpContext.Current != null) { throw; } } finally { if ((web != sourcePageWeb) && (web != null)) { web.Close(); } if ((web2 != destinationPageWeb) && (web2 != null)) { web2.Close(); } } }
private static ArrayList BreadCrumbLinks(SPWeb current) { ArrayList Links = new ArrayList(); SPWeb web = current; try { Links.Add(String.Format("<a href=\"{0}\">{1}</a>", current.Url, current.Title)); while (!web.IsRootWeb) { Links.Add(String.Format("<a href=\"{0}\">{1}</a>", web.Url, web.Title)); web = web.ParentWeb; } Links.Add(String.Format("<a href=\"{0}\">{1}</a>", web.Url, web.Title)); } catch { } finally { web.Close(); } return(Links); }
/*********************************************** * Procedure: protected void Page_Load() * Purpose: Create header of xml file * Parameters In: object sender, EventArgs e * Parameters Out: void ***********************************************/ protected void Page_Load(object sender, EventArgs e) { using (SPSite site = SPContext.Current.Site) { using (SPWeb web = site.RootWeb) { try { if (Request["maxlistsyncdate"] != null) { sMaxListSyncDate = Request["maxlistsyncdate"]; } if (Request["ttype"] != null && Request["ttype"].ToString() == "tmpltcolonly") { EPMLiveSiteTemplateIDs = web.Properties["EPMLiveSiteTemplateIDs"]; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Expires = -1; Response.ContentType = "text/xml"; Response.ContentEncoding = System.Text.Encoding.UTF8; web.Site.CatchAccessDeniedException = false; doc.LoadXml("<rows></rows>"); XmlNode mainNode = doc.ChildNodes[0]; XmlNode headNode = doc.CreateNode(XmlNodeType.Element, "head", doc.NamespaceURI); mainNode.AppendChild(headNode); XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "tree"; XmlAttribute attrWidth = doc.CreateAttribute("width"); attrWidth.Value = "598"; XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNode.Attributes.Append(attrType); newNode.Attributes.Append(attrWidth); newNode.InnerText = "Sites"; headNode.AppendChild(newNode); try { addSynchedTemplatesColumn(web, mainNode); } catch { } data = doc.OuterXml; } else if (Request["ttype"] != null && Request["ttype"].ToString() == "non") { EPMLiveSiteTemplateIDs = web.Properties["EPMLiveSiteTemplateIDs"]; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Expires = -1; Response.ContentType = "text/xml"; Response.ContentEncoding = System.Text.Encoding.UTF8; web.Site.CatchAccessDeniedException = false; doc.LoadXml("<rows></rows>"); XmlNode mainNode = doc.ChildNodes[0]; XmlNode headNode = doc.CreateNode(XmlNodeType.Element, "head", doc.NamespaceURI); mainNode.AppendChild(headNode); XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "tree"; XmlAttribute attrWidth = doc.CreateAttribute("width"); attrWidth.Value = "298"; XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNode.Attributes.Append(attrType); newNode.Attributes.Append(attrWidth); newNode.InnerText = "Sites"; headNode.AppendChild(newNode); try { addNonSynchedTemplates(web, mainNode); } catch { } data = doc.OuterXml; } else { EPMLiveSiteTemplateIDs = web.Properties["EPMLiveSiteTemplateIDs"]; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Expires = -1; Response.ContentType = "text/xml"; Response.ContentEncoding = System.Text.Encoding.UTF8; web.Site.CatchAccessDeniedException = false; doc.LoadXml("<rows></rows>"); XmlNode mainNode = doc.ChildNodes[0]; XmlNode headNode = doc.CreateNode(XmlNodeType.Element, "head", doc.NamespaceURI); XmlNode ndSettings = doc.CreateNode(XmlNodeType.Element, "settings", doc.NamespaceURI); XmlNode ndColwith = doc.CreateNode(XmlNodeType.Element, "colwidth", doc.NamespaceURI); ndColwith.InnerText = "%"; ndSettings.AppendChild(ndColwith); headNode.AppendChild(ndSettings); mainNode.AppendChild(headNode); XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "tree"; XmlAttribute attrWidth = doc.CreateAttribute("width"); attrWidth.Value = "25"; XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNode.Attributes.Append(attrType); newNode.Attributes.Append(attrWidth); newNode.InnerText = "Sites"; headNode.AppendChild(newNode); XmlAttribute attrTypeEdit = doc.CreateAttribute("type"); attrTypeEdit.Value = "ro"; XmlAttribute attrWidthEdit = doc.CreateAttribute("width"); attrWidthEdit.Value = "12"; XmlAttribute attrEditTemplateAlign = doc.CreateAttribute("align"); attrEditTemplateAlign.Value = "center"; XmlNode newNodeEdit = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNodeEdit.Attributes.Append(attrTypeEdit); newNodeEdit.Attributes.Append(attrWidthEdit); newNodeEdit.Attributes.Append(attrEditTemplateAlign); newNodeEdit.InnerText = "Edit"; headNode.AppendChild(newNodeEdit); XmlAttribute attrTypeSave = doc.CreateAttribute("type"); attrTypeSave.Value = "ro"; XmlAttribute attrWidthSave = doc.CreateAttribute("width"); attrWidthSave.Value = "12"; XmlAttribute attrSaveTemplateAlign = doc.CreateAttribute("align"); attrSaveTemplateAlign.Value = "center"; XmlNode newNodeSave = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNodeSave.Attributes.Append(attrTypeSave); newNodeSave.Attributes.Append(attrWidthSave); newNodeSave.Attributes.Append(attrSaveTemplateAlign); newNodeSave.InnerText = "Save"; headNode.AppendChild(newNodeSave); XmlAttribute attrTypeRename = doc.CreateAttribute("type"); attrTypeRename.Value = "ro"; XmlAttribute attrWidthRename = doc.CreateAttribute("width"); attrWidthRename.Value = "12"; XmlAttribute attrRenameTemplateAlign = doc.CreateAttribute("align"); attrRenameTemplateAlign.Value = "center"; XmlNode newNodeRename = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNodeRename.Attributes.Append(attrTypeRename); newNodeRename.Attributes.Append(attrWidthRename); newNodeRename.Attributes.Append(attrRenameTemplateAlign); newNodeRename.InnerText = "Rename"; headNode.AppendChild(newNodeRename); XmlAttribute attrTypeDelete = doc.CreateAttribute("type"); attrTypeDelete.Value = "ro"; XmlAttribute attrWidthDelete = doc.CreateAttribute("width"); attrWidthDelete.Value = "12"; XmlAttribute attrRemoveTemplateAlign = doc.CreateAttribute("align"); attrRemoveTemplateAlign.Value = "center"; XmlNode newNodeDelete = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNodeDelete.Attributes.Append(attrTypeDelete); newNodeDelete.Attributes.Append(attrWidthDelete); newNodeDelete.Attributes.Append(attrRemoveTemplateAlign); newNodeDelete.InnerText = "Remove"; headNode.AppendChild(newNodeDelete); //XmlAttribute attrTypeSync = doc.CreateAttribute("type"); //attrTypeSync.Value = "ro"; //XmlAttribute attrWidthSync = doc.CreateAttribute("width"); //attrWidthSync.Value = "7"; //XmlAttribute attrLastSaveTemplateAlign = doc.CreateAttribute("align"); //attrLastSaveTemplateAlign.Value = "center"; //XmlNode newNodeSync = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); //newNodeSync.Attributes.Append(attrTypeSync); //newNodeSync.Attributes.Append(attrWidthSync); //newNodeSync.Attributes.Append(attrLastSaveTemplateAlign); //newNodeSync.InnerText = "Synchronize"; //headNode.AppendChild(newNodeSync); XmlAttribute attrTypeSaveStatus = doc.CreateAttribute("type"); attrTypeSaveStatus.Value = "ro"; XmlAttribute attrWidthSaveStatus = doc.CreateAttribute("width"); attrWidthSaveStatus.Value = "12"; XmlNode newNodeSaveStatus = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNodeSaveStatus.Attributes.Append(attrTypeSaveStatus); newNodeSaveStatus.Attributes.Append(attrWidthSaveStatus); newNodeSaveStatus.InnerText = "Save Status"; headNode.AppendChild(newNodeSaveStatus); XmlAttribute attrTypeLastSave = doc.CreateAttribute("type"); attrTypeLastSave.Value = "ro"; XmlAttribute attrWidthLastSave = doc.CreateAttribute("width"); attrWidthLastSave.Value = "15"; XmlNode newNodeLastSave = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); newNodeLastSave.Attributes.Append(attrTypeLastSave); newNodeLastSave.Attributes.Append(attrWidthLastSave); newNodeLastSave.InnerText = "Last Saved"; headNode.AppendChild(newNodeLastSave); //XmlAttribute attrTypeSyncStatus = doc.CreateAttribute("type"); //attrTypeSyncStatus.Value = "ro"; //XmlAttribute attrWidthSyncStatus = doc.CreateAttribute("width"); //attrWidthSyncStatus.Value = "5"; //XmlNode newNodeSyncStatus = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); //newNodeSyncStatus.Attributes.Append(attrTypeSyncStatus); //newNodeSyncStatus.Attributes.Append(attrWidthSyncStatus); //newNodeSyncStatus.InnerText = "Sync Status"; //headNode.AppendChild(newNodeSyncStatus); //XmlAttribute attrTypeResults = doc.CreateAttribute("type"); //attrTypeResults.Value = "ro"; //XmlAttribute attrWidthResults = doc.CreateAttribute("width"); //attrWidthResults.Value = "20"; //XmlNode newNodeResults = doc.CreateNode(XmlNodeType.Element, "column", doc.NamespaceURI); //newNodeResults.Attributes.Append(attrTypeResults); //newNodeResults.Attributes.Append(attrWidthResults); //newNodeResults.InnerText = "Sync Results"; //headNode.AppendChild(newNodeResults); try { addWebs(web, mainNode); } catch { } data = doc.OuterXml; } } catch (Exception exc) { data = exc.Message; } finally { GC.Collect(); web.Close(); } } } }
static internal void processResources(SqlConnection cn, string tsuid, SPWeb web, string username) { string rate = GetStandardRates(cn, tsuid, web, username); SqlCommand cmd = new SqlCommand("DELETE FROM TSRESMETA where TS_UID = @TS_UID", cn); cmd.Parameters.AddWithValue("@TS_UID", tsuid); cmd.ExecuteNonQuery(); string resUrl = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL", true, false); if (resUrl != "") { try { SPSecurity.RunWithElevatedPrivileges(delegate() { SPWeb resWeb = null; using (SPSite tempSite = new SPSite(resUrl)) { resWeb = tempSite.OpenWeb(); if (resWeb != null) { SPList list = resWeb.Lists["Resources"]; string[] fields = EPMLiveCore.CoreFunctions.getConfigSetting(web.Site.RootWeb, "EPMLiveTSFields-" + System.IO.Path.GetDirectoryName(list.DefaultView.Url)).Split(','); SPUser user = web.AllUsers[username]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name=\"SharePointAccount\" /><Value Type=\"User\">" + user.Name + "</Value></Eq></Where>"; SPListItem li = list.GetItems(query)[0]; foreach (string field in fields) { SPField f = null; string val = ""; try { f = list.Fields.GetFieldByInternalName(field); if (field.ToLower() == "standardrate") { if (!string.IsNullOrEmpty(rate)) { val = rate; } else { val = f.GetFieldValueAsText(li[f.Id]); } } else { val = f.GetFieldValueAsText(li[f.Id]); } } catch { } if (f != null) { cmd = new SqlCommand("INSERT INTO TSRESMETA (TS_UID,UserName,ColumnName,DisplayName,ColumnValue) VALUES (@TS_UID,@username,@ColumnName,@DisplayName,@ColumnValue)", cn); cmd.Parameters.AddWithValue("@TS_UID", tsuid); cmd.Parameters.AddWithValue("@ColumnName", field); cmd.Parameters.AddWithValue("@UserName", username); cmd.Parameters.AddWithValue("@DisplayName", f.Title); cmd.Parameters.AddWithValue("@ColumnValue", val); cmd.ExecuteNonQuery(); } } if (SPContext.Current != null && resWeb.ID != SPContext.Current.Web.ID) { resWeb.Close(); } } } }); } catch { } } }
public void RemoveTemplate(string sTemplate) { SPWeb web = null; try { using (SPSite site = SPContext.Current.Site) { web = site.AllWebs[sTemplate]; } } catch (Exception ex) { } if (web != null) { string sWebId = web.ID.ToString(); using (SPWeb rootWeb = SPContext.Current.Site.RootWeb) { if (rootWeb.Properties.ContainsKey("EPMLiveSiteTemplateIDs")) { string sIDs = rootWeb.Properties["EPMLiveSiteTemplateIDs"]; rootWeb.AllowUnsafeUpdates = true; if (sIDs.Contains(sWebId)) { int iPipeLocation = sIDs.IndexOf("|" + sWebId); if (iPipeLocation > 0 && iPipeLocation < (sIDs.Length - (sWebId.Length))) // has more { sIDs = sIDs.Replace("|" + sWebId, ""); } else { sIDs = ""; } rootWeb.Properties["EPMLiveSiteTemplateIDs"] = sIDs; rootWeb.Properties.Update(); //SPFeature oFT = null; //try //{ // oFT = web.Features[new Guid("dfb82bdd-a86c-4314-a0f2-654526c7814e")]; //} //catch { } //if (oFT == null) //{ // try // { // web.Features.Remove(new Guid("dfb82bdd-a86c-4314-a0f2-654526c7814e")); // } // catch { } //} } LogHelper logHlpr = new LogHelper(); logHlpr.Action = "synchtemplate"; logHlpr.Source = web.ServerRelativeUrl; string sLastResults = logHlpr.DeleteLastResult(); rootWeb.Properties.Update(); rootWeb.AllowUnsafeUpdates = false; } } if (web.Properties.ContainsKey("EPMLiveTemplateID")) { web.AllowUnsafeUpdates = true; web.Properties.Remove("EPMLiveTemplateID"); web.Properties.Update(); web.AllowUnsafeUpdates = false; } web.Close(); web.Dispose(); } }
private static void Process(string requestUrl, bool ContentApproval, bool Versioning, bool IsRecursive) { SPSite rootsite = null; SPWeb rootweb = null; try { Uri rootweburi = new Uri(requestUrl); if (SPSite.Exists(rootweburi)) // Check if Site is there { // Open Site using (rootsite = new SPSite(requestUrl)) { using (rootweb = rootsite.OpenWeb()) { // Allow unsafe updates rootweb.AllowUnsafeUpdates = true; rootweb.Update(); // Process settings of the document libraries HandleDocumentLibrary(rootweb, ContentApproval, Versioning); // disable unsafe updates rootweb.AllowUnsafeUpdates = false; rootweb.Update(); if (IsRecursive) // Check if recurve was defined { // Loop though each sub-site and handle versioning & content approval settings for (int i = 0; i <= rootweb.Webs.Count; i++) { using (SPWeb subweb = rootweb.Webs[i]) { HandleDocumentLibrary(subweb, ContentApproval, Versioning); } } } } } } else { Console.WriteLine(string.Format("Web Application at {0} was not found, please check the \"URL\" argument and try again.", requestUrl)); } } catch (SPException spex) { Console.WriteLine(spex.ToString()); Console.WriteLine(Environment.NewLine); Console.WriteLine("Push any key to continue"); Console.ReadLine(); } finally { // If somethign went south and rootweb is not null, dispose of it correctly if (rootweb != null) { rootweb.Close(); rootweb.Dispose(); } // If something went south and rootsite is not null, dispose of it correctly if (rootsite != null) { rootsite.Close(); rootsite.Dispose(); } } }
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); } }
protected void Page_Load(object sender, EventArgs e) { SqlConnection cn = null; SPSecurity.RunWithElevatedPrivileges(delegate() { cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(SPContext.Current.Site.WebApplication.Id)); cn.Open(); }); if (cn != null) { SPWeb web = SPContext.Current.Web; string resUrl = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL", true, false); if (resUrl != "") { SPWeb resWeb = null; try { if (resUrl.ToLower() != web.Url.ToLower()) { using (SPSite tempSite = new SPSite(resUrl)) { resWeb = tempSite.OpenWeb(); if (resWeb.Url.ToLower() != resUrl.ToLower()) { resWeb = null; } } } else { resWeb = web; } } catch { } if (resWeb != null) { switch (Request["Report"]) { case "1": try { SPList list = resWeb.Lists["Resources"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='TimesheetManager'/><Value Type='User'><UserID/></Value></Eq></Where>"; SPListItemCollection lic = list.GetItems(query); foreach (SPListItem li in lic) { string username = ""; string name = ""; try { string user = li["SharePointAccount"].ToString(); SPFieldUserValue uv = new SPFieldUserValue(resWeb, user); username = uv.User.LoginName; name = uv.User.Name; } catch { } if (username != "") { SqlCommand cmd = new SqlCommand("spTSData", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@siteuid", web.Site.ID); cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@start", Request["start"]); cmd.Parameters.AddWithValue("@end", Request["end"]); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dttemp = new DataTable(); da.Fill(dttemp); dtRollup.Merge(dttemp, false, MissingSchemaAction.Add); } } } catch { } break; case "2": try { SPList list = resWeb.Lists["Resources"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='SharePointAccount'/><Value Type='User'><UserID/></Value></Eq></Where>"; SPListItemCollection lic = list.GetItems(query); if (lic.Count > 0) { try { if (lic[0]["TimesheetAdministrator"].ToString().ToLower() == "true") { foreach (SPListItem li in list.Items) { string username = ""; string name = ""; try { string user = li["SharePointAccount"].ToString(); SPFieldUserValue uv = new SPFieldUserValue(resWeb, user); username = uv.User.LoginName; name = uv.User.Name; } catch { } if (username != "") { SqlCommand cmd = new SqlCommand("spTSData", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@siteuid", web.Site.ID); cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@start", Request["start"]); cmd.Parameters.AddWithValue("@end", Request["end"]); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dttemp = new DataTable(); da.Fill(dttemp); dtRollup.Merge(dttemp, false, MissingSchemaAction.Add); } } } } catch { } } } catch { } break; case "3": try { SPList list = resWeb.Lists["Resources"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='SharePointAccount'/><Value Type='User'><UserID/></Value></Eq></Where>"; SPListItemCollection lic = list.GetItems(query); if (lic.Count > 0) { try { foreach (SPListItem li in lic) { string username = ""; string name = ""; try { string user = li["SharePointAccount"].ToString(); SPFieldUserValue uv = new SPFieldUserValue(resWeb, user); username = uv.User.LoginName; name = uv.User.Name; } catch { } if (username != "") { SqlCommand cmd = new SqlCommand("spTSData", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@siteuid", web.Site.ID); cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@start", Request["start"]); cmd.Parameters.AddWithValue("@end", Request["end"]); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dttemp = new DataTable(); da.Fill(dttemp); dtRollup.Merge(dttemp, false, MissingSchemaAction.Add); } } } catch { } } } catch { } break; } ; if (resWeb.ID != SPContext.Current.Web.ID) { resWeb.Close(); } } } cn.Close(); listGrid.DataSource = dtRollup; listGrid.DataBind(); } }
/// <summary> /// Restores site collection under given url from backup. /// </summary> /// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="siteCollection">Site collection to be restored.</param> /// <param name="filename">Backup file name to restore from.</param> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception> public void RestoreSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection, string filename) { string url = siteCollection.Url; try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); try { SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri); string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); string tempPath = Path.GetTempPath(); // Unzip uploaded files if required. string expandedFile = filename; if (Path.GetExtension(filename).ToLower() == ".zip") { // Unpack file. expandedFile = FileUtils.UnzipFiles(filename, tempPath)[0]; // Delete zip archive. FileUtils.DeleteFile(filename); } // Delete existent site and restore new one. rootWebApplication.Sites.Delete(siteCollectionUrl, false); rootWebApplication.Sites.Restore(siteCollectionUrl, expandedFile, true, true); SPSite restoredSite = rootWebApplication.Sites[siteCollectionUrl]; SPWeb web = restoredSite.OpenWeb(); SPUser owner = null; try { owner = web.SiteUsers[siteCollection.OwnerLogin]; } catch { // Ignore this error. } if (owner == null) { web.SiteUsers.Add(siteCollection.OwnerLogin, siteCollection.OwnerEmail, siteCollection.OwnerName, String.Empty); owner = web.SiteUsers[siteCollection.OwnerLogin]; } restoredSite.Owner = owner; web.Close(); rootWebApplication.Update(); // Delete expanded file. FileUtils.DeleteFile(expandedFile); } finally { wic.Undo(); } } catch (Exception ex) { throw new InvalidOperationException("Failed to restore site collection.", ex); } }
protected override void RenderWebPart(HtmlTextWriter output) { output.Write(error); if (activation != 0) { output.Write(act.translateStatus(activation)); return; } output.Write("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\">"); SPWeb web = SPContext.Current.Web; string resUrl = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL", true, false); if (resUrl != "") { SPWeb resWeb = null; try { if (resUrl.ToLower() != web.Url.ToLower()) { using (SPSite tempSite = new SPSite(resUrl)) { resWeb = tempSite.OpenWeb(); if (resWeb.Url.ToLower() != resUrl.ToLower()) { resWeb = null; } } } else { resWeb = web; } } catch { } if (resWeb != null) { try { SPList list = resWeb.Lists["Resources"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='TimesheetManager'/><Value Type='User'><UserID/></Value></Eq></Where>"; SPListItemCollection lic = list.GetItems(query); bool hasReports = false; if (lic.Count > 0) { hasReports = true; output.Write("<tr><td><img src=\"/_layouts/images/XLS16.GIF\"></td><td><a href=\"#\" onclick=\"window.open('" + web.Url + "/_layouts/epmlive/gettsreport.aspx?report=1','', config='height=270,width=340, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, directories=no, status=no');\">Timesheet Manager Report</a></td></tr>"); } query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='SharePointAccount'/><Value Type='User'><UserID/></Value></Eq></Where>"; lic = list.GetItems(query); if (lic.Count > 0) { try { if (lic[0]["TimesheetAdministrator"].ToString().ToLower() == "true") { hasReports = true; output.Write("<tr><td><img src=\"/_layouts/images/XLS16.GIF\"></td><td><a href=\"#\" onclick=\"window.open('" + web.Url + "/_layouts/epmlive/gettsreport.aspx?report=2','', config='height=270,width=340, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, directories=no, status=no');\">Administrative Report</a></td></tr>"); } } catch { } } query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='SharePointAccount'/><Value Type='User'><UserID/></Value></Eq></Where>"; lic = list.GetItems(query); if (lic.Count > 0) { try { hasReports = true; output.Write("<tr><td><img src=\"/_layouts/images/XLS16.GIF\"></td><td><a href=\"#\" onclick=\"window.open('" + web.Url + "/_layouts/epmlive/gettsreport.aspx?report=3','', config='height=270,width=340, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, directories=no, status=no');\">My Timesheet Report</a></td></tr>"); } catch { } } if (!hasReports) { output.Write("<tr><td>No Available Reports.</td></tr>"); } } catch (Exception ex1) { output.Write("<tr><td>Error: + " + ex1.Message + "</td></tr>"); } if (resWeb.ID != SPContext.Current.Web.ID) { resWeb.Close(); } } else { output.Write("<tr><td>Failed to open Resource Pool.</td></tr>"); } } else { output.Write("<tr><td>Resource Pool Not Configured.</td></tr>"); } output.Write("</table>"); }
public static string processActualWork(SqlConnection cn, string tsuid, SPSite site, bool bApprovalScreen, bool bApproved) { string error = ""; //SPSecurity.RunWithElevatedPrivileges(delegate() //{ //using (SPSite site = new SPSite(s.ID, s.SystemAccount.UserToken)) { string sql = "SELECT * FROM vwTSItemHoursByTS where ts_uid=@ts_uid order by web_uid,list_uid"; //if(!bApprovalScreen) // sql = "SELECT * FROM vwTSItemHoursByMyTS where ts_uid=@ts_uid order by web_uid,list_uid"; //SqlCommand cmd = new SqlCommand("spTSGetProjectsHours", cn); //cmd.Parameters.AddWithValue("@TSUID", tsuid); //cmd.Parameters.AddWithValue("@approved", bApproved); //cmd.CommandType = CommandType.StoredProcedure; //DataSet dsProjects = new DataSet(); //SqlDataAdapter da = new SqlDataAdapter(cmd); //da.Fill(dsProjects); SqlCommand cmd = new SqlCommand(sql, cn); cmd.Parameters.AddWithValue("@TS_UID", tsuid); SqlDataReader dr = cmd.ExecuteReader(); Guid webGuid = new Guid(); Guid listGuid = new Guid(); SPWeb iWeb = null; SPList iList = null; while (dr.Read()) { try { Guid wGuid = new Guid(dr["WEB_UID"].ToString()); Guid lGuid = new Guid(dr["LIST_UID"].ToString()); if (webGuid != wGuid) { try { if (iWeb != null) { iWeb.Close(); iWeb = site.OpenWeb(wGuid); } else { iWeb = site.OpenWeb(wGuid); } webGuid = iWeb.ID; } catch { } } if (iWeb != null) { if (listGuid != lGuid) { iList = iWeb.Lists[lGuid]; listGuid = iList.ID; } iWeb.AllowUnsafeUpdates = true; SPListItem li = null; try { li = iList.GetItemById(int.Parse(dr["ITEM_ID"].ToString())); } catch { } if (li != null) { //If the project server feature is not active and it is in approval mode then process actual work. if (iWeb.Features[new Guid("ebc3f0dc-533c-4c72-8773-2aaf3eac1055")] == null && bApprovalScreen) { SPField f = null; try { f = iList.Fields.GetFieldByInternalName("TimesheetHours"); } catch { } if (f != null) { li[f.Id] = dr["TotalHours"].ToString(); li.Update(); //processProject(dsProjects, wGuid, iWeb); } } else { SPField f = null; try { f = iList.Fields.GetFieldByInternalName("TimesheetHours"); } catch { } if (f != null) { string taskuid = ""; try { taskuid = li["taskuid"].ToString(); } catch { } //if the item has a taskuid (Meaning this item is a Project Task) if (taskuid != "" && taskuid.Contains(".")) { string login = ""; try { SPFieldUserValueCollection uvc = (SPFieldUserValueCollection)li[iList.Fields.GetFieldByInternalName("AssignedTo").Id]; if (uvc.Count > 0) { login = uvc[0].User.LoginName.ToLower(); } } catch { } if (login != "")//if we found a user { if (login == SPContext.Current.Web.CurrentUser.LoginName.ToLower()) { li[f.Id] = dr["SubmittedHours"].ToString(); li.Update(); //processProject(dsProjects, wGuid, iWeb); } } } else if (bApprovalScreen)//otherwise it must be in approval mode { li[f.Id] = dr["TotalHours"].ToString(); li.Update(); //processProject(dsProjects, wGuid, iWeb); } } } } } } catch (Exception exception) { error += "Error: " + exception.Message + "<br>SharePoint User: "******"<br><br><br>"; } } dr.Close(); } //});\ return(error + processProjectWork(cn, tsuid, site, bApprovalScreen, bApprovalScreen)); }
private void ProcessDataRow(SortedList arrGTemp, SPWeb curWeb, DataSet dataSet, bool newTimeSheet) { Guard.ArgumentIsNotNull(dataSet, nameof(dataSet)); Guard.ArgumentIsNotNull(curWeb, nameof(curWeb)); Guard.ArgumentIsNotNull(arrGTemp, nameof(arrGTemp)); var webGuid = new Guid(); var listGuid = new Guid(); SPWeb iWeb = null; SPList iList = null; foreach (DataRow dr in dataSet.Tables[0].Rows) { var found = false; try { var wGuid = new Guid(dr[0].ToString()); var lGuid = new Guid(dr[1].ToString()); if (webGuid != wGuid) { if (iWeb != null) { iWeb.Close(); iWeb = site.OpenWeb(wGuid); } else { iWeb = site.OpenWeb(wGuid); } webGuid = iWeb.ID; } if (listGuid != lGuid) { iList = iWeb.Lists[lGuid]; listGuid = iList.ID; } var itemById = iList.GetItemById(int.Parse(dr[2].ToString())); found = true; if (newTimeSheet) { try { if (itemById["Timesheet"].ToString() == TrueText) { addItem(itemById, arrGTemp); } } catch (Exception exception) { DiagTrace.WriteLine(exception); } } else { addItem(itemById, arrGTemp); } } catch (Exception exception) { DiagTrace.WriteLine(exception); } finally { iWeb.Close(); } if (!found && !newTimeSheet) { addItem(dr, arrGTemp, curWeb); } } }
private static void CheckDefaultLang(SPItemEventProperties property) { try { SPWeb currentWeb = property.OpenWeb(); SPSite currentSite = property.OpenSite(); bool loadBalancingServersListExist = false; foreach (SPList list in currentWeb.Lists) { if (list.ToString() == "LoadBalancingServers") { if (list.ItemCount > 1) { loadBalancingServersListExist = true; } break; } } if (loadBalancingServersListExist) { SPList listLoadBalancingServers = currentWeb.Lists["LoadBalancingServers"]; SPListItem item = property.ListItem; SPList parentList = item.ParentList; if (parentList.ToString() == "TranslationContents" || (parentList.ToString() == "TranslationContentsSub")) { bool reloadCache = true; foreach (SPField currentField in item.Fields) { if (item[currentField.InternalName] != null) { if (item[currentField.InternalName].ToString().Contains("SPS_ADDED_")) { item[currentField.InternalName] = item[currentField.InternalName].ToString().Replace( "SPS_ADDED_", string.Empty); currentWeb.AllowUnsafeUpdates = true; item.SystemUpdate(false); currentWeb.AllowUnsafeUpdates = false; reloadCache = false; } } } if (reloadCache) { foreach (SPListItem server in listLoadBalancingServers.Items) { #pragma warning disable 612,618 ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); #pragma warning restore 612,618 string webId = string.Empty; if (parentList.ToString() == "TranslationContentsSub") { webId = "_" + item.Web.ID; } var req = (HttpWebRequest)WebRequest.Create(server["Title"] + "/_layouts/CacheControl.aspx?list=TranslationContents&webId=" + webId); req.Method = "GET"; req.Credentials = CredentialCache.DefaultCredentials; req.GetResponse(); } } } if (parentList.ToString() == "LanguagesVisibility" || parentList.ToString() == "Configuration Store") { foreach (SPListItem server in listLoadBalancingServers.Items) { #pragma warning disable 612,618 ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); #pragma warning restore 612,618 var req = (HttpWebRequest)WebRequest.Create(server["Title"] + "/_layouts/CacheControl.aspx?list=TranslationContentsOrLanguagesVisibility"); req.Method = "GET"; req.Credentials = CredentialCache.DefaultCredentials; req.GetResponse(); } } if (parentList.ToString() == "PagesTranslations") { foreach (SPListItem server in listLoadBalancingServers.Items) { #pragma warning disable 612,618 ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); #pragma warning restore 612,618 var req = (HttpWebRequest)WebRequest.Create(server["Title"] + "/_layouts/CacheControl.aspx?list=PagesTranslations"); req.Method = "GET"; req.Credentials = CredentialCache.DefaultCredentials; req.GetResponse(); } } } else { int serversCount = GetNumberOfFrontEndServer(); SPListItem item = property.ListItem; SPList parentList = item.ParentList; if ((parentList.ToString() == "TranslationContents") || (parentList.ToString() == "TranslationContentsSub") || (parentList.ToString() == "LanguagesVisibility")) { bool reloadCache = true; foreach (SPField currentField in item.Fields) { if (item[currentField.InternalName] != null) { if (item[currentField.InternalName].ToString().Contains("SPS_ADDED_")) { item[currentField.InternalName] = item[currentField.InternalName].ToString().Replace("SPS_ADDED_", string.Empty); currentWeb.AllowUnsafeUpdates = true; item.SystemUpdate(false); currentWeb.AllowUnsafeUpdates = false; reloadCache = false; } } } if (reloadCache) { if (serversCount > 1) { string webId = "_" + item.Web.ID; if (parentList.ToString().Equals("TranslationContents")) { webId = "_" + currentWeb.Site.WebApplication.Id; } CreateReloadCacheTimer(currentSite, currentWeb, "/_layouts/CacheControl.aspx?list=TranslationContents&webId=" + webId); } else { ResetSiteFirstLevelCache(currentWeb); if (parentList.ToString() == "TranslationContents" || parentList.ToString() == "TranslationContentsSub") { string webId = "_" + item.Web.ID; HttpRuntime.Cache.Remove("SPS_TRANSLATION_CACHE_IS_LOADED" + webId); HttpRuntime.Cache.Add("SPS_TRANSLATION_CACHE_IS_LOADED" + webId, "2", null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } else { var cacheLoadedKey = new StringCollection(); IDictionaryEnumerator cacheEnum = HttpRuntime.Cache.GetEnumerator(); while (cacheEnum.MoveNext()) { string key = cacheEnum.Key.ToString(); if (key.IndexOf("SPS_TRANSLATION_CACHE_IS_LOADED") != -1) { cacheLoadedKey.Add(key); } } foreach (string key in cacheLoadedKey) { HttpRuntime.Cache.Remove(key); } } } } // Traitement pour update des resx if ((HttpRuntime.Cache["AlphamosaikResxFilesUpdate"] != null) && (bool)HttpRuntime.Cache["AlphamosaikResxFilesUpdate"]) { UpdateResxFiles(item); } } if (parentList.ToString() == "PagesTranslations") { if (serversCount > 1) { CreateReloadCacheTimer(currentSite, currentWeb, "/_layouts/CacheControl.aspx?list=PagesTranslations"); } else { HttpRuntime.Cache.Remove("AdminPagesToTranslate"); HttpRuntime.Cache.Remove("PagesNotToTranslate"); HttpRuntime.Cache.Remove("PagesToTranslate"); } } if (parentList.ToString() == "Configuration Store") { if (serversCount > 1) { CreateReloadCacheTimer(currentSite, currentWeb, "/_layouts/CacheControl.aspx?list=TranslationContentsOrLanguagesVisibility"); } else { var cacheLoadedKey = new StringCollection(); IDictionaryEnumerator cacheEnum = HttpRuntime.Cache.GetEnumerator(); while (cacheEnum.MoveNext()) { string key = cacheEnum.Key.ToString(); if (key.IndexOf("SPS_TRANSLATION_CACHE_IS_LOADED") != -1) { cacheLoadedKey.Add(key); } } foreach (string key in cacheLoadedKey) { HttpRuntime.Cache.Remove(key); } } } } currentWeb.Dispose(); currentWeb.Close(); } catch (Exception ex) { Utilities.LogException("Error in ReloadCacheEvent: " + ex.Message); } }
private void autoAdd(SqlConnection cn, string tsuid, SPWeb web, string rolluplists) { SqlConnection cnwss = null; SPSecurity.RunWithElevatedPrivileges(delegate() { SPSite s = SPContext.Current.Site; { string dbCon = s.ContentDatabase.DatabaseConnectionString; cnwss = new SqlConnection(dbCon); cnwss.Open(); } }); if (cnwss.State == ConnectionState.Open) { string period = Request["period"]; string siteurl = web.ServerRelativeUrl.Substring(1); if (tsuid == null || tsuid == "") { tsuid = Guid.NewGuid().ToString(); SqlCommand cmd1 = new SqlCommand("INSERT INTO TSTIMESHEET (TS_UID,USERNAME,PERIOD_ID,SITE_UID,resourcename) VALUES (@TS_UID,@USERNAME,@PERIOD_ID,@SITE_UID,@resourcename)", cn); cmd1.Parameters.AddWithValue("@TS_UID", tsuid); cmd1.Parameters.AddWithValue("@USERNAME", username); cmd1.Parameters.AddWithValue("@resourcename", resName); cmd1.Parameters.AddWithValue("@PERIOD_ID", period); cmd1.Parameters.AddWithValue("@SITE_UID", web.Site.ID); cmd1.ExecuteNonQuery(); } SharedFunctions.processResources(cn, tsuid, web, username); SqlCommand cmd = new SqlCommand("SELECT period_start,period_end from TSPERIOD where site_id=@siteid and period_id=@period_id", cn); cmd.Parameters.AddWithValue("@siteid", web.Site.ID); cmd.Parameters.AddWithValue("@period_id", period); SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); DateTime pstart = dr.GetDateTime(0); DateTime pend = dr.GetDateTime(1); dr.Close(); foreach (string rlist in rolluplists.Replace("\r\n", "\n").Split('\n')) { string lists = ""; string query = ""; if (siteurl == "") { query = "SELECT dbo.AllLists.tp_ID FROM dbo.Webs INNER JOIN dbo.AllLists ON dbo.Webs.Id = dbo.AllLists.tp_WebId WHERE (dbo.Webs.FullUrl LIKE '" + siteurl + "%' OR dbo.Webs.FullUrl = '" + siteurl + "') AND (dbo.AllLists.tp_Title like '" + rlist.Replace("'", "''") + "')"; } else { query = "SELECT dbo.AllLists.tp_ID FROM dbo.Webs INNER JOIN dbo.AllLists ON dbo.Webs.Id = dbo.AllLists.tp_WebId WHERE (dbo.Webs.FullUrl LIKE '" + siteurl + "/%' OR dbo.Webs.FullUrl = '" + siteurl + "') AND (dbo.AllLists.tp_Title like '" + rlist.Replace("'", "''") + "')"; } cmd = new SqlCommand(query, cnwss); dr = cmd.ExecuteReader(); while (dr.Read()) { lists += "<List ID='" + dr.GetGuid(0).ToString() + "'/>"; } dr.Close(); if (lists != "") { SPUser u = web.Site.RootWeb.AllUsers[username]; SPSiteDataQuery dq = new SPSiteDataQuery(); dq.ViewFields = "<FieldRef Name='Title' Nullable='TRUE'/><FieldRef Name='Project' Nullable='TRUE'/>"; dq.Webs = "<Webs Scope='Recursive'/>"; dq.Lists = "<Lists>" + lists + "</Lists>"; dq.Query = "<Where><And><And><And><Eq><FieldRef Name=\"AssignedTo\" LookupId='True'/><Value Type=\"User\">" + u.ID.ToString() + "</Value></Eq><Eq><FieldRef Name=\"Timesheet\" /><Value Type=\"Boolean\">1</Value></Eq></And><Geq><FieldRef Name=\"DueDate\" /><Value Type=\"DateTime\">" + pstart.ToString("u") + "</Value></Geq></And><Leq><FieldRef Name=\"StartDate\" /><Value Type=\"DateTime\">" + pend.ToString("u") + "</Value></Leq></And></Where>"; DataTable dt = web.GetSiteData(dq); Guid webGuid = new Guid(); Guid listGuid = new Guid(); SPWeb iWeb = null; SPSite iSite = web.Site; SPList iList = null; SPList pList = null; foreach (DataRow dRow in dt.Rows) { cmd = new SqlCommand("SELECT * FROM TSITEM where WEB_UID=@web_uid and LIST_UID = @list_uid and item_id=@item_id and ts_uid=@ts_uid", cn); cmd.Parameters.AddWithValue("@WEB_UID", dRow["WEBID"]); cmd.Parameters.AddWithValue("@LIST_UID", dRow["LISTID"]); cmd.Parameters.AddWithValue("@ITEM_ID", dRow["ID"]); cmd.Parameters.AddWithValue("@ts_uid", tsuid); dr = cmd.ExecuteReader(); bool found = false; if (dr.Read()) { found = true; } dr.Close(); if (!found) { Guid wGuid = new Guid(dRow["WEBID"].ToString()); Guid lGuid = new Guid(dRow["LISTID"].ToString()); if (webGuid != wGuid) { pList = null; if (iWeb != null) { iWeb.Close(); iWeb = iSite.OpenWeb(wGuid); } else { iWeb = iSite.OpenWeb(wGuid); } webGuid = iWeb.ID; } if (listGuid != lGuid) { iList = iWeb.Lists[lGuid]; pList = pList = SharedFunctions.getProjectCenterList(iList); listGuid = iList.ID; } SPListItem li = iList.GetItemById(int.Parse(dRow["ID"].ToString())); string project = ""; string project_id = ""; try { //project = iList.Fields["Project"].GetFieldValueAsText(dRow["Project"].ToString()); try { SPFieldLookupValue lv = new SPFieldLookupValue(li["Project"].ToString()); project = lv.LookupValue; project_id = lv.LookupId.ToString(); if (project == null) { project = ""; project_id = "0"; } } catch { } } catch { } Guid newTS = Guid.NewGuid(); cmd = new SqlCommand("INSERT INTO TSITEM (TS_UID,TS_ITEM_UID,WEB_UID,LIST_UID,ITEM_TYPE,ITEM_ID,TITLE,PROJECT,LIST,PROJECT_ID,PROJECT_LIST_UID) VALUES (@TS_UID,@TS_ITEM_UID,@WEB_UID,@LIST_UID,@ITEM_TYPE,@ITEM_ID,@TITLE,@PROJECT,@LIST,@PROJECT_ID,@projectlistuid)", cn); cmd.Parameters.AddWithValue("@TS_UID", tsuid); cmd.Parameters.AddWithValue("@TS_ITEM_UID", newTS); cmd.Parameters.AddWithValue("@WEB_UID", dRow["WEBID"].ToString()); cmd.Parameters.AddWithValue("@LIST_UID", dRow["LISTID"].ToString()); cmd.Parameters.AddWithValue("@ITEM_TYPE", 1); cmd.Parameters.AddWithValue("@ITEM_ID", dRow["ID"].ToString()); cmd.Parameters.AddWithValue("@TITLE", dRow["Title"].ToString()); cmd.Parameters.AddWithValue("@PROJECT", project); cmd.Parameters.AddWithValue("@PROJECT_ID", project_id); cmd.Parameters.AddWithValue("@LIST", rlist); if (pList != null) { cmd.Parameters.AddWithValue("@projectlistuid", pList.ID); } else { cmd.Parameters.AddWithValue("@projectlistuid", DBNull.Value); } cmd.ExecuteNonQuery(); SharedFunctions.processMeta(iWeb, iList, li, newTS, project, cn, pList); //processMeta(cn, iWeb, iList, li, newTS, project, pList); } } } } SqlCommand cmd2 = new SqlCommand("UPDATE TSTIMESHEET set lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@TS_UID", cn); cmd2.Parameters.AddWithValue("@TS_UID", tsuid); cmd2.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName); cmd2.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name); cmd2.ExecuteNonQuery(); cnwss.Close(); } }
protected void Page_Load(object sender, EventArgs e) { string strAction = Request["action"]; string period = Request["period"]; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Expires = -1; data = ""; string fEmail = SPContext.Current.Web.CurrentUser.Email; SPSite site = SPContext.Current.Site; //using () { //using () SPWeb web = SPContext.Current.Web; { try { SqlConnection cn = null; SPSecurity.RunWithElevatedPrivileges(delegate() { cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(site.WebApplication.Id)); cn.Open(); string requestedUser = Page.Request["duser"]; if (requestedUser != null && requestedUser != "") { if (SharedFunctions.canUserImpersonate(username, requestedUser, SPContext.Current.Site.RootWeb, out resName)) { username = requestedUser; } else { impFailed = true; } } bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSLiveHours"), out liveHours); }); if (impFailed) { data = "Error: Impersonation Failed"; } else { if (cn != null) { SqlCommand cmd; int iperiod; SqlDataReader dr; switch (strAction) { case "deleteTS": if (web.CurrentUser.IsSiteAdmin) { string[] tsuids = Request["ts_uids"].Split(','); foreach (string tsuidData in tsuids) { cmd = new SqlCommand("DELETE FROM TSTIMESHEET where ts_uid=@ts_uid", cn); cmd.Parameters.AddWithValue("@ts_uid", tsuidData); cmd.ExecuteNonQuery(); } data = "Success"; } else { data = "Error: Access Denied"; } break; case "closePeriod": cmd = new SqlCommand("update tsperiod set locked=1 where period_id=@periodid and site_id=@siteid", cn); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); cmd.Parameters.AddWithValue("@periodid", period); cmd.ExecuteNonQuery(); data = period; break; case "openPeriod": cmd = new SqlCommand("update tsperiod set locked=0 where period_id=@periodid and site_id=@siteid", cn); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); cmd.Parameters.AddWithValue("@periodid", period); cmd.ExecuteNonQuery(); data = period; break; case "submitTime": cmd = new SqlCommand("update TSTIMESHEET set submitted=1,approval_status=0,lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@ts_uid", cn); cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]); cmd.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName); cmd.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name); cmd.ExecuteNonQuery(); SPSecurity.RunWithElevatedPrivileges(delegate() { SPWeb tweb = SPContext.Current.Web; { SharedFunctions.processResources(cn, Request["ts_uid"], tweb, username); } }); if (EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSDisableApprovals").ToLower() == "true") { approve(Request["ts_uid"], SPContext.Current.Web, Request["Period"]); } else { string actualWork = ""; //SPSecurity.RunWithElevatedPrivileges(delegate() //{ // actualWork = EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSActualWork"); //}); //if (actualWork != "") //{ if (!liveHours) { data = SharedFunctions.processActualWork(cn, Request["ts_uid"], site, false, true); } //} } if (data == "") { data = "Success"; } cmd = new SqlCommand("select ts_item_uid,web_uid,list_uid,item_id,project from TSITEM where TS_UID=@ts_uid", cn); cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); SPList pList = null; SPWeb iWeb = null; SPList iList = null; Guid webGuid = Guid.Empty; Guid listGuid = Guid.Empty; foreach (DataRow dataRow in ds.Tables[0].Rows) { try { Guid wGuid = new Guid(dataRow["WEB_UID"].ToString()); Guid lGuid = new Guid(dataRow["LIST_UID"].ToString()); if (webGuid != wGuid) { if (iWeb != null) { iWeb.Close(); iWeb = site.OpenWeb(wGuid); } else { iWeb = site.OpenWeb(wGuid); } webGuid = iWeb.ID; } if (listGuid != lGuid) { iList = iWeb.Lists[lGuid]; try { pList = SharedFunctions.getProjectCenterList(iList); } catch { } listGuid = iList.ID; } SPListItem li = iList.GetItemById(int.Parse(dataRow["ITEM_ID"].ToString())); SharedFunctions.processMeta(iWeb, iList, li, new Guid(dataRow["ts_item_uid"].ToString()), dataRow["project"].ToString(), cn, pList); } catch { } } break; case "unsubmitTime": cmd = new SqlCommand("update TSTIMESHEET set submitted=0,approval_status=0,lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@ts_uid", cn); cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]); cmd.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName); cmd.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name); cmd.ExecuteNonQuery(); if (EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSDisableApprovals").ToLower() == "true" && !liveHours) { data = SharedFunctions.processActualWork(cn, Request["ts_uid"], site, true, true); } if (data == "") { data = "Success"; } break; case "deletePeriod": cmd = new SqlCommand("delete from tsperiod where period_id=@periodid and site_id=@siteid", cn); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); cmd.Parameters.AddWithValue("@periodid", period); cmd.ExecuteNonQuery(); data = "Success"; break; case "addPeriod": cmd = new SqlCommand("select top 1 period_id from tsperiod where site_id=@siteid order by period_id desc", cn); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); dr = cmd.ExecuteReader(); iperiod = 1; if (dr.Read()) { iperiod = dr.GetInt32(0) + 1; } dr.Close(); cmd = new SqlCommand("insert into tsperiod (period_start,period_end,period_id,site_id) values (@periodstart,@periodend,@period_id,@siteid)", cn); cmd.Parameters.AddWithValue("@periodstart", Request["start"]); cmd.Parameters.AddWithValue("@periodend", Request["end"]); cmd.Parameters.AddWithValue("@period_id", iperiod); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); cmd.ExecuteNonQuery(); data = "Success"; break; case "addPeriods": var periods = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(Request[JsonDataParameter]); var createdIds = CreatePeriods(cn, periods); data = string.Format("Success,{0},{1}", strAction, string.Join(",", createdIds)); break; case "addType": cmd = new SqlCommand("select top 1 tstype_id from tstype where site_uid=@siteid order by tstype_id desc", cn); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); dr = cmd.ExecuteReader(); iperiod = 1; if (dr.Read()) { iperiod = dr.GetInt32(0) + 1; } dr.Close(); cmd = new SqlCommand("insert into tstype (tstype_id,tstype_name,site_uid) values (@tstype_id,@tstype_name,@siteid)", cn); cmd.Parameters.AddWithValue("@tstype_name", Request["typename"]); cmd.Parameters.AddWithValue("@tstype_id", iperiod); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); cmd.ExecuteNonQuery(); data = "Success"; break; case "editType": cmd = new SqlCommand("update tstype set tstype_name = @tstype_name where tstype_id=@tstype_id and site_uid=@siteid", cn); cmd.Parameters.AddWithValue("@tstype_name", Request["typename"]); cmd.Parameters.AddWithValue("@tstype_id", Request["typeid"]); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); cmd.ExecuteNonQuery(); data = "Success"; break; case "approveTS": { approve(Request["ts_uids"].ToString(), SPContext.Current.Web, Request["Period"]); if (data == "") { data = "Success"; } } break; case "rejectTS": { string[] tsuids = Request["ts_uids"].Split(','); foreach (string tsuidData in tsuids) { string[] tsuid = tsuidData.Split('|'); cmd = new SqlCommand("update TSTIMESHEET set approval_status=2,approval_notes=@notes where ts_uid=@ts_uid", cn); cmd.Parameters.AddWithValue("@ts_uid", tsuid[0]); cmd.Parameters.AddWithValue("@notes", tsuid[1]); cmd.ExecuteNonQuery(); data += SharedFunctions.processActualWork(cn, tsuid[0], site, true, true); } if (data == "") { data = "Success"; } } break; case "unlockTS": { string[] tsuids = Request["ts_uids"].Split(','); foreach (string tsuidData in tsuids) { string[] tsuid = tsuidData.Split('|'); cmd = new SqlCommand("update TSTIMESHEET set approval_status=0 where ts_uid=@ts_uid", cn); cmd.Parameters.AddWithValue("@ts_uid", tsuid[0]); cmd.ExecuteNonQuery(); } data = "Success"; } break; case "rejectEmail": { string[] tsuids = Request["ts_uids"].Split(','); foreach (string tsuid in tsuids) { cmd = new SqlCommand("select username,approval_notes,period_start,period_end from vwTSApprovalNotes where ts_uid=@ts_uid", cn); cmd.Parameters.AddWithValue("@ts_uid", tsuid); dr = cmd.ExecuteReader(); if (dr.Read()) { string username = dr.GetString(0); string notes = dr.GetString(1); try { SPUser user = web.AllUsers[username]; if (user.Email != "") { System.Net.Mail.MailMessage mailMsg = new MailMessage(); mailMsg.From = new MailAddress(fEmail); mailMsg.To.Add(new MailAddress(user.Email)); mailMsg.Subject = web.Title + " Timesheet approval notice"; mailMsg.Body = "Your timesheet for period (" + dr.GetDateTime(2).ToShortDateString() + " - " + dr.GetDateTime(3).ToShortDateString() + ") has been rejected:<br>" + notes; mailMsg.IsBodyHtml = true; mailMsg.BodyEncoding = System.Text.Encoding.UTF8; mailMsg.Priority = MailPriority.Normal; // Configure the mail server SmtpClient smtpClient = new SmtpClient(); SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local; string sMailSvr = spWebAdmin.OutboundMailServiceInstance.Server.Name; smtpClient.Host = sMailSvr; smtpClient.Send(mailMsg); } } catch { } } dr.Close(); } } data = "Success"; break; case "autoadd": //string flagfield = ""; string lists = ""; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite uSite = SPContext.Current.Site) { //flagfield = EPMLiveCore.CoreFunctions.getConfigSetting(uSite.RootWeb, "EPMLiveTSFlag"); lists = EPMLiveCore.CoreFunctions.getConfigSetting(uSite.RootWeb, "EPMLiveTSLists"); } }); autoAdd(cn, Request["ts_uid"], web, lists); data = "Success"; break; case "approvePM": { string[] tsitemuids = Request["tsitemuids"].Split(','); foreach (string tsitemuid in tsitemuids) { //string[] tsuid = tsuidData.Split('|'); cmd = new SqlCommand("update tsitem set approval_status=1 where ts_item_uid=@tsitemuid", cn); cmd.Parameters.AddWithValue("@tsitemuid", tsitemuid); cmd.ExecuteNonQuery(); } data = "Success"; } break; case "rejectPM": { string[] tsitemuids = Request["tsitemuids"].Split(','); foreach (string tsitemuid in tsitemuids) { //string[] tsuid = tsuidData.Split('|'); cmd = new SqlCommand("update tsitem set approval_status=2 where ts_item_uid=@tsitemuid", cn); cmd.Parameters.AddWithValue("@tsitemuid", tsitemuid); cmd.ExecuteNonQuery(); } } data = "Success"; break; default: data = "Error: Invalid Command"; break; } ; } } } catch (Exception ex) { data = "Error: " + ex.Message; } } } }
public override void populateGroups(string query, SortedList arrGTemp, SPWeb curWeb) { SPSiteDataQuery dq = new SPSiteDataQuery(); dq.ViewFields = "<FieldRef Name='Title' Nullable='TRUE'/>"; dq.Webs = "<Webs Scope='Recursive'/>"; dq.Lists = "<Lists ServerTemplate='10701'/>"; dq.Query = "<Where><Eq><FieldRef Name=\"ProjectManagers\" /><Value Type=\"User\"><UserID/></Value></Eq></Where>"; DataTable dtData = curWeb.GetSiteData(dq); DataTable dtItems = new DataTable(); SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(curWeb.Site.WebApplication.Id))) { cn.Open(); using (SqlCommand cmd = new SqlCommand("select ts_item_uid,columnname,columnvalue from vwTSItemMeta where period_id=@period_id and site_uid=@siteid", cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@period_id", period); cmd.Parameters.AddWithValue("@siteid", curWeb.Site.ID); dsTimesheetMeta = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dsTimesheetMeta); } using (SqlCommand cmd = new SqlCommand("select web_uid, list_uid,item_id,username,resourcename,project,title,list_uid from vwTSTasks where web_uid=@webuid and period_id=@period_id and totalhours > 0", cn)) { cmd.Parameters.AddWithValue("@webuid", curWeb.ID.ToString()); cmd.Parameters.AddWithValue("@period_id", period); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); DataTable dtFilteredRecords = new DataTable(); foreach (DataRow drProjects in dtData.Rows) { DataView dv = new DataView(ds.Tables[0]); string filterquery = string.Format("(project='{0}' or (title='{0}' and list_uid='{1}'))", drProjects["Title"].ToString(), drProjects["ListId"].ToString()); dv.RowFilter = filterquery; if (dv.Count > 0) { dtFilteredRecords.Merge(dv.ToTable(), false); } } dtItems.Merge(dtFilteredRecords, false); } using (SqlCommand cmd = new SqlCommand("select title,project,ts_uid,web_uid,list_uid,item_id,ts_item_uid,approval_status,resourcename,username from vwTSTasks where period_id=@period_id and site_uid=@siteid order by project", cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@period_id", period); cmd.Parameters.AddWithValue("@siteid", curWeb.Site.ID); dsTimesheetTasks = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dsTimesheetTasks); } } } catch { } }); Guid webGuid = new Guid(); Guid listGuid = new Guid(); SPWeb iWeb = null; SPList iList = null; foreach (DataRow dr in dtItems.Rows) { try { Guid wGuid = new Guid(dr[0].ToString()); Guid lGuid = new Guid(dr[1].ToString()); if (webGuid != wGuid) { if (iWeb != null) { iWeb.Close(); iWeb = site.OpenWeb(wGuid); } else { iWeb = site.OpenWeb(wGuid); } webGuid = iWeb.ID; } if (listGuid != lGuid) { iList = iWeb.Lists[lGuid]; listGuid = iList.ID; } SPListItem li = iList.GetItemById(int.Parse(dr[2].ToString())); addTSItem(li, arrGTemp, dr[3].ToString(), dr[4].ToString()); } catch { } } }
public static string processProjectWork(SqlConnection cn, string tsuid, SPSite site, bool bApprovalScreen, bool bApproved) { string error = ""; //SPSecurity.RunWithElevatedPrivileges(delegate() //{ //using (SPSite site = new SPSite(s.ID, s.SystemAccount.UserToken)) { //string sql = "SELECT * FROM vwTSItemHoursByTS where ts_uid=@ts_uid order by web_uid,list_uid"; //if(!bApprovalScreen) // sql = "SELECT * FROM vwTSItemHoursByMyTS where ts_uid=@ts_uid order by web_uid,list_uid"; SqlCommand cmd = new SqlCommand("spTSGetProjectsHours", cn); cmd.Parameters.AddWithValue("@TSUID", tsuid); cmd.Parameters.AddWithValue("@approved", bApproved); cmd.CommandType = CommandType.StoredProcedure; DataSet dsProjects = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dsProjects); //cmd = new SqlCommand(sql, cn); //cmd.Parameters.AddWithValue("@TS_UID", tsuid); //SqlDataReader dr = cmd.ExecuteReader(); Guid webGuid = new Guid(); Guid listGuid = new Guid(); SPWeb iWeb = null; SPList iList = null; foreach (DataRow drProject in dsProjects.Tables[0].Rows) { try { if (drProject["PROJECT_LIST_UID"].ToString() != "") { Guid wGuid = new Guid(drProject["WEB_UID"].ToString()); Guid lGuid = new Guid(drProject["PROJECT_LIST_UID"].ToString()); if (webGuid != wGuid) { try { if (iWeb != null) { iWeb.Close(); iWeb = site.OpenWeb(wGuid); } else { iWeb = site.OpenWeb(wGuid); } webGuid = iWeb.ID; } catch { } } if (iWeb != null) { if (listGuid != lGuid) { iList = iWeb.Lists[lGuid]; listGuid = iList.ID; } iWeb.AllowUnsafeUpdates = true; string project = drProject["Project_id"].ToString(); if (project != "0") { try { SPListItem liProject = iList.GetItemById(int.Parse(project)); liProject["TimesheetHours"] = drProject["Hours"].ToString(); liProject.SystemUpdate(); } catch { } } } } } catch (Exception exception) { error += "Error: " + exception.Message + "<br>SharePoint User: "******"<br><br><br>"; } } } //});\ return(error); }
/// <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)); } } }
protected void BtnOK_Click(object sender, EventArgs e) { try { //using ( SPWeb mySite = SPContext.Current.Web; { string sCurrURL = mySite.Url; pnlTitle.Visible = false; pnlURL.Visible = false; pnlURLBad.Visible = false; string title = txtTitle.Text; string group = DdlTemplate.SelectedItem.Value; string selectedWorkspace = Request["hdnSelectedWorkspace"]; string sParentWSURL = selectedWorkspace.Replace(mySite.ServerRelativeUrl, ""); if (!String.IsNullOrEmpty(sParentWSURL)) { sParentWSURL = sParentWSURL.Substring(1); } SPWeb w = mySite; if (sParentWSURL != "") { w = mySite.Webs[sParentWSURL]; } string err = ""; if (w.Exists) { string sNewURL = txtURL.Text; err = CoreFunctions.createSite(title, sNewURL, group, mySite.CurrentUser.LoginName, true, rdoTopLinkYes.Checked, mySite); } else { err = "The site that you selected does not exist."; } w.Close(); if (err.Substring(0, 1) == "0") { SPSite site = new SPSite(err.Substring(2)); SPWeb web = site.OpenWeb(); if (!web.Properties.ContainsKey("EPMLiveTemplateID")) { string sGUID = System.Guid.NewGuid().ToString(); web.Properties.Add("EPMLiveTemplateID", sGUID); web.Properties.Update(); } SPWeb rootWeb = site.RootWeb; AddAsSynchedTemplate(rootWeb, web.ID.ToString()); Response.Redirect(sCurrURL + "/_layouts/epmlive/templates.aspx"); } else { label1.Text = err; Panel2.Visible = true; } } } catch (Exception ex) { label1.Text = "Error: " + ex.Message + ex.StackTrace; Panel2.Visible = true; } }
private static void CopyAllWebParts(string destinationPageUrlServerRelative, SPWeb destinationPageWeb, string sourcePageUrlServerRelative, SPWeb sourcePageWeb, bool shouldOverwriteDestinationWebParts) { SPWeb web = null; SPWeb web2 = null; try { SPLimitedWebPartManager limitedWebPartManager = destinationPageWeb.GetLimitedWebPartManager(destinationPageUrlServerRelative, PersonalizationScope.Shared); SPLimitedWebPartManager manager2 = sourcePageWeb.GetLimitedWebPartManager(sourcePageUrlServerRelative, PersonalizationScope.Shared); web2 = limitedWebPartManager.Web; web = manager2.Web; SPLimitedWebPartCollection webParts = manager2.WebParts; SPLimitedWebPartCollection parts2 = limitedWebPartManager.WebParts; if (webParts.Count > 0) { foreach (System.Web.UI.WebControls.WebParts.WebPart part in webParts) { if (!part.IsClosed) { System.Web.UI.WebControls.WebParts.WebPart webPart = parts2[part.ID]; if (webPart == null) { try { string zoneID = manager2.GetZoneID(part); limitedWebPartManager.AddWebPart(part, zoneID, part.ZoneIndex); } catch (ArgumentException e) { } } else { if (webPart.IsClosed) { limitedWebPartManager.OpenWebPart(webPart); } } } } } } catch (Exception e) { if (HttpContext.Current != null) { throw; } } finally { if ((web != sourcePageWeb) && (web != null)) { web.Close(); } if ((web2 != destinationPageWeb) && (web2 != null)) { web2.Close(); } } }
public void execute(SPSite site, SPWeb web, string sListName) { percentInterval = 1; SPList oCurrList = web.Lists[base.ListUid]; CreateNewList = false; try { string creatnew = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveSyncCreateNew-" + System.IO.Path.GetDirectoryName(oCurrList.DefaultView.ServerRelativeUrl)); if (creatnew == "") { CreateNewList = false; } else { CreateNewList = bool.Parse(creatnew); } } catch { } FromWeb = web; sListName = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveSyncAltListName-" + System.IO.Path.GetDirectoryName(oCurrList.DefaultView.ServerRelativeUrl)); if (sListName == "") { sListName = oCurrList.Title; } try { string sSiteGuid = web.Site.ID.ToString(); oFromList = oCurrList; ListSyncher oListSyncher = new ListSyncher(); oListSyncher.oFromList = oFromList; oListSyncher.FromWeb = oFromWeb; oListSyncher.ListName = sListName; oListSyncher.CreateNewList = this.CreateNewList; oListSyncher.SynchronizationType = SyncItemBaseType.SyncType.List; oListSyncher.bErrors = false; string sURL = FromWeb.ServerRelativeUrl; //LogHelper logHlpr = new LogHelper(); if (oFromList != null) { EPMLiveCore.CoreFunctions.setListSetting("TotalSettings", EPMLiveCore.CoreFunctions.getListSetting("TotalSettings", oFromList), oFromList); EPMLiveCore.CoreFunctions.setListSetting("GeneralSettings", EPMLiveCore.CoreFunctions.getListSetting("GeneralSettings", oFromList), oFromList); EPMLiveCore.CoreFunctions.setListSetting("DisplaySettings", EPMLiveCore.CoreFunctions.getListSetting("DisplaySettings", oFromList), oFromList); EPMLiveCore.CoreFunctions.setListSetting("EnableResourcePlan", EPMLiveCore.CoreFunctions.getListSetting("EnableResourcePlan", oFromList), oFromList); } var dbConnectionString = web.Site.ContentDatabase.DatabaseConnectionString; using (var connectionsWss = new SqlConnection(dbConnectionString)) { connectionsWss.Open(); var siteurl = web.ServerRelativeUrl.Substring(1); var query = string.Empty;; if (!string.IsNullOrWhiteSpace(siteurl)) { query = $"SELECT id from webs WHERE (FullUrl LIKE '" + siteurl + "/%')"; } else { query = $"SELECT id from webs WHERE (siteid = '" + web.Site.ID + "' and parentwebid is not null)"; } using (var command = new SqlCommand(query, connectionsWss)) { using (var dataSet = new DataSet()) { using (var dataAdapter = new SqlDataAdapter(command)) { dataAdapter.Fill(dataSet); connectionsWss.Close(); totalCount = dataSet.Tables[0].Rows.Count; float webCount = 0; foreach (DataRow dataRow in dataSet.Tables[0].Rows) { try { using (SPWeb subWeb = web.Site.OpenWeb(new Guid(dataRow[0].ToString()))) { if (subWeb.Properties.ContainsKey(EPMLiveAllowListSynchKey)) { var bAllowListSynch = bool.Parse(subWeb.Properties[EPMLiveAllowListSynchKey]); if (bAllowListSynch) { sErrors += $"Web: {subWeb.Title} ({subWeb.ServerRelativeUrl}) - {DateTime.Now.ToLongTimeString()}<br>"; subWeb.AllowUnsafeUpdates = true; oListSyncher.Results = string.Empty; oListSyncher.ToWeb = subWeb; subWeb.AllowUnsafeUpdates = true; uint LCID = subWeb.RegionalSettings.LocaleId; subWeb.RegionalSettings.LocaleId = web.RegionalSettings.LocaleId; subWeb.Update(); oListSyncher.Sync(); subWeb.AllowUnsafeUpdates = true; subWeb.RegionalSettings.LocaleId = LCID; subWeb.Update(); sErrors += oListSyncher.Results; if (oListSyncher.bErrors) { bErrors = true; } } } subWeb.Close(); subWeb.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); } } catch (Exception exc) { SystemTrace.WriteLine(exc.ToString()); bErrors = true; sErrors += "<br><br>General Error: " + exc.Message; } updateProgress(webCount++); } } } } } } catch (Exception ex) { bErrors = true; sErrors += "<br><br>General Error: " + ex.Message; } }
protected override void CreateChildControls() { if (IsFieldValueCached) { base.CreateChildControls(); } else if (Field != null) { base.CreateChildControls(); if (ControlMode != SPControlMode.Display) { var field = (SPFieldLookup)Field; if (!field.AllowMultipleValues) { Controls.Clear(); if (Throttled) { var maxItemsPerThrottledOperation = Web.Site.WebApplication.MaxItemsPerThrottledOperation; var str = SPResource.GetString( Field.Required ? "RequiredLookupThrottleMessage" : "LookupThrottleMessage", new object[] { maxItemsPerThrottledOperation.ToString( CultureInfo.InvariantCulture) }); var child = new Literal { Text = SPHttpUtility.HtmlEncode(str) }; var literal2 = new Literal { Text = @"<span style=""vertical-align:middle"">" }; var literal3 = new Literal { Text = @"</span>" }; Controls.Add(literal2); Controls.Add(child); Controls.Add(literal3); } else { if (AutoPostBack || ((DataSource == null) || (DataSource.Count <= 20)) || ((InDesign || !IsIE55Up(Page.Request)) || IsAccessibilityMode(Page.Request))) { dropList = new DropDownList { ID = "Lookup", TabIndex = TabIndex, DataSource = DataSource, DataValueField = "ValueField", DataTextField = "TextField", ToolTip = SPHttpUtility.NoEncode(field.Title), }; if (AutoPostBack) { dropList.AutoPostBack = true; dropList.SelectedIndexChanged += OnSelectedIndexChanged; } dropList.DataBind(); Controls.Add(dropList); } else { textBox = new TextBox(); textBox.Attributes.Add("choices", Choices); textBox.Attributes.Add("match", ""); textBox.Attributes.Add("onkeydown", "CoreInvoke('HandleKey')"); textBox.Attributes.Add("onkeypress", "CoreInvoke('HandleChar')"); textBox.Attributes.Add("onfocusout", "CoreInvoke('HandleLoseFocus')"); textBox.Attributes.Add("onchange", "CoreInvoke('HandleChange')"); textBox.Attributes.Add("class", "ms-lookuptypeintextbox"); textBox.Attributes.Add("title", SPHttpUtility.HtmlEncode(field.Title)); textBox.TabIndex = TabIndex; textBox.Attributes["optHid"] = HiddenFieldName; var literal4 = new Literal { Text = @"<span style=""vertical-align:middle"">" }; var literal5 = new Literal { Text = @"</span>" }; Controls.Add(literal4); Controls.Add(textBox); textBox.Attributes.Add("opt", "_Select"); dropImage = new Image { ImageUrl = "/_layouts/images/dropdown.gif" }; dropImage.Attributes.Add("alt", SPResource.GetString("LookupWordWheelDropdownAlt", new object[0])); dropImage.Attributes.Add("style", "vertical-align:middle;"); Controls.Add(dropImage); Controls.Add(literal5); } if (webForeign != null) { webForeign.Close(); webForeign = null; } Controls.Add(new LiteralControl("<br/>")); SetFieldControlValue(ItemFieldValue); } } } } }
private int Process(StringDictionary keyValues, out string output, bool ContentApproval, bool Versioning) { // Get the URL string requestUrl = this.GetURL(keyValues); bool IsRecursive = false; // Set if we are running Recursive or not if (string.IsNullOrEmpty(keyValues["includesubsites"])) { IsRecursive = true; } SPSite rootsite = default(SPSite); SPWeb rootweb = null; try { Uri rootweburi = new Uri(requestUrl); if (SPSite.Exists(rootweburi)) // Check if Site is there { // Open Site using (rootsite = new SPSite(requestUrl)) { using (rootweb = rootsite.OpenWeb()) { // Allow unsafe updates rootweb.AllowUnsafeUpdates = true; rootweb.Update(); // Process settings of the document libraries this.HandleDocumentLibrary(rootweb, ContentApproval, Versioning); // disable unsafe updates rootweb.AllowUnsafeUpdates = false; rootweb.Update(); if (IsRecursive) // Check if recurve was defined { // Loop though each sub-site and handle versioning & content approval settings for (int i = 0; i <= rootweb.Webs.Count; i++) { using (SPWeb subweb = rootweb.Webs[i]) { HandleDocumentLibrary(subweb, ContentApproval, Versioning); } } } } } } else { Console.WriteLine(string.Format("Web Application at {0} was not found, please check the \"URL\" argument and try again.", requestUrl)); } } catch (SPException spex) { StringBuilder sbError = new StringBuilder(); sbError.AppendLine(spex.ToString()); output = sbError.ToString(); return(-1); } finally { // If somethign went south and rootweb is not null, dispose of it correctly if (rootweb != null) { rootweb.Close(); rootweb.Dispose(); } // If something went south and rootsite is not null, dispose of it correctly if (rootsite != null) { rootsite.Close(); rootsite.Dispose(); } } output = "Completed."; return(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); } }
// 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(); }