How to parse this XML using linq to xml? - asp.net

i am trying to parse following xml but no sucess any one guide me what mistake am i doing here
string feedURL = "http://www.bbc.co.uk/arabic/index.xml";
XDocument feedSource;
feedSource = XDocument.Load(feedURL);
var another = (from myFeed in feedSource.Descendants("entry")
select new
{
feedTitle = myFeed.Element("title").Value,
//feedDescription = myFeed.Element("description").Value,
//feedLink = myFeed.Element("link").Value,
feedpubDate = myFeed.Element("published") != null ? myFeed.Element("published").Value : null
//feedcategory = myFeed.Element("category") != null ? myFeed.Element("category").Value : null,
//feedItems = myFeed.Descendants("entry")
}
);
if (another != null && another.Count() > 0)
{
}
else
{
Response.Write("No Record Found");
}
it is showing me no record found.
any help would be appreciated.

This worked in LINQPad:
XNamespace xns = "http://www.w3.org/2005/Atom";
var xdoc = XDocument.Load("http://www.bbc.co.uk/arabic/index.xml");
xdoc.Element(xns + "feed").Elements(xns + "entry");
Problem was the lacking namespace.

Related

ASP.MVC Image edit

public ActionResult Edit([Bind(Include = "id,category,title,image,active,ImageFile")] page_image page_image)
{
if (ModelState.IsValid)
{
if (page_image.ImageFile != null)
{
string fileName = Path.GetFileNameWithoutExtension(page_image.ImageFile.FileName);
string extension = Path.GetExtension(page_image.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssff") + extension;
page_image.image = "/Uploads/page_images/" + fileName;
fileName = Path.Combine(Server.MapPath("/Uploads/page_images"), fileName);
page_image.ImageFile.SaveAs(fileName);
}
db.Entry(page_image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.category = new SelectList(db.page, "id", "title", page_image.category);
return View(page_image);
}
Here I'm able to edit the User but is not showing the previous Image so If I click submit with out loading a new Image it will delete the previous one. What I have to do is the Edit view, I want it to show the name of the image. Can you guide me to the right direction?
The problem is because you save the view model as is to the Database, you should have a DTO. Anyway, try to get the ImageFile from the DB again, in case it submitted null.
if(page_image.ImageFile != null)
{
// your uploading logic
}
else
{
var oldData = db.Set<page_image>().Where(x => x.id == page_image.id).FirstOrDefault();
page_image.ImageFile = oldData.ImageFile;
}
If page_image.Image is null then get previous image and assign
if (page_image.ImageFile != null)
{
string fileName = Path.GetFileNameWithoutExtension(page_image.ImageFile.FileName);
string extension = Path.GetExtension(page_image.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssff") + extension;
page_image.image = "/Uploads/page_images/" + fileName;
fileName = Path.Combine(Server.MapPath("/Uploads/page_images"), fileName);
page_image.ImageFile.SaveAs(fileName);
} else {
// get existing image from database
var data = db.page_image.AsNoTracking().Where(b => b.id == page_image.id).FirstOrDefault();
//assign to existing image
page_image.image = data.image ;
}
db.Entry(page_image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
Update :
Error is throwing here because of same instance of dbcontext. You can create new instance to fetch or do as following.
var data = db.page_image.AsNoTracking().Where(b => b.id == page_image.id).FirstOrDefault();
or
using (var db2 = new YourDbContext())
{
var data = db2.page_image.Where(b => b.id == page_image.id).FirstOrDefault();
}

DBnull issue when converting empty string to number

Hello I am trying to connect with Oracle and sending parameters as part of store procedure. Two of my parameters are coming as empty string so I need to pass null values but the datatype is set as number in the db end. When ever I run the script it gives me error that "Object cannot be cast from DBNull to other types".
Here is my code snippet remember string Case, string SRE_Pricing are coming in as "" .So I need to convert to number if there is anyting in text like "52" and if "" then assign DB null.
OracleParameter CaseParam = new OracleParameter("arg_CASE_NUMBER", OracleType.Number);
CaseParam.Direction = ParameterDirection.Input;
if (Case != null || Case!="")
{
CaseParam.Value = Convert.ToInt32((Case.Equals(string.Empty)) ? (object)DBNull.Value : Case);
}
else
{
CaseParam.Value = DBNull.Value;
}
//CaseParam.Value =Convert.ToInt32(Case);
cmd.Parameters.Add(CaseParam);
OracleParameter SRE_pricingParam = new OracleParameter("arg_SRE_PRICING_ELEMENT", OracleType.Number);
SRE_pricingParam.Direction = ParameterDirection.Input;
if (SRE_Pricing != null || SRE_Pricing != "")
{
SRE_pricingParam.Value = Convert.ToInt32((SRE_Pricing.Equals(string.Empty)) ? (object)DBNull.Value : SRE_Pricing);
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}
//SRE_pricingParam.Value = Convert.ToInt32(SRE_Pricing);
cmd.Parameters.Add(SRE_pricingParam);
enter image description here
You need to use && operator instead of || in the if condition
if (SRE_Pricing != null && SRE_Pricing != "")
{
SRE_pricingParam.Value = Convert.ToInt32(SRE_Pricing);
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}
Better to use Int32.TryParse()
int price;
if (Int32.TryParse(SRE_Pricing, out price))
{
SRE_pricingParam.Value = price;
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}

.NET Already Open DataReader

I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?
There is already an open DataReader associated with this Command which must be closed first.
public ActionResult CheckLinks(Link model)
{
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
string live = "";
if (pageContent.Contains(item.Obpage))
{
live = "Yes";
}
else { live = "No"; }
var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
db.Entry(link).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:
db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
So your code could look like this:
var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)

Attaching the DbEntityEntry to Context

i am trying to implement a log system to the entitiy framework context.
i want to get the deleted element primary key when its state is deleted.
this is my code:
if (item.State == EntityState.Added || item.State == EntityState.Deleted) {
log = new dt_islemLog();
log.eskiDeger = null;
log.islem = (item.State == EntityState.Added) ? Enums.GetDBValue(Enums.islemDurum.EKLENDI) : Enums.GetDBValue(Enums.islemDurum.SILINDI);
log.islemYapanKullanici_id = kullaniciID;
log.nesneAd = item.Entity.GetType().Name;
log.oturum_id = oturumID;
log.zaman = DateTime.Now;
base.SaveChanges();
var ID = GetPrimaryKeyValue(item);
log.nesneID = ID != null ? ID.ToString() : null;
this.dt_islemLog.Add(log);
}
And this is the method that i get the primary key
object GetPrimaryKeyValue(DbEntityEntry entry) {
try {
if (entry.State == EntityState.Detached)
((IObjectContextAdapter)this).ObjectContext.Attach((System.Data.Entity.Core.Objects.DataClasses.IEntityWithKey)entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch(Exception ex) {
return null;
}
}
But i can't attach the (entry.Entitiy) to context because the cast operation is invalid. How can i get the primary key ?
If someone needs i have found the solution. i have updated the primary key method to like this
object GetPrimaryKeyValue(DbEntityEntry entry)
{
try
{
if (entry.State == EntityState.Detached)
this.Set(entry.Entity.GetType()).Attach(entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch
{
return null;
}
}

Linq update record

How do you update a record with a specific ID in LINQ to SQL (ASP.Net / C#)?
You can do it like this...
var record =
(
from x in db.TableName
where x.Id == 12345
select x
)
.Single();
record.DateUpdated = DateTime.Now;
db.SubmitChanges();
Hope it helps :)
Care to post some sample code you've taken a stab at.
If it's linq2sql, then it should be a simple matter of Retrieving your object using your linq datacontext using a Where<T>() clause , updating the object property and then calling the DataContext.SubmitChanges()
Look at this piece of code for example.
void UpdateRow(Int32 intID)
{
bool IsSuccessfullyUpdated = false;
var db = new DataContext();
try
{
var dbCstInfo = db.TableName
.Where(w => w.ID == intID)
.SingleOrDefault();
if (dbCstInfo != null)
{
dbCstInfo.IsActive = !dbCstInfo.IsActive;
dbCstInfo.Name = "BJP";
dbCstInfo.Comp = "PVtal";
db.SubmitChanges();
IsSuccessfullyUpdated = true;
}
}
catch
{
IsSuccessfullyUpdated = false;
}
return IsSuccessfullyUpdated;
}

Resources