SerializeObject is returning an empty object - c#

JsonConvert.SerializeObject is returning an empty object
I can serialize a generic object, and I can serialize this object in a different assembly. I've verified the properties are public and also explicitly marked with json tags. No exception is being thrown by Newtonsoft.Json. Relevant version Newtonsoft.Json 12.0.2, installed via nuget.
The test is failing because the expected call and actual call are different. The actual call (not pasted) is what I expect, but the Json serializes gives an empty object in the test.
logger.Verify(m => m.LogUsage(JsonConvert.SerializeObject(_svc), "AddService", string.Empty, false), Times.Once());
UPDATE: I tried adding the following test and it still is serializing to an empty object, despite _svc being defined correctly (I can tell by setting a breakpoint and inspecting it.)
[TestMethod]
public async Task TestUnableToSerialize()
{
string result = JsonConvert.SerializeObject(_svc);
Assert.AreEqual(string.Empty, result);
}
[TestClass]
public class ServiceDirectoryTests
{
private Service _defaultSvc;
private ServiceInfoResponse _defaultSvcInfo;
private Mock<ILogger> logger;
private ILogger _logger;
public Service _svc;
private ServiceInfoResponse _svcInfo;
private List<string> _serviceMonikers;
private string _serialized;
[TestInitialize()]
public void Initialize()
{
logger = new Mock<ILogger>();
_logger = logger.Object;
_defaultSvcInfo = new ServiceInfoResponse()
{
endpoint = "default endpoint",
environment_id = string.Empty,
id = "defaultId",
iso_a2_country_code = "UK",
moniker = "Account",
tenant_moniker = "default",
url_selection_scheme = UrlSelectionScheme.ServiceDefault
};
_defaultSvc = new Service(_defaultSvcInfo);
_svcInfo = new ServiceInfoResponse()
{
endpoint = "service endpoint",
environment_id = string.Empty,
id = "nonDefaultId",
iso_a2_country_code = "UK",
moniker = "Account",
tenant_moniker = "ztorstrick",
url_selection_scheme = UrlSelectionScheme.ServiceDefault
};
_svc = new Service(_svcInfo);
}
[TestMethod]
public async Task AddServiceDefaultReturned()
{
Mock<IServiceDirectory> mockClient = new Mock<IServiceDirectory>();
mockClient.Setup(x => x.CreateService(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()
))
.ReturnsAsync(_defaultSvcInfo);
ServiceDirectory svc = new ServiceDirectory(mockClient.Object, _logger);
Service result = await svc.AddService(_svc, "");
Assert.AreEqual(_defaultSvc.Endpoint, result.Default);
Assert.AreEqual(result.Default, result.Endpoint);
Assert.AreEqual(_defaultSvc.EnvironmentId, result.EnvironmentId);
Assert.AreEqual(string.Empty, result.Id);
Assert.AreEqual(_defaultSvc.IsoA2CountryCode, result.IsoA2CountryCode);
Assert.AreEqual(_defaultSvc.Moniker, result.Moniker);
Assert.AreEqual(_defaultSvc.ServiceName, result.ServiceName);
Assert.AreEqual(_defaultSvc.TenantMoniker, result.TenantMoniker);
Assert.AreEqual("ServiceDefault", result.UrlSelectionScheme);
logger.Verify(m => m.LogUsage(JsonConvert.SerializeObject(_svc), "AddService", string.Empty, false), Times.Once());
}
}
public class Service : PropertyChangedBase
{
#region " Private Variables "
private string _default;
private string _endpoint;
private string _environmentId;
private string _id;
private bool _isSelected;
private string _isoA2CountryCode;
private string _moniker;
private string _serviceName;
private string _tenantMoniker;
private string _urlSelectionScheme;
private string _version;
#endregion
#region "Constructors"
public Service()
{
Id = string.Empty;
IsDirty = false;
IsSelected = false;
}
public Service(Service service)
{
if (service == null) { throw new ArgumentNullException(); }
Default = service.Default;
Endpoint = service.Endpoint;
EnvironmentId = service.EnvironmentId;
Id = service.Id;
IsDirty = service.IsDirty;
IsoA2CountryCode = service.IsoA2CountryCode;
IsSelected = service.IsSelected;
Moniker = service.Moniker;
ServiceName = service.ServiceName;
TenantMoniker = service.TenantMoniker;
UrlSelectionScheme = service.UrlSelectionScheme;
// DO NOT keep Ids for default services, to prevent accidental editing and deletion
if (string.IsNullOrWhiteSpace(service.TenantMoniker) ||
string.Equals(service.TenantMoniker, "default", StringComparison.CurrentCultureIgnoreCase))
{
Id = string.Empty;
}
}
public Service(ServiceInfoResponse response)
{
if (response == null) { throw new ArgumentNullException(); }
IsDirty = false;
Endpoint = response.endpoint;
EnvironmentId = response.environment_id;
Id = response.id;
IsoA2CountryCode = response.iso_a2_country_code;
IsSelected = false;
Moniker = response.moniker;
ServiceName = response.service_name;
TenantMoniker = response.tenant_moniker;
UrlSelectionScheme = response.url_selection_scheme.ToString();
// DO NOT keep Ids for default services, to prevent accidental editing and deletion
if(string.IsNullOrWhiteSpace(response.tenant_moniker) ||
string.Equals(response.tenant_moniker, "default", StringComparison.CurrentCultureIgnoreCase))
{
Id = string.Empty;
}
}
#endregion
#region "Properties"
[JsonIgnore]
public string Default
{
get { return _default; }
set
{
if (_default != value)
{
_default = value;
NotifyOfPropertyChange(() => Default);
}
}
}
[JsonProperty("endpoint")]
public string Endpoint
{
get { return _endpoint; }
set
{
if (_endpoint != value)
{
_endpoint = value;
NotifyOfPropertyChange(() => Endpoint);
}
}
}
[JsonProperty("environment_id")]
public string EnvironmentId
{
get { return _environmentId; }
set
{
if (_environmentId != value)
{
_environmentId = value;
NotifyOfPropertyChange(() => EnvironmentId);
}
}
}
[JsonProperty("id")]
public string Id
{
get { return _id; }
set
{
if (_id != value)
{
_id = value;
NotifyOfPropertyChange(() => Id);
NotifyOfPropertyChange(() => IsDefault);
}
}
}
[JsonIgnore]
public bool IsDefault
{
get
{
return string.IsNullOrWhiteSpace(Id);
}
}
[JsonIgnore]
public bool IsDirty { get; set; }
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_isSelected = value;
NotifyOfPropertyChange(() => IsSelected);
}
}
}
[JsonProperty("iso_a2_country_code")]
public string IsoA2CountryCode
{
get { return _isoA2CountryCode; }
set
{
if (_isoA2CountryCode != value)
{
_isoA2CountryCode = value;
NotifyOfPropertyChange(() => IsoA2CountryCode);
}
}
}
[JsonIgnore]
public bool MatchesDefault { get { return string.Equals(Endpoint, Default, StringComparison.CurrentCultureIgnoreCase); } }
[JsonProperty("moniker")]
public string Moniker
{
get { return _moniker; }
set
{
if (_moniker != value)
{
_moniker = value;
NotifyOfPropertyChange(() => Moniker);
}
}
}
[JsonProperty("service_name")]
public string ServiceName
{
get { return _serviceName; }
set
{
if (_serviceName != value)
{
_serviceName = value;
NotifyOfPropertyChange(() => ServiceName);
}
}
}
[JsonProperty("tenant_moniker")]
public string TenantMoniker
{
get { return _tenantMoniker; }
set
{
if (_tenantMoniker != value)
{
_tenantMoniker = value;
NotifyOfPropertyChange(() => TenantMoniker);
}
}
}
[JsonProperty("url_selection_scheme")]
public string UrlSelectionScheme
{
get { return _urlSelectionScheme; }
set
{
if (_urlSelectionScheme != value)
{
_urlSelectionScheme = value;
NotifyOfPropertyChange(() => UrlSelectionScheme);
}
}
}
[JsonProperty("version")]
public string Version
{
get { return _version; }
set
{
if (_version != value)
{
_version = value;
NotifyOfPropertyChange(() => Version);
}
}
}
#endregion
}

