Monday, March 8, 2010

RemovePortalURL

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using Microsoft.SharePoint.WebPartPages;using System.Collections.Generic;using System.Text;using Microsoft.SharePoint.Administration;

public partial class PortalUrlRemove : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) {
SPSecurity.RunWithElevatedPrivileges(delegate() { SPFarm GlobalAdministration = new SPFarm(); System.Uri uri = new System.Uri(SPContext.Current.Web.Url); SPWebApplication WebApplication = SPWebApplication.Lookup(uri); SPSiteCollection SiteCollections = WebApplication.Sites; //Console.WriteLine("Web Application: " + WebApplication.DisplayName.ToString()); Response.Write(""); foreach (SPSite SiteCollection in SiteCollections) { SiteCollection.AllowUnsafeUpdates = true; if (SiteCollection.PortalUrl != "") //SiteCollection.PortalUrl != null { Response.Write(""); SiteCollection.PortalName = null;// "Contoso Home"; SiteCollection.PortalUrl = null;// "http://www.consoto.com"; } //else //{ // SiteCollection.PortalName = "Contoso Home"; // SiteCollection.PortalUrl = "http://www.consoto.com"; //} } Response.Write("
"); Response.Write(" Site Collection list (remove portal URL)
"+SiteCollection.Url + "
"); });
}}

ExpirationTaskJob

-=-=-=-==-==-===-=-ExpirationWorkSpaceTimerJob.cs=============using System;using System.Collections.Generic;using System.Text;using Microsoft.SharePoint;using Microsoft.SharePoint.Administration;using Microsoft.SharePoint.Utilities;namespace ExpirationWorkSpace{ class ExpirationWorkSpaceTimerJob : SPFeatureReceiver { const string _JOB_NAME = "WorkSpace Expiration Timer Job"; //const string _JOB_NAME = "WorkSpace Expiration Date Task"; public override void FeatureActivated(SPFeatureReceiverProperties properties) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { // SPWeb web = null; // SPSite site = null; // SPWebApplication webApplication = this.Parent as SPWebApplication; SPWebApplication webapp = properties.Feature.Parent as SPWebApplication; if (webapp == null) throw new SPException("Error obtaining sp webapp"); // SPWeb web = properties.Feature.Parent as SPWeb; // string siteUrl = web.Site.Url; // SPSite site = new SPSite(siteUrl); //// SPSite site = properties.Feature.Parent as SPSite; // if (site != null) { // make sure the job isn't already registered //foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) foreach (SPJobDefinition job in webapp.JobDefinitions) { if (job.Name == _JOB_NAME) { job.Delete(); } } // install the job ExpirationTaskJob taskLoggerJob = new ExpirationTaskJob(_JOB_NAME, webapp); SPMinuteSchedule schedule = new SPMinuteSchedule(); schedule.BeginSecond = 0; schedule.EndSecond = 59; schedule.Interval = 1; taskLoggerJob.Schedule = schedule; //taskLoggerJob.Properties.Add("siteurl", web.Url); ////taskLoggerJob.Properties.Add("JobID", _jobID); //taskLoggerJob.Properties.Add("JobName", _JOB_NAME); taskLoggerJob.Update(); } }); } catch (Exception ex) { SPUtility.TransferToErrorPage(ex.Message); } } public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { //SPSite site = properties.Feature.Parent as SPSite; //// delete the job //foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) //{ // if (job.Name == wORKSPACE_EXPIRATION_JOB_NAME) // job.Delete(); //} ////throw new Exception("The method or operation is not implemented."); //SPWeb web = null; //SPSite site = null; try { SPSecurity.RunWithElevatedPrivileges(delegate() { //SPWeb web = properties.Feature.Parent as SPWeb; //string siteUrl = web.Site.Url; //SPSite site = new SPSite(siteUrl); //web = properties.Feature.Parent as SPWeb; //site = web.Site as SPSite; //if (site != null) SPWebApplication webapp = properties.Feature.Parent as SPWebApplication; if (webapp == null) throw new SPException("Error obtaining sp webapp"); // SPSite site = properties.Feature.Parent as SPSite; foreach (SPJobDefinition job in webapp.JobDefinitions ) { if (job.Name == _JOB_NAME) { job.Delete(); } } }); } catch (Exception ex) { Microsoft.SharePoint.Utilities.SPUtility.TransferToErrorPage(ex.Message); } } public override void FeatureInstalled(SPFeatureReceiverProperties properties) { // throw new Exception("The method or operation is not implemented."); } public override void FeatureUninstalling(SPFeatureReceiverProperties properties) { // throw new Exception("The method or operation is not implemented."); } }}===========================-=-=-===---------ExpirationTaskJob.cs------------==========
using System;using System.Web;using System.Data;using Microsoft.SharePoint;using Microsoft.SharePoint.Administration;using System.Collections.Specialized;using Microsoft.SharePoint.Utilities;using System.Text;namespace ExpirationWorkSpace{ class ExpirationTaskJob : SPJobDefinition{ public ExpirationTaskJob () : base(){ } /// Name of the job. /// The service. /// The server. /// Type of the target. public ExpirationTaskJob (string jobName, SPService service, SPServer server, SPJobLockType targetType) : base (jobName, service, server, targetType) { } /// /// Initializes a new instance of the class. /// /// Name of the job. /// The web application. public ExpirationTaskJob(string jobName, SPWebApplication webApplication) : base (jobName, webApplication, null, SPJobLockType.ContentDatabase) { this.Title = "WorkSpace Expiration Timer Job"; //this.Title = "WorkSpace Expiration Date Task"; } /// /// Executes the specified content db id. /// public override void Execute (Guid contentDbId) { #if (DEBUG) System.Diagnostics.Trace.Assert(false);#endif // get a reference to the current site collection's content database SPWebApplication webApplication = this.Parent as SPWebApplication; // SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId]; // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database // SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"]; ////SPList taskList = contentDb.Sites[0].RootWeb.Lists["ExpirationReport"]; SPList taskList = webApplication.Sites[0].RootWeb.Lists["ExpirationReport"]; SPListItemCollection allitems = taskList.Items; DataTable tbl = allitems.GetDataTable(); if (tbl != null) { DataView dv = new DataView(); dv = tbl.DefaultView; // dv.Table.Columns["ExpirationReport"].DataType = Type.GetType("System.DateTime"); dv.RowFilter = "ExpirationDate >='" + DateTime.Now.AddDays(-7) + "'"; DataTable newtbl = new DataTable(); newtbl = dv.ToTable(); int i; if (newtbl.Rows.Count > 0) { for (i = 0; i < sweburl =" newtbl.Rows[i][" _mailbody =" string.Empty;" _mailcontents =" new">"); _mailContents.Append(""); _mailContents.Append(" Following Workspace is about to expire on date Please do needful "); _mailContents.Append(" "); _mailContents.Append("" + sWebUrl.ToString() + ""); _mailContents.Append(" "); _mailContents.Append(""); _mailBody = _mailContents.ToString(); string body = _mailBody; string strToId = ExtractUserName((string)newtbl.Rows[i]["OwnerGrpUser"]) + "@u2ucourse.com"; string strsubject = "Workspace about to Expire"; StringDictionary headers = new StringDictionary(); headers.Add("to", strToId);// "administrator@u2ucourse.com"); headers.Add("from", "administrator@u2ucourse.com"); headers.Add("subject", strsubject); headers.Add("content-type", "text/html"); //This is the default type, so isn't neccessary. bool success = SPUtility.SendEmail(webApplication.Sites[0].RootWeb, headers, body); } } } } string ExtractUserName(string path) { string[] userPath = path.Split(new char[] { '\\' }); return userPath[userPath.Length - 1]; } }}
======================elements.xml
http://schemas.microsoft.com/sharepoint/"> ============================feature.xml=================

DocumentCounterWebPart

using System;using System.Runtime.InteropServices;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Serialization;using Microsoft.SharePoint.Administration;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using Microsoft.SharePoint.WebPartPages;using System.Collections.Generic;using System.Data;using System.Web.UI.HtmlControls;using System.Text;namespace DocumentCounter{ [Guid("97c4024e-90cc-43a0-b635-4dced2b5276b")] public class DocumentCounter : Microsoft.SharePoint.WebPartPages.WebPart { int countDocList = 0; int totalItemcount = 0; public DocumentCounter() { this.ExportMode = WebPartExportMode.All; } /// /// Create all your controls here for rendering. /// Try to avoid using the RenderWebPart() method. /// protected override void CreateChildControls() { SPSite rootSite = SPContext.Current.Site; SPWebApplication webApp = rootSite.WebApplication; SPSecurity.RunWithElevatedPrivileges(delegate() { string sTitel, sUrl, sRelUrl; for (int i = 0; i < href="http://dha02202-mosd05:500/orgs/30018526/30002982">http://dha02202-mosd05:500/orgs/30018526/30002982") try { using (SPSite site = webApp.Sites[i]) { //Response.Write(webApp.Sites[i] + "
"); for (int j = 0; j < web =" site.AllWebs[j])" web =" site.AllWebs[j];" isrootweb ="=" lists =" web.Lists;"> 0) { foreach (SPList list in lists) { try { #region Calculate Count & Total //**********DocumentLibrary**********/// if (list.BaseTemplate == SPListTemplateType.DocumentLibrary) { countDocList += list.ItemCount; totalItemcount += 1; } #endregion end start } catch { continue; } finally { site.Dispose(); } } // foreach } //if } } //if root element count //else part { //top level site and subsites URL SPWebCollection sites = web.Webs; foreach (SPWeb subSite in sites) { SPListCollection lists = subSite.Lists; foreach (SPList list in lists) { #region Count & Total try { //**********DocumentLibrary**********/// if (list.BaseTemplate == SPListTemplateType.DocumentLibrary) { countDocList += list.ItemCount; totalItemcount += 1; } subSite.Dispose(); } // try catch { continue; } finally { site.Dispose(); subSite.Dispose(); } #endregion } // for } } web.Dispose(); } sTitel = site.RootWeb.Title; sUrl = site.RootWeb.Url; sRelUrl = site.RootWeb.ServerRelativeUrl; } } // try catch { continue; } } }); base.CreateChildControls(); } protected override void Render(HtmlTextWriter writer) { writer.Write(""); writer.Write(""); base.Render(writer); } }}

DiscussionListSelectorWebPart

using System;using System.Collections;using System.Collections.Generic;using System.Security.Permissions;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using System.Xml.Serialization;using System.Data;using System.Web.UI.HtmlControls;using System.Runtime.InteropServices;using DiscussionListSelector.WebPartCode;
namespace DiscussionListSelector{ [Guid("bbabc7fa-982c-4d13-81f8-2165eeacaa61")] public class DiscussionListSelector : Microsoft.SharePoint.WebPartPages.WebPart { private CustomValidator validator; protected LiteralControl openEditorPartControl; protected HtmlTable htmTbl; private Guid guidList; private string selectedWebUrl; private string ItmChkBox; SPGridView grdView; private ObjectDataSource gridDS; // public DataTable newtbl = new DataTable();
#region Properties
public SPWeb SelectedWeb { get { if (string.IsNullOrEmpty(SelectedWebUrl)) { return SPContext.Current.Web; } else { SPWeb currentWeb;
try { currentWeb = new SPSite(SelectedWebUrl).OpenWeb(); if (currentWeb.DoesUserHavePermissions(SPBasePermissions.Open)) { return currentWeb; } else { return null; } } catch (Exception) { return null; } } } }
private SPList SelectedCheckList { get { if (guidList != Guid.Empty) { if (SelectedWeb != null) { return this.SelectedWeb.Lists[this.guidList]; } else { return null; } } else { return null; } } }

[Personalizable(PersonalizationScope.Shared), WebBrowsable(false), WebDisplayName("Selected Web URL")] public string SelectedWebUrl { get { return this.selectedWebUrl; } set { this.selectedWebUrl = value; } }
[Personalizable(PersonalizationScope.Shared), WebBrowsable(false), WebDisplayName("Selected Itme Cheked Box value"), WebDescription("Selected Itme Cheked Box value")] public string SelectedItmChkBox { get { if (String.IsNullOrEmpty(ItmChkBox)) { return string.Empty; } else { return ItmChkBox; } } set { ItmChkBox = value; } } [Personalizable(PersonalizationScope.Shared), WebBrowsable(false), WebDisplayName("ListName"), WebDescription("ListName Property")] public string ListGuid { get { if (guidList == Guid.Empty) { return String.Empty; } else { return guidList.ToString(); } }
set { if (string.IsNullOrEmpty(value)) { guidList = Guid.Empty; } else { guidList = new Guid(value); } } }
#endregion
public override EditorPartCollection CreateEditorParts() { ArrayList editorArray = new ArrayList();
if (this.EffectiveStorage == Microsoft.SharePoint.WebPartPages.Storage.Shared) {
DiscussionListSelectorEditPart editorPart2 = new DiscussionListSelectorEditPart(); editorPart2.ID = this.ID + "_editorPart1"; editorArray.Add(editorPart2); }
EditorPartCollection editorParts = new EditorPartCollection(editorArray); return editorParts; }
public DiscussionListSelector() { this.ExportMode = WebPartExportMode.All; }
public override void RenderControl(System.Web.UI.HtmlTextWriter writer) {
grdView.DataBind(); EnsureChildControls(); try { base.Render(writer); } catch (Exception exception) { writer.WriteLine("The following error occurred in this Web Part: {0}.\nPlease contact your administrator for further assistance.", exception.Message); } }
protected override void CreateChildControls() { try {
SPSecurity.RunWithElevatedPrivileges(delegate() { validator = new CustomValidator(); validator.ID = "validator"; validator.IsValid = true; validator.ErrorMessage = String.Empty; validator.Display = ValidatorDisplay.Dynamic; Controls.Add(validator);
const string GRIDID = "grid"; const string DATASOURCEID = "gridDS";
gridDS = new ObjectDataSource(); gridDS.ID = DATASOURCEID; gridDS.SelectMethod = "SelectData"; gridDS.TypeName = this.GetType().AssemblyQualifiedName; gridDS.ObjectCreating += new ObjectDataSourceObjectEventHandler(gridDS_ObjectCreating); this.Controls.Add(gridDS);
grdView = new SPGridView(); grdView.ID = "MyGridView"; grdView.AutoGenerateColumns = false; grdView.EmptyDataText = "There are no Content Items";
BoundField col = new BoundField(); col.DataField = "RowID"; //"Discussion Icon"; col.HeaderText = "Discussion Icon"; col.HeaderStyle.CssClass = "ms-vh2"; col.HtmlEncode = false; grdView.Columns.Add(col); HyperLinkField hLinkCol = new HyperLinkField();
hLinkCol.DataTextField = "Name"; hLinkCol.HeaderText = "Name"; grdView.Columns.Add(hLinkCol);
BoundField colItem = new BoundField(); colItem.DataField = "Items"; colItem.HeaderText = "Items"; colItem.HeaderStyle.CssClass = "ms-vh2"; colItem.HtmlEncode = false; grdView.Columns.Add(colItem);
col = new BoundField(); col.DataField = "Last Modified"; col.SortExpression = "Last Modified"; col.HeaderText = "Last Modified"; grdView.Columns.Add(col);
grdView.AllowSorting = true; grdView.AllowFiltering = true; grdView.FilterDataFields = ",Name,"; //grdView.FilterDataFields = ",LoginName,Name,Group"; grdView.FilteredDataSourcePropertyName = "FilterExpression"; grdView.FilteredDataSourcePropertyFormat = "{1} LIKE '{0}'"; grdView.AllowPaging = false; grdView.AutoGenerateColumns = false; grdView.ID = GRIDID; grdView.DataSourceID = gridDS.ID;
// to persists filter Expression. when a sort action is performed
if (SelectedWeb == null) { validator.IsValid = false; return; } //SelectedCheckList if (SelectedWeb == null) { openEditorPartControl = new LiteralControl( string.Format( "Use the web part's Tool Pane to adjust its settings.", 1, 129, this.ID ) ); this.Controls.Add(openEditorPartControl); } else { // if (SelectedWebUrl != null) { SelectData();
} string url = String.Empty; grdView.RowDataBound += new GridViewRowEventHandler(grdView_RowDataBound);
System.Web.HttpRequest req = System.Web.HttpContext.Current.Request; if (req.Form["__CALLBACKID"] == null req.Form["__CALLBACKPARAM"] == null !req.Form["__CALLBACKID"].EndsWith("grid")) //GRIDID Group { if (ViewState["FilterExpression"] != null) gridDS.FilterExpression = (string)ViewState["FilterExpression"];
}

} }); Controls.Add(grdView); //grdView.DataBind(); base.CreateChildControls(); } catch (Exception exc) { validator.IsValid = false; ; validator.ErrorMessage = exc.Message; } }
//use a standard DataTable as the data source for our SPGridView //which we’ll bind to an ObjectDataSource(found in System.Web.UI.WebControls). public DataTable SelectData() {
DataTable newtbl = new DataTable(); SPSite MySite = SPContext.Current.Site; SPWeb CurrentSite = MySite.RootWeb; newtbl.Columns.Add("RowID", typeof(string)); newtbl.Columns.Add("Name", typeof(string)); newtbl.Columns.Add("Items", typeof(string)); newtbl.Columns.Add("Last Modified", typeof(string)); DataRow row; //SelectedItmChkBox
if (SelectedItmChkBox != "") //SelectedItmChkBox != null { string[] selectedDiscuLst = SelectedItmChkBox.Split(new char[] { ',' });//,new char()) int i; for (i = 0; i < selectedDiscuLst.Length; i++) { string sListName = selectedDiscuLst[i].Trim(); SPList forum = (SPList)CurrentSite.Lists[sListName]; int cin = forum.ItemCount; row = newtbl.Rows.Add(); row["RowID"] = forum.ID; // tbl.Rows[i]["Id"]; row["Name"] = forum.Title;// tbl.Rows[i]["Name"]; row["Items"] = cin; row["Last Modified"] = forum.LastItemModifiedDate; } } newtbl.AcceptChanges();
return newtbl; }
private void gridDS_ObjectCreating(object sender, ObjectDataSourceEventArgs e) { e.ObjectInstance = this; }
// protected void RadGridPubDocs_ItemDataBound(object sender, GridItemEventArgs e) //{ // try // { // if (e.Item.ItemType == GridItemType.Item e.Item.ItemType == GridItemType.AlternatingItem e.Item.ItemType == GridItemType.SelectedItem) // { // GridDataItem item = (GridDataItem)e.Item; // if (((DataRowView)item.DataItem).Row.Table.Columns.Contains("FILE_EXT")) // { // DataRowView dr = (DataRowView)dataItem.DataItem; // Image img = (Image)dataItem["ImageColumnUniqueName"].Controls[0]; // // set the image url by concatenating the image path with the datarowview values // img.ImageUrl = "~/Images/" + dr["FILE_EXT"].ToString(); // } // .....
// { // try // { // if (e.Item.ItemType == GridItemType.Item e.Item.ItemType == GridItemType.AlternatingItem e.Item.ItemType == GridItemType.SelectedItem) // { // GridDataItem item = (GridDataItem)e.Item; // if (((DataRowView)item.DataItem).Row.Table.Columns.Contains("FILE_EXT")) // { // // set the image here // }

protected void grdView_ItemDataBound(object sender, GridItemEventArgs e) { if (e.Item.ItemType == GridItemType.Item) { GridDataItem item = (GridDataIte)e.Item;
if (((DataRowView)item.DataItem).Row.Table.Columns.Contains("FILE_EXT")) { DataRowView dr = (DataRowView)dataItem.DataItem; Image img = (Image)dataItem["Discussion Icon"].Controls[0]; // set the image url by concatenating the image path with the datarowview values img.ImageUrl = "~/Images/" + dr["FILE_EXT"].ToString(); } } }
protected void grdView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DataRowView d = (DataRowView)e.Row.DataItem; string surl = d["Name"].ToString();

//TableCellCollection myCells = e.Row.Cells; HyperLink planLink = new HyperLink(); planLink = (HyperLink)e.Row.Cells[0].Controls[0]; planLink.ImageUrl = "~/Images/" + "itdisc.gif";

HyperLink hc = new HyperLink(); hc = (HyperLink)e.Row.Cells[1].Controls[0]; SPSite spsiteurl = SPContext.Current.Site; // string surl = spsiteurl.Url + "/" + SelectedList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;// +"?ID=" + rowIdNo;//dtr["ID"];
hc.NavigateUrl = spsiteurl.Url + "/Lists/" + surl;
//Image img = e.Row.FindControl("RowID") as Image; //img.ImageUrl = "~/Images/" + "itdisc.gif";
}
}
}
}

==================DiscussionListSelectorEditPart.cs ============

using System;using System.Collections.Generic;using System.Security.Permissions;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;
namespace DiscussionListSelector.WebPartCode{ class DiscussionListSelectorEditPart:EditorPart { private CustomValidator validator; //private DropDownList ddlLists; private CheckBoxList chkLst; private Label lblLists, lblWebUrl; private Table tblMain; private Button btnOpenWeb; private TextBox txtWebUrl;
#region Properties // private SPList SelectedList { get { return this.SelectedWeb.Lists[this.SelectedListId]; } }
public SPWeb SelectedWeb { get { if (string.IsNullOrEmpty(txtWebUrl.Text)) { return SPContext.Current.Web; } else { SPWeb webNew; try { webNew = new SPSite(txtWebUrl.Text).OpenWeb();
if (webNew.DoesUserHavePermissions(SPBasePermissions.Open)) { txtWebUrl.Text = webNew.Url; return webNew; } else { validator.IsValid = false; return null; } } catch (Exception exception) { validator.IsValid = false; validator.ErrorMessage = exception.Message; return null; } } } }
private Guid SelectedCheckListId { get { Guid guid = Guid.Empty;
if (ViewState["SelectedCheckListId"] == null) { guid = Guid.Empty; } else { guid = new Guid((string)ViewState["SelectedCheckListId"]); }
return guid; } set { ViewState["SelectedCheckListId"] = value.ToString(); } }

//private Guid SelectedListId //{ // get // { // Guid guid = Guid.Empty;
// if (ViewState["SelectedListId"] == null) // { // guid = Guid.Empty; // } // else // { // guid = new Guid((string)ViewState["SelectedListId"]); // }
// return guid; // } // set { ViewState["SelectedListId"] = value.ToString(); } //} public string SelectedWebUrl { get { string webUrl = String.Empty;
if (ViewState["SelectedWebUrl"] == null) { webUrl = String.Empty; } else { webUrl = (string)ViewState["SelectedWebUrl"]; }
return webUrl; } set { ViewState["SelectedWebUrl"] = value.ToString(); } }
protected string SelectedItmChkBox { get { string ItmChkBox = String.Empty;
if (ViewState["SelectedItmChkBox"] == null) { ItmChkBox = String.Empty; } else { ItmChkBox = (string)ViewState["SelectedItmChkBox"]; }
return ItmChkBox; } set { ViewState["SelectedItmChkBox"] = value.ToString(); } }
#endregion
public override void SyncChanges() { DiscussionListSelector parentWebPart = (DiscussionListSelector)this.WebPartToEdit;
if (!string.IsNullOrEmpty(parentWebPart.SelectedWebUrl)) { SelectedWebUrl = parentWebPart.SelectedWebUrl; }
if (parentWebPart.ListGuid != String.Empty) { //SelectedListId = new Guid(parentWebPart.ListGuid); } if (parentWebPart.SelectedItmChkBox != string.Empty parentWebPart.SelectedItmChkBox != "") { SelectedItmChkBox = parentWebPart.SelectedItmChkBox; string[] selectedDiscuLst = SelectedItmChkBox.Split(new char[] { ',' });//,new char()) int i; for (i = 0; i < selectedDiscuLst.Length; i++) //foreach (string sDissLst in selectedDiscuLst) { if (chkLst != null) { for (int j = 0; j < chkLst.Items.Count; j++) { if (chkLst.Items[j].Text == selectedDiscuLst[i]) { chkLst.Items[j].Selected = true; } } }
} }
}
public override bool ApplyChanges() {
DiscussionListSelector parentWebPart = (DiscussionListSelector)this.WebPartToEdit;
// Send the custom text to the Web Part. //if (ddlLists.SelectedValue != String.Empty) //{ // parentWebPart.ListGuid = ddlLists.SelectedValue; //} //else //{ // parentWebPart.ListGuid = String.Empty; //} parentWebPart.SelectedWebUrl = txtWebUrl.Text; SelectedItmChkBox = string.Empty; //CheckBoxList chkBoxList = sender as CheckBoxList; foreach (ListItem item in chkLst.Items) if (item.Selected) SelectedItmChkBox += "," + item;
if (SelectedItmChkBox.Length == 1 SelectedItmChkBox == "") SelectedItmChkBox = string.Empty; else { SelectedItmChkBox = SelectedItmChkBox.Remove(0, 1); } // ViewState["SelectedItmChkBox"] = SelectedItmChkBox;
parentWebPart.SelectedItmChkBox = SelectedItmChkBox; return true; }
protected override void CreateChildControls() { //CustomListViewWebPart parentWebPart = (CustomListViewWebPart)this.WebPartToEdit; validator = new CustomValidator(); validator.ID = "customValidator"; validator.IsValid = true; validator.ErrorMessage = String.Empty; validator.Display = ValidatorDisplay.Dynamic; chkLst = new CheckBoxList(); chkLst.ID = "chkLists"; chkLst.Visible = true; chkLst.AutoPostBack = true; chkLst.SelectedIndexChanged += new EventHandler(chkLst_SelectedIndexChanged);
// ddlLists = new DropDownList(); // ddlLists.ID = "ddlLists"; // ddlLists.Visible = true; // ddlLists.Enabled = true; //// ddlLists.AutoPostBack = true; // //ddlLists.SelectedIndexChanged += new EventHandler(OnListsChange);
// //ddlLists.SelectedItem = ListSelectionMode.Multiple;
lblLists = new Label(); lblLists.ID = "lblLists"; lblLists.Visible = true; lblLists.Text = "Lists:";
lblWebUrl = new Label(); lblWebUrl.Text = "Site URL:"; lblWebUrl.ID = "lblWebURL";
txtWebUrl = new TextBox(); txtWebUrl.ID = "txtWebUurl"; txtWebUrl.CssClass = "ms-input"; txtWebUrl.Width = Unit.Pixel(180); txtWebUrl.Text = SelectedWebUrl;
btnOpenWeb = new Button(); btnOpenWeb.Text = "Open"; btnOpenWeb.ID = "btnOpenWeb"; btnOpenWeb.Click += new EventHandler(btnOpenWeb_Click);
TableRow trTop = new TableRow(); TableCell tcTop = new TableCell(); tcTop.ColumnSpan = 2; tcTop.Controls.Add(validator); trTop.Cells.Add(tcTop);
TableRow trSelectWeb = new TableRow(); TableCell tcSelectWebLabel = new TableCell(); tcSelectWebLabel.Controls.Add(lblWebUrl); tcSelectWebLabel.Wrap = false; trSelectWeb.Cells.Add(tcSelectWebLabel); TableCell tcSelectedWebControl = new TableCell(); tcSelectedWebControl.Controls.Add(txtWebUrl); tcSelectedWebControl.Controls.Add(new LiteralControl(" ")); tcSelectedWebControl.Controls.Add(btnOpenWeb); //tcSelectedWebControl.Controls.Add(txtMaxLmt);
trSelectWeb.Cells.Add(tcSelectedWebControl);
TableRow trLists = new TableRow(); TableCell tcListsLabel = new TableCell(); tcListsLabel.Controls.Add(lblLists); tcListsLabel.Wrap = false; trLists.Cells.Add(tcListsLabel); TableCell tcListsControl = new TableCell(); //tcListsControl.Controls.Add(ddlLists); //trLists.Cells.Add(tcListsControl);
TableRow trCheckLists = new TableRow(); TableCell tccheckListsLabel = new TableCell(); tccheckListsLabel.Controls.Add(lblLists); tccheckListsLabel.Wrap = false; trCheckLists.Cells.Add(tccheckListsLabel);
TableCell tcCheckListsControl = new TableCell(); tcCheckListsControl.Controls.Add(chkLst); trCheckLists.Cells.Add(tcCheckListsControl);

tblMain = new Table(); tblMain.Rows.Add(trSelectWeb); tblMain.Rows.Add(trTop); // tblMain.Rows.Add(trLists); tblMain.Rows.Add(trCheckLists); // tblMain.Rows.Add(trMaxMoreLimitControl); //tblMain.Rows.Add(trFilterValue); try { Controls.Add(tblMain); PopulateCheckBox(); base.CreateChildControls(); } catch (Exception exc) { validator.IsValid = false; ; validator.ErrorMessage = exc.Message; } }
private void btnOpenWeb_Click(object sender, EventArgs e) { SelectedWebUrl = txtWebUrl.Text; PopulateCheckBox(); }
private void PopulateCheckBox() { if( chkLst != null ) chkLst.Items.Clear(); ListItem newItem; if (SelectedWeb == null) { chkLst.Enabled = false; return; } else { chkLst.Enabled = true; }
if (SelectedWebUrl != "") // txtWebUrl.Text { foreach (SPList item in this.SelectedWeb.Lists) { if (item.BaseTemplate == SPListTemplateType.DiscussionBoard) { if (item.Hidden == false) { newItem = new ListItem(); newItem.Text = item.Title; newItem.Value = item.ID.ToString(); //// if (this.SelectedListId == item.ID) // { // newItem.Selected = true; // }
//ddlLists.Items.Add(newItem); chkLst.Items.Add(newItem); } } }
//if (ddlLists.SelectedItem == null) if (chkLst == null) { //newItem = new ListItem(); //newItem.Text = String.Empty; //newItem.Value = String.Empty; //newItem.Selected = true; ////ddlLists.Items.Add(newItem); //chkLst.Items.Add(newItem); } else { //OnListsChange(ddlLists, new EventArgs()); chkLst_SelectedIndexChanged(chkLst, new EventArgs());
} } }
#region event handlers
private void chkLst_SelectedIndexChanged(object sender, EventArgs e) { //SelectedCheckListId = new Guid(chkLst.SelectedValue); // SPList currentList = SelectedList;
SelectedItmChkBox = string.Empty; CheckBoxList chkBoxList = sender as CheckBoxList; foreach (ListItem item in chkBoxList.Items) if (item.Selected ) SelectedItmChkBox += "," + item; if (SelectedItmChkBox.Length == 1 SelectedItmChkBox=="") SelectedItmChkBox = string.Empty; else { SelectedItmChkBox = SelectedItmChkBox.Remove(0, 1); } ViewState["SelectedItmChkBox"] = SelectedItmChkBox; } #endregion
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer) {
//lblWebUrl.RenderControl(writer); //txtWebUrl.RenderControl(writer); //btnOpenWeb.RenderControl(writer); //tblMain.RenderControl(writer); //writer.Write("

"); //chkLst.RenderControl(writer); //writer.Write("
"); base.RenderContents(writer);
}
}}

