Razor View Engine in Console App with Complex Bass Class - c#

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.

Related

How can I actually use JSON in C#?

I have a Json file that was deserialized from a Json Api-Call, now I have to use this file as an object in the main program.
Here is a small section of it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Api1
{
public class EcmSimpleField
{
public string value { get; set; }
public string displayName { get; set; }
public string internalName { get; set; }
public string dbName { get; set; }
public bool visible { get; set; }
public string type { get; set; }
}
public class BaseParameter
{
public string value { get; set; }
public string type { get; set; }
}
public class SystemField
{
public string value { get; set; }
public string type { get; set; }
}
How can I use this file as an object in the main program and work with it?
Create a class for the json like you shared above and use deserialise it using Newtonsoft.json dll or any other library.
var obj = JsonConvert.DeserializeObject<YourClass>(jsonString);
This thread will probably help you:
How can I parse JSON with C#?
If your JSON file has changing parameters then the parameters will need to be retrieved in arrays because the array index will always be the same even if the "parameter" changes.

How to use FIND() for a MongoDB query on a MVC .net C# project

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);
}

XML data not being loaded into c# class

I am trying to load data from an XML file into a c# class but am not getting data being loaded in Notifications. The rest of the class (not shown) is correctly populated so I am assuming that my class definition is incorrect. Can anyone shed any light on this?
public partial class ISTimetables
{
[XmlElement]
public List<ISNotification> Notifications { get; set; }
}
[Serializable()]
public partial class ISNotification
{
public ISNotification()
{
On = new List<ISProcessStep>();
Notify = new List<ISNotify>();
}
[XmlElement]
public List<ISProcessStep> On { get; set; }
[XmElement]
public List<ISNotify> Notify { get; set; }
}
[Serializable()]
public partial class ISNotify
{
public string Email { get; set; }
public string SimpleEmail { get; set; }
public string SMS { get; set; }
}
[Serializable()]
public enum ISProcessStep
{
[XmlEnum("Calculated")]
Calculated,
[XmlEnum("Reported")]
Reported,
[XmlEnum("Customer Approved")]
CustomerApproved,
[XmlEnum("Rejected")]
Rejected
}
The data I am trying to load is as follows:
<Notifications>
<Notification>
<On>Calculated</On>
<On>Reported</On>
<Notify SimpleEmail="me#company.com"/>
<Notify Email="you#company.com"/>
<Notify SMS="0123456789"/>
</Notification>
<Notification>
<On>Customer Approved</On>
<Notify Email="him#company.com"/>
</Notification>
</Notifications>
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication21
{
class Program
{
const string FILEName = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(ISTimetables));
XmlTextReader reader = new XmlTextReader(FILEName);
ISTimetables tables = (ISTimetables)serializer.Deserialize(reader);
}
}
[XmlRoot("Notifications")]
public partial class ISTimetables
{
[XmlElement("Notification")]
public List<ISNotification> Notifications { get; set; }
}
[XmlRoot("Notification")]
public partial class ISNotification
{
public ISNotification()
{
On = new List<ISProcessStep>();
Notify = new List<ISNotify>();
}
[XmlElement]
public List<ISProcessStep> On { get; set; }
[XmlElement]
public List<ISNotify> Notify { get; set; }
}
[Serializable()]
public partial class ISNotify
{
public string Email { get; set; }
public string SimpleEmail { get; set; }
public string SMS { get; set; }
}
[Serializable()]
public enum ISProcessStep
{
[XmlEnum("Calculated")]
Calculated,
[XmlEnum("Reported")]
Reported,
[XmlEnum("Customer Approved")]
CustomerApproved,
[XmlEnum("Rejected")]
Rejected
}
}

Class won't serialize into JSON using unity's JSONUtility

I have the following class, which is serializable and only has strings as fields:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Cabeza
{
string id, urlOBJ, urlTextura, pathOBJbajado, pathTexturaBajada;
public string Id { get; set; }
public string UrlOBJ { get; set; }
public string UrlTextura { get; set; }
public string PathOBJbajado { get; set; }
public string PathTexturaBajada { get; set; }
public Cabeza (string nuevoId)
{
Id = nuevoId;
UrlOBJ = nuevoId +".obj";
UrlTextura = nuevoId + ".png";
}
}
As far I know it should be possible to obtain a JSON from it...However, JsonUtility.ToJson() returns just { }. How is this possible? What am I missing?
The documentation mentions (but doesn't make clear) that .ToJson() serializes fields, not properties.
I think the following code would work as you intend:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Cabeza
{
public string Id;
public string UrlOBJ;
public string UrlTextura;
public string PathOBJbajado;
public string PathTexturaBajada;
public Cabeza (string nuevoId)
{
Id = nuevoId;
UrlOBJ = nuevoId +".obj";
UrlTextura = nuevoId + ".png";
}
}

Binding List to GridView

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; }

Categories