I had a NuGet reference to Newtonsoft.Json in my unit test project. I removed that, rebuilt, and now it works. The only thing I can think is there were different versions of Json floating around (this has happened to me before) and it was breaking something.

Related

How can I fix the issue with the input string in this cmdlet?

In the last month of so I have been trying to learn some C# with the aim of writing some PowerShell modules. I looked at some articles and documentation (Creating a client with C# - Microsoft.Management.Infrastructure) to try and put together a simple CIM cmdlet that would return the local network adapters.
The class library compiles okay, but when I run the command in PowerShell, it shows a format exception.
Show-LocalAdapter : Input string was not in a correct format.
In function based problems, I would normally see an issue with a line in the error reporting, but the error does not point me in the right direction with a cmdlet.
Hopefully someone here can help me as I have exhausted my, admittedly limited, knowledge on debugging this problem.
Here is the code for the cmdlet.
using System.Collections;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using Microsoft.Management.Infrastructure;
namespace NetTest
{
[Cmdlet(VerbsCommon.Show, "LocalAdapter")]
[OutputType(typeof(NetworkAdapter))]
public class ShowLocalAdapterCmdlet : PSCmdlet
{
private string[] _manufacturer;
private string _name;
private bool? _physicalAdapter;
private int _maxEntries = 100;
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Alias("Vendor")]
public string[] Manufacturer
{
get { return this._manufacturer; }
set { _manufacturer = value; }
}
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]
public string Name
{
get { return this._name; }
set { _name = value; }
}
[Parameter(Position = 2, ValueFromPipelineByPropertyName = true)]
public bool? PhysicalAdapter
{
get { return this._physicalAdapter; }
set { _physicalAdapter = value; }
}
[Parameter(Position = 3)]
public int MaxEntries
{
get { return this._maxEntries; }
set { _maxEntries = value; }
}
protected override void BeginProcessing()
{
base.BeginProcessing();
}
protected override void ProcessRecord()
{
CimSession session = CimSession.Create("localHost");
IEnumerable cimResults = session.QueryInstances(#"root\cimv2", "WQL", "SELECT * FROM Win32_NetworkAdapter");
var query = cimResults.Cast<CimInstance>().Select(ReturnNetworkAdapter);
// Filter Name
if (Name != null)
{
query = query.Where(adapter => adapter.Name != null && adapter.Name.StartsWith(Name));
}
// Manufacturer Filter
if (Manufacturer != null)
{
query = query.Where(
adapter =>
adapter.Manufacturer != null &&
Regex.IsMatch(adapter.Manufacturer.ToString(),
string.Format("^(?:{0})", string.Join("|", Manufacturer))));
}
// Physical Adapter: true or false
if (PhysicalAdapter != null)
{
query = query.Where(adapter =>
adapter.PhysicalAdapter == PhysicalAdapter);
}
// Return objects
query.Take(MaxEntries).ToList().ForEach(WriteObject);
}
private static NetworkAdapter ReturnNetworkAdapter(CimInstance item)
{
return new NetworkAdapter
{
Name = item.CimInstanceProperties["Name"].ToString(),
Description = item.CimInstanceProperties["Description"].ToString(),
DeviceId = int.Parse(item.CimInstanceProperties["DeviceId"].ToString()),
Manufacturer = item.CimInstanceProperties["Manufacturer"].ToString(),
NetConnectionId = item.CimInstanceProperties["NetConnectionId"].ToString(),
PhysicalAdapter = bool.Parse(item.CimInstanceProperties["PhysicalAdapter"].ToString())
};
}
}
}
Here is the class for the network adapter object.
namespace NetTest
{
public class NetworkAdapter
{
private string _name;
private string _description;
private int _deviceId;
private string _manufacturer;
private string _netConnectionId;
private bool _physicalAdapter;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public int DeviceId
{
get { return _deviceId; }
set { _deviceId = value; }
}
public string Manufacturer
{
get { return _manufacturer; }
set { _manufacturer = value; }
}
public string NetConnectionId
{
get { return _netConnectionId; }
set { _netConnectionId = value; }
}
public bool PhysicalAdapter
{
get { return _physicalAdapter; }
set { _physicalAdapter = value; }
}
}
}
Calls like this item.CimInstanceProperties["Name"].ToString() is not what are you expecting. You should look at property Value:
private static NetworkAdapter ReturnNetworkAdapter(CimInstance item)
{
return new NetworkAdapter
{
Name = item.CimInstanceProperties["Name"].Value.ToString(),
Description = item.CimInstanceProperties["Description"].Value?.ToString(),
DeviceId = int.Parse(item.CimInstanceProperties["DeviceId"].Value.ToString()),
Manufacturer = item.CimInstanceProperties["Manufacturer"].Value?.ToString(),
NetConnectionId = item.CimInstanceProperties["NetConnectionId"].Value?.ToString(),
PhysicalAdapter = bool.Parse(item.CimInstanceProperties["PhysicalAdapter"].Value.ToString())
};
}