LastestCoPAnnunser

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
//using System.Collections.Generic;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Web.UI.WebControls;

namespace CoPAnnouncer
{
[Guid("0c6833bc-aa4a-4b77-b2c6-e6d81e263cec")]
public class CoPAnnouncer : Microsoft.SharePoint.WebPartPages.WebPart
{
//private bool _error = false;
//private string _myProperty = null;
public DataTable tbl;
int countDocList = 0;
Label lblName = new Label();
HyperLink hlnk = new HyperLink();


//[Personalizable(PersonalizationScope.Shared)]
//[WebBrowsable(true)]
//[System.ComponentModel.Category("My Property Group")]
//[WebDisplayName("MyProperty")]
//[WebDescription("Meaningless Property")]
//public string MyProperty
//{
// get
// {
// if (_myProperty == null)
// {
// _myProperty = "CoP Announcer";
// }
// return _myProperty;
// }
// set { _myProperty = value; }
//}


public CoPAnnouncer()
{
this.ExportMode = WebPartExportMode.All;
}

///
/// Create all your controls here for rendering.
/// Try to avoid using the RenderWebPart() method.
///

///
protected override void Render(HtmlTextWriter writer)
{
///Creating the main table and adding step by step rows
///along with column and rendering the controls within the
///columns.
writer.Write("
Total Documents in ShareK : " + countDocList + "
"); // width='100%'
writer.Write("");
writer.Write("
Total Number of CoPs : " + countDocList + "
Latest CoP " + lblName.Text + "
");
base.Render(writer);
}

protected override void CreateChildControls()
{
DataTable tbl = new DataTable();
DataRow row;
tbl.Columns.Add("UrlName", typeof(string));
tbl.Columns.Add("Url", typeof(string));
tbl.Columns.Add("LastDate", typeof(DateTime));
// SPWebApplication webApp = SPContext.Current.Site.WebApplication;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWebApplication webApp = SPContext.Current.Site.WebApplication;
// SPSiteCollection siteCollections = webApplication.Sites;
for (int i = 0; i < webApp.Sites.Count; i++)
{
try
{
SPSite site = webApp.Sites[i];
string[] sSite = site.ServerRelativeUrl.Split(new char[] { '/' });
if (sSite[1] == "cops")
{
countDocList++;
row = tbl.Rows.Add();
row["UrlName"] = site.RootWeb.Title;
row["Url"] = site.Url;
row["LastDate"] = site.RootWeb.Created;
//Convert.ToDateTime(webApp.Sites[i].WebApplication.LastContentModifiedDate);
}
}
catch
{
continue;
}
}
});

tbl.AcceptChanges();
DataView dv = new DataView();
dv = tbl.DefaultView;
dv.Table.Columns["LastDate"].DataType = Type.GetType("System.DateTime");
dv.RowFilter = "LastDate = Max(LastDate)";
DataTable newtbl = new DataTable();
newtbl = dv.ToTable();
lblName.Text = newtbl.Rows[0][0].ToString();
hlnk.Text = newtbl.Rows[0][1].ToString();
base.CreateChildControls();
}




}
}

