jsonsettings does not exist nancy.json in nancy - nancy

public class TakeRateDataNModule : NancyModule
{
private ObjectCache _apiCache;
public TakeRateDataNModule()
{
_apiCache = MemoryCache.Default;
var stopWatch = new Stopwatch();
Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;

Related

Problem loading view with MEF and ExportAttribute

I have a WPF app and I'm trying to use MEF to load viewmodels and view.
I can't successfully load Views.
The code:
public interface IContent
{
void OnNavigatedFrom( );
void OnNavigatedTo( );
}
public interface IContentMetadata
{
string ViewUri { get; }
}
[MetadataAttribute]
public class ExtensionMetadataAttribute : ExportAttribute
{
public string ViewUri { get; private set; }
public ExtensionMetadataAttribute(string uri) : base(typeof(IContentMetadata))
{
this.ViewUri = uri;
}
}
class ViewContentLoader
{
[ImportMany]
public IEnumerable<ExportFactory<IContent, IContentMetadata>> ViewExports
{
get;
set;
}
public object GetView(string uri)
{
// Get the factory for the View.
var viewMapping = ViewExports.FirstOrDefault(o =>
o.Metadata.ViewUri == uri);
if (viewMapping == null)
throw new InvalidOperationException(
String.Format("Unable to navigate to: {0}. " +
"Could not locate the View.",
uri));
var viewFactory = viewMapping.CreateExport();
var view = viewFactory.Value;
return viewFactory;
}
}
I supposed to use this code like this:
1)Decorate a User control
[Export(typeof(IContent))]
[ExtensionMetadata("CustomPause")]
[PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
public partial class CustomPause : Page , IContent, IPartImportsSatisfiedNotification
{
public CustomPause()
{
InitializeComponent();
}
}
2) Compose the parts:
var cv = new CompositionContainer(aggregateCatalog);
var mef = new ViewContentLoader();
cv.ComposeParts(mef);
3) Load the view at runtime given a URI, for example:
private void CustomPause_Click(object sender, RoutedEventArgs e)
{
var vc = GlobalContainer.Instance.GetMefContainer() as ViewContentLoader;
MainWindow.MainFrame.Content = vc.GetView ("CustomPause");
}
Problem is this line in the GetView method fails:
var viewMapping = ViewExports.FirstOrDefault(o =>
o.Metadata.ViewUri == uri);
The query fails and so viewMapping is null but composition seems ok and I can see that ViewExports contains an object of type:
{System.ComponentModel.Composition.ExportFactory<EyesGuard.MEF.IContent, EyesGuard.MEF.IContentMetadata>[0]
I don't know where I'm wrong. Do you have a clue?
Gianpaolo
I had forgot this
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
in the MetadataAttribute

Exception thrown: 'System.Net.WebException' in System.dll

In the button click event of below code, I'm able to send my data to post action of API Controller now.
Button Click Event of Windows Form
private void button1_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
MyClass myClass = new MyClass();
myClass.SearchText = textBox1.Text;
myClass.CountryCode = textBox2.Text;
string serialisedData = JsonConvert.SerializeObject(myClass);
var response = client.UploadString("http://localhost:50232/api/Place/PostSimple", serialisedData);
var x= JsonConvert.DeserializeObject(response);
}
}
public class MyClass
{
public string SearchText { get; set; }
public string CountryCode { get; set; }
}
But while debugging, I'm not able to move after
GeocodingResponse geocode = GoogleMaps.Geocode.Query(geocodeRequest);
this line of PostSimple action method. and getting the exception in
var response = client.UploadString("http://localhost:50232/api/Place/PostSimple", serialisedData); of Windows form application as
Exception thrown: 'System.Net.WebException' in System.dll
Additional information: The operation has timed out
ApiController Code
[HttpPost]
public List<Place> PostSimple(MyClass value)
{
List<Place> list = new List<Place>();
var geocodeRequest = new GeocodingRequest
{
Address = value.SearchText,
Components = new GeocodingComponents()
{
Country = value.CountryCode
}
};
try
{
GeocodingResponse geocode = GoogleMaps.Geocode.Query(geocodeRequest);
if (geocode.Status == GoogleMapsApi.Entities.Geocoding.Response.Status.OK)
{
TimeZoneRequest request = new TimeZoneRequest();
request.Location = new Location(geocode.Results.First().Geometry.Location.Latitude, geocode.Results.First().Geometry.Location.Longitude);
request.Language = "en";
request.TimeStamp = DateTime.Now.AddDays(-60);
TimeZoneResponse result = GoogleMaps.TimeZone.Query(request);
var x = System.TimeZoneInfo.FindSystemTimeZoneById(result.TimeZoneName);
}
}
catch (Exception ex)
{
throw ex;
}
return list;
}
MyClass code
public class MyClass
{
public string SearchText { get; set; }
public string CountryCode { get; set; }
}
Can anyone help me to solve this issue..Thanks in Advance