Using ServerManager to list virtual directories separated by type

I'm using ServerManager (Microsoft.Web.Administration.dll) to create an Application to manage my web servers, All of my server are running IIS 7 and above. Majority of the site is complete, i can manage servers, sites, FTP, SSL etc.
Here is my issue,
I am able to create virtual directories and applications, but having an issue with listing them separately when viewing the site information as you can do in IIS. I am able to list the all together as Virtual Directories by just getting item.VirtualDirectories[0].PhysicalPath but would like to show Applications in one column and basic virtual directories in the second column. I'm sure i need to be looking for if root application path is siteid, or if it has an AppPool somehow but having a hard time figuring how. Any help would be appreciated.
My Code:
SiteVirtualDirectory.cs
private string anonymousUsername;
private string anonymousUserPassword;
private string contentPath;
private bool enableWritePermissions;
private bool enableParentPaths;
private bool enableDirectoryBrowsing;
private bool enableAnonymousAccess;
private bool enableWindowsAuthentication;
private bool enableBasicAuthentication;
private bool enableDynamicCompression;
private bool enableStaticCompression;
private string defaultDocs;
private string httpRedirect;
private HttpError[] httpErrors;
private HttpErrorsMode errorMode;
private HttpErrorsExistingResponse existingResponse;
private MimeMap[] mimeMaps;
private HttpHeader[] httpHeaders;
private bool aspInstalled;
private string aspNetInstalled;
private string phpInstalled;
private bool perlInstalled;
private bool pythonInstalled;
private bool coldfusionInstalled;
private bool cgiBinInstalled;
private string applicationPool;
private bool dedicatedApplicationPool;
private string parentSiteName;
private bool redirectExactUrl;
private bool redirectDirectoryBelow;
private bool redirectPermanent;
private bool sharePointInstalled;
private bool iis7;
private string consoleUrl;
private string php5VersionsInstalled;
public string AnonymousUsername
{
get { return anonymousUsername; }
set { anonymousUsername = value; }
}
public string AnonymousUserPassword
{
get { return anonymousUserPassword; }
set { anonymousUserPassword = value; }
}
public string ContentPath
{
get { return contentPath; }
set { contentPath = value; }
}
public string HttpRedirect
{
get { return httpRedirect; }
set { httpRedirect = value; }
}
public string DefaultDocs
{
get { return defaultDocs; }
set { defaultDocs = value; }
}
public MimeMap[] MimeMaps
{
get { return mimeMaps; }
set { mimeMaps = value; }
}
public HttpError[] HttpErrors
{
get { return httpErrors; }
set { httpErrors = value; }
}
public HttpErrorsMode ErrorMode
{
get { return errorMode; }
set { errorMode = value; }
}
public HttpErrorsExistingResponse ExistingResponse
{
get { return existingResponse; }
set { existingResponse = value; }
}
public string ApplicationPool
{
get { return this.applicationPool; }
set { this.applicationPool = value; }
}
public bool EnableParentPaths
{
get { return this.enableParentPaths; }
set { this.enableParentPaths = value; }
}
public HttpHeader[] HttpHeaders
{
get { return this.httpHeaders; }
set { this.httpHeaders = value; }
}
public bool EnableWritePermissions
{
get { return this.enableWritePermissions; }
set { this.enableWritePermissions = value; }
}
public bool EnableDirectoryBrowsing
{
get { return this.enableDirectoryBrowsing; }
set { this.enableDirectoryBrowsing = value; }
}
public bool EnableAnonymousAccess
{
get { return this.enableAnonymousAccess; }
set { this.enableAnonymousAccess = value; }
}
public bool EnableWindowsAuthentication
{
get { return this.enableWindowsAuthentication; }
set { this.enableWindowsAuthentication = value; }
}
public bool EnableBasicAuthentication
{
get { return this.enableBasicAuthentication; }
set { this.enableBasicAuthentication = value; }
}
public bool EnableDynamicCompression
{
get { return this.enableDynamicCompression; }
set { this.enableDynamicCompression = value; }
}
public bool EnableStaticCompression
{
get { return this.enableStaticCompression; }
set { this.enableStaticCompression = value; }
}
public bool AspInstalled
{
get { return this.aspInstalled; }
set { this.aspInstalled = value; }
}
public string AspNetInstalled
{
get { return this.aspNetInstalled; }
set { this.aspNetInstalled = value; }
}
public string PhpInstalled
{
get { return this.phpInstalled; }
set { this.phpInstalled = value; }
}
public bool PerlInstalled
{
get { return this.perlInstalled; }
set { this.perlInstalled = value; }
}
public bool PythonInstalled
{
get { return this.pythonInstalled; }
set { this.pythonInstalled = value; }
}
public bool ColdFusionInstalled
{
get { return this.coldfusionInstalled; }
set { this.coldfusionInstalled = value; }
}
public bool DedicatedApplicationPool
{
get { return this.dedicatedApplicationPool; }
set { this.dedicatedApplicationPool = value; }
}
public string ParentSiteName
{
get { return this.parentSiteName; }
set { this.parentSiteName = value; }
}
public bool RedirectExactUrl
{
get { return this.redirectExactUrl; }
set { this.redirectExactUrl = value; }
}
public bool RedirectDirectoryBelow
{
get { return this.redirectDirectoryBelow; }
set { this.redirectDirectoryBelow = value; }
}
public bool RedirectPermanent
{
get { return this.redirectPermanent; }
set { this.redirectPermanent = value; }
}
public bool CgiBinInstalled
{
get { return this.cgiBinInstalled; }
set { this.cgiBinInstalled = value; }
}
public bool SharePointInstalled
{
get { return this.sharePointInstalled; }
set { this.sharePointInstalled = value; }
}
public bool IIs7
{
get { return this.iis7; }
set { this.iis7 = value; }
}
public string ConsoleUrl
{
get { return consoleUrl; }
set { consoleUrl = value; }
}
public string Php5VersionsInstalled
{
get { return php5VersionsInstalled; }
set { php5VersionsInstalled = value; }
}
[XmlIgnore]
public string VirtualPath
{
get
{
// virtual path is rooted
if (String.IsNullOrEmpty(ParentSiteName))
return "/"; //
else if (!Name.StartsWith("/"))
return "/" + Name;
//
return Name;
}
}
[XmlIgnore]
public string FullQualifiedPath
{
get
{
if (String.IsNullOrEmpty(ParentSiteName))
return Name;
else if (Name.StartsWith("/"))
return ParentSiteName + Name;
else
return ParentSiteName + "/" + Name;
}
}
Get Virtual Directories:
public class GetVirtualDirectories(ServerManager iismanager, string siteId)
{
if (!SiteExists(iismanager, siteId))
return new SiteVirtualDirectory[] { };
var vdirs = new List<SiteVirtualDirectory>();
var iisObject = iismanager.Sites[siteId];
//
foreach (var item in iisObject.Applications)
{
// do not list root Virtual Directory
if (item.Path == "/")
continue;
//
vdirs.Add(new SiteVirtualDirectory
{
Name = ConfigurationUtility.GetNonQualifiedVirtualPath(item.Path),
ContentPath = item.VirtualDirectories[0].PhysicalPath
});
}
//
return vdirs.ToArray();
}

