Get the All Infromation of SharePoint Server using Client Object Model - sharepoint

I want to Create a Windows Application that
Display :
all Web Application,
Sites Collection of Each web Applications,
Sites of Each Site Collection,
Sub-Sites of Each Sites,
All lists-Libraries of Each Site and Sub-Sites in Tree-view
here i don't want to Give any Static URL, on Application Start up That All Information Filled Automatically in Tree-view if SharePoint is Installed on that Computer.
Is this Possible ? if yes then how ?

.Net Managed Client Object Model: Fetch All Webs, Libraries, Items
In SharePoint 2010, we have 3 client object model.
.Net Managed Client Object Model
Silverlight
ECMA Script / JavaScript
Today, I am presenting .NET Managed Client Object Model to retrieve all webs, libraries, items from SharePoint.
Prerequisites References for your desktop application:
1. Microsoft.SharePoint.Client.dll
2. Microsoft.SharePoint.Client.Runtime.dll
My Custom Classes to feel like we are working on SharePoint Server Object model:
public class SPWeb
{
public string WebGUID { get; set; }
public string Title { get; set; }
public string ServerRelativeUrl { get; set; }
public string ParentType { get; set; }
public SPBase Parent { get; set; }
}
public class SPList
{
public string ListGUID { get; set; }
public string Title { get; set; }
public string ParentWebUrl { get; set; }
public string RootFolderServerRelativeUrl { get; set; }
}
public class SPFolder
{
public string ID { get; set; }
public string UniqueID { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string ParentWebUrl { get; set; }
public string ListName { get; set; }
public string ServerRelativeUrl { get; set; }
public string ParentFolderServerRelativeUrl { get; set; }
}
public class SPListItem
{
public string ID { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string ServerRelativeUrl { get; set; }
public string Modified { get; set; }
public string ModifiedBy { get; set; }
public string CreatedBy { get; set; }
public string Size { get; set; }
public string Created { get; set; }
public string UniqueId { get; set; }
public string ListName { get; set; }
}
Methods which is used to fetch Webs / libraries / Items:
public List<SPWeb> GetAllWebs(string webURL)
{
var webColl = new List<SPWeb>();
try
{
var currentWeb = _ctx.Site.OpenWeb(webURL);
var allWebs = currentWeb.Webs;
var webCollection = _ctx.LoadQuery(allWebs.Include(web => web.Title,
web => web.Id, web => web.ServerRelativeUrl));
_ctx.ExecuteQuery();
webColl.AddRange(webCollection.Select(web => new SPWeb
{
Title = web.Title,
WebGUID = web.Id.ToString(),
ServerRelativeUrl = web.ServerRelativeUrl
}));
}
catch (Exception ex)
{
// error log
}
return webColl;
}
public List<SPList> GetAllLibraries(string webURL)
{
var listColl = new List<SPList>();
try
{
var currentWeb = _ctx.Site.OpenWeb(webURL);
var query = from list in currentWeb.Lists
where list.BaseType == BaseType.DocumentLibrary
select list;
var AllLists = currentWeb.Lists;
var listCollection = _ctx.LoadQuery(query.Include(myList => myList.Title,
myList => myList.Id,
myList => myList.RootFolder.ServerRelativeUrl,
myList => myList.ParentWebUrl,
myList => myList.Hidden,
myList => myList.IsApplicationList));
_ctx.ExecuteQuery();
listColl.AddRange(from list in listCollection
where !list.Hidden
select new SPList
{
Title = list.Title,
ListGUID = list.Id.ToString(),
RootFolderServerRelativeUrl = list.RootFolder.ServerRelativeUrl,
ParentWebUrl = list.ParentWebUrl
});
}
catch (Exception ex)
{
// error log
}
return listColl;
}
public List<SPFolder> GetAllFolder(string webURL, string listName, string folderName)
{
var itemColl = new List<SPFolder>();
try
{
var currentWeb = _ctx.Site.OpenWeb(webURL);
var currentList = currentWeb.Lists.GetByTitle(listName);
var query = new CamlQuery();
if (folderName.Length > 0)
query.FolderServerRelativeUrl = folderName;
query.ViewXml = #"<View><Query><Where>
<Or>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>Document Set</Value>
</Eq>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>Folder</Value>
</Eq>
</Or>
</Where></Query></View>";
var listitems = currentList.GetItems(query);
_ctx.Load(listitems);
_ctx.ExecuteQuery();
itemColl.AddRange(listitems.ToList().Select(item => new SPFolder()
{
ID = Convert.ToString(item["ID"]),
UniqueID = Convert.ToString(item["GUID"]),
ListName = listName,
ParentWebUrl = webURL,
Title = Convert.ToString(item["FileLeafRef"]),
Name = "folder",
ServerRelativeUrl = Convert.ToString(item["FileRef"])
}).AsEnumerable());
}
catch (Exception ex)
{
// error log
}
return itemColl;
}
public List<SPListItem> GetAllItems(string webURL, string listName, string folderName)
{
var itemColl = new List<SPListItem>();
try
{
var currentWeb = _ctx.Site.OpenWeb(webURL);
var currentList = currentWeb.Lists.GetByTitle(listName);
var query = new CamlQuery();
if (folderName.Length > 0)
query.FolderServerRelativeUrl = folderName;
var myquery = from myitems in currentList.GetItems(query)
select myitems;
var listitems = _ctx.LoadQuery(myquery.Include(myitem => myitem["ID"],
myitem => myitem["FileLeafRef"],
myitem => myitem["Modified"],
myitem => myitem["File_x0020_Size"],
myitem => myitem["Modified_x0020_By"],
myitem => myitem["Created_x0020_By"],
myitem => myitem["FileRef"],
myitem => myitem["UniqueId"],
));
_ctx.ExecuteQuery();
foreach (var nitem in listitems.Select(item => new SPListItem
{
ID = Convert.ToString(item["ID"]),
ParentWebUrl = webURL,
Title = Convert.ToString(item["FileLeafRef"]),
Modified = item["Modified"] != null ? Convert.ToString(item["Modified"]) : string.Empty, Size = item["File_x0020_Size"] != null ? Convert.ToString(item["File_x0020_Size"]) : string.Empty,
CreatedBy = item["Created_x0020_By"] != null ? Convert.ToString(item["Created_x0020_By"]) : string.Empty,
ModifiedBy = item["Modified_x0020_By"] != null ? Convert.ToString(item["Modified_x0020_By"]) : string.Empty,
UniqueId = item["UniqueId"].ToString(),
ServerRelativeUrl = Convert.ToString(item["FileRef"]),
ListName = listName
}))
itemColl.Add(nitem);
}
catch (Exception ex)
{
// error log
}
return itemColl;
}
For this I used following reference,
http://shahjinesh11.wordpress.com/2012/06/14/net-managed-client-object-model-fetch-all-webs-libraries-items/
it may helps you Good Luck :-)

my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var service = SPFarm.Local.Services.GetValue<SPWebService>(string.Empty);
foreach (SPWebApplication webApplication in service.WebApplications)
{
ShowSiteCollection(webApplication.Sites);
}
}
}
private void ShowSiteCollection(IEnumerable<SPSite> sites)
{
foreach (SPSite site in sites)
{
using (site)
{
var rootWeb = site.RootWeb;
var node = new TreeNode(rootWeb.Title, rootWeb.Url);
if (rootWeb.Webs.Count > 0)
{
ShowWebCollection(rootWeb.Webs, (title, url) => node.ChildNodes.Add(new TreeNode(title, url)));
}
siteCollectionTree.Nodes.Add(node);
}
}
}
private static void ShowWebCollection(SPWebCollection collection, Action<string, string> func)
{
for (var i = 0; i < collection.Count; i++)
{
var info = collection.WebsInfo[i];
func.Invoke(info.Title, info.ServerRelativeUrl);
if (collection[i].Webs.Count > 0)
{
ShowWebCollection(collection[i].Webs, func);
}
}
}
And method for getting list:
private static IEnumerable<List> GetSiteLists(string siteUrl)
{
using (var context = new ClientContext(siteUrl))
{
var query = from lists in context.Web.Lists
where !lists.Hidden
select lists;
var siteLists = context.LoadQuery(query);
context.ExecuteQuery();
return siteLists;
}
}
I don't claim, that the solution is the best, but it works. Good luck!