Caliburn.Micro: moving between pages with Conductor: how can I call a parent class method or property from a child class?

This is my main, parent class, ViewModel:
[AutofacRegisterType(PAGE_NAME, typeof(IMainPage), IsSingleInstance = false)]
public class MainPageViewModel : MainPageViewModelBase
{
public const string PAGE_NAME = "MainPage";
public MainPageChildsConductor ChildPages { get; private set; }
public IMainPageChild ActiveChildPage
{
get { return ChildPages.ActiveItem; }
}
public MainPageViewModel()
{
PageName = PAGE_NAME;
DisplayName = PAGE_NAME;
DisposeOnDeactivate = true;
InitChildPages();
}
private void InitChildPages()
{
ChildPages = new MainPageChildsConductor();
ChildPages.Parent = this;
ChildPages.ConductWith(this);
var trallchilds = TypeRegistry.GetItemsByType<IMainPageChild>();
var trchilds = trallchilds.Where(p => p.AutoRegister != null && p.AutoRegister.Name.StartsWith(PAGE_NAME + ":")).ToList();
var childs = new List<IMainPageChild>();
foreach (var trchild in trchilds)
{
var child = trchild.CreateType<IMainPageChild>();
childs.Add(child);
}
childs.Sort((a, b) => a.PageIndex.CompareTo(b.PageIndex));
ChildPages.Items.AddRange(childs);
ChildPages.ActivateWith(this);
ChildPages.DeactivateWith(this);
}
}
This is one of my child classes, ViewModel:
[AutofacRegisterType(PAGE_NAME, typeof(IMainPageChild), IsSingleInstance = false)]
public class Child1PageViewModel : MainPageChildViewModelBase
{
public const string PAGE_NAME = "ChildPage:Child1Page";
public const int PAGE_INDEX = 30;
public Child1PageViewModel()
{
PageName = PAGE_NAME;
DisplayName = "Child1";
PageIndex = PAGE_INDEX;
InitButtons();
InitSummaryData();
}
}
And this is the class that inherits the Caliburn.Micro class Conductor:
public class MainPageChildsConductor : Conductor<IMainPageChild>.Collection.OneActive
{
public MainPageChildsConductor()
{
}
public override void NotifyOfPropertyChange([CallerMemberName] string propertyName = null)
{
base.NotifyOfPropertyChange(propertyName);
if (Parent is INotifyPropertyChangedEx)
((INotifyPropertyChangedEx)Parent).Refresh();
}
}
The question is: how can I call a method or property that exists in the parent page 'MainPageViewModel' from the child page 'Child1PageViewModel'???
Your child view needs to inherit from Screen and when activated in the parent view model, you obtain a reference to the child VM's Parent property via inheritance from Screen.
See this page in the documentation for more details:
Screens, Conductors and Composition.
This is how I do it in one of my projects:
public class MainViewModel : Conductor<IScreen>.Collection.OneActive, IHandle<CreateNewGraphEvent>, IHandle<AddMeasurementsToGraphEvent>, IHandle<DeleteNamedGraphEvent>,
IHandle<GraphRenamedEvent>, IHandle<AddDuplicateGraphEvent>
{
private readonly TreeListViewModel _TreeView;
private readonly StatusBarViewModel _StatusBar;
private readonly IEventAggregator _Aggregator;
private readonly ProgressDialogViewModel _Progress;
public MainViewModel(IEventAggregator aggregator, TreeListViewModel treeView, StatusBarViewModel statusBar)
{
if (aggregator == null)
throw new ArgumentNullException("aggregator");
_Aggregator = aggregator;
_Aggregator.Subscribe(this);
if (statusBar == null)
throw new ArgumentNullException("statusBar");
_StatusBar = statusBar;
if (treeView == null)
throw new ArgumentNullException("treeView");
_TreeView = treeView;
this.Items.CollectionChanged += Items_CollectionChanged;
}
public void Handle(CreateNewGraphEvent message)
{
ChartViewModel document = IoC.Get<ChartViewModel>(message.SelectedGraphType.ToString());
if (document == null) return;
document.DisplayName = message.GraphName;
document.CloseAction = this.CloseAction;
document.SelectedGraphType = message.SelectedGraphType;
ActivateItem(document);
}
}
public class ChartViewModel : Screen, IHandle<MeasurementRenamedEvent>
{
private readonly IEventAggregator _Aggregator;
private readonly ISupportServices _Services;
public ChartViewModel(IEventAggregator aggregator, ISupportServices services) : base(aggregator, services)
{
if (aggregator == null)
throw new ArgumentNullException("aggregator");
_Aggregator = aggregator;
_Aggregator.Subscribe(this);
if (services == null)
throw new ArgumentNullException("services");
_Services = services;
}}
When ActivateItem item method is called in MainViewModel, the CihldViewModel is added to the Items collection in MainViewModel and activates the child VM, where you can then access MainViewModel through the this.Parent property in ChildViewModel.