objectcontext instance is not null but its disposed even if i declare it and give it same value

i know that this question have asked many times but i havent find any answer that can help me
the problem is
the-objectcontext-instance-has-been-disposed-and-can-no-longer-be-used-for-operations-that-require-a-connection
after i declare copy of entity object that have linked to other entity with 1 to many relation
this is the class
using System;
using System.Linq;
using School.Component;
using System.Windows.Input;
using DataAccess;
using System.Collections.ObjectModel;
using DataAccess.Repository;
using Microsoft.Practices.Prism.Commands;
using System.Collections.Generic;
namespace School.WpfApp.ViewModels
{
public class LevelsPerYearNewVM : ViewModelBase
{
SchAvaiLevelsPerYear _CurrentLevelsPerYear;
SchAvaiLevelsPerYear _old;
private bool _isnew = false;
bool _IsEnabled = false;
StudyYearRepository _Repository = new StudyYearRepository();
SchoolSettingRepository _SRepository = new SchoolSettingRepository();
ObservableCollection<StageLevel> _AllStageLevel;
StageLevel _SelectrdStageLevel;
ObservableCollection<SchAvaiLevelsPerYear> _allSchAvaiLevelsPerYear;
ObservableCollection<CoursesLevelsPerStYear> _AllCoursesLevelsPerStYear;
private string errorMasseg;
public LevelsPerYearNewVM(SchAvaiLevelsPerYear f, ObservableCollection<SchAvaiLevelsPerYear> _list)
: base()
{
_old = (f);
CurrentLevelsPerYear = new SchAvaiLevelsPerYear()
{
Avalible = f.Avalible,
CoursCount = f.CoursCount,
YearID = f.YearID,
ID = f.ID,
SchoolID = f.SchoolID,
UserID = f.UserID,
StageLevelID = f.StageLevelID,
};
InitVars();
CreateCommands();
ErrorMasseg = "";
if (_CurrentLevelsPerYear.ID > 0)
{
this.Title = "تعديل بيانات المستوى الدراسي";
}
else
{ this.Title = "اضافة مستوى دراسي"; IsEnabled = true; _isnew = true; }
_allSchAvaiLevelsPerYear = _list;
}
protected override async void InitVars()
{
AllStageLevel = await _SRepository.GetAllStageLevelsIncludeCourses();
if(!isnew)
AllCoursesLevelsPerStYear = await _SRepository.GetAllAllCoursesLevelsPerStYearBySchAvaiLevelsPerYearID( _CurrentLevelsPerYear.ID);
}
protected override void CreateCommands()
{
SaveCommand = new RelayCommand(o =>
{
Save();
}
, o => Valdite());
CanselCommand = new DelegateCommand(() =>
{
if (Closed != null)
{
_CurrentLevelsPerYear = null;
Closed(_CurrentLevelsPerYear);
}
}
, () => true);
}
private void Save()
{
SchAvaiLevelsPerYear a = null;
string masseg = "";
if (Valdite())
{
a = _allSchAvaiLevelsPerYear.FirstOrDefault(i => i.ID != CurrentLevelsPerYear.ID && i.StageLevelID == _CurrentLevelsPerYear.StageLevelID);
if (a == null)
{
_CurrentLevelsPerYear.CoursCount = _AllCoursesLevelsPerStYear.Where(cc=>cc.Avalible).Count();
_CurrentLevelsPerYear.UserID = Session.SessionData.CurrentUser.UserID;
_CurrentLevelsPerYear.ID = _Repository.SaveSchAvaiLevelsPerYear(_CurrentLevelsPerYear);
CoursesLevelsPerStYear v;
foreach (CoursesLevelsPerStYear c in _AllCoursesLevelsPerStYear)
{
if (_isnew)
c.SALByYearID = _CurrentLevelsPerYear.ID;
c.UserID = Session.SessionData.CurrentUser.UserID;
v = (CoursesLevelsPerStYear)MyDataAccessTools.Clone<CoursesLevelsPerStYear>(c);
c.ID= _Repository.SaveCoursesLevelsPerStYearDirctliy(v);
}
///// the error massage aaper her when i use break point to know what are the changes that have been done
_CurrentLevelsPerYear.CoursesLevelsPerStYears = _AllCoursesLevelsPerStYear
//////
/////
}
else
masseg = "يوجد مستوى دراسي مماثل";
}
if (string.IsNullOrWhiteSpace(masseg))
Closed(a);
else
ErrorMasseg = masseg;
}
private bool Valdite()
{
bool result = false;
if (_CurrentLevelsPerYear != null && _CurrentLevelsPerYear.StageLevelID>0 )
result = true;
return result;
}
public override void Reset()
{
}
public SchAvaiLevelsPerYear CurrentLevelsPerYear
{
get { return _CurrentLevelsPerYear; }
set
{
if (_CurrentLevelsPerYear != value)
{
_CurrentLevelsPerYear = value;
NotifyPropertyChanged("CurrentLevelsPerYear");
}
}
}
public ObservableCollection<StageLevel> AllStageLevel
{
get { return _AllStageLevel; }
set
{
if (_AllStageLevel != value)
{
_AllStageLevel = value;
NotifyPropertyChanged("AllStageLevel");
}
}
}
public StageLevel SelectrdStageLevel
{
get { return _SelectrdStageLevel; }
set
{
if (_SelectrdStageLevel != value)
{
_SelectrdStageLevel = value;
NotifyPropertyChanged("SelectrdStageLevel");
if (_isnew)
{
ObservableCollection<CoursesLevelsPerStYear> allcby = new ObservableCollection<CoursesLevelsPerStYear>();
CoursesLevelsPerStYear cby;
foreach (CoursesByLevel cbl in _SelectrdStageLevel.CoursesByLevels)
{
cby = new CoursesLevelsPerStYear() {StartDate = Session.SessionData.CurrentYear.StartDate, Avalible =true
, CoursByLevelID = cbl.ID , CoursesByLevel= cbl, UserID = Session.SessionData.CurrentUser.UserID,
MaxLecturePerWeak = cbl.MaxLecturePerWeak,MinLecturePerWeak = cbl.MinLecturePerWeak,
SchAvaiLevelsPerYear = _CurrentLevelsPerYear
};
allcby.Add(cby);
}
AllCoursesLevelsPerStYear = allcby;
}
}
}
}
public ObservableCollection<CoursesLevelsPerStYear> AllCoursesLevelsPerStYear
{
get { return _AllCoursesLevelsPerStYear; }
set
{
if (_AllCoursesLevelsPerStYear != value)
{
_AllCoursesLevelsPerStYear = value;
NotifyPropertyChanged("AllCoursesLevelsPerStYear");
}
}
}
public bool IsEnabled
{
get { return _IsEnabled; }
set
{
if (_IsEnabled != value)
{
_IsEnabled = value;
NotifyPropertyChanged("IsEnabled");
}
}
}
public string ErrorMasseg
{
get { return errorMasseg; }
private set
{
if (value != errorMasseg)
{
errorMasseg = value;
NotifyPropertyChanged("ErrorMasseg");
}
}
}
public event Action<SchAvaiLevelsPerYear> Closed;
public ICommand SaveCommand
{
private set;
get;
}
public DelegateCommand CanselCommand
{
private set;
get;
}
}
}
this the entity
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataAccess
{
using System;
using System.Collections.ObjectModel;
public partial class SchAvaiLevelsPerYear : BaseModel
{
public SchAvaiLevelsPerYear()
{
this.CoursesLevelsPerStYears = new ObservableCollection<CoursesLevelsPerStYear>();
this.StduyYearLevelFrogs = new ObservableCollection<StduyYearLevelFrog>();
}
private int _iD;
public int ID
{
get { return _iD; }
set { SetProperty(ref _iD, value); }
}
private int _yearID;
public int YearID
{
get { return _yearID; }
set { SetProperty(ref _yearID, value); }
}
private int _stageLevelID;
public int StageLevelID
{
get { return _stageLevelID; }
set { SetProperty(ref _stageLevelID, value); }
}
private int _schoolID;
public int SchoolID
{
get { return _schoolID; }
set { SetProperty(ref _schoolID, value); }
}
private bool _avalible;
public bool Avalible
{
get { return _avalible; }
set { SetProperty(ref _avalible, value); }
}
private int _coursCount;
public int CoursCount
{
get { return _coursCount; }
set { SetProperty(ref _coursCount, value); }
}
private byte[] _timestamp;
public byte[] Timestamp
{
get { return _timestamp; }
set { SetProperty(ref _timestamp, value); }
}
private int _userID;
public int UserID
{
get { return _userID; }
set { SetProperty(ref _userID, value); }
}
public virtual Branch Branch { get; set; }
public virtual ObservableCollection<CoursesLevelsPerStYear> CoursesLevelsPerStYears { get; set; }
public virtual StageLevel StageLevel { get; set; }
public virtual StudyYear StudyYear { get; set; }
public virtual ObservableCollection<StduyYearLevelFrog> StduyYearLevelFrogs { get; set; }
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataAccess
{
using System;
using System.Collections.ObjectModel;
public partial class CoursesLevelsPerStYear : BaseModel
{
public CoursesLevelsPerStYear()
{
this.CourseGroups = new ObservableCollection<CourseGroup>();
this.Teachers = new ObservableCollection<Teacher>();
}
private int _iD;
public int ID
{
get { return _iD; }
set { SetProperty(ref _iD, value); }
}
private int _coursByLevelID;
public int CoursByLevelID
{
get { return _coursByLevelID; }
set { SetProperty(ref _coursByLevelID, value); }
}
private int _sALByYearID;
public int SALByYearID
{
get { return _sALByYearID; }
set { SetProperty(ref _sALByYearID, value); }
}
private int _maxLecturePerWeak;
public int MaxLecturePerWeak
{
get { return _maxLecturePerWeak; }
set { SetProperty(ref _maxLecturePerWeak, value); }
}
private int _minLecturePerWeak;
public int MinLecturePerWeak
{
get { return _minLecturePerWeak; }
set { SetProperty(ref _minLecturePerWeak, value); }
}
private bool _haveGroup;
public bool HaveGroup
{
get { return _haveGroup; }
set { SetProperty(ref _haveGroup, value); }
}
private bool _avalible;
public bool Avalible
{
get { return _avalible; }
set { SetProperty(ref _avalible, value); }
}
private Nullable<int> _holeID;
public Nullable<int> HoleID
{
get { return _holeID; }
set { SetProperty(ref _holeID, value); }
}
private bool _hasHole;
public bool HasHole
{
get { return _hasHole; }
set { SetProperty(ref _hasHole, value); }
}
private System.DateTime _startDate;
public System.DateTime StartDate
{
get { return _startDate; }
set { SetProperty(ref _startDate, value); }
}
private Nullable<System.DateTime> _stopDate;
public Nullable<System.DateTime> StopDate
{
get { return _stopDate; }
set { SetProperty(ref _stopDate, value); }
}
private byte[] _timestamp;
public byte[] Timestamp
{
get { return _timestamp; }
set { SetProperty(ref _timestamp, value); }
}
private int _userID;
public int UserID
{
get { return _userID; }
set { SetProperty(ref _userID, value); }
}
public virtual ObservableCollection<CourseGroup> CourseGroups { get; set; }
public virtual CoursesByLevel CoursesByLevel { get; set; }
public virtual Hole Hole { get; set; }
public virtual SchAvaiLevelsPerYear SchAvaiLevelsPerYear { get; set; }
public virtual ObservableCollection<Teacher> Teachers { get; set; }
}
}
namespace DataAccess
{
partial class CoursesLevelsPerStYear : BaseModel
{
private bool _CanEdit;
public bool CanEdit
{
get { return _CanEdit; }
set
{
SetProperty(ref _CanEdit, value);
}
}
private bool _EditMode;
public bool EditMode
{
get { return _EditMode; }
set
{
SetProperty(ref _EditMode, value);
}
}
string _EditButtonVisibility = "";
public string EditButtonVisibility
{
get
{
return _EditButtonVisibility;
}
set { SetProperty(ref _EditButtonVisibility, value); }
}
}
}
this only relation that Have problem like this . yes i have forget to mention that i change the DBContext of the entity framework using this and this
and i am using entity framework 6.2
excuse my english i am not a good english writer .

Casting a linq query to ObservableCollection

This is my code that I am trying to bind a datagrid to:
var query = (from s in entity.Sources
where s.CorporationId == corporationId
select new SourceItem
{
CorporationId = s.CorporationId,
Description=s.Description,
IsActive = s.IsActive,
Name=s.Name,
SourceId=s.SourceId,
TokenId=s.TokenId
});
var x = new ObservableCollection<Source>(query);
And this is my SourceItetm class:
private void SourceDataGrid_AddingNewItem(object sender, System.Windows.Controls.AddingNewItemEventArgs e)
{
var sources = new Source();
sources.CorporationId = _corporationId;
sources.Description = string.Empty;
sources.IsActive = true;
sources.Name = string.Empty;
sources.SourceId = Guid.NewGuid();
sources.TokenId = Guid.NewGuid();
e.NewItem = sources;
}
public class SourceItem
{
private Guid _corporationId1;
private string _description;
private bool _isActive;
private string _name;
private Guid _sourceId;
private Guid _tokenId;
public Guid CorporationId
{
set
{
_corporationId1 = value;
onPropertyChanged(this, "CorporationId");
}
get { return _corporationId1; }
}
public string Description
{
set
{
_description = value;
onPropertyChanged(this, "Description");
}
get { return _description; }
}
public bool IsActive
{
set
{
_isActive = value;
onPropertyChanged(this, "IsActive");
}
get { return _isActive; }
}
public string Name
{
set
{
_name = value;
onPropertyChanged(this, "NAme");
}
get { return _name; }
}
public Guid SourceId
{
set
{
_sourceId = value;
onPropertyChanged(this, "SourceId");
}
get { return _sourceId; }
}
public Guid TokenId
{
set
{
_tokenId = value;
onPropertyChanged(this, "TokenId");
}
get { return _tokenId; }
}
// Declare the PropertyChanged event
public event PropertyChangedEventHandler PropertyChanged;
// OnPropertyChanged will raise the PropertyChanged event passing the
// source property that is being updated.
private void onPropertyChanged(object sender, string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
}
}
I'm having problems getting the binding right. This line in particular:
var x = new ObservableCollection<Source>(query);
It is telling me that it cannot resolve constructor.
Am I doing the binding right?
The type you select is SourceItem therefore you should use:
new ObservableCollection<SourceItem>(query.ToList());

XML serialization C#, not processing certain fields

I have a serialization method as follows:
public string SerializeObject(object obj, Type type)
{
var setting = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };
var xml = new StringBuilder();
using (var writer = XmlWriter.Create(xml, setting))
{
var nsSerializer = new XmlSerializerNamespaces();
nsSerializer.Add(string.Empty, string.Empty);
var xmlSerializer = new XmlSerializer(type);
xmlSerializer.Serialize(writer, obj, nsSerializer);
}
return xml.ToString();
}
Which I call as follows:
requestXML = serializer.SerializeObject(InboundIterate, typeof(INBOUND));
The output is as expected for any field I have defined in my structure as a string, but all the decimal values are missing.
For example my output will look like:
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</SD_DIMENSION_UOM>
<SALES_UOM>CS</SD_SALES_UOM>
</PRODUCT_EXTENSION>
when I am expecting
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</DIMENSION_UOM>
<DIMENSION>15.83</DIMENSION>
<SALES_UOM>CS</SALES_UOM>
<SALES>24</SALES>
</PRODUCT_EXTENSION>
any help would be appreciated, thank you.
class below
public partial class PRODUCT_EXTENSION {
private System.Nullable<decimal> LENGTHField;
private bool LENGTHFieldSpecified;
private System.Nullable<decimal> NET_WEIGHTField;
private bool NET_WEIGHTFieldSpecified;
private string SALES_UOMField;
private string WEIGHT_UOMField;
private List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEMField;
public PRODUCT_EXTENSION() {
this.SOURCE_SYSTEMField = new List<PRODUCT_EXTENSIONSOURCE_SYSTEM>();
}
public System.Nullable<decimal> LENGTH {
get {
return this.LENGTHField;
}
set {
this.LENGTHField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool SD_LENGTHSpecified {
get {
return this.LENGTHFieldSpecified;
}
set {
this.LENGTHFieldSpecified = value;
}
}
public System.Nullable<decimal> NET_WEIGHT {
get {
return this.NET_WEIGHTField;
}
set {
this.NET_WEIGHTField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool NET_WEIGHTSpecified {
get {
return this.NET_WEIGHTFieldSpecified;
}
set {
this.NET_WEIGHTFieldSpecified = value;
}
}
public string SALES_UOM {
get {
return this.SALES_UOMField;
}
set {
this.SALES_UOMField = value;
}
}
public string SD_WEIGHT_UOM {
get {
return this.WEIGHT_UOMField;
}
set {
this.WEIGHT_UOMField = value;
}
}
public List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEM {
get {
return this.SOURCE_SYSTEMField;
}
set {
this.SOURCE_SYSTEMField = value;
}
}
}
I've tried your code snippet, and it works fine for me fine with public properties, but if i change the property protection to protected or private. These properties are missing from the XML.
Check your properties.

Categories