public void Page_Load() { try { if (!IsPostBack) { ListItemCollection c = new ListItemCollection(); c.Add(new ListItem("Total Posts", TransitStats.PostsCount.ToString())); c.Add(new ListItem("Total Images", TransitStats.ImagesCount.ToString())); if (!DisqusEnabled) { c.Add(new ListItem("Total Comments", TransitStats.CommentsCount.ToString())); } if (SessionManager.CountersEnabled) { c.Add(new ListItem("Rss Hits", string.Format("{0} since {1}", TransitStats.RssCount.Count, TransitStats.RssCount.Created.ToString("d")))); c.Add(new ListItem("Atom Hits", string.Format("{0} since {1}", TransitStats.AtomCount.Count, TransitStats.AtomCount.Created.ToString("d")))); } grid.DataSource = c; grid.DataBind(); summaryLinks.Visible = SessionManager.CountersEnabled; } } catch (Exception ex) { ReportException(ex); } }
public static void Bind(RadioButtonList rdolst, ListItemCollection list) { foreach (ListItem item in list) { rdolst.Items.Add(item); } }
public static ListItemCollection ExecuteSQL(string sql = "", string text = "", string value = "", List<SqlParameter> parameters = null) { ListItemCollection lic = new ListItemCollection(); using (SqlConnection conn = new SqlConnection(Connection)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { if (parameters != null) { cmd.Parameters.AddRange(parameters.ToArray()); } using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { lic.Add(new ListItem(reader[text].ToString(), reader[value].ToString())); } } } } } return lic; }
protected void Page_Load(object sender, EventArgs e) { var bornCities = new ListItemCollection() { "", "San Salvador", "Aguilares", "Apopa", "Ayutuxtepeque", "Cuscatancingo", "Delgado", "El Paisnal", "Guazapa", "Ilopango", "Mejicanos", "Nejapa", "Panchimalco", "Rosario de Mora", "San Marcos", "San Martín", "Santiago Texacuangos", "Santo Tomás", "Soyapango", "Tonacatepeque", }; personBornCitySelect.DataSource = bornCities; if (!Page.IsPostBack) { personBornCitySelect.DataBind(); } }
public void AddGroupReturnsFalseIfGroupAlreadyExists() { var list = new ListItemCollection<string>(); var toAdd = new List<string> { "Foo", "Bar" }; var toAddSecond = new List<string> { "Foo", "Bar", "Hello" }; list.AddGroup("Bob", toAdd).Should().BeTrue(); list.AddGroup("Bob", toAddSecond).Should().BeFalse(); list.Count.Should().Be(1); list[0].Title.Should().Be("Bob"); list[0].Should().ContainInOrder(toAdd); list[0].Should().OnlyContain(s => toAdd.Contains(s)); list[0].Count.Should().Be(2); }
void OnEnable() { mCollection = new ListItemCollection(); for (int i = 0; i < 20; i++) { mCollection.Add(new LabelListItem("Item " + i.ToString() + " example")); } }
protected void Add_Click(object sender, EventArgs e) { ListItemCollection removeList = new ListItemCollection(); // deselect all items foreach (ListItem item in SelectedMembers.Items) { item.Selected = false; } for (int i = 0; i < AvailableMembers.Items.Count; i++) { ListItem li = AvailableMembers.Items[i]; if (!li.Selected) continue; // check to see if user is already selected IUserActivity attendee = Activity.Attendees.FindAttendee(li.Value); if (attendee != null) continue; li.Attributes.Add("style", "color:lightgrey"); li.Attributes.Add("status", "unconfirmed"); SelectedMembers.Items.Add(li); Activity.Attendees.Add(li.Value); removeList.Add(li); } foreach (ListItem li in removeList) { AvailableMembers.Items.Remove(li); } }
protected void AddTradeItems( int TradeId, int TeamId, ListItemCollection List ) { foreach ( ListItem i in List ) { if ( i.Selected ) { int Id = int.Parse( i.Value.Substring( 1 ) ); int PlayerId = -1; int PickId = -1; if ( i.Value.ToCharArray()[0] == 'd' ) { PickId = Id; } else { PlayerId = Id; } int DontCare = ( int )SqlHelper.ExecuteScalar( System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"], "spAddTradeItem", TradeId, TeamId, PickId, PlayerId ); } } }
private static void ProcessItems(ListItemCollection items) { //foreach (var item in items) // Console.WriteLine(item.Id); totalCount += items.Count; Console.WriteLine("Batch count : " + items.Count); }
/// <summary> /// Previews the event info entered by the user in a new window. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnPreview_Click(object sender, EventArgs e) { if (this.IsValid) { string WebinarRecordingID = CareerCruisingWeb.CCLib.Common.Strings.GetQueryString("WebinarRecordingID"); // if showing criteria for an existing event if (WebinarRecordingID != "") { ClientScript.RegisterStartupScript(this.Page.GetType(), "New Window", "window.open('../../../Public/Webinars/VideoDetails.aspx?WebinarRecordingID=" + WebinarRecordingID + "','','height=580,width=600,scrollbars=1,resizable=1');", true); } else { Session["WebinarVideoDisplayTitle"] = lblDisplayTitle.Text; Session["WebinarVideoRegistrationURL"] = CareerCruisingWeb.CCLib.Common.Strings.GenerateHttpLink(txtRegistrationUrl.Text.Trim()); string commandText = "SELECT Description FROM Webinar_DescriptionsLookup WHERE WebinarDescriptionID = " + ddlListTitle.SelectedValue; string webinarDescription = CareerCruisingWeb.CCLib.Common.DataAccess.GetValue(commandText).ToString(); Session["WebinarVideoDescription"] = webinarDescription; Session["WebinarVideoPresenterFullName"] = ddlPresenter.SelectedItem.Text; commandText = "SELECT Title, Bio, PhotoImagePath FROM Webinar_PresenterLookup WHERE WebinarPresenterID = " + ddlPresenter.SelectedValue; DataRow presenterInfo = CareerCruisingWeb.CCLib.Common.DataAccess.GetDataTable(commandText).Rows[0]; Session["WebinarVideoPresenterTitle"] = presenterInfo["Title"].ToString(); Session["WebinarVideoPresenterBio"] = presenterInfo["Bio"].ToString(); Session["WebinarVideoPresenterPhotoImagePath"] = presenterInfo["PhotoImagePath"].ToString(); Session["WebinarVideoRecordingDate"] = DateTime.Parse(txtSessionDates.Text.Trim()).ToString("MM/dd/yyyy"); commandText = "SELECT wal.WebinarAudienceID, wal.AudienceDescription_EN "; commandText += "FROM Webinar_AudienceLookup wal "; commandText += "INNER JOIN Webinar_DescriptionsAudience wda ON wal.WebinarAudienceID = wda.WebinarAudienceID "; commandText += "WHERE wda.WebinarDescriptionID = " + ddlListTitle.SelectedValue; commandText += "GROUP BY wal.AudienceDescription_EN, wal.WebinarAudienceID "; commandText += "ORDER BY wal.AudienceDescription_EN"; DataTable webinarAudience = CareerCruisingWeb.CCLib.Common.DataAccess.GetDataTable(commandText); if (webinarAudience.Rows.Count > 0) { ListItemCollection collection = new ListItemCollection(); foreach (DataRow row in webinarAudience.Rows) { collection.Add(new ListItem(row["AudienceDescription_EN"].ToString())); } Session["WebinarVideoAudienceDescriptionList"] = collection; } else { Session["WebinarVideoAudienceDescriptionList"] = null; } ClientScript.RegisterStartupScript(this.Page.GetType(), "New Window", "window.open('../../../Public/Webinars/VideoDetails.aspx','','height=580,width=600,scrollbars=1,resizable=1');", true); } } }
public static List<Tarefa> ItensParaTarefas(ListItemCollection itensTarefas) { List<Tarefa> tarefas = new List<Tarefa>(); foreach (ListItem item in itensTarefas) { tarefas.Add(ItemParaTarefa(item)); } return tarefas; }
ComboBoxCell MyDropDown() { var combo = new ComboBoxCell (); var items = new ListItemCollection (); items.Add (new ListItem{ Text = "Item 1" }); items.Add (new ListItem{ Text = "Item 2" }); items.Add (new ListItem{ Text = "Item 3" }); items.Add (new ListItem{ Text = "Item 4" }); combo.DataStore = items; return combo; }
protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { SetDefaultButton(save); ListItemCollection intervals = new ListItemCollection(); intervals.Add(new ListItem("Never", Convert.ToString(-1))); intervals.Add(new ListItem("Every Request", Convert.ToString(0))); intervals.Add(new ListItem("One Minute", Convert.ToString(60))); intervals.Add(new ListItem("Five Minutes", Convert.ToString(5 * 60))); intervals.Add(new ListItem("Ten Minutes", Convert.ToString(10 * 60))); intervals.Add(new ListItem("Half Hour", Convert.ToString(30 * 60))); intervals.Add(new ListItem("One Hour", Convert.ToString(60 * 60))); intervals.Add(new ListItem("Twelve Hours", Convert.ToString(12 * 60 * 60))); intervals.Add(new ListItem("One Day", Convert.ToString(24 * 60 * 60))); inputInterval.DataSource = intervals; inputInterval.DataBind(); inputType.DataSource = Enum.GetValues(typeof(TransitFeedType)); inputType.DataBind(); if (RequestId > 0) { inputName.Text = Feed.Name; inputUrl.Text = Feed.Url; inputDescription.Text = Feed.Description; inputXsl.PostedFile = new UploadControl.HttpPostedFile(string.IsNullOrEmpty(Feed.Xsl) ? "None" : string.Format("{0} bytes", Feed.Xsl.Length)); ListItem li = inputInterval.Items.FindByValue(Feed.Interval.ToString()); if (li == null) { li = new ListItem(string.Format("{0} Seconds", Feed.Interval), Feed.Interval.ToString()); inputInterval.Items.Add(li); } inputInterval.ClearSelection(); li.Selected = true; inputUsername.Text = Feed.Username; inputPassword.Attributes["value"] = Feed.Password; inputType.Items.FindByValue(Feed.Type.ToString()).Selected = true; } } } catch (Exception ex) { ReportException(ex); } }
public void AddAddsToExistingGroupIfGroupDoesExist() { var list = new ListItemCollection<string>(); list.AddGroup("Hello", new List<string> { "Foo" }); list.Add("Hello", "Bar"); list.Should().HaveCount(1); list.Should().Contain(g => g.Title == "Hello" && g.Count == 2 && g.Contains("Foo") && g.Contains("Bar")); }
public void AddAddsToNewGroupIfGroupDoesntExist() { var list = new ListItemCollection<string>(); list.AddGroup("Hello", new List<string> { "Foo" }); list.Add("World", "Bar"); list.Should().HaveCount(2); list.Should().Contain(g => g.Title == "Hello" && g.Count == 1 && g[0] == "Foo"); list.Should().Contain(g => g.Title == "World" && g.Count == 1 && g[0] == "Bar"); }
public SPClientView IncludeItems(ListItemCollectionPosition position = null, bool datesInUtc = false, string folderServerRelativeUrl = null, params Expression<Func<ListItemCollection, object>>[] retrievals) { _items = ClientList.List.GetItems(new CamlQuery { ListItemCollectionPosition = position, ViewXml = View.ListViewXml }); View.Context.Load(_items, retrievals); _executeQuery = true; return this; }
private void BindData() { ClientContext clientContext = Util.GetContext(); Web web = clientContext.Web; ListCollection spLists = web.Lists; spList = spLists.GetByTitle("Business Partner Survey"); clientContext.Load(spList); listItems = spList.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listItems); clientContext.ExecuteQueryAsync(GridSucceededCallback, webFailedCallback); }
/// <summary> /// Function to verify if Folder already exists in Site Assets /// </summary> /// <param name="matterCenterAssetsFolder">Matter Center Assets Folder</param> /// <param name="clientContext">Client Context</param> /// <param name="siteAssets">Site Assets</param> /// <param name="matterLandingFolder">Matter Landing Folder</param> /// <param name="listFolders">List Folder</param> /// <returns>List of items in folder</returns> private static ListItemCollection CheckFolderExists(string matterCenterAssetsFolder, ClientContext clientContext, out List siteAssets, out ListItemCollection matterLandingFolder, out FolderCollection listFolders) { CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Folder'>" + matterCenterAssetsFolder + "</Value></Eq></Where></Query><ViewFields><FieldRef Name='FileLeafRef' /></ViewFields></View>"; siteAssets = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["LibraryName"]); matterLandingFolder = siteAssets.GetItems(camlQuery); listFolders = siteAssets.RootFolder.Folders; clientContext.Load(matterLandingFolder); clientContext.Load(siteAssets.RootFolder); clientContext.Load(listFolders); clientContext.ExecuteQuery(); return matterLandingFolder; }
public MainPage() { InitializeComponent(); _clientContext = new ClientContext("http://jakesharepointsaturday.sharepoint.com/TeamSite"); Web site = _clientContext.Web; _list = site.Lists.GetByTitle("Important Documents"); _items = _list.GetItems(new CamlQuery()); _clientContext.Load(_items); _clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback); }
private void GetListItemsClientObjectModel() { _clientContext = new ClientContext("http://jakesharepointsaturday.sharepoint.com/TeamSite"); Web site = _clientContext.Web; _list = site.Lists.GetByTitle("Death Star Inventory 2"); _items = _list.GetItems(new CamlQuery()); //_clientContext.Load(_items); _clientContext.Load(_items, items => items.Include(i => i["Item_x0020_Type"], i => i["Fire_x0020_Power"], i => i["Title"])); _clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback); }
protected static string[] listItemCollectionToStringArray(ListItemCollection items) { ArrayList arrayList = new ArrayList(items.Count); foreach (ListItem listItem in items) { if (listItem.Selected == true) arrayList.Add(listItem.Text); } arrayList.TrimToSize(); return (string[])arrayList.ToArray(typeof(string)); }
protected void AdAll_Click(object sender, EventArgs e) { ListItemCollection liC = new ListItemCollection(); foreach (ListItem li in AvForumsList.Items) { MdForumsList.Items.Add(li); li.Selected = false; liC.Add(li); } foreach (ListItem li in liC) AvForumsList.Items.Remove(li); }
protected void RemoveSelectedFromBasket_ButtonClick(object sender, EventArgs e) { ListItemCollection ItemsForRemoveActionInBasketListBox = new ListItemCollection(); foreach (ListItem CurrentItem in this.ListBoxSelectedProducts.Items) { if (CurrentItem.Selected) { this.ListBoxProducts.Items.Add(CurrentItem); ItemsForRemoveActionInBasketListBox.Add(CurrentItem); } } foreach (ListItem CurrentItem in ItemsForRemoveActionInBasketListBox) { this.ListBoxSelectedProducts.Items.Remove(CurrentItem); } }
protected string BuildValueList(ListItemCollection items, bool itemMustBeSelected) { StringBuilder idList = new StringBuilder(); foreach (ListItem item in items) { if (itemMustBeSelected && !item.Selected) continue; else { idList.Append(item.Value.ToString()); idList.Append(","); } } return idList.ToString(); }
public MainPage() { InitializeComponent(); ClientContext context = new ClientContext(ApplicationContext.Current.Url); context.Load(context.Web); List employees = context.Web.Lists.GetByTitle("Employees"); context.Load(employees); CamlQuery query = new CamlQuery(); string camlQueryXml = null; query.ViewXml = camlQueryXml; _employees = employees.GetItems(query); context.Load(_employees); context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), null); }
protected void AdAll_Click(object sender, EventArgs e) { ListItemCollection liC = new ListItemCollection(); foreach (ListItem li in AvForumsList.Items) { ArchiveForumsList.Items.Add(li); li.Selected = false; liC.Add(li); } foreach (ListItem li in liC) AvForumsList.Items.Remove(li); ArchiveBtn.Enabled = true; Panel2.Visible = false; }
public static void Bind(RadioButtonList rdolst, ListItemCollection list, EnumHelper.ListItemType listType) { foreach (ListItem item in list) { //if (listType == EnumHelper.ListItemType.CommissionType) //{ // if (Convert.ToInt32(item.Value) == Convert.ToInt32(EnumHelper.CommissionType.Dollar)) // { // item.Text = "$"; // } // if (Convert.ToInt32(item.Value) == Convert.ToInt32(EnumHelper.CommissionType.Percentage)) // { // item.Text = "%"; // } //} rdolst.Items.Add(item); } }
public void AddGroupReturnsTrueIfGroupIsAdded() { var list = new ListItemCollection<string>(); var toAdd = new List<string> { "Foo", "Bar" }; list.AddGroup("Bob", toAdd).Should().BeTrue(); list.Count.Should().Be(1); list[0].Title.Should().Be("Bob"); list[0].Should().ContainInOrder(toAdd); list[0].Should().OnlyContain(s => toAdd.Contains(s)); list[0].Count.Should().Be(2); }
protected void Ad2_Click(object sender, EventArgs e) { if (AvModsList.SelectedItem != null) { ListItemCollection liC = new ListItemCollection(); foreach (ListItem li in AvModsList.Items) if (li.Selected) { CurModsList.Items.Add(li); li.Selected = false; liC.Add(li); } foreach (ListItem li in liC) AvModsList.Items.Remove(li); } }
//save news to azure table from inparameter listItems public static void SaveNews(ListItemCollection listItems) { var batchOperation = new TableBatchOperation(); //make only one call to Azure Table, use Batch. foreach (ListItem item in listItems) { //Convert ListItems to Table-entries(Entity) var entity = new StebraEntity( "News", //string Stebratype item["Title"].ToString(), //string newsEntry "Descriptive text", //string NewsDescription item["Article"].ToString(), //string NewsArticle item["Datum"].ToString(), //string NewsDate item["Body"].ToString() //string NewsBody ); batchOperation.Insert(entity); //Batch this } NewsTable.ExecuteBatch(batchOperation); //Execute Batch }
/**********Employee List Display Data***********/ public static void DisplayEmployeeListItems(ClientContext clientContext) { List emplist = clientContext.Web.Lists.GetByTitle("Employees"); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><RowLimit></RowLimit></View>"; ListItemCollection empcoll = emplist.GetItems(camlQuery); clientContext.Load( empcoll, items => items.Take(5).Include( item => item["FirstName"], item => item["Company"], item => item["Department"] ) ); clientContext.ExecuteQuery(); foreach (ListItem employee in empcoll) { Console.WriteLine("\n First Name: {0} \n Company: {1}\n Department: {2}\n-----------------------\n", employee["FirstName"], employee["Company"], employee["Department".ToString()]); } }
public void buildListBox(ListItemCollection Items, string sSQL, string sId, string sTitle, string CustomInitialDisplayValue, string CustomInitialSubmitValue) { Items.Clear(); OleDbCommand command = new OleDbCommand(sSQL, Connection); OleDbDataReader reader = command.ExecuteReader(); if (CustomInitialDisplayValue != null) { Items.Add(new ListItem(CustomInitialDisplayValue, CustomInitialSubmitValue)); } while (reader.Read()) { if (sId == "" && sTitle == "") { Items.Add(new ListItem(reader[1].ToString(), reader[0].ToString())); } else { Items.Add(new ListItem(reader[sTitle].ToString(), reader[sId].ToString())); } } reader.Close(); }
public IEnumerable <string> GetFilmsBySuperhero(int superheroId) { CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = $@"<View> <Query> <Where> <Eq> <FieldRef Name='SuperheroId'/> <Value Type='Number'>{superheroId}</Value> </Eq> </Where> </Query> </View>"; ListItemCollection filmsuperheroes = website.Lists.GetByTitle("FilmSuperheroes").GetItems(camlQuery); clientContext.Load(filmsuperheroes); clientContext.ExecuteQuery(); List <int> filmIds = filmsuperheroes //.Where(f => Convert.ToInt32(f["SuperheroId"]) == superheroId) .Select(fs => Convert.ToInt32(fs["Title"])) .ToList(); ListItemCollection films = website.Lists.GetByTitle("Films").GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(films); clientContext.ExecuteQuery(); List <string> result = films.Where(f => filmIds.Any(id => Convert.ToInt32(f.Id) == id)) .Select(a => a["Title"].ToString()) .ToList(); return(result); }
//系统字体绑定 public static void DropDownListFontSizeBind(DropDownList DDLFontSize, string SessionID) { try { ListItemCollection LIC = new ListItemCollection(); //LIC.Clear(); ListItem LI = null; InstalledFontCollection IFontC = new InstalledFontCollection(); FontFamily[] FFonts = IFontC.Families; foreach (FontFamily FF in FFonts) { LI = new ListItem(); LI.Text = FF.Name.ToString(); LI.Value = FF.Name.ToString(); LIC.Add(LI); } DDLFontSize.DataSource = LIC; DDLFontSize.DataBind(); } catch (Exception Err) { ErrorLog.LogInsert(Err.Message, "CS/ControlDataBind.DropDownListFontSizeBind", SessionID); } }
public ActionResult Index() { var contextToken = TokenHelper.GetContextTokenFromRequest(Request); var appWebUrl = Request["SPAppWebUrl"]; ViewBag.AlertsListLink = appWebUrl + "/Lists/Alerts"; using (var ctx = TokenHelper.GetClientContextWithContextToken(appWebUrl, contextToken, Request.Url.Authority)) { List alertList = ctx.Web.Lists.GetByTitle("Alerts"); ctx.Load(alertList); ListItemCollection alertItems = alertList.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(alertItems); ctx.ExecuteQuery(); List <Alert> alerts = new List <Alert>(); foreach (ListItem alertItem in alertItems) { Alert alert = new Alert() { ID = (int)alertItem["ID"], Title = (alertItem["Title"] == null) ? string.Empty : alertItem["Title"].ToString(), Body = (alertItem["Body"] == null) ? string.Empty : alertItem["Body"].ToString(), Expires = (alertItem["Expires"] == null) ? null : (DateTime?)alertItem["Expires"] }; alerts.Add(alert); } ViewBag.Alerts = alerts; } return(View()); }
public static ListItemCollection GetItemsFromGuid(string listGuid) { ListItemCollection items = null; var spContext = SharePointContextProvider.Current.GetSharePointContext(CurrentHttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { listGuid = listGuid.Replace("{", "").Replace("}", ""); Guid guid = new Guid(listGuid); List list = clientContext.Web.Lists.GetById(guid); clientContext.Load(list); clientContext.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @" <View> <Query> <Where> <IsNotNull> <FieldRef Name='Title' /> </IsNotNull> </Where> </Query> </View>"; items = list.GetItems(camlQuery); clientContext.Load(items); clientContext.ExecuteQuery(); } } return(items); }
private void LoadDataFromServer(string ViewName, Action <LoadViewCompletedEventArgs> loadItemCompletedCallback, params object[] filterParameters) { CamlQuery query = CamlQueryBuilder.GetCamlQuery(ViewName); ListItemCollection items = Context.Web.Lists.GetByTitle(ListTitle).GetItems(query); Context.Load(items); Context.Load(items, listItems => listItems.Include(item => item.FieldValuesAsText)); Context.Load(items, listItems => listItems.Include(item => item.File)); Context.ExecuteQueryAsync( delegate(object sender, ClientRequestSucceededEventArgs args) { base.CacheView(ViewName, items); loadItemCompletedCallback(new LoadViewCompletedEventArgs { ViewName = ViewName, Items = base.GetCachedView(ViewName) }); }, delegate(object sender, ClientRequestFailedEventArgs args) { loadItemCompletedCallback(new LoadViewCompletedEventArgs { Error = args.Exception }); }); }
/// <summary> /// Attempts to retrieve navigation items from web.config file /// and display in drop-down list. /// </summary> /// private void BindNavigationDropDown() { //get values from web.config file string configItems = Utilities.GetApplicationKeyValue("LookupTablesNavigationItems"); if (string.IsNullOrEmpty(configItems)) { drpSelectedLookupTable.Items.Add("Not Available"); } else { //parse by comma string[] navItems = configItems.Split(','); ListItemCollection collection = new ListItemCollection(); //replacing any spaces in navigation item for value property foreach (string item in navItems) { collection.Add(new ListItem { Text = item, Value = item.Replace(" ", "") }); } drpSelectedLookupTable.DataSource = collection; drpSelectedLookupTable.DataBind(); if (this.CurrentNavigationLink != LookupTablesNavigation.None) { drpSelectedLookupTable .Items.Insert(0, new ListItem { Text = "(Select Lookup Table)", Value = "0" }); } } }
void ListScheduledTask() { ListItemCollection list = ListBoxScheduledTask.Items; list.Clear(); IList scheduledTaskList = TheAdminServer.ScheduledTaskManager.ScheduledTaskList; for (int i = 0; i < scheduledTaskList.Count; i++) { ScheduledTaskUnit unit = scheduledTaskList[i] as ScheduledTaskUnit; string itemText = unit.Task.ToString(); if (!unit.Task.Enabled) { itemText += " [" + StringDef.Disable + "]"; } ListItem item = new ListItem(itemText, unit.Task.SecurityObject.Id.ToString()); //string color = unit.Task.Enabled ? "color:Green;" : "color:Red;"; //item.Attributes.Add("style", color); list.Add(item); } ShowScheduledTaskCount(); }
public HttpResponseMessage GetByMasterNumber([FromUri] string id) { string authorizationString = DecodeAuthorizationString(); SPHelper.SetSharePointCredentials(authorizationString); List <SharePointDocument> files = new List <SharePointDocument>(); ListItemCollection list = SPHelper.GetDocumentsByNumber(id); if (list != null && list.AreItemsAvailable) { foreach (ListItem item in list) { SharePointDocument file = ListItemToSharePointDocument(item); files.Add(file); } } var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(JsonConvert.SerializeObject(files), Encoding.UTF8, "application/json"); return(response); }
static void Main() { string siteUrl = "http://MyServer/sites/MySiteCollection"; ClientContext clientContext = new ClientContext(siteUrl); SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements"); //get partner listitem using this line, but you can use caml query to get many partner items //ListItem partnerItem = lstCIs.GetItemById(lv.LookupId); // get subsite url //if (partnerItem["CISite"] != null) // { // FieldUrlValue subSiteUrl = partnerItem["CISite"] as FieldUrlValue; // using (ClientContext subsiteContext = new ClientContext(subSiteUrl.Url)) // { } // } CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" + "<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>"; ListItemCollection collListItem = oList.GetItems(camlQuery); clientContext.Load(collListItem); clientContext.ExecuteQuery(); foreach (ListItem oListItem in collListItem) { Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]); } }
public void LimpiarTabla(HttpContextBase HttpContext) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { SP.List oList = clientContext.Web.Lists.GetByTitle("Persona"); ListItemCollection listItems = oList.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listItems, eachItem => eachItem.Include( item => item["ID"])); clientContext.ExecuteQuery(); var totalListItems = listItems.Count; if (totalListItems > 0) { for (var counter = totalListItems - 1; counter > -1; counter--) { listItems[counter].DeleteObject(); clientContext.ExecuteQuery(); } } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { UsuarioEntidad usuario = new UsuarioEntidad(); String identificación = (Request.QueryString["idIdentificacion"].ToString()); usuario = UsuarioLN.obtenerUsuarioId(identificación); this.txtDireccion.Text = usuario.direccion; this.txtEmail.Text = usuario.email; this.txtIdentificación.Text = usuario.idUsuario; this.txtNombre.Text = usuario.nombre; password = usuario.password; this.txtTelefono.Text = usuario.telefono; this.ddlRol.DataSource = RolLN.ObtenerTodos(); this.ddlRol.DataTextField = "descripcion"; this.ddlRol.DataValueField = "idRol"; this.ddlRol.DataBind(); this.ddlRol.SelectedValue = usuario.rol.idRol.ToString(); ListItemCollection items = new ListItemCollection { new ListItem("Desactivo", "0"), new ListItem("Activo", "1"), }; this.ddlEstado.DataSource = items; this.ddlEstado.DataBind(); this.ddlEstado.SelectedIndex = usuario.estado; } catch (Exception) { Response.Redirect("MantenimientoUsuarios.aspx"); } } }
protected void GenerateModeList(object sender, EventArgs e) { WebPartManager _manager = WebPartManager.GetCurrentWebPartManager(Page); String browserModeName = WebPartManager.BrowseDisplayMode.Name; DropDownListModes.Items.Clear(); // Fill the drop-down list with the names of supported display modes foreach (WebPartDisplayMode mode in _manager.SupportedDisplayModes) { String modeName = mode.Name; if (mode.IsEnabled(_manager)) { ListItem item = new ListItem(modeName, modeName); DropDownListModes.Items.Add(item); } } // Select current mode ListItemCollection items = DropDownListModes.Items; int selectedIndex = items.IndexOf(items.FindByText(_manager.DisplayMode.Name)); DropDownListModes.SelectedIndex = selectedIndex; }
public Dictionary <string, string> LoadList(string list) { var site = ConfigurationManager.AppSettings["SharePointSite"]; ClientContext clientContext = new ClientContext(site); Web oWebsite = clientContext.Web; ListCollection collList = oWebsite.Lists; var spList = collList.GetByTitle(list); var q = new CamlQuery(); ListItemCollection collListItem = spList.GetItems(q); clientContext.Load( collListItem, items => items.Include( item => item["Key"], item => item["Value"])); clientContext.ExecuteQuery(); var dictionary = new Dictionary <string, string>(); object keyName; object valueName; foreach (var item in collListItem) { item.FieldValues.TryGetValue("Key", out keyName); item.FieldValues.TryGetValue("Value", out valueName); dictionary.Add(keyName.ToString(), valueName as string); } return(dictionary); }
public static string RenewSaUserPassword(string userGsmNumber) { try { System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(DAT.DataStatics.UserNameForService, DAT.DataStatics.PasswordForService, DAT.DataStatics.DomainForService); ClientContext clientContext = new ClientContext(usersListSiteUrl); clientContext.Credentials = credentials; List oList = clientContext.Web.Lists.GetByTitle(usersListName); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = string.Format(userCamlQueryByGsmNumber, userGsmNumber); ListItemCollection collListItems = oList.GetItems(camlQuery); clientContext.Load(collListItems); clientContext.ExecuteQuery(); ListItem item = collListItems[0]; clientContext.Load(item); clientContext.ExecuteQuery(); string newPassword = GeneratePassword(); newPassword = EncodeToBase64(newPassword); item["Password"] = newPassword; // Mevcut User için Yazma Erişimi Reddedildiği için aşağıdaki kod satırları yorum satırı yapıldı //item.Update(); //clientContext.ExecuteQuery(); clientContext.Dispose(); return(newPassword); } catch (Exception ex) { EXP.RedirectToErrorPage(ex.Message); return(null); } }
public void LoadMin(DropDownList ddlMin) { ListItemCollection lic = new ListItemCollection(); int count = 0; while (count < 60) { ListItem li = new ListItem(); if (count < 10) { li.Text = "0" + count.ToString(); li.Value = "0" + count.ToString(); } else { li.Text = count.ToString(); li.Value = count.ToString(); } lic.Add(li); count++; } ddlMin.DataSource = lic; ddlMin.DataBind(); }
public static System.Web.UI.WebControls.ListItemCollection GetTaskStatusList() { ListItemCollection objListItemCollection = new ListItemCollection(); //----------- Start DP ----------------- //objListItemCollection.Add(new ListItem("Open", Convert.ToByte(JGConstant.TaskStatus.Open).ToString())); //objListItemCollection.Add(new ListItem("Requested", Convert.ToByte(JGConstant.TaskStatus.Requested).ToString())); //objListItemCollection.Add(new ListItem("Assigned", Convert.ToByte(JGConstant.TaskStatus.Assigned).ToString())); //objListItemCollection.Add(new ListItem("In Progress", Convert.ToByte(JGConstant.TaskStatus.InProgress).ToString())); //objListItemCollection.Add(new ListItem("Pending", Convert.ToByte(JGConstant.TaskStatus.Pending).ToString())); //objListItemCollection.Add(new ListItem("Re-Opened", Convert.ToByte(JGConstant.TaskStatus.ReOpened).ToString())); //objListItemCollection.Add(new ListItem("Finished", Convert.ToByte(JGConstant.TaskStatus.Finished).ToString())); //objListItemCollection.Add(new ListItem("Closed", Convert.ToByte(JGConstant.TaskStatus.Closed).ToString())); //objListItemCollection.Add(new ListItem("Specs In Progress", Convert.ToByte(JGConstant.TaskStatus.SpecsInProgress).ToString())); //objListItemCollection.Add(new ListItem("Test", Convert.ToByte(JGConstant.TaskStatus.Test).ToString())); //objListItemCollection.Add(new ListItem("Live", Convert.ToByte(JGConstant.TaskStatus.Live).ToString())); int enumlen = Enum.GetNames(typeof(JGConstant.TaskStatus)).Length; foreach (var item in Enum.GetNames(typeof(JGConstant.TaskStatus))) { int enumval = (int)Enum.Parse(typeof(JGConstant.TaskStatus), item); if (item != "Deleted") { objListItemCollection.Add(new ListItem(item, enumval.ToString())); } } //----------- End DP ----------------- if (CheckAdminAndItLeadMode()) { objListItemCollection.Add(new ListItem("Deleted", Convert.ToByte(JGConstant.TaskStatus.Deleted).ToString())); } return(objListItemCollection); }
protected void RemoveButton_Click(object sender, EventArgs e) { ListItemCollection removeQueue = new ListItemCollection(); foreach (ListItem li in ListBox2.Items) { if (li.Selected) { if (ListBox2.Items.Contains(li)) { removeQueue.Add(li); } } } foreach (ListItem rli in removeQueue) { if (ListBox2.Items.Contains(rli)) { ListBox2.Items.Remove(rli); } } UpdateShoppingCartLabel(); UpdateTotalCostLabel(); }
ListItemCollection GetPageHierarchy() { CMS.PageCollection pages = CMS.ContentService.GetHierarchicalPageCollection(); if (pageHierarchy == null) { pageHierarchy = new ListItemCollection(); lstHierarchy.Items.Clear(); ListItem item; foreach (CMS.Page page in pages) { string lvlIndicator = string.Empty; for (int i = 0; i < page.Level; i++) { lvlIndicator += " - "; } item = new ListItem(lvlIndicator + page.Title, page.PageID.ToString()); pageHierarchy.Add(item); } } return(pageHierarchy); }
static void DisplayListAndTaxanomyRead(ClientContext ctx) { List list = ctx.Web.GetListByTitle("Super Heroes"); ListItemCollection listcol = list.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(listcol); ctx.ExecuteQuery(); foreach (var items in listcol) { Console.WriteLine("############################"); TaxonomyFieldValue taxValue = items["TIM_SuperPower"] as TaxonomyFieldValue; TaxonomyFieldValueCollection TaxValueList = items["TIM_Weapon"] as TaxonomyFieldValueCollection; Console.WriteLine(items["Title"].ToString()); Console.WriteLine(taxValue.Label); foreach (var item in TaxValueList) { Console.WriteLine("----------------------"); Console.WriteLine(" " + item.Label); } } }
/// <summary> /// Used to key/value custom properities /// </summary> /// <param name="ctx"></param> /// <returns></returns> private Dictionary <string, string> GetCustomProfileProperties(ClientContext ctx) { CamlQuery _query = new CamlQuery(); var _siteInfoList = ctx.Web.Lists.GetByTitle(SiteClassificationList.SiteClassificationListTitle); ListItemCollection _items = _siteInfoList.GetItems(_query); ctx.Load(_items, eachItem => eachItem.Include( item => item, item => item[SiteClassificationFields.FLD_KEY_INTERNAL_NAME], item => item[SiteClassificationFields.FLD_VALUE_INTERNAL_NAME])); ctx.ExecuteQuery(); Dictionary <string, string> _siteInfo = new Dictionary <string, string>(); if (_items.Count > 0) { foreach (ListItem _item in _items) { _siteInfo.Add(BaseSet(_item, SiteClassificationFields.FLD_KEY_INTERNAL_NAME), BaseSet(_item, SiteClassificationFields.FLD_VALUE_INTERNAL_NAME)); } } return(_siteInfo); }
private void GenerateHtml(ArrayList al) { string s = ""; int c = 1; int xCount = 0, xMaxCount = 10, questionsMarked = 0; string dispQuestionId = "0"; s += "<table><tr>"; for (int k = 0; k < al.Count; k++) { if (xCount == xMaxCount) { s += "<tr>"; } if (al[k].ToString().Equals(currentQuestionId)) { dispQuestionId = (c).ToString(); if (al.Count == k + 1) { Session["nextQuestionId"] = al[0].ToString(); } else { Session["nextQuestionId"] = al[k + 1].ToString(); } if (k == 0) { Session["prevQuestionId"] = al[al.Count - 1].ToString(); } else { Session["prevQuestionId"] = al[k - 1].ToString(); } } /* * if (dispQuestionId.ToString().Equals(c.ToString())) * { * s += "<td><font size=large><a href=StartExam.aspx?id=" + al[k] + " style='color: #ffffff;'>Q" + c++ + "</a></font></td>"; * if (Session[al[k] + "MA"] != null) * questionsMarked++; * c++; * } * else * {*/ if (Session[al[k] + "VQ"] != null) { if (Session[al[k] + "MA"] != null) { s += "<td><a href=StartExam.aspx?id=" + al[k] + " style='color: #33cc33;'>Q" + c++ + "</a></td>"; questionsMarked++; } else { s += "<td><a href=StartExam.aspx?id=" + al[k] + " style='color: #3366ff;'>Q" + c++ + "</a></td>"; } } else { s += "<td><a href=StartExam.aspx?id=" + al[k] + " style='color: #ff3300'>Q" + c++ + "</a></td>"; } //} xCount++; if (xCount == xMaxCount || k == al.Count - 1) { s += "</tr>"; xCount = 0; } } s += "</table>"; Label2.Text = s; if (questionsMarked == al.Count) { if (SessionsCommon.RedirectStudentToSummaryPage(Session)) { Response.Redirect("./ObjectiveExamSummary.aspx"); } } if (questionID != null) { // Exam summary now makes a lot of human sense to me. Eeeeee haaaaaa DataTable DtQuestion = AptitudeTestBLL.Instance.GetQuestionsByID(Int32.Parse(questionID)); JG_Prospect.Common.modal.Aptitude.QuestionRow selectedQuestion = new Common.modal.Aptitude.QuestionRow(); foreach (DataRow Ques in DtQuestion.Rows) // It will be only 1 rows. { //selectedQuestion = new Common.modal.Aptitude.QuestionRow(); selectedQuestion.QuestionID = Convert.ToInt32(Ques["QuestionID"]); selectedQuestion.Question = Ques["Question"].ToString(); selectedQuestion.QuestionType = Convert.ToInt32(Ques["QuestionType"]); selectedQuestion.PositiveMarks = Convert.ToInt32(Ques["PositiveMarks"]); selectedQuestion.NegetiveMarks = Convert.ToInt32(Ques["NegetiveMarks"]); selectedQuestion.PictureURL = ""; selectedQuestion.ExamID = Convert.ToInt32(Ques["ExamID"]);; selectedQuestion.AnswerTemplate = ""; } //JG_Prospect.Common.modal.Aptitude.QuestionRow selectedQuestion = AptitudeTestBLL.Instance.GetQuestionsByID(Int32.Parse(questionID)); //QuestionType questionType = (QuestionType)selectedQuestion.QuestionType; lblQuestion.Text = "<font color=black>Q" + dispQuestionId + "." + selectedQuestion.Question + "</font>"; positiveMarks = selectedQuestion.PositiveMarks; negetiveMarks = selectedQuestion.NegetiveMarks; lblPositiveMarks.Text = positiveMarks.ToString(); lblNegetiveMarks.Text = negetiveMarks.ToString(); //string pictureURL = selectedQuestion.PictureURL; //showPicture(pictureURL); if ("SingleSelect" == "SingleSelect") { //Single Select #region Single Select pnlMultiSelect.Visible = false; pnlSingleSelect.Visible = true; pnlPhrase.Visible = false; ListItemCollection coll = (ListItemCollection)Session[questionID]; if (coll != null) { RadioButtonList1.Items.Clear(); foreach (ListItem li in coll) { RadioButtonList1.Items.Add(li); } return; } DataTable optionData = AptitudeTestBLL.Instance.GetQuestionsoptionByQustionID(Int32.Parse(questionID)); foreach (DataRow OptionRow in optionData.Rows) { string item = OptionRow["OptionText"].ToString(); RadioButtonList1.Items.Add(new ListItem(item, item)); } #endregion } //else if (questionType == QuestionType.MultiSelect) //{ // #region Multi Select // //Multiple Select // pnlMultiSelect.Visible = true; // pnlSingleSelect.Visible = false; // pnlPhrase.Visible = false; // ListItemCollection coll = (ListItemCollection)Session[questionID]; // if (coll != null) // { // CheckBoxList1.Items.Clear(); // foreach (ListItem li in coll) // CheckBoxList1.Items.Add(li); // return; // } // OptionTableAdapter optionAdapter = new OptionTableAdapter(); // ExamOMaticSchema.OptionDataTable optionData = optionAdapter.GetDataByQuestionID(Int32.Parse(questionID)); // for (int k = 0; k < optionData.Rows.Count; k++) // { // string item = optionData[k].OptionText; // CheckBoxList1.Items.Add(new ListItem(item, item)); // } // #endregion //} else { //Phrase Mode pnlMultiSelect.Visible = false; pnlSingleSelect.Visible = false; pnlPhrase.Visible = true; string str = (string)Session[questionID]; if (str != null) { txtAnswer.Text = str; } } } }
public void InsertData(ClientContext clientContext, DKBSDbContext dbContext) { try { Console.WriteLine(" Successfully Connected"); SP.List oList = clientContext.Web.Lists.GetByTitle("Partnere"); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View Scope='RecursiveAll'><Query></Query></View>"; ListItemCollection collListItem = oList.GetItems(camlQuery); clientContext.Load(collListItem); clientContext.ExecuteQuery(); foreach (ListItem oListItem in collListItem) { var hyperLink = ((SP.FieldUrlValue)(oListItem["CISite"])); if (hyperLink != null) { Console.WriteLine("ID: {0} \nTitle: {1} \nSite: {2} \nSiteUrl: {3} ", oListItem.Id, oListItem["Title"], oListItem["CISite"], oListItem["CISiteShortUrl"]); var hLink = ((SP.FieldUrlValue)(oListItem["CISite"])).Url; Console.WriteLine(hLink); ClientContext Context = new ClientContext(hLink); Context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; Context.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("CRM Automation", "9LEkTny4"); Context.ExecuteQuery(); SP.List oListData = Context.Web.Lists.GetByTitle("Centerbeskrivelse"); camlQuery.ViewXml = "<View Scope='RecursiveAll'><Query></Query></View>"; ListItemCollection oListDataItem = oListData.GetItems(camlQuery); Context.Load(oListDataItem); Context.ExecuteQuery(); foreach (ListItem oItem in oListDataItem) { Console.WriteLine("ID: {0} \nDescription: {1} \nLanguageType:{2} \nRooms:{3}", oItem["ID"], oItem["Description"], oItem["LanguageType"], oItem["Rooms"]); Console.WriteLine("TraficConnections: {0} \nCapacity: {1} \nFacilities:{2} \nActivities:{3}", oItem["TraficConnections"], oItem["Capacity"], oItem["Facilities"], oItem["Activities"]); Console.WriteLine("TextOffer: {0} \nFurtherIncluded: {1}", oItem["TextOffer"], oItem["FurtherIncluded"]); Console.WriteLine(((SP.FieldUserValue)(oItem["Author"])).LookupValue); Console.WriteLine(((SP.FieldUserValue)(oItem["Editor"])).LookupValue); Console.WriteLine(oItem["Created"].ToString()); Console.WriteLine(oItem["Modified"].ToString()); PartnerCenterDescription partnerCenterDescription = new PartnerCenterDescription(); // partnerCenterDescription.CRMPartnerId = 1;//oListItem.Id partnerCenterDescription.CRMPartnerId = oListItem.Id; // partnerCenterDescription.ContentStatusId = 2;//Approved if (oItem["Rooms"] != null) { partnerCenterDescription.Rooms = oItem["Rooms"].ToString(); } if (oItem["Capacity"] != null) { partnerCenterDescription.Capacity = oItem["Capacity"].ToString(); } if (oItem["Facilities"] != null) { partnerCenterDescription.Facilities = oItem["Facilities"].ToString(); } if (oItem["Activities"] != null) { partnerCenterDescription.Activities = oItem["Activities"].ToString(); } if (oItem["TextOffer"] != null) { partnerCenterDescription.TextforQuotationforEmail = oItem["TextOffer"].ToString(); } if (oItem["TraficConnections"] != null) { partnerCenterDescription.Transportation = oItem["TraficConnections"].ToString(); } if (oItem["Description"] != null) { partnerCenterDescription.Description = oItem["Description"].ToString(); } if (oItem["ID"] != null) { partnerCenterDescription.PartnerCenterDescriptionSpId = oItem["ID"].ToString(); } if (oItem["FurtherIncluded"] != null) { partnerCenterDescription.AdditionalIncluded = oItem["FurtherIncluded"].ToString(); } if (oItem["LanguageType"] != null) { partnerCenterDescription.Language = oItem["LanguageType"].ToString(); } if (((SP.FieldUserValue)(oItem["Author"])).LookupValue != null) { partnerCenterDescription.CreatedBy = ((SP.FieldUserValue)(oItem["Author"])).LookupValue; } if (oItem["Created"] != null) { partnerCenterDescription.CreatedDate = Convert.ToDateTime(oItem["Created"].ToString()); } if (((SP.FieldUserValue)(oItem["Editor"])).LookupValue != null) { partnerCenterDescription.LastModifiedBY = ((SP.FieldUserValue)(oItem["Editor"])).LookupValue; } if (oItem["Modified"] != null) { partnerCenterDescription.LastModified = Convert.ToDateTime(oItem["Modified"].ToString()); } partnerCenterDescription.ContentStatusId = 1; dbContext.Add(partnerCenterDescription); dbContext.SaveChanges(); } } } } catch (Exception) { throw; } }
private void ProcessAction(List <Web> webs) { bool processAction; int webCount = webs.Count; for (int webIndex = 0; webIndex < webCount; webIndex++) { Web currentWeb = webs[webIndex]; //Update current connection context to the web that is beeing process //So commands like Get-PnPList returns the correct list for the current web beeing proccess PnPConnection.Current.Context = (ClientContext)currentWeb.Context; currentWeb.LoadProperties(_webActions.Properties); UpdateWebProgressBar(webs, webIndex, webCount, 0, _totalExecutionTimeStopWatch); if (!_webActions.ShouldProcessAnyAction(currentWeb)) { continue; } processAction = ProcessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessAction, _webActions.Action, ref _currentWebsProcessed, ref _averageWebTime, ref _averageShouldProcessWebTime); if (!processAction) { continue; } if (_listActions.HasAnyAction || _listItemActions.HasAnyAction) { ListCollection lists = currentWeb.Lists; int listCount = lists.Count; for (int listIndex = 0; listIndex < listCount; listIndex++) { List currentList = lists[listIndex]; currentList.LoadProperties(_listActions.Properties); if (_isListNameSpecified && !currentList.Title.Equals(_listName, StringComparison.CurrentCultureIgnoreCase)) { continue; } UpdateWebProgressBar(webs, webIndex, webCount, listIndex, _totalExecutionTimeStopWatch); UpdateListProgressBar(lists, listIndex, listCount); processAction = ProcessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessAction, _listActions.Action, ref _currentListsProcessed, ref _averageListTime, ref _averageShouldProcessListTime); if (!processAction) { continue; } if (_listItemActions.HasAnyAction) { ListItemCollection listItems = currentList.GetItems(CamlQuery.CreateAllItemsQuery()); currentList.Context.Load(listItems); currentList.Context.ExecuteQueryRetry(); int listItemCount = listItems.Count; for (int listItemIndex = 0; listItemIndex < listItemCount; listItemIndex++) { ListItem currentListItem = listItems[listItemIndex]; currentListItem.LoadProperties(_listItemActions.Properties); WriteIterationProgress(ListItemProgressBarId, ListProgressBarId, "Iterating list items", GetTitle(currentListItem), listItemIndex, listItemCount, CalculateRemainingTimeForListItems(listItemCount, listItemIndex)); ProcessAction(currentListItem, GetTitle, _listItemActions.Properties, _listItemActions.ShouldProcessAction, _listItemActions.Action, ref _currentListItemsProcessed, ref _averageListItemTime, ref _averageShouldProcessListItemTime); } CompleteProgressBar(ListItemProgressBarId); } processAction = ProcessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessPostAction, _listActions.PostAction, ref _currentPostListsProcessed, ref _averagePostListTime, ref _averageShouldProcessPostListTime); } CompleteProgressBar(ListProgressBarId); } processAction = ProcessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessPost, _webActions.PostAction, ref _currentPostWebsProcessed, ref _averagePostWebTime, ref _averageShouldProcessPostWebTime); } CompleteProgressBar(WebProgressBarId); }
private void button1_Click(object sender, EventArgs e) { string siteUrl = "https://hp-27b0ee14ded081.sharepoint.com/teams/spohub/ACSMigrationManager/"; ClientContext clientContext = new ClientContext(siteUrl); System.Security.SecureString pwd = new System.Security.SecureString(); pwd.AppendChar('p'); pwd.AppendChar('a'); pwd.AppendChar('s'); pwd.AppendChar('s'); pwd.AppendChar('@'); pwd.AppendChar('w'); pwd.AppendChar('o'); pwd.AppendChar('r'); pwd.AppendChar('d'); pwd.AppendChar('1'); clientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", pwd); Web site = clientContext.Web; clientContext.Load(site); clientContext.ExecuteQuery(); SP.List oList = clientContext.Web.Lists.GetByTitle("Migration Tasks"); CamlQuery query; string sitesText = "" + textBox1.Text; sitesText = sitesText.Replace("\r", ""); sitesText = sitesText.Replace("\n", ","); string[] sites = null; if (sitesText.Length > 0) { sites = sitesText.Split(','); for (int i = 0; i < sites.Length; i++) { if (sites[i].Trim().Length > 0) { query = new CamlQuery(); query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='ContentSource'/><Value Type='Text'>" + sites[i] + "</Value></Contains></Where></Query></View>"; ListItemCollection collListItem = oList.GetItems(query); clientContext.Load(collListItem); clientContext.ExecuteQuery(); if (collListItem.Count == 1) { ListItem oListItem = collListItem[0]; //listBox1.DataSource = collListItem; textBox3.Text += oListItem["Title"].ToString() + @" "; oListItem["MigrationStatus"] = textBox2.Text; oListItem.Update(); clientContext.ExecuteQuery(); } } } } }
private void AddUsers(string siteName, string siteUrl, frm_Data_User userForm) { ClientContext clientContext = SharePoint.GetClient(siteUrl, frm_Main_Menu.username, frm_Main_Menu.password); Web web = clientContext.Web; // Instantiates the User Information List SP.List userList = web.SiteUserInfoList; // Get the current user SP.User user = web.CurrentUser; // Initialise row counter int rowNum = 0; // Create a new Caml Query CamlQuery camlQuery = new CamlQuery(); // Set the XML camlQuery.ViewXml = "<View><Query>{0}</Query></View>"; // Define a collection to store the list items in ListItemCollection collListItem = userList.GetItems(camlQuery); // Load in the items clientContext.Load(collListItem, icol => icol.Include(i => i.ContentType)); clientContext.Load(collListItem); // Attempt to retreive the List Items try { clientContext.ExecuteQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } foreach (SP.ListItem oListItem in collListItem) { // Increment counter rowNum++; int id = (int)oListItem.FieldValues["ID"]; object firstName = oListItem.FieldValues["FirstName"]; object lastName = oListItem.FieldValues["LastName"]; object fullName = oListItem.FieldValues["Title"]; object userName = oListItem.FieldValues["UserName"]; object email = oListItem.FieldValues["EMail"]; object sipAddress = oListItem.FieldValues["SipAddress"]; object isSiteAdmin = oListItem.FieldValues["IsSiteAdmin"]; object deleted = oListItem.FieldValues["Deleted"]; object hidden = oListItem.FieldValues["UserInfoHidden"]; object isActive = oListItem.FieldValues["IsActive"]; string ContentTypeName = oListItem.ContentType.Name; object guid = oListItem.FieldValues["GUID"]; DateTime createDate = Convert.ToDateTime(oListItem.FieldValues["Created"]); SP.FieldUserValue author = (SP.FieldUserValue)oListItem.FieldValues["Author"]; string createUser = author.LookupValue.ToString(); DateTime modifyDate = Convert.ToDateTime(oListItem.FieldValues["Modified"]); SP.FieldUserValue editor = (SP.FieldUserValue)oListItem.FieldValues["Editor"]; string modifyUser = editor.LookupValue.ToString(); if (firstName != null) { //System.Diagnostics.Debugger.Break(); } userForm.AddRow ( rowNum, id, firstName, lastName, fullName, userName, email, sipAddress, isSiteAdmin, deleted, hidden, isActive, ContentTypeName, guid, createDate, createUser, modifyDate, modifyUser ); lbl_Row_Count.Text = rowNum.ToString() + " record(s) found"; lbl_Row_Count.Refresh(); if (rowNum >= nud_Row_Limit.Value && nud_Row_Limit.Value != 0) { break; } } }
/// <summary> /// This method will get all list items from external access requests and process all /// requests which are in accpeted state /// </summary> /// <param name="originalMatter"></param> /// <param name="log"></param> /// <param name="configuration"></param> private static void GetExternalAccessRequestsFromSPO(MatterInformationVM originalMatter, TextWriter log, IConfigurationRoot configuration) { try { foreach (var assignUserEmails in originalMatter.Matter.AssignUserEmails) { foreach (string email in assignUserEmails) { using (var ctx = new ClientContext(originalMatter.Client.Url)) { SecureString password = Utility.GetEncryptedPassword(configuration["General:AdminPassword"]); ctx.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password); //First check whether the user exists in SharePoint or not log.WriteLine($"Checking whether the user {email} has been present in the system or not"); if (CheckUserPresentInMatterCenter(ctx, originalMatter.Client.Url, email, configuration, log) == true) { string requestedForPerson = email; string matterId = originalMatter.Matter.MatterGuid; var listTitle = configuration["Settings:ExternalAccessRequests"]; var list = ctx.Web.Lists.GetByTitle(listTitle); CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(); camlQuery.ViewXml = ""; ListItemCollection listItemCollection = list.GetItems(camlQuery); ctx.Load(listItemCollection); ctx.ExecuteQuery(); log.WriteLine($"Looping all the records from {configuration["Settings:ExternalAccessRequests"]} lists"); foreach (ListItem listItem in listItemCollection) { //The matter id for whom the request has been sent string requestedObjectTitle = listItem["RequestedObjectTitle"].ToString(); //The person to whom the request has been sent string requestedFor = listItem["RequestedFor"].ToString(); //The matter url for which the request has been sent string url = ((FieldUrlValue)listItem["RequestedObjectUrl"]).Url; //The status of the request whether it has been in pending=0, accepeted=2 or withdrawn=5 string status = listItem["Status"].ToString(); //If the status is accepted and the person and matter in table storage equals to item in Access Requests list if (requestedFor == requestedForPerson && matterId == requestedObjectTitle && status == "2") { log.WriteLine($"The user {email} has been present in the system and he has accepted the invitation and providing permssions to matter {originalMatter.Matter.Name} from the user {email}"); UpdateMatter umd = new UpdateMatter(); //Update all matter related lists and libraries permissions for external users umd.UpdateUserPermissionsForMatter(originalMatter, configuration, password); //Update permissions for external users in Catalog Site Collection using (var catalogContext = new ClientContext(configuration["General:CentralRepositoryUrl"])) { catalogContext.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password); umd.AssignPermissionToCatalogLists(configuration["Catalog:SiteAssets"], catalogContext, email.Trim(), configuration["Catalog:SiteAssetsPermissions"], configuration); } log.WriteLine($"The matter permissions has been updated for the user {email}"); log.WriteLine($"Updating the matter status to Accepted in Azure Table Storage"); Utility.UpdateTableStorageEntity(originalMatter, log, configuration["General:CloudStorageConnectionString"], configuration["Settings:TableStorageForExternalRequests"], "Accepted"); } } } } } } } catch (Exception ex) { log.WriteLine($"Exception occured in the method GetExternalAccessRequestsFromSPO. {ex}"); } }
/// <summary> /// Event handler that's being executed by the threads processing the sites. Everything in here must be coded in a thread-safe manner /// </summary> private void SBScanner_TimerJobRun(object sender, TimerJobRunEventArgs e) { lock (scannedSitesLock) { ScannedSites++; } Console.WriteLine("Processing site {0}...", e.Url); try { if (!firstSiteCollectionDone) { firstSiteCollectionDone = true; // Telemetry e.WebClientContext.ClientTag = "SPDev:SBScanner"; e.WebClientContext.Load(e.WebClientContext.Web, p => p.Description); e.WebClientContext.ExecuteQuery(); } // Query the solution gallery CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(); ListItemCollection itemCollection = e.WebClientContext.Web.GetCatalog(121).GetItems(camlQuery); e.WebClientContext.Load(e.WebClientContext.Site, s => s.Id); e.WebClientContext.Load(itemCollection); e.WebClientContext.ExecuteQueryRetry(); string siteOwner = string.Empty; int totalSolutions = 0; int assemblySolutions = 0; int activeSolutions = 0; int activeAssemblySolutions = 0; foreach (ListItem item in itemCollection) { // We've found solutions totalSolutions++; bool status = false; if (item["Status"] != null) { activeSolutions++; status = true; } bool hasAssembly = false; foreach (string s in item["MetaInfo"].ToString().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { if (s.Contains("SolutionHasAssemblies")) { if (s.Contains("1")) { assemblySolutions++; if (status) { activeAssemblySolutions++; } hasAssembly = true; } break; } } if (hasAssembly && string.IsNullOrEmpty(siteOwner)) { // Let's add site owners for the solutions which need our attention List <string> admins = new List <string>(); UserCollection users = e.WebClientContext.Web.SiteUsers; e.WebClientContext.Load(users); e.WebClientContext.ExecuteQueryRetry(); foreach (User u in users) { if (u.IsSiteAdmin) { if (!string.IsNullOrEmpty(u.Email) && u.Email.Contains("@")) { admins.Add(u.Email); } } } if (this.Separator == ";") { siteOwner = string.Join(",", admins.ToArray()); } else { siteOwner = string.Join(";", admins.ToArray()); } } SBScanResult result = new SBScanResult() { SiteURL = e.Url, SiteOwner = hasAssembly ? siteOwner : "", WSPName = item["FileLeafRef"].ToString(), Author = ((FieldUserValue)item["Author"]).LookupValue.Replace(",", ""), CreatedDate = Convert.ToDateTime(item["Created"]), Activated = status, HasAssemblies = hasAssembly, SolutionHash = item["SolutionHash"].ToString(), SolutionID = item["SolutionId"].ToString(), SiteId = e.WebClientContext.Site.Id.ToString(), }; // Doing more than a simple scan... if (Mode == Mode.scananddownload || Mode == Mode.scanandanalyze) { // Only download the solution when there's an assembly. By default we're only downloading and scanning each unique solution just once if (hasAssembly && (!SBProcessed.ContainsKey(result.SolutionHash) || Duplicates == true)) { // Add this solution hash to the dictionary SBProcessed.TryAdd(result.SolutionHash, ""); // Download the WSP package ClientResult <Stream> data = item.File.OpenBinaryStream(); e.WebClientContext.Load(item.File); e.WebClientContext.ExecuteQueryRetry(); if (data != null) { int position = 1; int bufferSize = 200000; Byte[] readBuffer = new Byte[bufferSize]; string localFilePath = System.IO.Path.Combine(".", this.OutputFolder, e.WebClientContext.Site.Id.ToString()); System.IO.Directory.CreateDirectory(localFilePath); string wspPath = System.IO.Path.Combine(localFilePath, item["FileLeafRef"].ToString()); using (System.IO.Stream stream = System.IO.File.Create(wspPath)) { while (position > 0) { // data.Value holds the Stream position = data.Value.Read(readBuffer, 0, bufferSize); stream.Write(readBuffer, 0, position); readBuffer = new Byte[bufferSize]; } stream.Flush(); } // Analyze the WSP package by cracking it open and looking inside if (Mode == Mode.scanandanalyze) { Analyzer analyzer = new Analyzer(); analyzer.Init(this.Verbose); var res = analyzer.ProcessFileInfo(System.IO.Path.GetFullPath(wspPath)); result.IsEmptyAssembly = (res.Assemblies.Count == 1 && res.Assemblies[0].ReferencedAssemblies.Count <= 1 && res.Assemblies[0].Classes.Count == 0); result.IsInfoPath = res.InfoPathSolution; result.HasWebParts = (res.WebPartsCount > 0) || (res.UserControlsCount > 0) || res.Features.Where(f => f.WebParts.Any()).Count() > 0; result.HasWebTemplate = res.Features.Where(f => f.WebTemplateDetails.Any()).Count() > 0; result.HasFeatureReceivers = res.FeatureReceiversCount > 0 || res.Features.Where(f => f.FeatureReceivers.Any()).Count() > 0; result.HasEventReceivers = res.EventHandlersCount > 0 || res.Features.Where(f => f.EventReceivers.Any()).Count() > 0; result.HasListDefinition = res.ListTemplatesCount > 0 || res.Features.Where(f => f.ListTemplates.Any()).Count() > 0; result.HasWorkflowAction = res.Features.Where(f => f.WorkflowActionDetails.Any()).Count() > 0; if (res.InfoPathSolution) { result.IsEmptyInfoPathAssembly = IsEmptyInfoPathAssembly(res); } // Dump the analysis results var serializer = new XmlSerializer(typeof(SolutionInformation)); using (var writer = new StreamWriter(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(wspPath), (System.IO.Path.GetFileNameWithoutExtension(wspPath) + ".xml")))) { serializer.Serialize(writer, res); } // Create new package without assembly if (result.IsEmptyAssembly.Value) { string tempFolder = null; tempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString().Replace("-", "")); // unpack analyzer.UnCab(System.IO.Path.GetFullPath(wspPath), tempFolder); // delete all assemblies var filesToDelete = Directory.GetFiles(tempFolder, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase)); foreach (var file in filesToDelete) { System.IO.File.Delete(file); } // repack (also deletes the temp folder) analyzer.ReCab(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(wspPath), (System.IO.Path.GetFileNameWithoutExtension(wspPath) + "_fixed.wsp")), tempFolder); } } } } } this.SBScanResults.Push(result); } if (totalSolutions > 0) { Console.WriteLine("Site {0} processed. Found {1} solutions in total of which {2} have assemblies and are activated", e.Url, totalSolutions, activeAssemblySolutions); } } catch (Exception ex) { SBScanError error = new SBScanError() { Error = ex.Message, SiteURL = e.Url, }; this.SBScanErrors.Push(error); Console.WriteLine("Error for site {1}: {0}", ex.Message, e.Url); } }
private IDictionary <string, string> AtualizarListaCamposVisiveis() { var temp = new ListItemCollection(); foreach (ListItem item in chkListaCamposVisiveis.Items) { temp.Add(item); } //pegar lista já marcada nos checkbox var manterModulosProgramas = new ManterModulo(); IList <Dominio.Classes.Modulo> ls; var resultado = new Dictionary <string, string>(); var idPrograma = string.IsNullOrEmpty(txtPrograma.Text) ? 0 : int.Parse(txtPrograma.Text); var idOferta = string.IsNullOrWhiteSpace(cbxOfertas.SelectedValue) ? 0 : int.Parse(cbxOfertas.SelectedValue); var idModulo = string.IsNullOrWhiteSpace(cbxModulos.SelectedValue) ? 0 : int.Parse(cbxModulos.SelectedValue); if (idModulo != 0) { ls = new List <Modulo> { manterModulosProgramas.ObterPorId(idModulo) }; } else if (idOferta != 0) { ls = manterModulosProgramas.ObterPorCapacitacao(idOferta); WebFormHelper.PreencherLista(ls, cbxModulos, true); } else if (idPrograma != 0) { ls = manterModulosProgramas.ObterPorPrograma(idPrograma); } else { ls = manterModulosProgramas.ObterTodos(); } foreach (var item in ls) { var itemPrazo = new ListItem { Selected = true, Text = item.Nome + " - Prazo", Value = "MD__" + RemoveExtraChars(item.Nome) + "__prazo__" + item.ID + "__" }; var itemSolucoesInscritas = new ListItem { Selected = true, Text = item.Nome + " - Soluções Inscritas", Value = "MD__" + RemoveExtraChars(item.Nome) + "__SolucoesInscritas__" + item.ID + "__" }; var itemSolucoesConcluidas = new ListItem { Selected = true, Text = item.Nome + " - Soluções Concluídas", Value = "MD__" + RemoveExtraChars(item.Nome) + "__SolucoesConcluidas__" + item.ID + "__" }; _lsItens.Add(itemPrazo); _lsItens.Add(itemSolucoesInscritas); _lsItens.Add(itemSolucoesConcluidas); resultado.Add(itemPrazo.Value, item.Nome); resultado.Add(itemSolucoesInscritas.Value, item.Nome); resultado.Add(itemSolucoesConcluidas.Value, item.Nome); } WebFormHelper.PreencherLista(_lsItens, chkListaCamposVisiveis); foreach (ListItem item in chkListaCamposVisiveis.Items) { var valor = true; if (temp.Count > 0) { var item1 = item; foreach (var tmp in temp.Cast <ListItem>().Where(tmp => tmp.Value == item1.Value)) { valor = tmp.Selected; break; } } item.Selected = valor; } foreach (var item in ls) { foreach (var item2 in _lsItens.Cast <ListItem>().Where(item2 => item2.Text.IndexOf(item.Nome) >= 0)) { item2.Text = item2.Text.Replace(item.Nome + " - ", ""); } } dgRelatorio.Columns.Clear(); foreach (ListItem item in _lsItens) { dgRelatorio.Columns.Add(new BoundField { HeaderText = item.Text, DataField = item.Value, SortExpression = item.Value }); } return(resultado); }