Related

Adding multiple classes to a shopping cart class .net mvc 5

I'm trying to come up with a car service booking application that allows one to either book a car into a service as well as buy a few parts, which is not essential, but I get an error that reads as follows:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.BasketLines_dbo.Parts_PartID". The conflict occurred in database "aspnet-Noir-20190224082924", table "dbo.Parts", column 'PartId'.
The statement has been terminated.
My classes are as follows:
PART
public class Part
{
[Key]
public int PartId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public byte[] ImageFile { get; set; }
public string ImageFilePath { get; set; }
public decimal Price { get; set; }
public virtual ICollection<ServicePartMapping>
ServicePartMappings { get; set;}
}
Service
public class Service
{
public int ServiceId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public decimal Price { get; set; }
public ICollection<Part> Parts { get; set; }
}
ServicePartMapping
public class ServicePartMapping
{
public int ServicePartMappingID { get; set; }
public int PartNumber { get; set; }
public int? ServiceId { get; set; }
public int? ServicePartId { get; set; }
public virtual Service Service { get; set; }
public virtual ServicePart ServicePart { get;
set; }
}
Basket
public class Basket
{
public int Id { get; set; }
private string BasketID { get; set; }
private const string BasketSessionKey =
"BasketID";
private ApplicationDbContext db = new
ApplicationDbContext();
private string GetBasketID()
{
if
(HttpContext.Current.Session[BasketSessionKey]
== null)
{
if
(!string.IsNullOrWhiteSpace
(HttpContext.Current
.User.Identity.Name))
{
HttpContext.Current
.Session[BasketSessionKey] =
HttpContext.Current
.User.Identity.Name;
}
else
{
Guid tempBasketID = Guid.NewGuid()
HttpContext.Current
.Session[BasketSessionKey]
= tempBasketID.ToString();
}
}
return
HttpContext.Current
.Session[BasketSessionKey].ToString();
}
public static Basket GetBasket()
{
Basket basket = new Basket();
basket.BasketID = basket.GetBasketID();
return basket;
}
public void AddServiceToBasket(int serviceID,
int quantity)
{
var basketLine =
db.BasketLines.FirstOrDefault(b =>
b.BasketID == BasketID && b.ServiceID
== serviceID);
if (basketLine == null)
{
basketLine = new BasketLine
{
ServiceID = serviceID,
BasketID = BasketID,
Quantity = quantity,
DateCreated = DateTime.Now
};
db.BasketLines.Add(basketLine);
}
else
{
basketLine.Quantity += quantity;
}
db.SaveChanges();
}
public void AddPartToBasket(int partID, int
quantity)
{
var basketLine =
db.BasketLines.FirstOrDefault(b =>
b.BasketID == BasketID && b.PartId
== partID);
if (basketLine == null)
{
basketLine = new BasketLine
{
PartId = partID,
BasketID = BasketID,
Quantity = quantity,
DateCreated = DateTime.Now
};
db.BasketLines.Add(basketLine);
}
else
{
basketLine.Quantity += quantity;
}
db.SaveChanges();
}
public void RemoveLine(int ID)
{
var basketLine = db.BasketLines.FirstOrDefault(b => b.BasketID == BasketID && b.ServiceID
== ID || b.PartId == ID);
if (basketLine != null)
{
db.BasketLines.Remove(basketLine);
}
db.SaveChanges();
}
public void UpdateBasket(List<BasketLine> lines)
{
foreach (var line in lines)
{
var basketLine = db.BasketLines.FirstOrDefault(b => b.BasketID == BasketID &&
b.ServiceID == line.ServiceID);
if (basketLine != null)
{
if (line.Quantity == 0)
{
RemoveLine(line.ServiceID);
}
else
{
basketLine.Quantity = line.Quantity;
}
}
}
db.SaveChanges();
}
public void EmptyBasket()
{
var basketLines = db.BasketLines.Where(b => b.BasketID == BasketID);
foreach (var basketLine in basketLines)
{
db.BasketLines.Remove(basketLine);
}
db.SaveChanges();
}
public List<BasketLine> GetBasketLines()
{
return db.BasketLines.Where(b => b.BasketID == BasketID).ToList();
}
public decimal GetTotalCost()
{
decimal basketTotal = decimal.Zero;
decimal serviceTotal = decimal.Zero;
decimal partTotal = decimal.Zero;
if (GetBasketLines().Count > 0)
{
serviceTotal = db.BasketLines.Where(b => b.BasketID == BasketID).Sum(b => b.Service.Price
* b.Quantity);
partTotal = db.BasketLines.Where(b => b.BasketID == BasketID).Sum(b => b.Part.Price
* b.Quantity);
basketTotal = serviceTotal + partTotal;
}
return basketTotal;
}
public int GetNumberOfItems()
{
int numberOfItems = 0;
if (GetBasketLines().Count > 0)
{
numberOfItems = db.BasketLines.Where(b => b.BasketID == BasketID).Sum(b => b.Quantity);
}
return numberOfItems;
}
public void MigrateBasket(string userName)
{
//find the current basket and store it in memory using ToList()
var basket = db.BasketLines.Where(b => b.BasketID == BasketID).ToList();
//find if the user already has a basket or not and store it in memory using ToList()
var usersBasket = db.BasketLines.Where(b => b.BasketID == userName).ToList();
//if the user has a basket then add the current items to it
if (usersBasket != null)
{
//set the basketID to the username
string prevID = BasketID;
BasketID = userName;
//add the lines in anonymous basket to the user's basket
foreach (var line in basket)
{
AddServiceToBasket(line.ServiceID, line.Quantity);
AddPartToBasket(line.PartId, line.Quantity);
}
//delete the lines in the anonymous basket from the database
BasketID = prevID;
EmptyBasket();
}
else
{
//if the user does not have a basket then just migrate this one
foreach (var basketLine in basket)
{
basketLine.BasketID = userName;
}
db.SaveChanges();
}
HttpContext.Current.Session[BasketSessionKey] = userName;
}
public decimal CreateOrderLines(int orderID)
{
decimal orderTotal = 0;
var basketLines = GetBasketLines();
foreach (var item in basketLines)
{
BillLine BillLine = new BillLine
{
Service = item.Service,
ServiceID = item.ServiceID,
ServiceName = item.Service.Name,
Quantity = item.Quantity,
ServicePrice = item.Service.Price,
BillID = orderID
};
orderTotal += (item.Quantity * item.Service.Price);
db.BillLines.Add(BillLine);
}
db.SaveChanges();
EmptyBasket();
return orderTotal;
}
}
BasketLine
public class BasketLine
{
public int ID { get; set; }
public string BasketID { get; set; }
public int ServiceID { get; set; }
public int PartId { get; set; }
[Range(0, 50, ErrorMessage = "Please enter a quantity between 0 and 50")]
public int Quantity { get; set; }
public DateTime DateCreated { get; set; }
public virtual Service Service { get; set; }
public virtual Part Part { get; set; }
}
Assumed that EF Code First is used, the exception message indicates that you're using foreign key constraint inside BasketLines table which references PartId primary key column in Parts table, and you're trying to insert a value into BasketLines.PartId column which not exist in Parts table at this statement:
basketLine = new BasketLine
{
PartId = partID, // this assignment is the problem source
BasketID = BasketID,
Quantity = quantity,
DateCreated = DateTime.Now
};
db.BasketLines.Add(basketLine);
Based from inspection, you're trying to build relationship between Service, Part and BasketLine entities, therefore I suggested to add ForeignKeyAttribute for ServiceId and PartId property in BasketLine entity:
public class BasketLine
{
public int ID { get; set; }
public string BasketID { get; set; }
[ForeignKey("Service")]
public int ServiceID { get; set; }
[ForeignKey("Part")]
public int PartId { get; set; }
[Range(0, 50, ErrorMessage = "Please enter a quantity between 0 and 50")]
public int Quantity { get; set; }
public DateTime DateCreated { get; set; }
public virtual Service Service { get; set; }
public virtual Part Part { get; set; }
}
Additionally, since it's stated that a BasketLine requires Service with optional Part, you may also try modify OnModelCreating() method inside DbContext like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BasketLine>()
.HasOptional(x => x.Part) // can save BasketLine without specifying Part
.WithRequired(x => x.Service); // cannot save BasketLine without using Service
}
Related issues:
Configure One-to-One Relationships in EF Code First
The INSERT statement conflicted with the FOREIGN KEY constraint

