Why is of two same types of xmls, one is not deserializing and the other is? - c#-2.0

Suppose I have two different xml files as embedded-resource in a same assembly:
Hummer.xml
<?xml version="1.0" encoding="utf-8" ?>
<car company="GMC" brand="Hummer" />
HammerHead.xml
<?xml version="1.0" encoding="utf-8" ?>
<shark species="HammerHead" length="45" />
Car.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace XmlDeserialization_Test
{
[XmlRoot("car"), XmlType("car")]
public class Car
{
[XmlAttribute("company")]
public string Company { get; set; }
[XmlAttribute("brand")]
public string Brand { get; set; }
}
}
Shark.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace XmlDeserialization_Test
{
[XmlRoot("shark"), XmlType("shark")]
public class Shark
{
[XmlAttribute("species")]
public string Species { get; set; }
[XmlAttribute("length")]
public double Length { get; set; }
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;
namespace XmlDeserialization_Test
{
class Program
{
static void Main(string[] args)
{
List<Car> carList = new List<Car>();
List<Shark> sharkList = new List<Shark>();
Assembly assembly = Assembly.LoadFrom("XmlDeserialization_Test.exe");
string[] manifestResourceNames = assembly.GetManifestResourceNames();
Array.Sort<string>(manifestResourceNames);
foreach (string mrn in manifestResourceNames)
{
Stream stream = assembly.GetManifestResourceStream(mrn);
XmlSerializer serializer = new XmlSerializer(typeof(Shark));
object obj = serializer.Deserialize(stream);
if (obj is Car)
{
carList.Add((Car)obj);
}
else if (obj is Shark)
{
sharkList.Add((Shark)obj);
}
}
}
}
}
HammerHead - Shark is deserializing perfectly.
But, Hummer - car is not. The following exception is being generated:
There is an error in XML document (2, 2).
"<car xmlns=''> was not expected."
If Shark is deserializing, why Car is not? If Car is generating exception, why Shark is not?
I am clueless!!!

You're trying the desearilize a 'car' object with a 'shark' deserialize it. If you change to create a deserializer of type Car, you'll have the opposite result:
XmlSerializer serializer = new XmlSerializer(typeof(Car));
I don't know how you're serializing, but this should give you an idea.

Related

Is there get method which not found while run web api service

I'm creating a web api controller and implement ([HttpGet])parameterized get method with datatype class but when I run this its show 404 Not Found.
When i am implementing normal datatype like string or int its show me the answer or datatype like List still it's giving me answer but when I directly declare datatype as class like Student its show 404 not found error. I don't know why it's so. I am trying to learn web api with mvc please help me.
I am creating one simple class Student and one studentapicontroller.In my api controller, I create get method with datatype class and for testing purpose i make other get method with different datatype
Student.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace epay.Models
{
public class student
{
public int id { get; set; }
public string name { get; set; }
}
}
studentapiController :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using epay.Models;
namespace epay.Controllers
{
public class studentapiController : ApiController
{
// GET api/studentapi
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/studentapi/5
{
return "value";
}
// POST api/studentapi
public void Post([FromBody]string value)
{
}
// PUT api/studentapi/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/studentapi/5
public void Delete(int id)
{
}
//POST api/studentapi/
[HttpGet]
public student getdetails(int id, string na)
{
student st = new student();
st.id = id;
st.name = na;
return st;
}
//GET api/studentapi/getstud
[HttpGet]
public List<student> getstud()
{
List<student> lst = new List<student>();
student st = new student();
st.name = "manlai";
st.id = 5;
lst.Add(st);
return lst;
}
}
}
I just want getdetails result or how to do if I want my method datatype as a class and I am passing parameter with my get method how to do this
Make getdetails route like below because it is conflicting with get
[HttpGet("getdetails")]
public student getdetails(int id, string na)
{
student st = new student();
st.id = id;
st.name = na;
return st;
}
you can call route something like this with querystring /studentapi/getdetails?id=1&na=test

Connection lost with sdf file in a mvc project

I´m starting to learn mvc with the tutorial MVC Music Store v3.0b. The code download from mvcmusicstore.codeplex.com Works fine. Now I´m trying the same example but using my own model.
My connectionstring in my web.config file is:
<connectionStrings>
<add name="PlanetStampEntities"
connectionString="Data Source=|DataDirectory|MvcPlanetStamp.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
The problem is that I can´t access to data stored in the class SampleData.cs under Models folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcPlanetStamp.Models;
namespace MvcPlanetStamp.Controllers
{
public class StoreController : Controller
{
PlanetStampEntities storeDB = new PlanetStampEntities();
public ActionResult Index()
{
var tematicas = storeDB.Tematicas.ToList();
return View(tematicas);
}
}
}
var tematicas never get results. But I have records in my class SampleData.cs
public class SampleData : DropCreateDatabaseIfModelChanges<PlanetStampEntities>
{
protected override void Seed(PlanetStampEntities context)
{
var tematicas = new List<Tematica>
{
new Tematica { Nombre = "Modernismo" },
new Tematica { Nombre = "Alhambra" },
new Tematica { Nombre = "Hollywood" },
new Tematica { Nombre = "Dibujos" },
new Tematica { Nombre = "Montañas" },
};
----
Finally, the code for my class PlanetStampsEntities.cs is:
using System.Data.Entity;
namespace MvcPlanetStamp.Models
{
public class PlanetStampEntities : DbContext
{
public DbSet<Sello> Sellos { get; set; }
public DbSet<Tematica> Tematicas { get; set; }
public DbSet<Pais> Paises { get; set; }
}
}
Table Selloes in the tree seems wrong. My class is Sello.cs. Where this name Selloes could be created?
Thank you
Change your table name in .sdf file from Selloes to Sello

Unable to access the object which is defined in the model class

I am trying to list a data which is presented in the database and i created a class ViewingGoals and implement its business logic in the class ViewingGoalsBusinessLayer codes are as like follows
ViewingGoals.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer
{
public class ViewingGoals
{
public string Goal { get; set; }
}
}
ViewingGoalsBusinessLayer.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using BusinessLayer;
namespace BusinessLayer
{
public class ViewingGoalsBusinessLayer
{
public void ViewData(ViewingGoals viewgoal)
{
try
{
string Connectionstring = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
List<ViewingGoals> viewgoals = new List<ViewingGoals>();
using (SqlConnection con = new SqlConnection(Connectionstring))
{
SqlCommand cmd = new SqlCommand("ViewGoal", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//ViewingGoals viewgoal = new ViewingGoals();
viewgoal.Goal = rdr["Goal"].ToString();
viewgoals.Add(viewgoal);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
and my controller code is :
ViewingGoalsController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer;
namespace AppraisalManagementSystemFinal.Controllers
{
public class ViewingGoalsController : Controller
{
//
// GET: /ViewingGoals/
public ActionResult ViewingGoals()
{
ViewingGoalsBusinessLayer viewinggoalsbusinessLayer = new ViewingGoalsBusinessLayer();
List<ViewingGoals> viewgoals = viewinggoalsbusinessLayer.viewgoal.ToList();
return View(viewgoals);
}
}
}
in that controller wen i am trying to access the object from the ViewingGoalBusinessLayer
List viewgoals = viewinggoalsbusinessLayer.viewgoal.ToList(); i got error as doesnot contain a definition for viewgoal.
please help me to overcome it.
When you use viewinggoalsbusinessLayer.viewgoal, you are trying to access a viewgoal property from your viewinggoalsbusinessLayer object.
Problem is that you haven't defined such a property in that object !
Here is an updated part of your code
public class ViewingGoalsBusinessLayer
{
public List<ViewingGoals> ViewGoals;
public void ViewData(ViewingGoals viewgoal)
{
try
{
string Connectionstring = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
Viewgoals = new List<ViewingGoals>();
// Rest of code is unchanged ...
}
catch (Exception ex)
{
throw ex;
}
}
}
Next problem is that you'll need to initialize that list, and I'm not sure what your ViewData function is doing...

MVC c# controller return view()

below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models = We.Models;
using We.BAL;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Helpers;
using System.Diagnostics.CodeAnalysis;
using System.Security.Principal;
using System.Web.Routing;
using System.Web.Security;
using PagedList;
using We.Models.ViewModels;
using We.Models.Interface;
using We.Models.DBData;
using We.Models.Repository;
using System.Data.Sql;
using System.Data.Query;
using System.Data.SqlClient;
namespace We.Controllers
{
public class ClientEnquiryController : Controller
{
private Models.Interface.IPolicyService _repository;
private Models.Repository.PolicyServiceRepository clientenqRepository;
public ClientEnquiryController()
: this(new Models.Repository.PolicyServiceRepository())
{
}
public ClientEnquiryController(Models.Interface.IPolicyService repository)
{
_repository = repository;
}
public ActionResult MasterView( string PolicyNo, string carrierCode, string sPol, string languageCode)
{
carrierCode = "2";
sPol = "502-0877220";
languageCode = "eng";
return View(_repository.policymaster(carrierCode, sPol, languageCode));
}
From my codeI am do the return like this :
return View(_repository.policymaster(carrierCode, sPol, languageCode));
how about if i want return the view with more than one statement in same time? for example:
_repository.policymaster(carrierCode, sPol, languageCode);
_repository.policyAgent(carrierCode, sPol, languageCode);
Anyone can help me?
I think you might benefit from modelling the view with the two return objects. For example,
public class MasterViewVM
{
public PolicyMaster {get; set;}
public PolicyAgent {get; set;}
}
Then you return the view model with the data entities:
public ActionResult MasterView(string PolicyNo,
string carrierCode, string sPol, string languageCode)
{
carrierCode = "2";
sPol = "502-0877220";
languageCode = "eng";
MasterViewVM model = new MasterViewVM
{
PolicyMaster =_repository.policymaster(carrierCode, sPol, languageCode),
PolicyAgent = _repository.policyAgent(carrierCode, sPol, languageCode)
};
return View(model);
}
Another possibility is to use a child action. See
http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

How to create a strongly typed MVC View based on a custom Linq2Sql class

I have created a custom entity because I need to populate an entity with some data from a join in L2S.
When I right click on the ActionResult code in the Controller to "Add View", and then choose "Create strongly typed view", my class doesn't show up in the classes available in the selector. I'm not sure why. Here is my code:
//The Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace FurnitureStore.Models.Repository
{
public class FurnitureRepository
{
public IQueryable<Listing> GetProductListings()
{
FurnitureDataContext dc = new FurnitureDataContext();
return (from p in dc.Products
join c in dc.Categories
on p.CategoryId equals c.CategoryId
select new Listing
{
ProductName = p.ProductName,
CategoryDescription = c.CategoryDescription
});
}
}
}
//The entity class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FurnitureStore.Models
{
public class Listing
{
public string ProductName { get; set; }
public string CategoryDescription { get; set; }
}
}
//The Method in the Controller
public ActionResult ProductListings()
{
FurnitureRepository fr = new FurnitureRepository();
var listings = fr.GetProductListings();
return View("ProductListings",listings);
}
Make sure that you compile the code, if the code is not compiled the newly added classes dont showup in the classes available in the selector
Just create a normal view and edit the view's page definition (inherits attribute specifically) yourself.
<%# Page ... Inherits="System.Web.Mvc.ViewPage<IQueryable<FurnitureStore.Models.Listing>>" %>
Off the top of my head I can't answer why it isn't appearing in your class selector.
HTHs
Charles

Resources