ContentMangerAdminRightsCanAddUsers

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using Microsoft.SharePoint.WebPartPages;using System.Collections.Generic;using System.Text;using Microsoft.SharePoint.Administration;using System.Xml;using System.Data.SqlClient;using System.Collections;using System.DirectoryServices;
namespace Sharek{ public partial class ContentManagementAdmin : System.Web.UI.Page { string sLoginName = null;
protected void Page_Load(object sender, EventArgs e) { LblMsg.Text = ""; LblMsg.Text = "Login User " + sLoginName; }
protected override void OnPreInit(EventArgs e) { base.OnPreInit(e);
//if (!HttpContext.Current.User.Identity.IsAuthenticated) //{ // //re-direct the user to log-in page and authenticate // Response.Redirect("/_layouts/accessdenied.aspx"); //} //else { sLoginName = HttpContext.Current.User.Identity.Name; // Added NewLy to get only login username sLoginName = ExtractUserName(sLoginName); // Response.Write(sLoginName);
if (!IsExistInAD(sLoginName)) { Response.Write(" User has no access "); } //Check user against AD group name "HelpDesk" ArrayList UserList = new ArrayList(); UserList = GetADGroupUsers("CACADeDocShareKSiteCollectionAdmin"); // UserList = GetADGroupUsers("CACADeDocShareK"); // UserList = GetADGroupUsers("CACADeDocDivision"); // UserList = GetADGroupUsers("CA/CAD/e-Doc Division"); //UserList = GetADGroupUsers("HelpDesk");
for (int i = 0; i <>"); string value = UserList[i] as string; value.ToUpper().Trim(); sLoginName.ToUpper().Trim(); // Response.Write("
"); // Response.Write("value :- " + value + "
"); // Response.Write("sLoginName :- " + sLoginName); if (value.ToUpper() == sLoginName.ToUpper()) { // LblMsg.Text = "Login User " + sLoginName; return; } } //Response.Write("U DON'T HAVE ACCESS"); Response.Redirect("/_layouts/accessdenied.aspx"); } }
protected void Button1_Click(object sender, EventArgs e) { try { LblMsg.Text = ""; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(TextBox1.Text)) { using (SPWeb subWeb = site.OpenWeb())// .Rootweb { subWeb.AllowUnsafeUpdates = true; SPUser UserId = subWeb.EnsureUser((TextBox2.Text)); string strGroup = null; foreach (SPGroup mySPGroup in subWeb.Groups) { foreach (SPRole mySPRole in mySPGroup.Roles) { if (mySPRole.Name == "Content Manager") { strGroup = mySPGroup.ToString(); } } } if (strGroup != null) { SPGroup spGroup = subWeb.SiteGroups[strGroup]; if (!IsUserAuthorized(strGroup, UserId)) { spGroup.AddUser(UserId); //You need to break role inheritence if you want to assign unique permission to subsite if (!subWeb.HasUniqueRoleAssignments) subWeb.BreakRoleInheritance(true); SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup); roleAssignment.RoleDefinitionBindings.Add(subWeb.RoleDefinitions["Content Manager"]); subWeb.RoleAssignments.Add(roleAssignment); subWeb.Update(); subWeb.AllowUnsafeUpdates = false; LblMsg.Text = "User " + UserId + " Added Succesfully"; } else { LblMsg.Text = "User " + UserId + " Already available"; } } } } }); } catch (Exception err) { // throw err; LblMsg.Text = err.Message; } } protected void Button2_Click(object sender, EventArgs e) { try { LblMsg.Text = ""; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite sps = new SPSite(TextBox1.Text)) { using (SPWeb spWeb = sps.OpenWeb()) { SPUser UserId = spWeb.EnsureUser((TextBox2.Text)); spWeb.AllowUnsafeUpdates = true; string strGrpName = null; foreach (SPGroup mySPGroup in spWeb.Groups) { //spWeb.CurrentUser. foreach (SPRole mySPRole in mySPGroup.Roles) { if (mySPRole.Name == "Content Manager") { //Retrieving all the user groups in the site/web SPGroupCollection userGroups = UserId.Groups; strGrpName = mySPGroup.ToString(); if (IsUserAuthorized(strGrpName, UserId) == true) { //Loops through the grops and check if the user is part of given group or not. foreach (SPGroup group in userGroups) { //Checking the group if (group.Name.Contains(strGrpName)) { strGrpName = mySPGroup.ToString(); mySPRole.Groups[strGrpName].RemoveUser(UserId); LblMsg.Text = "User " + UserId + " Remove Succesfully"; } } } else { LblMsg.Text = "User " + UserId + " could not be found"; } } } } spWeb.AllowUnsafeUpdates = false; } } }); } catch (Exception err) { LblMsg.Text = err.Message; } }
protected void Button3_Click(object sender, EventArgs e) { TextBox2.Text = ""; TextBox1.Text = ""; }

///// ///// Establish identity (principal) and culture for a thread. ///// //public static void SetCultureAndIdentity() //{ // AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); // WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal; // WindowsIdentity identity = (WindowsIdentity)principal.Identity; // System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); //}
public bool IsUserAuthorized(string groupName, SPUser currentUser) { SPGroupCollection userGroups = currentUser.Groups; //Loops through the grops and check if the user is part of given group or not. foreach (SPGroup group in userGroups) { //Checking the group if (group.Name.Contains(groupName)) return true; } return false; }
ArrayList GetADGroupUsers(string groupName) { ///////////////////
////SetCultureAndIdentity();

////////////////
SearchResult result; DirectorySearcher search = new DirectorySearcher(); // search.Filter = String.Format("(cn=)", groupName); // search.Filter = String.Format("(cn={0})", groupName); // search.Filter = "(&objectClass=" + groupName + ")"; search.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; // search.Filter = "(&(objectClass=group) (cn={0})" + groupName + "))"; search.PropertiesToLoad.Add("member"); result = search.FindOne(); ArrayList userNames = new ArrayList(); if (result != null) {
for (int counter = 0; counter < user =" (string)result.Properties[" usern =" user.Split(',');" user =" userN[0].Replace(" cn=", " user =" userN[2].Replace(" dc=", " cn=", "> --USER N AF SPLIT--
"); //Response.Write(userN); userNames.Add(user);
} } // Response.Write(result + " -:USRR Name not Found. COUNT IS " + userNames.Count + " grp name:- " + groupName); return userNames;
}
string ExtractUserName(string path) { string[] userPath = path.Split(new char[] { '\\' }); return userPath[userPath.Length - 1]; } bool IsExistInAD(string loginName) { string userName = ExtractUserName(loginName); DirectorySearcher search = new DirectorySearcher(); search.Filter = String.Format("(SAMAccountName={0})", userName); search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne();
if (result == null) { return false; } else { return true; } }
}}

-=======================-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
<%@ Page Language="C#" AutoEventWireup="true" Debug="true" CodeFile="ContentManagementAdmin.aspx.cs" Inherits="Sharek.ContentManagementAdmin" %>





Content Mangement Rights assign Application

































Header

*

*

     







Friday, January 1, 2010

Application Wise Count(site collection) Announcements,No. Document Librarys, Tasks,calender

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Xml;
using System.Data.SqlClient;
using System.Security.Principal;
using System.IO;
using System.Diagnostics;
public partial class ApplicationWiseStatisstics : System.Web.UI.Page
{
public static string ListName, sDocumentLibrary;
protected void Page_Load(object sender, EventArgs e)
{
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
SPSite rootSite = SPContext.Current.Site;
SPWebApplication webApp = rootSite.WebApplication;
//SPWebApplicationCollection webApplicationCol = SPWebService.ContentService.WebApplications;
DataTable tbl = new DataTable();
tbl.Columns.Add("Title", typeof(string));
tbl.Columns.Add("Url", typeof(string));
tbl.Columns.Add("DocumentCount", typeof(string));
tbl.Columns.Add("TotDocItemCnt", typeof(string));
tbl.Columns.Add("Announcements", typeof(string));
tbl.Columns.Add("TotItemAnnouncements", typeof(string));
tbl.Columns.Add("Links", typeof(string));
tbl.Columns.Add("TotItemLinks", typeof(string));
tbl.Columns.Add("Tasks", typeof(string));
tbl.Columns.Add("TotItemTasks", typeof(string));
tbl.Columns.Add("PictureLibrary", typeof(string));
tbl.Columns.Add("TotItemPictureLibrary", typeof(string));
tbl.Columns.Add("Posts", typeof(string));
tbl.Columns.Add("TotItemPosts", typeof(string));
DataRow row;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//foreach (SPWebApplication webApp in webApplicationCol)
{ //Web application name
for (int i = 0; i < webApp.Sites.Count; i++)
// if (webApp.Sites.Count <= 50)
{
if (webApp.Sites[i].Url != "http://dha02202-mosd05:500/orgs/30018526/30002982")
{

SPSite site = webApp.Sites[i];

// Response.Write(webApp.Sites[i].Url + " webApp.Sites.Names
");

int countDocList = 0;
int totalItemcount = 0;
//int countDocList = 0;
int countAnnouncements = 0;
int countTask = 0;
int countLink = 0;
int countCalender = 0;
int countImg = 0;
int countPost = 0;
int totAnnouncount = 0;
int totTaskcount = 0;
int totLinkcount = 0;
int totCalendercount = 0;
int totPostcount = 0;
int totImgcount = 0;
string lastItemIdOnPage = null; // Page position.
// Response.Write(site.AllWebs.Count + " WEB COUNT
");
for (int j = 0; j < site.AllWebs.Count; j++)
{
SPWeb web = site.AllWebs[j];
SPWebCollection sites = web.Webs;

if (sites.Count > 0)
{
// Response.Write(sites.Count + " sites.Count
");

foreach (SPWeb subSite in sites)
{
try
{
// Response.Write(subSite.Title + "
");
//SPWeb rootWeb = site.RootWeb;
SPListCollection lists = subSite.Lists;
// SPListCollection lists = web.Site.RootWeb.Lists;
if (lists.Count > 0)
{
// Response.Write(lists.Count + " lists.Count
");
foreach (SPList list in lists)
{
//**********DocumentLibrary**********///
//if (List.BaseType == SPBaseType.DocumentLibrary && List.BaseTemplate == SPListTemplateType. .DocumentLibrary)

if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)
{
countDocList += list.ItemCount;
totalItemcount += 1;
}
//**********Announcement**********///
if (list.BaseTemplate == SPListTemplateType.Announcements)
{
countAnnouncements += list.ItemCount;
totAnnouncount += 1;
}
//**********Links **********///
if (list.BaseTemplate == SPListTemplateType.Links)
{
countLink += list.ItemCount;
totLinkcount += 1;
}
//**********Task **********///
if (list.BaseTemplate == SPListTemplateType.Tasks)
{
countTask += list.ItemCount;
totTaskcount += 1;
}
//**********Images PictureLibrary **********///
if (list.BaseTemplate == SPListTemplateType.PictureLibrary)
{
countImg += list.ItemCount;
totImgcount += 1;
}
//*********Events blogs**********///
//119 Wiki Page library
if (list.BaseTemplate == SPListTemplateType.Events)//SPListTemplateType.Posts)
{
countPost += list.ItemCount;
totPostcount += 1;
}
subSite.Dispose();
}
}
//subSite.Dispose();
}//if check
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
site.Dispose();
// web.Dispose();
subSite.Dispose();
}
}
} //if
web.Dispose();

}// for
row = tbl.Rows.Add();
row["Title"] = site.RootWeb.Title;
row["Url"] = site.RootWeb.Url;
row["DocumentCount"] = countDocList;
row["TotDocItemCnt"] = totalItemcount;
row["Announcements"] = countAnnouncements;
row["TotItemAnnouncements"] = totAnnouncount;
row["Links"] = countLink;
row["TotItemLinks"] = totLinkcount;
row["Tasks"] = countTask;
row["TotItemTasks"] = totTaskcount;
row["PictureLibrary"] = countImg;
row["TotItemPictureLibrary"] = totImgcount;
row["Posts"] = countPost;
row["TotItemPosts"] = totPostcount;
site.Dispose();

} //
}
}
});
tbl.AcceptChanges();
gdView.AutoGenerateColumns = false;
gdView.Visible = true;
gdView.DataSource = tbl;
gdView.DataBind();
gdView.PageIndex = 0;
wic.Undo();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void gdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdView.PageIndex = e.NewPageIndex;
gdView.DataBind();
}
}
=======================================================