Serializing a DataSet/DataTable with properties in json.net

I'm looking a solution to serialize dataset to json, but I need to get the rowstate in json.
Does json.net serialize / deserialize properties of the dataset / datatable, like rowstate? I can only find examples with row value.
Thanks.
No, the DataTableConverter that ships with Json.Net does not serialize the RowState. If you really need this value in the JSON, it should be possible to create a custom JsonConverter to output it. However, it will not be possible to deserialize the RowState back to its original value due to the fact that it is a read-only property. (In fact, this value is calculated from a variety of internal state variables.)
I wrote a custom converter for DataSet which keeps the row state. The DataSet class can write the schema as xml with WriteXmlSchema, and it can write the data including the rowstate with WriteXml(sw, XmlWriteMode.DiffGram). This produces two strings that are properties in the DataSetSerializer class, which then can be serialized and deserialized with JsonSerializer. Here is the code in a test class:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace TestProject3
{
public class DataSetConverter : JsonConverter<DataSet>
{
private class DataSetSerializer
{
public string SchemaString { get; set; }
public string DataString { get; set; }
private static string GetSchema(DataSet ds)
{
using (var sw = new StringWriter())
{
ds.WriteXmlSchema(sw);
return sw.ToString();
}
}
private static string GetData(DataSet ds)
{
using (var sw = new StringWriter())
{
ds.WriteXml(sw, XmlWriteMode.DiffGram);
return sw.ToString();
}
}
private DataSet GetDataSet()
{
var ds = new DataSet();
using (var sr1 = new StringReader(SchemaString))
{
ds.ReadXmlSchema(sr1);
}
using (var sr2 = new StringReader(DataString))
{
ds.ReadXml(sr2, XmlReadMode.DiffGram);
}
return ds;
}
public static string Serialize(DataSet ds)
{
var serializer = new DataSetSerializer() { SchemaString = GetSchema(ds), DataString = GetData(ds) };
return JsonSerializer.Serialize<DataSetSerializer>(serializer);
}
public static DataSet DeSerialize(string s)
{
var serializer = JsonSerializer.Deserialize<DataSetSerializer>(s);
return serializer.GetDataSet();
}
}
public override DataSet Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DataSetSerializer.DeSerialize(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DataSet value, JsonSerializerOptions options)
{
writer.WriteStringValue(DataSetSerializer.Serialize(value));
}
}
[TestClass]
public class TestDataSet
{
private DataSet CreateTestDataSet()
{
var ds = new DataSet();
var dt = ds.Tables.Add();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Rows.Add("A1", "B1");
var dr = dt.Rows.Add("A2", "B2");
ds.AcceptChanges();
dr["A"] = "AA2";
return ds;
}
private void CheckTestDataSet(DataSet ds)
{
var dt = ds.Tables[0];
Assert.IsTrue(dt.Rows[0].RowState == DataRowState.Unchanged && dt.Rows[1].RowState == DataRowState.Modified);
}
[TestMethod]
public void TestDataSetConverter()
{
var ds = CreateTestDataSet();
var serializeOptions = new JsonSerializerOptions { Converters = { new DataSetConverter() } };
var jsonstring = JsonSerializer.Serialize(ds, serializeOptions);
ds = JsonSerializer.Deserialize<DataSet>(jsonstring, serializeOptions);
CheckTestDataSet(ds);
}
}
}
I needed a solution that maintained RowState for DataSets and DataTables for a legacy app migrating from SOAP calls to WebApi calls but using Newtonsoft rather than System.Text.Json. Thank you Alex for the last answer which was just what I needed.
Here is a Newtonsoft version of the same thing:
using System;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using Xunit;
namespace DataSetsAndTablesTester
{
public class CustomJsonConverter_DataSet : JsonConverter<DataSet>
{
private class DataSetSerializer
{
public string SchemaString { get; set; }
public string DataString { get; set; }
private static string GetSchema(DataSet ds)
{
using (var sw = new StringWriter())
{
ds.WriteXmlSchema(sw);
return sw.ToString();
}
}
private static string GetData(DataSet ds)
{
using (var sw = new StringWriter())
{
ds.WriteXml(sw, XmlWriteMode.DiffGram);
return sw.ToString();
}
}
private DataSet GetDataSet()
{
var ds = new DataSet();
using (var sr1 = new StringReader(SchemaString))
{
ds.ReadXmlSchema(sr1);
}
using (var sr2 = new StringReader(DataString))
{
ds.ReadXml(sr2, XmlReadMode.DiffGram);
}
return ds;
}
public static string Serialize(DataSet ds)
{
var serializer = new DataSetSerializer() { SchemaString = GetSchema(ds), DataString = GetData(ds) };
return JsonConvert.SerializeObject(serializer);
}
public static DataSet DeSerialize(string s)
{
var serializer = JsonConvert.DeserializeObject<DataSetSerializer>(s);
return serializer.GetDataSet();
}
}
public override void WriteJson(JsonWriter writer, DataSet value, JsonSerializer serializer)
{
if (value == null)
throw new Exception("Passed in DataSet is null");
writer.WriteValue(DataSetSerializer.Serialize(ds: value));
}
public override DataSet ReadJson(JsonReader reader, Type objectType, DataSet existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return DataSetSerializer.DeSerialize((string)reader.Value);
}
}
public class CustomJsonConverter_DataTable : JsonConverter<DataTable>
{
private class DataTableSerializer
{
public string SchemaString { get; set; }
public string DataString { get; set; }
private static string GetSchema(DataTable dt)
{
using (var sw = new StringWriter())
{
dt.WriteXmlSchema(sw);
return sw.ToString();
}
}
private static string GetData(DataTable dt)
{
using (var sw = new StringWriter())
{
dt.WriteXml(sw, XmlWriteMode.DiffGram);
return sw.ToString();
}
}
private DataTable GetDataTable()
{
var dt = new DataTable();
using (var sr1 = new StringReader(SchemaString))
{
dt.ReadXmlSchema(sr1);
}
using (var sr2 = new StringReader(DataString))
{
dt.ReadXml(sr2);
}
return dt;
}
public static string Serialize(DataTable dt)
{
var serializer = new DataTableSerializer() { SchemaString = GetSchema(dt), DataString = GetData(dt) };
return JsonConvert.SerializeObject(serializer);
}
public static DataTable DeSerialize(string s)
{
var serializer = JsonConvert.DeserializeObject<DataTableSerializer>(s);
return serializer.GetDataTable();
}
}
public override void WriteJson(JsonWriter writer, DataTable value, JsonSerializer serializer)
{
if (value == null)
throw new Exception("Passed in DataTable is null");
if (string.IsNullOrEmpty(value.TableName))
throw new Exception("Passed in DataTable Name is null or empty");
writer.WriteValue(DataTableSerializer.Serialize(dt: value));
}
public override DataTable ReadJson(JsonReader reader, Type objectType, DataTable existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return DataTableSerializer.DeSerialize((string)reader.Value);
}
}
public class JsonConverterTester
{
public void TestJsonDataSetConverter()
{
DataSet ds = CreateTestDataSet();
String json = JsonConvert.SerializeObject(value: ds, converters: new CustomJsonConverter_DataSet());
Console.WriteLine(json);
DataSet ds2 = JsonConvert.DeserializeObject<DataSet>(value: json, converters: new CustomJsonConverter_DataSet());
CheckTestDataSet(ds2);
}
public void TestJsonDataTableConverter()
{
DataTable dt = CreateTestDataTable();
String json = JsonConvert.SerializeObject(value: dt, converters: new CustomJsonConverter_DataTable());
Console.WriteLine(json);
DataTable dt2 = JsonConvert.DeserializeObject<DataTable>(value: json, converters: new CustomJsonConverter_DataTable());
CheckTestDataTable(dt2);
}
private DataSet CreateTestDataSet()
{
var ds = new DataSet();
var dt = ds.Tables.Add();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Rows.Add("A1", "B1");
var dr = dt.Rows.Add("A2", "B2");
ds.AcceptChanges();
dr["A"] = "AA2";
return ds;
}
private void CheckTestDataSet(DataSet ds)
{
var dt = ds.Tables[0];
Assert.True(dt.Rows[0].RowState == DataRowState.Unchanged && dt.Rows[1].RowState == DataRowState.Modified);
}
private DataTable CreateTestDataTable()
{
var dt = new DataTable();
dt.TableName = "TestTable";
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Rows.Add("A1", "B1");
var dr = dt.Rows.Add("A2", "B2");
dt.AcceptChanges();
dr["A"] = "AA2";
return dt;
}
private void CheckTestDataTable(DataTable dt)
{
Assert.True(dt.Rows[0].RowState == DataRowState.Unchanged && dt.Rows[1].RowState == DataRowState.Modified);
}
}
}