Navigation property is null

Album navigation property is null in SellingRequest when I try to load it by include() while it seems every thing is OK!
These are the codes:
public class Album
{
public int Id { get; set; }
public string Note { get; set; }
public virtual SellingRequest SellingRequest { get; set; }
public int? SellingRequestId { get; set; }
public List<Photo> Photos { get; set; }
public virtual MortgageAndRent MortgageAndRent { get; set; }
public int? MortgageAndRentId { get; set; }
}
public class SellingRequest
{
#region Properies
public int Id { get; set; }
public virtual Album Album { get; set; }
public int AlbumId { get; set; }
#endregion Properies
}
Here is where I create album for SellingRequest.
public ActionResult DoUpload(HttpPostedFileBase file, UploadPopupViewModel uploadPopupViewModel)
{
if (file != null && file.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath("~/Contents/Images"), Path.GetFileName(file.FileName));
file.SaveAs(path);
Photo photo = new Photo() { Path = path };
ResponseMessage<Album> album = new ResponseMessage<Album>();
if(uploadPopupViewModel.SellingRequestId!=0)
album = _albumService.GetAlbumBySellingRequestId(uploadPopupViewModel.SellingRequestId);
if (uploadPopupViewModel.MortgageAndRentId != 0)
album = _albumService.GetAlbumByMortgageAndRentId(uploadPopupViewModel.SellingRequestId);
if (album.IsSuccess)
{
photo.AlbumId = album.Result.Id;
}
else
{
Album newAlbum = new Album();
if (uploadPopupViewModel.SellingRequestId != 0)
newAlbum.SellingRequestId = uploadPopupViewModel.SellingRequestId;
if (uploadPopupViewModel.MortgageAndRentId != 0)
newAlbum.MortgageAndRentId = uploadPopupViewModel.MortgageAndRentId;
ResponseMessage<Album> beingSavedAlbum = _albumService.Insert(newAlbum);
ResponseMessage<SellingRequest> sellingRequest = _sellingRequestService.GetById(uploadPopupViewModel.SellingRequestId);
if(sellingRequest.IsSuccess)
{
sellingRequest.Result.AlbumId = newAlbum.Id;
_sellingRequestService.Update(sellingRequest.Result);
}
if(beingSavedAlbum.IsSuccess)
photo.AlbumId = beingSavedAlbum.Result.Id;
}
ResponseMessage<Photo> beingSavedPhoto = _photoService.Insert(photo);
if (beingSavedPhoto.IsSuccess)
{
return RedirectToAction("UploadPopup", "Photo", uploadPopupViewModel);
}
else
{
ModelState.AddModelError("ImageError", beingSavedPhoto.ErrorMessages[0]);
return View("AddPhoto");
}
}
else
{
ModelState.AddModelError("ImageError", "Please choose a photo.");
return View("AddPhoto");
}
}
}
And Here is where I Try to query:
public IEnumerable<TEntity> GET(Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = _context.Set<TEntity>();
if (filter != null)
query = query.Where(filter);
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
query = query.Include(includeProperty);
if (orderBy != null)
return orderBy(query).ToList();
else
return query.ToList();
}
And consequently, Here is where I try to load Album by include.
public List<SellingRequest> GetAllSellingRequests()
{
List<SellingRequest> sellingRequests = _sellingRepository.GET(null, includeProperties: "Address,Album.Photos", orderBy: sR => sR.OrderBy(s => s.RegisteredDate).OrderByDescending(s => s.RegisteredDate)).ToList();
return sellingRequests;
}
With this function I have the Address property but Album is null! It also happens vise versa. I mean when I include the sellingRequest from album, it returns me null, as well! This is while I can include all other entities with no problem!
Edit
This is the schema of my table in database:
SellingRequest Table
And this is the picture of Get.
Any suggestion would be appreciated in advance.
Regards