<%@ Page Language="C#" AutoEventWireup="true" Debug="true" CodeFile="ApplicationWiseStatisstics.aspx.cs" Inherits="ApplicationWiseStatisstics" %>



Application Wise Count





Application Wise Count


AutoGenerateColumns="False"
GridLines="None"
AllowPaging="false"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" OnPageIndexChanging="gdView_PageIndexChanging" >






















Hit Count Statistics with Monthly Usage and Site Owner List

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Xml;
using System.Data.SqlClient;

public partial class SiteDetailsOwner : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SPSite rootSite = SPContext.Current.Site;
SPWebApplication webApp = rootSite.WebApplication;
//SPWebApplicationCollection webApplicationCol = SPWebService.ContentService.WebApplications;
DataTable tbl = new DataTable();
tbl.Columns.Add("Id", typeof(string));
tbl.Columns.Add("Title", typeof(string));
tbl.Columns.Add("Url", typeof(string));
tbl.Columns.Add("RelativeUrl", typeof(string));
//tbl.Columns.Add("ContentDB", typeof(string));
//tbl.Columns.Add("NoSubSites", typeof(string));
//tbl.Columns.Add("Size", typeof(string));
//tbl.Columns.Add("Bandwidth", typeof(string));
//tbl.Columns.Add("Hits", typeof(string));
//tbl.Columns.Add("Visits", typeof(string));
tbl.Columns.Add("MonthlyUsage", typeof(string));
tbl.Columns.Add("NoUsersinRoot", typeof(string));
tbl.Columns.Add("OwnerGrpUser", typeof(string));
DataRow row;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//commented
// foreach (SPWebApplication webApp in webApplicationCol)
{ //Web application name
for (int i = 0; i < finaltotal =" 0;" site =" webApp.Sites[i];" j =" 0;" web =" site.AllWebs[j];" sites =" web.Webs;" itot =" 0;" row =" tbl.Rows.Add();" itot =" PopulateUserUsageData(subSite);" autogeneratecolumns =" false;" visible =" true;" datasource =" tbl;" pageindex =" 0;" pageindex =" e.NewPageIndex;">
/// //Users who visited the site
///
///
public int PopulateUserUsageData(SPWeb site)
{
int totcount = 0;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
DataTable Dt = new DataTable();
//Users who visited the site
Dt = site.GetUsageData(SPUsageReportType.user, SPUsagePeriodType.lastMonth);
totcount = 0;
if (Dt != null)
{
foreach (DataRow r in Dt.Rows) // Loop over the items.
{
int itemCount = 0;
itemCount = Convert.ToInt32(r["Total Hits"]);
totcount += itemCount;
}
}
});
return totcount;
}
public String SelectData(SPWeb sWeb)
{
string sName = null;
string sAllUsers = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
foreach (SPGroup Grp in sWeb.Groups)
{
if (Grp.Name == Grp.Owner.ToString())
{
foreach (SPUser singleUser in Grp.Users)
{
sName += singleUser.Name + ",";

}
sAllUsers += sName;
string[] words = sAllUsers.Split(',');
List list = new List();
foreach (string word in words)
{
if (!list.Contains(word))
{
list.Add(word);
}
}
string sspl = string.Join("," + Environment.NewLine, list.ToArray());
//sspl.Remove(sspl.Length - 1, 1);
sspl = sspl.Substring(0, sspl.Length - 3);
sAllUsers = sspl;
}
}
});
return sAllUsers;
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
SPWeb Web = SPContext.Current.Web;
string strUrl =
Web.ServerRelativeUrl + "/_catalogs/masterpage/default.master";
this.MasterPageFile = strUrl;
}
}
======================SiteDetailsOwner.aspx=======================
<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/_layouts/application.master" CodeFile="SiteDetailsOwner.aspx.cs" Inherits="SiteDetailsOwner" %>
<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages,
Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint"
Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities"
Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


AutoGenerateColumns="False" BorderWidth="2" GridLines="Both"
AllowPaging="false"
AlternatingRowStyle-BorderStyle="Solid"
CssClass="mGrid"
PagerStyle-CssClass="pgr" Width="98%"
AlternatingRowStyle-CssClass="alt" OnPageIndexChanging="gdView_PageIndexChanging" >





ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">
Site Hit Count Statistics with Monthly Usage

Tuesday, June 16, 2009

Moss FAQ

There are two ways to create custom webpart-
1. using User control
2. using class library project