Caliburn.Micro and WebServiceResult

I'm looking for the correct version of this class for Caliburn.Micro
public class WebServiceResult : IResult where T : new()
The above signature is from the ContactManager example in the full Caliburn framework.
It does not cut and paste directly into a Micro-based project. There are too many missing classes to use this directly. Thoughts? or anyone know of the replacement?
Event though the underlying infrastructure is very different in Caliburn Micro (which is based on System.Windows.Interactivity), the concepts are pretty much the same.
Here is the CM version:
public class WebServiceResult<T, K> : IResult
where T : new()
where K : EventArgs
{
readonly static Func<bool> ALWAYS_FALSE_GUARD= () => false;
readonly static Func<bool> ALWAYS_TRUE_GUARD = () => true;
private readonly Action<K> _callback;
private readonly Expression<Action<T>> _serviceCall;
private ActionExecutionContext _currentContext;
private Func<bool> _originalGuard;
public WebServiceResult(Expression<Action<T>> serviceCall)
{
_serviceCall = serviceCall;
}
public WebServiceResult(Expression<Action<T>> serviceCall, Action<K> callback)
{
_serviceCall = serviceCall;
_callback = callback;
}
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
public void Execute(ActionExecutionContext context)
{
_currentContext = context;
//if you would to disable the control that caused the service to be called, you could do this:
ChangeAvailability(false);
var lambda = (LambdaExpression)_serviceCall;
var methodCall = (MethodCallExpression)lambda.Body;
var eventName = methodCall.Method.Name.Replace("Async", "Completed");
var eventInfo = typeof(T).GetEvent(eventName);
var service = new T();
eventInfo.AddEventHandler(service, new EventHandler<K>(OnEvent));
_serviceCall.Compile()(service);
}
public void OnEvent(object sender, K args)
{
//re-enable the control that caused the service to be called:
ChangeAvailability(true);
if (_callback != null)
_callback(args);
Completed(this, new ResultCompletionEventArgs());
}
private void ChangeAvailability(bool isAvailable)
{
if (_currentContext == null) return;
if (!isAvailable) {
_originalGuard = _currentContext.CanExecute;
_currentContext.CanExecute = ALWAYS_FALSE_GUARD;
}
else if (_currentContext.CanExecute == ALWAYS_FALSE_GUARD) {
_currentContext.CanExecute = _originalGuard ?? ALWAYS_TRUE_GUARD;
}
_currentContext.Message.UpdateAvailability();
}
}

Resources