I'm using ASP.NET Web API Help Page for my web API, but unfortunately controller method's that uses ParameterBindingAttribute are not being listed on GetApiExplorer(). Example bellow GetOutPut is listed and GetEntrance not.
public HelpController() : this(GlobalConfiguration.Configuration) { }
public HelpController(HttpConfiguration config)
{
Configuration = config;
}
public ActionResult Index()
{
ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
Controller's methods
/// <summary>
/// Entrance
/// </summary>
/// <param name="foo"></param>
/// <param name="initialDate"></param>
/// <param name="finalDate"></param>
/// <returns></returns>
[Route("entrance/{foo}/{initialDate}/{finalDate}")]
[HttpGet]
[ResponseType(typeof(BooModel))]
public IHttpActionResult GetEntrance(string foo,
[DateTimeParameter(DateFormat = DateTimeBindingFormats.yyyyMMddHHmm)] DateTime? initialDate,
[DateTimeParameter(DateFormat = DateTimeBindingFormats.yyyyMMddHHmm)] DateTime? finalDate)
{
try
{
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
/// <summary>
/// Out Put
/// </summary>
/// <param name="foo"></param>
/// <param name="initialDate"></param>
/// <param name="finalDate"></param>
/// <returns></returns>
[Route("output/{foo}/{initialDate}/{finalDate}")]
[HttpGet]
[ResponseType(typeof(FooModel))]
public IHttpActionResult GetOutPut(string foo, DateTime? initialDate, DateTime? finalDate)
{
try
{
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
XMLDocument.xml
<member name="M:IntegrationServices.Controllers.FooController.GetEntrance(System.String,System.Nullable{System.DateTime},System.Nullable{System.DateTime})">
<summary>
Entrance
</summary>
<param name="foo"></param>
<param name="initialDate"></param>
<param name="finalDate"></param>
<returns></returns>
</member>
<member name="M:IntegrationServices.Controllers.FooController.GetOutPut(System.String,System.Nullable{System.DateTime},System.Nullable{System.DateTime})">
<summary>
Out Put
</summary>
<param name="foo"></param>
<param name="initialDate"></param>
<param name="finalDate"></param>
<returns></returns>
</member>
ParameterBindingAttribute's class
public class DateTimeParameterAttribute : ParameterBindingAttribute
{
public string DateFormat { get; set; }
public bool ReadFromQueryString { get; set; }
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
{
if (parameter.ParameterType != typeof(DateTime?)) return parameter.BindAsError("Expected type DateTime?");
var binding = new DateTimeParameterBinding(parameter)
{
DateFormat = DateFormat,
ReadFromQueryString = ReadFromQueryString
};
return binding;
}
}
Any ideas?
Related
I would like to create a Handler that will take a lambda expression and return the name of the property that is passes in, and the value of the property.
Here is a sample:
class Program
{
static void Main(string[] args) {
var handler = new Handler();
Contact contact = new Contact() { FirstName = "John", LastName = "Travolta" };
handler.DoSomething(x => contact.FirstName);
handler.DoSomething(x => contact.LastName);
}
}
public class Contact {
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Handler {
public void DoSomething(Func<object, object> func) {
//Write the name of the property.
Console.WriteLine(?);
//Write the Value of the property.
Console.WriteLine(?);
}
}
How can I do this?
public void DoSomething<T>(Expression<Func<T, object>> expr, T target) {
var pi = (PropertyInfo)(((MemberExpression)expr.Body).Member);
Console.WriteLine(pi.Name);
//Write the Value of the property.
Console.WriteLine(expr.Compile()(target));
}
You'll have to pass the target to the method as well:
handler.DoSomething(x => contact.FirstName, x);
Some code from my library to get the property name.
Type ExpressionUtils.GetPropertyName in Handler.DoSomething
public static class ExpressionUtils
{
/// <summary>
/// Gets the name of any argument given in the lambda expression.
/// Sample:
/// int argument = 10;
/// string name = ExpressionUtils.GetName(() => argument);
/// </summary>
/// <typeparam name="T">Argument type</typeparam>
/// <param name="selector">Selector for the name of the argument</param>
/// <returns>Argument name</returns>
public static string GetName<T>(Expression<Func<T>> selector)
{
if (selector == null)
{
throw new ArgumentNullException("selector");
}
MemberExpression member = RemoveUnary(selector.Body);
if (member == null)
{
throw new InvalidOperationException("Unable to get name from expression.");
}
return member.Member.Name;
}
/// <summary>
/// Gets the name of the property given in the lambda expression.
/// Sample:
/// string propertyName = ExpressionUtils.GetPropertyName(() => x.Property);
/// </summary>
/// <typeparam name="TProperty">Property type</typeparam>
/// <param name="propertySelector">Selector for the name of the property</param>
/// <returns></returns>
public static string GetPropertyName<TProperty>(Expression<Func<TProperty>> propertySelector)
{
return GetPropertyNameImpl(propertySelector);
}
/// <summary>
/// Gets the name of the property given in the lambda expression.
/// Sample:
/// <![CDATA[
/// string propertyName = ExpressionUtils.GetPropertyName<Entity, int>(y => y.Property);
/// ]]>
/// </summary>
/// <typeparam name="TEntity">Entity containing the property type</typeparam>
/// <typeparam name="TProperty">Propety type</typeparam>
/// <param name="propertySelector">Selector for the name of the property</param>
/// <returns></returns>
public static string GetPropertyName<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> propertySelector)
{
return GetPropertyNameImpl(propertySelector);
}
/// <summary>
/// Gets the name of the property given in the lambda expression.
/// Sample:
/// <![CDATA[
/// string propertyName = ExpressionUtils.GetPropertyName<Entity, int>(y => y.Property);
/// ]]>
/// </summary>
/// <typeparam name="TEntity">Entity containing the property type</typeparam>
/// <param name="propertySelector">Selector for the name of the property</param>
/// <returns></returns>
public static string GetPropertyName<TEntity>(Expression<Func<TEntity, object>> propertySelector)
{
return GetPropertyNameImpl(propertySelector);
}
private static string GetPropertyNameImpl(LambdaExpression propertySelector)
{
if (propertySelector == null)
{
throw new ArgumentNullException("propertySelector");
}
MemberExpression member = RemoveUnary(propertySelector.Body);
if (member == null)
{
throw new InvalidOperationException("Expression is not an access expression.");
}
var property = member.Member as PropertyInfo;
if (property == null)
{
throw new InvalidOperationException("Member in expression is not a property.");
}
return member.Member.Name;
}
private static MemberExpression RemoveUnary(Expression toUnwrap)
{
if (toUnwrap is UnaryExpression)
{
return ((UnaryExpression)toUnwrap).Operand as MemberExpression;
}
return toUnwrap as MemberExpression;
}
}
This is my code :
http://i43.tinypic.com/acpgdd.jpg
entities = new SamaEntities();
var institute_ContractInstitute = entities.ContractInstitutes;
I get this error in watch page
institute_ContractInstitute The name 'institute_ContractInstitute'
does not exist in the current context
What does it mean?
This is ContractInstitute Class :
public partial class ContractInstitute : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new ContractInstitute object.
/// </summary>
/// <param name="id">Initial value of the Id property.</param>
/// <param name="contractId">Initial value of the ContractId property.</param>
/// <param name="instituteId">Initial value of the InstituteId property.</param>
/// <param name="status">Initial value of the Status property.</param>
/// <param name="level">Initial value of the Level property.</param>
/// <param name="user_">Initial value of the User_ property.</param>
public static ContractInstitute CreateContractInstitute(global::System.Int32 id, global::System.Int32 contractId, global::System.Int32 instituteId, global::System.Int16 status, global::System.Int16 level, global::System.Int32 user_)
{
ContractInstitute contractInstitute = new ContractInstitute();
contractInstitute.Id = id;
contractInstitute.ContractId = contractId;
contractInstitute.InstituteId = instituteId;
contractInstitute.Status = status;
contractInstitute.Level = level;
contractInstitute.User_ = user_;
return contractInstitute;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Id
{
get
{
return _Id;
}
set
{
if (_Id != value)
{
OnIdChanging(value);
ReportPropertyChanging("Id");
_Id = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Id");
OnIdChanged();
}
}
}
private global::System.Int32 _Id;
partial void OnIdChanging(global::System.Int32 value);
partial void OnIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> Price
{
get
{
return _Price;
}
set
{
OnPriceChanging(value);
ReportPropertyChanging("Price");
_Price = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Price");
OnPriceChanged();
}
}
private Nullable<global::System.Double> _Price;
partial void OnPriceChanging(Nullable<global::System.Double> value);
partial void OnPriceChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ContractId
{
get
{
return _ContractId;
}
set
{
OnContractIdChanging(value);
ReportPropertyChanging("ContractId");
_ContractId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ContractId");
OnContractIdChanged();
}
}
private global::System.Int32 _ContractId;
partial void OnContractIdChanging(global::System.Int32 value);
partial void OnContractIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 InstituteId
{
get
{
return _InstituteId;
}
set
{
OnInstituteIdChanging(value);
ReportPropertyChanging("InstituteId");
_InstituteId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("InstituteId");
OnInstituteIdChanged();
}
}
private global::System.Int32 _InstituteId;
partial void OnInstituteIdChanging(global::System.Int32 value);
partial void OnInstituteIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int16 Status
{
get
{
return _Status;
}
set
{
OnStatusChanging(value);
ReportPropertyChanging("Status");
_Status = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Status");
OnStatusChanged();
}
}
private global::System.Int16 _Status;
partial void OnStatusChanging(global::System.Int16 value);
partial void OnStatusChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> CouncilPrice
{
get
{
return _CouncilPrice;
}
set
{
OnCouncilPriceChanging(value);
ReportPropertyChanging("CouncilPrice");
_CouncilPrice = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CouncilPrice");
OnCouncilPriceChanged();
}
}
private Nullable<global::System.Double> _CouncilPrice;
partial void OnCouncilPriceChanging(Nullable<global::System.Double> value);
partial void OnCouncilPriceChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> CurrencyId
{
get
{
return _CurrencyId;
}
set
{
OnCurrencyIdChanging(value);
ReportPropertyChanging("CurrencyId");
_CurrencyId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CurrencyId");
OnCurrencyIdChanged();
}
}
private Nullable<global::System.Int32> _CurrencyId;
partial void OnCurrencyIdChanging(Nullable<global::System.Int32> value);
partial void OnCurrencyIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int16 Level
{
get
{
return _Level;
}
set
{
OnLevelChanging(value);
ReportPropertyChanging("Level");
_Level = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Level");
OnLevelChanged();
}
}
private global::System.Int16 _Level;
partial void OnLevelChanging(global::System.Int16 value);
partial void OnLevelChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 User_
{
get
{
return _User_;
}
set
{
OnUser_Changing(value);
ReportPropertyChanging("User_");
_User_ = StructuralObject.SetValidValue(value);
ReportPropertyChanged("User_");
OnUser_Changed();
}
}
private global::System.Int32 _User_;
partial void OnUser_Changing(global::System.Int32 value);
partial void OnUser_Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> UserDelegate_
{
get
{
return _UserDelegate_;
}
set
{
OnUserDelegate_Changing(value);
ReportPropertyChanging("UserDelegate_");
_UserDelegate_ = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UserDelegate_");
OnUserDelegate_Changed();
}
}
private Nullable<global::System.Int32> _UserDelegate_;
partial void OnUserDelegate_Changing(Nullable<global::System.Int32> value);
partial void OnUserDelegate_Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> UserLoginAz_
{
get
{
return _UserLoginAz_;
}
set
{
OnUserLoginAz_Changing(value);
ReportPropertyChanging("UserLoginAz_");
_UserLoginAz_ = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UserLoginAz_");
OnUserLoginAz_Changed();
}
}
private Nullable<global::System.Int32> _UserLoginAz_;
partial void OnUserLoginAz_Changing(Nullable<global::System.Int32> value);
partial void OnUserLoginAz_Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> HoldingPrice
{
get
{
return _HoldingPrice;
}
set
{
OnHoldingPriceChanging(value);
ReportPropertyChanging("HoldingPrice");
_HoldingPrice = StructuralObject.SetValidValue(value);
ReportPropertyChanged("HoldingPrice");
OnHoldingPriceChanged();
}
}
private Nullable<global::System.Double> _HoldingPrice;
partial void OnHoldingPriceChanging(Nullable<global::System.Double> value);
partial void OnHoldingPriceChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> CouncilHoldingPrice
{
get
{
return _CouncilHoldingPrice;
}
set
{
OnCouncilHoldingPriceChanging(value);
ReportPropertyChanging("CouncilHoldingPrice");
_CouncilHoldingPrice = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CouncilHoldingPrice");
OnCouncilHoldingPriceChanged();
}
}
private Nullable<global::System.Double> _CouncilHoldingPrice;
partial void OnCouncilHoldingPriceChanging(Nullable<global::System.Double> value);
partial void OnCouncilHoldingPriceChanged();
#endregion
#region Navigation Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "ConInsGroup", "Group")]
public EntityCollection<Group> Groups
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Group>("SamaModel.ConInsGroup", "Group");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Group>("SamaModel.ConInsGroup", "Group", value);
}
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "ContractContractInstitute", "Contract")]
public Contract Contract
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<Contract> ContractReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract", value);
}
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "InstituteContractInstitute", "Institute")]
public Institute Institute
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<Institute> InstituteReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute", value);
}
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "CurrencyContractInstitute", "Currency")]
public Currency Currency
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<Currency> CurrencyReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency", value);
}
}
}
#endregion
}
I get this error in watch page
The name 'institute_ContractInstitute' does not exist in the current context
That means exactly what it says: no variable with the name institute_ContractInstitute exists in the current context, i.e. where your program currently is.
Put a breakpoint after var institute_ContractInstitute = ... and then you can inspect its contents in the Watch window.
Probably the issue is due to lazy loading. whatever data is in entities.ContractInstitutes is not getting loaded. Try to use a List<> type variable and put the ContractInstitutes into the list using .ToList().
I have a string data get from service Location Xml
I want to read response text and return ObservableCollection
public void SearchLocation(string address)
{
var webclient = new WebClient();
if (address != "")
{
string url =
string.Format(
#"http://dev.virtualearth.net/REST/v1/Locations?countryRegion=Vietnam&adminDistrict=Ha Noi&locality={0}&o=xml&key={1}",
address, BingMapKey);
webclient.DownloadStringAsync(new Uri(url));
webclient.DownloadStringCompleted += WebclientOnDownloadStringCompleted;
}
}
private void WebclientOnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string data = e.Result;
ReadXml(data);
}
private void ReadXml(string data)
{
_locations.Clear();
XDocument document = XDocument.Parse(data);
var locations = from loca in document.Descendants("Location")
select
new Location(loca.Element("Name").Value,
loca.Element("Point").Element("Latitude").Value,"1",
"1", "1", "1", "1");
_locations = (ObservableCollection<Location>) locations;
}
}
Class Location:
public class Location
{
/// <summary>
/// Tên địa điểm
/// </summary>
public string Name { get; set; }
/// <summary>
/// Vĩ độ
/// </summary>
public double Latitude { get; set; }
/// <summary>
/// Kinh độ
/// </summary>
public double Longitute { get; set; }
/// <summary>
/// Vĩ độ Nam
/// </summary>
public double SouthLatitude { get; set; }
/// <summary>
/// Kinh độ Tây
/// </summary>
public double WestLongtitue { get; set; }
/// <summary>
/// Vĩ độ Bắc
/// </summary>
public double NorthLatitude { get; set; }
/// <summary>
/// Kinh độ Tây
/// </summary>
public double EastLongitude { get; set; }
/// <summary>
/// Khởi tạo Location
/// </summary>
/// <param name="name">tên địa điểm</param>
/// <param name="latitue">vĩ độ</param>
/// <param name="longitude">kinh độ</param>
/// <param name="southLatitude">vĩ độ nam</param>
/// <param name="westLongitude">kinh độ tây</param>
/// <param name="northLatitude">vĩ độ bắc</param>
/// <param name="eastLongitude">kinh độ đông</param>
public Location(string name, string latitue, string longitude, string southLatitude, string westLongitude,
string northLatitude, string eastLongitude)
{
Name = name;
Latitude = Convert.ToDouble(latitue);
Longitute = Convert.ToDouble(longitude);
SouthLatitude = Convert.ToDouble(southLatitude);
NorthLatitude = Convert.ToDouble(northLatitude);
WestLongtitue = Convert.ToDouble(westLongitude);
EastLongitude = Convert.ToDouble(eastLongitude);
}
}
I read and _location return null, where are errors?
You can cast IEnumerable<Location> which is a result of LINQ to XML query to ObservableCollection<Location> directly.
_locations = (ObservableCollection<Location>) locations;
Just add all elements from query result collection into existing ObservableCollection:
foreach(var location in locations)
_locations.Add(location);
Update
There is also namespace problem in your code. Try that one:
XDocument document = XDocument.Parse(data);
var ns = XNamespace.Get("http://schemas.microsoft.com/search/local/ws/rest/v1");
var locations = from loca in document.Descendants(ns + "Location")
select
new Location(loca.Element(ns + "Name").Value,
loca.Element(ns + "Point").Element(ns + "Latitude").Value, "1",
"1", "1", "1", "1");
In my .net (3.5) application with EF I use following code to insert new record, but AddObject() is not working.
I am surprise because it happens first time, even before when I had worked on EF at that time its was working.
My code
public void NewAirline(string name, string sname, string remark)
{
GsecEntities e = new GsecEntities();
tbAirLine al = new tbAirLine()
{
Name = name,
Remark = remark,
ShortName = sname
};
e.tbAirLines.AddObject(al);
e.SaveChanges();
}
As suggestion Here I am writing code of tbAirline
public partial class GsecEntities : global::System.Data.Objects.ObjectContext
{
/// <summary>
/// Initializes a new GsecEntities object using the connection string found in the 'GsecEntities' section of the application configuration file.
/// </summary>
public GsecEntities() :
base("name=GsecEntities", "GsecEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new GsecEntities object.
/// </summary>
public GsecEntities(string connectionString) :
base(connectionString, "GsecEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new GsecEntities object.
/// </summary>
public GsecEntities(global::System.Data.EntityClient.EntityConnection connection) :
base(connection, "GsecEntities")
{
this.OnContextCreated();
}
partial void OnContextCreated();
/// <summary>
/// There are no comments for tbAirLines in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbAirLine> tbAirLines
{
get
{
if ((this._tbAirLines == null))
{
this._tbAirLines = base.CreateQuery<tbAirLine>("[tbAirLines]");
}
return this._tbAirLines;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbAirLine> _tbAirLines;
/// <summary>
/// There are no comments for tbBanks in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbBank> tbBanks
{
get
{
if ((this._tbBanks == null))
{
this._tbBanks = base.CreateQuery<tbBank>("[tbBanks]");
}
return this._tbBanks;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbBank> _tbBanks;
/// <summary>
/// There are no comments for tbCities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbCity> tbCities
{
get
{
if ((this._tbCities == null))
{
this._tbCities = base.CreateQuery<tbCity>("[tbCities]");
}
return this._tbCities;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbCity> _tbCities;
/// <summary>
/// There are no comments for tbCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbCommodity> tbCommodities
{
get
{
if ((this._tbCommodities == null))
{
this._tbCommodities = base.CreateQuery<tbCommodity>("[tbCommodities]");
}
return this._tbCommodities;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbCommodity> _tbCommodities;
/// <summary>
/// There are no comments for tbCountries in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbCountry> tbCountries
{
get
{
if ((this._tbCountries == null))
{
this._tbCountries = base.CreateQuery<tbCountry>("[tbCountries]");
}
return this._tbCountries;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbCountry> _tbCountries;
/// <summary>
/// There are no comments for tbFlights in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbFlight> tbFlights
{
get
{
if ((this._tbFlights == null))
{
this._tbFlights = base.CreateQuery<tbFlight>("[tbFlights]");
}
return this._tbFlights;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbFlight> _tbFlights;
/// <summary>
/// There are no comments for tbGrpCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbGrpCommodity> tbGrpCommodities
{
get
{
if ((this._tbGrpCommodities == null))
{
this._tbGrpCommodities = base.CreateQuery<tbGrpCommodity>("[tbGrpCommodities]");
}
return this._tbGrpCommodities;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbGrpCommodity> _tbGrpCommodities;
/// <summary>
/// There are no comments for tbPersons in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbPerson> tbPersons
{
get
{
if ((this._tbPersons == null))
{
this._tbPersons = base.CreateQuery<tbPerson>("[tbPersons]");
}
return this._tbPersons;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbPerson> _tbPersons;
/// <summary>
/// There are no comments for tbPersonTypes in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbPersonType> tbPersonTypes
{
get
{
if ((this._tbPersonTypes == null))
{
this._tbPersonTypes = base.CreateQuery<tbPersonType>("[tbPersonTypes]");
}
return this._tbPersonTypes;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbPersonType> _tbPersonTypes;
/// <summary>
/// There are no comments for tbAirLines in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbAirLines(tbAirLine tbAirLine)
{
base.AddObject("tbAirLines", tbAirLine);
}
/// <summary>
/// There are no comments for tbBanks in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbBanks(tbBank tbBank)
{
base.AddObject("tbBanks", tbBank);
}
/// <summary>
/// There are no comments for tbCities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbCities(tbCity tbCity)
{
base.AddObject("tbCities", tbCity);
}
/// <summary>
/// There are no comments for tbCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbCommodities(tbCommodity tbCommodity)
{
base.AddObject("tbCommodities", tbCommodity);
}
/// <summary>
/// There are no comments for tbCountries in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbCountries(tbCountry tbCountry)
{
base.AddObject("tbCountries", tbCountry);
}
/// <summary>
/// There are no comments for tbFlights in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbFlights(tbFlight tbFlight)
{
base.AddObject("tbFlights", tbFlight);
}
/// <summary>
/// There are no comments for tbGrpCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbGrpCommodities(tbGrpCommodity tbGrpCommodity)
{
base.AddObject("tbGrpCommodities", tbGrpCommodity);
}
/// <summary>
/// There are no comments for tbPersons in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbPersons(tbPerson tbPerson)
{
base.AddObject("tbPersons", tbPerson);
}
/// <summary>
/// There are no comments for tbPersonTypes in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbPersonTypes(tbPersonType tbPersonType)
{
base.AddObject("tbPersonTypes", tbPersonType);
}
}
/// <summary>
/// There are no comments for GsecModel.tbAirLine in the schema.
/// </summary>
/// <KeyProperties>
/// Id
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="GsecModel", Name="tbAirLine")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class tbAirLine : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new tbAirLine object.
/// </summary>
/// <param name="id">Initial value of Id.</param>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public static tbAirLine CreatetbAirLine(long id)
{
tbAirLine tbAirLine = new tbAirLine();
tbAirLine.Id = id;
return tbAirLine;
}
/// <summary>
/// There are no comments for property Id in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public long Id
{
get
{
return this._Id;
}
set
{
this.OnIdChanging(value);
this.ReportPropertyChanging("Id");
this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("Id");
this.OnIdChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private long _Id;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnIdChanging(long value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnIdChanged();
/// <summary>
/// There are no comments for property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private string _Name;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnNameChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnNameChanged();
/// <summary>
/// There are no comments for property ShortName in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public string ShortName
{
get
{
return this._ShortName;
}
set
{
this.OnShortNameChanging(value);
this.ReportPropertyChanging("ShortName");
this._ShortName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("ShortName");
this.OnShortNameChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private string _ShortName;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnShortNameChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnShortNameChanged();
/// <summary>
/// There are no comments for property Remark in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public string Remark
{
get
{
return this._Remark;
}
set
{
this.OnRemarkChanging(value);
this.ReportPropertyChanging("Remark");
this._Remark = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Remark");
this.OnRemarkChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private string _Remark;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnRemarkChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnRemarkChanged();
}
And its give following error
Error 1 'System.Data.Objects.ObjectQuery' does not contain a definition for 'AddObject' and no extension method 'AddObject' accepting a first argument of type 'System.Data.Objects.ObjectQuery' could be found (are you missing a using directive or an assembly reference?)
.NET version 3.5 exposes ObjectQuery<T> versus ObjectSet<T> in .NET 4.0. Therefor you will need to use either e.AddTotbAirLines(tbAirLine) or e.AddObject("tbAirLines", tbAirLine). Both can be found on line 185 of the submitted generated code. In .NET 4.0 they decided to implement it like you were showing in your question.
I have a web app with that is using JQuery to interact with my backend. The backend successfully accepts JSON data. For instance, I can successfully send the following JSON:
{ "id":1, "firstName":"John", "lastName":"Smith" }
I now have a Windows Phone app that must hit this backend. I need to pass this same JSON via a WebClient. Currently I have the following, but i'm not sure how to actually pass the JSON.
string address = "http://www.mydomain.com/myEndpoint;
WebClient myService = new WebClient();
utilityService.UploadStringCompleted += new UploadStringCompletedEventHandler(utilityService_UploadStringCompleted);
utilityService.UploadStringAsync(address, string.Empty);
Can someone tell me what I need to do?
Although the question is already answered, I thought it would be nice to share my simple JsonService, based on the WebClient:
Base class
/// <summary>
/// Class BaseJsonService.
/// </summary>
public abstract class BaseJsonService
{
/// <summary>
/// The client
/// </summary>
protected WebClient client;
/// <summary>
/// Gets the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public abstract void Get<TResponse>(string url, Action<TResponse> onComplete, Action<Exception> onError);
/// <summary>
/// Sends the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="jsonData">The json data.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public abstract void Post<TResponse>(string url, string jsonData, Action<TResponse> onComplete, Action<Exception> onError);
}
Service implementation
/// <summary>
/// Class JsonService.
/// </summary>
public class JsonService : BaseJsonService
{
/// <summary>
/// Gets the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public override void Get<TResponse>(string url, Action<TResponse> onComplete, Action<Exception> onError)
{
if (client == null)
client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
TResponse returnValue = default(TResponse);
try
{
returnValue = JsonConvert.DeserializeObject<TResponse>(e.Result);
onComplete(returnValue);
}
catch (Exception ex)
{
onError(new JsonParseException(ex));
}
};
client.Headers.Add(HttpRequestHeader.Accept, "application/json");
client.Encoding = System.Text.Encoding.UTF8;
client.DownloadStringAsync(new Uri(url));
}
/// <summary>
/// Posts the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="jsonData">The json data.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public override void Post<TResponse>(string url, string jsonData, Action<TResponse> onComplete, Action<Exception> onError)
{
if (client == null)
client = new WebClient();
client.UploadDataCompleted += (s, e) =>
{
if (e.Error == null && e.Result != null)
{
TResponse returnValue = default(TResponse);
try
{
string response = Encoding.UTF8.GetString(e.Result);
returnValue = JsonConvert.DeserializeObject<TResponse>(response);
}
catch (Exception ex)
{
onError(new JsonParseException(ex));
}
onComplete(returnValue);
}
else
onError(e.Error);
};
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Encoding = System.Text.Encoding.UTF8;
byte[] data = Encoding.UTF8.GetBytes(jsonData);
client.UploadDataAsync(new Uri(url), "POST", data);
}
}
Example usage
/// <summary>
/// Determines whether this instance [can get result from service].
/// </summary>
[Test]
public void CanGetResultFromService()
{
string url = "http://httpbin.org/ip";
Ip result;
service.Get<Ip>(url,
success =>
{
result = success;
},
error =>
{
Debug.WriteLine(error.Message);
});
Thread.Sleep(5000);
}
/// <summary>
/// Determines whether this instance [can post result automatic service].
/// </summary>
[Test]
public void CanPostResultToService()
{
string url = "http://httpbin.org/post";
string data = "{\"test\":\"hoi\"}";
HttpBinResponse result = null;
service.Post<HttpBinResponse>(url, data,
response =>
{
result = response;
},
error =>
{
Debug.WriteLine(error.Message);
});
Thread.Sleep(5000);
}
}
public class Ip
{
public string Origin { get; set; }
}
public class HttpBinResponse
{
public string Url { get; set; }
public string Origin { get; set; }
public Headers Headers { get; set; }
public object Json { get; set; }
public string Data { get; set; }
}
public class Headers
{
public string Connection { get; set; }
[JsonProperty("Content-Type")]
public string ContentType { get; set; }
public string Host { get; set; }
[JsonProperty("Content-Length")]
public string ContentLength { get; set; }
}
Just to share some knowledge!
Good luck!
Figured it out. I was forgetting the following:
myService.Headers.Add("Content-Type", "application/json");