Create field in SharePoint programmatically using CSOM (Not with XML)

Is it possible to create fields in SharePoint with CSOM, not using XML?
I've seen many examples using XML, but none with just setting properties for the field programmatically?
fields.Add(new **FieldCreationInformation** {
InternalName = "Test",
etc..
});
That's doable, in the following example is introduced a FieldCreationInformation class:
[XmlRoot("Field")]
public class FieldCreationInformation
{
[XmlAttribute("ID")]
public Guid Id { get; set; }
[XmlAttribute()]
public string DisplayName { get; set; }
[XmlAttribute("Name")]
public string InternalName { get; set; }
[XmlIgnore()]
public bool AddToDefaultView { get; set; }
//public IEnumerable<KeyValuePair<string, string>> AdditionalAttributes { get; set; }
[XmlAttribute("Type")]
public FieldType FieldType { get; set; }
[XmlAttribute()]
public string Group { get; set; }
[XmlAttribute()]
public bool Required { get; set; }
public string ToXml()
{
var serializer = new XmlSerializer(GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, this, emptyNamepsaces);
return stream.ToString();
}
}
public FieldCreationInformation()
{
Id = Guid.NewGuid();
}
}
and then extension method for creating a new field:
public static class FieldCollectionExtensions
{
public static Field Add(this FieldCollection fields, FieldCreationInformation info)
{
var fieldSchema = info.ToXml();
return fields.AddFieldAsXml(fieldSchema, info.AddToDefaultView, AddFieldOptions.AddFieldToDefaultView);
}
}
Usage
var fieldInfo = new FieldCreationInformation();
fieldInfo.FieldType = FieldType.Geolocation;
fieldInfo.InternalName = "ContactsLocation";
fieldInfo.DisplayName = "Contacts Location";
ctx.Site.RootWeb.Fields.Add(fieldInfo);
ctx.ExecuteQuery();
When I add fields with CSOM/JSOM I use the method on the FieldCollection AddFieldAsXml. This requires you to build a string of xml with all of the properties for the desired field, but it works. I included an excerpt of the related cpde below:
Microsoft.SharePoint.Client.Web web = _context.Web;
FieldCollection fields = web.Fields;
_context.Load(fields);
_context.ExecuteQuery();
Field field = fields.FirstOrDefault(f => f.StaticName == _staticName);
if (field == null)
{
Field createdField = fields.AddFieldAsXml(xml, false, AddFieldOptions.AddToNoContentType);
_context.Load(createdField);
_context.ExecuteQuery();
}
Similar code is used if you would like to add a field directly to an existing list.

