I have a list of credit card objects. The credit card class is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Client
{
public class CreditCard
{
public String A_Number;
public String A_Name;
public String A_Type;
public String A_Owner_Type;
public String Bank_City;
public String Bank_State;
public String Bank_ZIP;
public String Balance;
public String C_Username;
public CreditCard()
{
}
}
}
In another class, I am trying to bind the list to a grid view as follows:
protected void Page_Load(object sender, EventArgs e)
{
List<CreditCard> list = (List<CreditCard>)Session["list"];
GridView_List.DataSource = list;
GridView_List.DataBind();
}
However, I am receiving the following error:
The data source for GridView with id 'GridView_List' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.
What is the problem? I checked that the list actually contains data so I don't know why it won't work? How can this problem be solved?
You must use public properties for DataBinding. Update your class as follows:
public class CreditCard
{
public String A_Number { get; set; }
public String A_Name { get; set; }
public String A_Type { get; set; }
public String A_Owner_Type { get; set; }
public String Bank_City { get; set; }
public String Bank_State { get; set; }
public String Bank_ZIP { get; set; }
public String Balance { get; set; }
public String C_Username { get; set; }
public CreditCard() { }
}
You have defined your CreditCard as an object with fields. Data binding can only be done with properties. So, you need to do something like this for all fields:
public String A_Number { get; set; }
Related
Hey all I am trying to figure out how to go about saving just one value in my JSON class instead of having to write the whole JSON out again with "New". I am using the Newton JSON.Net.
This is my JSON structure:
public class GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public static string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public static string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public static string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public static string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public static string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public static string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public static double LastSavedVolume { get; set; }
}
public class Root
{
public Data data { get; set; }
}
And I have no issues with loading that data from a file into my class:
GV.Root myDeserializedClass = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
currentAssemblyPath + String.Format(#"\Resources\{0}", "dataForLinks.json")
));
But I have yet to find anything searching that will let me do one update to an object in the class without wiping it out doing a New statement.
What I am wanting to do is something like the following:
-Load the json into my class object [Done]
-Save a value thats in my class object [stuck here]
GV.pathToNESContent = "new value here";
-Save class object (with the one new value) back to the file for which it came from preserving the other original values. [not here yet]
When I update just that one class object I am wanting to contain the original values for all the other JSON data I read in from the file.
Anyone have a good example of the above you can share?
update
I'd ditch the inner class structure:
namespace GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public double LastSavedVolume { get; set; }
}
public class Root
{
public Data Data { get; set; }
}
Deser (use Path.Combine to build paths, not string concat):
var x = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
Path.Combine(currentAssemblyPath, "Resources", "dataForLinks.json"))
));
Edit:
x.Data.PathToNESContent = "...";
and re-ser
I'm connecting a MongoDB (Azure) with a MVC .NET C# project. The connection and object definition are working very good so far. My problem is when I try to add the method FIND() to return all the data in the object USER.
My Model:
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace backendnet.Models
{
public class MongoCore
{
public class DB
{
static MongoClient Client = new MongoClient("mongodb://mydbconnect");
static public IMongoDatabase Database = Client.GetDatabase("mydb");
static public IMongoCollection<User> Users = Database.GetCollection<User>("users");
}
public class User
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("email")]
public string Email { get; set; }
[BsonElement("password")]
public string Password { get; set; }
[BsonElement("name")]
public List<DimensionName> Name { get; set; }
[BsonElement("address")]
public List<DimensionAddress> Address { get; set; }
[BsonElement("permissions")]
public List<DimensionPermissions> Permissions { get; set; }
[BsonElement("status")]
public string Status { get; set; }
[BsonElement("created")]
public string Created { get; set; }
[BsonElement("updated")]
public string Updated { get; set; }
}
public class DimensionName
{
[BsonElement("first")]
public string First { get; set; }
[BsonElement("last")]
public string Last { get; set; }
}
public class DimensionAddress
{
[BsonElement("stree")]
public string Stree { get; set; }
[BsonElement("number")]
public string Number { get; set; }
[BsonElement("city")]
public string City { get; set; }
[BsonElement("state")]
public string State { get; set; }
[BsonElement("zipcode")]
public string Zipcode { get; set; }
[BsonElement("type")]
public string Type { get; set; }
}
public class DimensionPermissions
{
[BsonElement("list")]
public string List { get; set; }
[BsonElement("create")]
public string Create { get; set; }
[BsonElement("edit")]
public string Edit { get; set; }
[BsonElement("delete")]
public string Delete { get; set; }
}
}
}
My Controller:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using backendnet.Models;
using MongoDB.Bson;
namespace backendnet.Controllers
{
public class DashboardController : Controller
{
private string _viewFolder = "../Admin/Dashboard";
public ActionResult Index()
{
var results = new MongoCore.DB();
ViewData["ListPost"] = results.ToJson();
return View (_viewFolder);
}
}
}
My View partial:
<p>HERE: #ViewData["ListPost"]</p>
I get this:
HERE: { }
So I tried adding in the Model -> DB the method Find:
MongoCursor<User> cursor = Users.Find("Email" != "");
But always show an error:
Expression is always 'true' ["Email" != ""]
May anyone show me what I'm missing here?
I Don't See you calling MongoDB.Find()? I have pasted below my code I use for MongoDB C# driver in order to attain a record based on a key:value pair in my MongoDB database.
The Find or FindAsync method both require a BsonDocument Argument, which can be created using the Builders as seen below. Your filter can be empty, which would get all records since you are not filtering out anything.
Once you call the find method, you will be able to access the information using Lambda, or other query methods. You can see in my query i just need one record so i ask for FirstOrDefault. Hope this helps.
async Task<Document> IDal.GetRecordAsync(string key, string value)
{
try
{
if (Database == null) ((IDal)this).StartConnection();
var filter = Builders<BsonDocument>.Filter.Eq(key, value);
var cursor = await Collection.FindAsync(filter);
var bsondocument = cursor.FirstOrDefault();
return bsondocument == null ? null : _converter.ConvertBsonDocumentToDocument(bsondocument);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
public ActionResult GetUsers()
{
MongoServer objServer = MongoServer.Create("Server=localhost:27017");
MongoDatabase objDatabse = objServer.GetDatabase("DBName");
List UserDetails = objDatabse.GetCollection("Colletion_Name").FindAll().ToList();
return View(UserDetails);
}
I would like to deserialize the following JSON (using Json.NET) to an object, but cannot, as the class name would need to begin with a number.
An example of this is the Wikipedia article API. Using the API to provide a JSON response returns something like this. Note the "16689396" inside the "pages" key.
{
"batchcomplete":"",
"continue":{
"grncontinue":"0.893378504602|0.893378998188|35714269|0",
"continue":"grncontinue||"
},
"query":{
"pages":{
"16689396":{
"pageid":16689396,
"ns":0,
"title":"Jalan Juru",
"extract":"<p><b>Jalan Juru</b> (Penang state road <i>P176</i>) is a major road in Penang, Malaysia.</p>\n\n<h2><span id=\"List_of_junctions\">List of junctions</span></h2>\n<p></p>\n<p><br></p>"
}
}
}
}
How could I deserialize this JSON containing a number which changes based on the article?
It sounds like the Pages property in your Query class would just need to be a Dictionary<int, Page> or Dictionary<string, Page>.
Complete example with the JSON you've provided - I've had to guess at some of the name meanings:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
public class Root
{
[JsonProperty("batchcomplete")]
public string BatchComplete { get; set; }
[JsonProperty("continue")]
public Continuation Continuation { get; set; }
[JsonProperty("query")]
public Query Query { get; set; }
}
public class Continuation
{
[JsonProperty("grncontinue")]
public string GrnContinue { get; set; }
[JsonProperty("continue")]
public string Continue { get; set; }
}
public class Query
{
[JsonProperty("pages")]
public Dictionary<int, Page> Pages { get; set; }
}
public class Page
{
[JsonProperty("pageid")]
public int Id { get; set; }
[JsonProperty("ns")]
public int Ns { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("extract")]
public string Extract { get; set; }
}
class Test
{
static void Main()
{
string text = File.ReadAllText("test.json");
var root = JsonConvert.DeserializeObject<Root>(text);
Console.WriteLine(root.Query.Pages[16689396].Title);
}
}
Related question: Json deserialize from wikipedia api with c#
Essentially you need to changes from using a class for the pages to a dictionary, which allows for the dynamic nature of the naming convention.
Class definitions :
public class pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
public class Query
{
public Dictionary<string, pageval> pages { get; set; }
}
public class Limits
{
public int extracts { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
Deserialization :
var root = JsonConvert.DeserializeObject<RootObject>(__YOUR_JSON_HERE__);
var page = responseJson.query.pages["16689396"];
You can implement your own DeSerializer or editing the JSON before you DeSerialize it.
I've created classes from XSD Schema using xsd.exe (also tried with xsd2code which had better results in a way that they worked immediately, and with xsd.exe I have to debug some errors). XSD Schema I've used can be found at http://www.landxml.org/schema/LandXML-1.2/LandXML-1.2.xsd , and sample file can be found at http://landxml.org/schema/LandXML-1.1/samples/AASHTO%20SDMS/MntnRoad.xml .
My code for deserialization looks like:
var mySerializer = new XmlSerializer(typeof (LandXML), new XmlRootAttribute(""));
TextReader myFileStream = new StreamReader("myFile.xml");
var myObject = (LandXML) mySerializer.Deserialize(myFileStream);
My problem is that result of deserialization is list of items of type XmlElement, so if I try to access their properties, I can't easy do that. If I want to access, for example, some Alignment object attribute in myFile.xml, the code is similar to this:
var a = myObject.Items[5];
var b = (XmlElement) a;
var c = b.ChildNodes.Item(5).ChildNodes.Item(0).ChildNodes.Item(0).Attributes[0].Value;
It is obvious that this is not a way which is meant to be while deserializing XML to classes. My idea was like (for same element):
var c = LandXML.Alignments.Alignment.CoordGeometry.Curve.rot
I don't know what I'm doing wrong, I've tried with simpler schemas, and this code was working well. Please help and tnx in advance!
EDIT 1
this is at top of my class and I think that this List type generating troubles. And there is a more similar code in my generated classes
public class LandXML
{
private List<object> _items;
private System.DateTime _date;
private System.DateTime _time;
private string _version;
private string _language;
private bool _readOnly;
private int _landXMLId;
private string _crc;
public LandXML()
{
this._items = new List<object>();
}
[System.Xml.Serialization.XmlAnyElementAttribute()]
[System.Xml.Serialization.XmlElementAttribute("Alignments", typeof(Alignments))]
[System.Xml.Serialization.XmlElementAttribute("Amendment", typeof(Amendment))]
[System.Xml.Serialization.XmlElementAttribute("Application", typeof(Application))]
[System.Xml.Serialization.XmlElementAttribute("CgPoints", typeof(CgPoints))]
[System.Xml.Serialization.XmlElementAttribute("CoordinateSystem", typeof(CoordinateSystem))]
[System.Xml.Serialization.XmlElementAttribute("FeatureDictionary", typeof(FeatureDictionary))]
[System.Xml.Serialization.XmlElementAttribute("GradeModel", typeof(GradeModel))]
[System.Xml.Serialization.XmlElementAttribute("Monuments", typeof(Monuments))]
[System.Xml.Serialization.XmlElementAttribute("Parcels", typeof(Parcels))]
[System.Xml.Serialization.XmlElementAttribute("PipeNetworks", typeof(PipeNetworks))]
[System.Xml.Serialization.XmlElementAttribute("PlanFeatures", typeof(PlanFeatures))]
[System.Xml.Serialization.XmlElementAttribute("Project", typeof(Project))]
[System.Xml.Serialization.XmlElementAttribute("Roadways", typeof(Roadways))]
[System.Xml.Serialization.XmlElementAttribute("Surfaces", typeof(Surfaces))]
[System.Xml.Serialization.XmlElementAttribute("Survey", typeof(Survey))]
[System.Xml.Serialization.XmlElementAttribute("Units", typeof(Units))]
public List<object> Items
{
get
{
return this._items;
}
set
{
this._items = value;
}
}
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlSerializer xs = new XmlSerializer(typeof(LandXML));
XmlTextReader reader = new XmlTextReader(FILENAME);
reader.Namespaces = false;
LandXML landXML = (LandXML)xs.Deserialize(reader);
}
}
[XmlRoot("LandXML")]
public class LandXML
{
[XmlAttribute("version")]
public double version { get;set; }
[XmlAttribute("date")]
public DateTime date { get;set; }
[XmlAttribute("time")]
public DateTime time { get; set; }
[XmlAttribute("readOnly")]
public Boolean readOnly { get;set; }
[XmlAttribute("language")]
public string language { get;set; }
[XmlElement("Project")]
public Project project { get; set; }
[XmlElement("Units")]
public Units units { get; set; }
[XmlElement("Application")]
public Application application { get; set; }
[XmlElement("Alignments")]
public Alignments alignments { get; set; }
}
[XmlRoot("Project")]
public class Project
{
[XmlAttribute("name")]
public string name;
}
[XmlRoot("Units")]
public class Units
{
[XmlElement("Imperial")]
public Imperial imperial { get; set; }
}
[XmlRoot("Application")]
public class Application
{
[XmlElement("Author")]
public Author author { get; set; }
}
[XmlRoot("Imperial")]
public class Imperial
{
[XmlAttribute("linearUnit")]
public string linearUnit;
[XmlAttribute("areaUnit")]
public string areaUnit;
[XmlAttribute("volumeUnit")]
public string volumeUnit;
[XmlAttribute("temperatureUnit")]
public string temperaturUnit;
[XmlAttribute("pressureUnit")]
public string pressureUnit;
[XmlAttribute("angularUnit")]
public string angularUnit;
[XmlAttribute("directionUnit")]
public string name;
}
[XmlRoot("Author")]
public class Author
{
[XmlAttribute("createdBy")]
public string createdBy;
[XmlAttribute("createdByEmail")]
public string createdByEmail;
[XmlAttribute("company")]
public string company;
[XmlAttribute("companyURL")]
public string companyURL;
}
[XmlRoot("Alignments")]
public class Alignments
{
[XmlAttribute("desc")]
public string desc;
[XmlElement("Alignment")]
public Alignment alignment { get; set; }
}
[XmlRoot("Alignment")]
public class Alignment
{
[XmlAttribute("name")]
public string name;
[XmlAttribute("desc")]
public string desc;
[XmlAttribute("length")]
public string length;
[XmlAttribute("staStart")]
public string staStart;
[XmlElement("AlignPIs")]
public AlignPIs alignPIs { get; set; }
}
[XmlRoot("AlignPIs")]
public class AlignPIs
{
[XmlElement("AlignPI")]
public List<AlignPI> alignPI { get; set; }
}
[XmlRoot("AlignPI")]
public class AlignPI
{
[XmlElement("PI")]
public PI pi { get; set; }
[XmlElement("InSpiral")]
public InSpiral inSpiral { get; set; }
[XmlElement("Curve1")]
public Curve1 cureve1 { get; set; }
[XmlElement("OutSpiral")]
public OutSpiral outSpiral { get; set; }
[XmlElement("Station")]
public Station station { get; set; }
}
[XmlRoot("Station")]
public class Station
{
[XmlText]
public string value { get; set; }
}
[XmlRoot("PI")]
public class PI
{
[XmlAttribute("code")]
public int code;
[XmlAttribute("name")]
public int name;
[XmlText]
public string value;
}
[XmlRoot("InSpiral")]
public class InSpiral
{
[XmlElement("Spiral")]
public Spiral spiral { get; set; }
}
[XmlRoot("Spiral")]
public class Spiral
{
[XmlAttribute("length")]
public double length;
[XmlAttribute("radiusEnd")]
public double radiusEnd;
[XmlAttribute("radiusStart")]
public double radiusStart;
[XmlAttribute("rot")]
public string rot;
[XmlAttribute("spiType")]
public string spiType;
}
[XmlRoot("Curve1")]
public class Curve1
{
[XmlElement("Curve")]
public Curve curve { get; set; }
}
[XmlRoot("Curve")]
public class Curve
{
[XmlAttribute("rot")]
public string rot;
[XmlAttribute("radius")]
public double radius;
}
[XmlRoot("OutSpiral")]
public class OutSpiral
{
[XmlElement("Spiral")]
public Spiral spiral { get; set; }
}
}
I'm using the Razor view engine to render some HTML which will then live within an XML document. the base class I'm using has a number of properties, along with a static method which will return a list of that object (using Dapper to populate the list). I'm having trouble executing the method since it needs to return the base class, which is an abstract class. Some sample code is below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
using System.IO;
namespace LocalBranchesPOC
{
public abstract class PersonData : TemplateBase
{
#region Properties
public string RecordId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Variable1 { get; set; }
public string Variable2 { get; set; }
public string Variable3 { get; set; }
#endregion
public static List<PersonData> GetPeople()
{
const string QUERY = "SELECT [RecordId], [Name], [Address], [City], [County], [State], [Country], [Zip], [Phone], [Variable1], [Variable2], [Variable3] FROM Data.Person";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BranchLocator"].ConnectionString))
{
return getPeople(QUERY, conn);
}
}
private static List<PersonData> getPeople(string QUERY, SqlConnection conn)
{
conn.Open();
var result = conn.Query<PersonData>(QUERY).ToList();
conn.Close();
return result;
}
}
public abstract class TemplateBase
{
[Browsable(false)]
public StringBuilder Buffer { get; set; }
[Browsable(false)]
public StringWriter Writer { get; set; }
public TemplateBase()
{
Buffer = new StringBuilder();
Writer = new StringWriter(Buffer);
}
public abstract void Execute();
// Writes the results of expressions like: "#foo.Bar"
public virtual void Write(object value)
{
// Don't need to do anything special
// Razor for ASP.Net does HTML encoding here.
WriteLiteral(value);
}
// Writes literals like markup: "<p>Foo</p>"
public virtual void WriteLiteral(object value)
{
Buffer.Append(value);
}
}
}
Basically my call to PersonData.GetPeople() is failing because the PersonData class is abstract. Any thoughts would be appreciated. I'm using the example from here as my guide.
You're trying to merge the model and the view.
Don't do that; it cannot possibly work.
Instead, pass the model to the view as a separate property, perhaps loading it in the TemplateBase constructor.