Create a DropDown List from a db Entity MVC5

I want to create a dropdown list based on the contents of a db entity.
This seems like a simple enough concept but I can't really seem to pin it down.
Here's my code:
MODEL
public partial class Escuela
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Escuela()
{
this.Empleadoes = new HashSet<Empleado>();
}
public int ID { get; set; }
public string Nombre { get; set; }
public int PuestoID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Empleado> Empleadoes { get; set; }
public virtual Puesto Puesto { get; set; }
}
public partial class ESCUELAEntities : DbContext
{
public ESCUELAEntities()
: base("name=ESCUELAEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Alumno> Alumnoes { get; set; }
public virtual DbSet<Empleado> Empleadoes { get; set; }
public virtual DbSet<Escuela> Escuelas { get; set; }
public virtual DbSet<Grupo> Grupoes { get; set; }
public virtual DbSet<Puesto> Puestoes { get; set; }
}
CONTROLLER
public ActionResult Index()
{
// HAVE TRIED THESE THREE
// #1
var EscQry = from d in db.Escuelas
select d.Nombre;
var escuelas = new SelectList(EscQry, "ID", "Nombre");
ViewData["esc"] = escuelas;
// #2
var escuelas = new SelectList(from d in db.Escuelas
select new SelectListItem { Text = d.Nombre, Value = d.ID.ToString() });
ViewData["esc"] = escuelas;
// #3
IEnumerable<Escuela> model = from p in db.Escuelas
select new Escuela { Nombre = p.Nombre };
// #1
return View();
// #2
return View();
// #3
return View(model);
}
VIEW
#model IEnumerable<_3E_III.Models.Escuela>
#{
ViewBag.Title = "Home Page";
}
#Html.DropDownList("Escuelas", ViewData["esc"] as List<SelectListItem>)
I get this error.
There is no ViewData item of type 'IEnumerable' that has the key 'Escuelas'.
I would make a View Model of the domain class, based on what properties I would need to show in my view.
public class EscuelaViewModel
{
public int ID { get; set; }
public string Nombre { get; set; }
public int PuestoID { get; set; }
.............. etc.
public Collection<SelectListItem> Escuelas {get; set;}
private static Collection<SelectListItem> CreateEscuelasOptions(string selectedOption == "")
{
var model = from p in db.Escuelas select new Escuela { Number = p.Nombre, Id= p.Id };
var options = new Collection<SelectListItem>();
foreach(var esc in model)
options.Add(new SelectListItem {Value = esc.Id, Text = esc.Number, Selected = selectedOption.Equals(esc.Number)});
return options;
}
public void LoadViewData()
{
Escuelas = CreateEscuelasOptions(Nombre);
}
}
Then, in the Controller:
public ActionResult Index()
{
var EscuelaViewModel = new EscuelaViewModel();
EscuelaViewModel.LoadViewData();
return View(EscuelaViewModel);
}
And the View:
#model EscuelaViewModel
#{
ViewBag.Title = "Home Page";
}
#Html.DropDownListFor(x => x.Nombre, Model.Escuelas, --Select option--)

Xml Parsing in C#

http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom on this site, I wrote the following code to retrieve the data.
protected void Button1_Click(object sender, EventArgs e)
{
string adresal = "http://" + txtAd.Text;
WebResponse GelenCevap;
WebRequest adresistegi = HttpWebRequest.Create(adresal);
GelenCevap = adresistegi.GetResponse();
StreamReader CevapOku = new StreamReader(GelenCevap.GetResponseStream());
string KaynakKodlar = CevapOku.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
xmlDoc.Load("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom"); // Load the XML document from the specified file
XmlNodeList depremler = xmlDoc.GetElementsByTagName("entry");
foreach (XmlNode node in depremler)
{
var a = node.ChildNodes;
foreach (XmlElement x in a)
{
ListBox1.Items.Add(x.InnerText);
}
}
}
In this way I get all the data in the ListBox.But I need to assign them to variable data line by line.How can I do? I would appreciate if you can help.
Also i need id,title, updated, georss:point,georss:elev variables.
First add an Enrty and Category class:
public class Entry
{
public string Id { get; set; }
public string Title { get; set; }
public string Updated { get; set; }
public string Summary { get; set; }
public string GPoint { get; set; }
public string GElev { get; set; }
public List<string> Categories { get; set; }
}
public class Category
{
public string Label { get; set; }
public string Term { get; set; }
}
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path");
List<Entry> entries = (from x in xDoc.Descendants("entry")
select new Entry()
{
Id = (string) x.Element("id"),
Title = (string)x.Element("title"),
Updated = (string)x.Element("updated"),
Summary = (string)x.Element("summary"),
GPoint = (string)x.Element("georss:point"),
GElev = (string)x.Element("georss:elev"),
Categories = (from c in x.Elements("category")
select new Category
{
Label = (string)c.Attribute("label"),
Term = (string)c.Attribute("term")
}).ToList();
}).ToList();

Resources