JavaScriptSerializer and monodevelop - serialization

Im reading this book but I JavaScriptSerializer from the System.Web.Script.Serialization namespace because it seems to be unavailable?

I know this a really old post but by chance someone stumbles upon this like I have, System.Web.Script.Serialization is available in System.Web.Extensions.

Download source here and add as existing project.
Then add as reference:
http://www.bloxify.com/post/MonoTouch-Easy-JSON-Library.aspx
Edit:
You may also find that the monotouch linker is pretty aggressive. I would have code work fine in the simulator but crash in the device with method missing exceptions. Add a method somewhere in your app (you dont have to call it) like so:
public void FixMonoTouchErrors()
{
var gc = new System.ComponentModel.GuidConverter();
var sc = new System.ComponentModel.StringConverter();
var dc = new System.ComponentModel.DateTimeConverter();
var cc = new System.ComponentModel.CharConverter();
var sh = new System.ComponentModel.Int16Converter();
var sh1 = new System.ComponentModel.Int32Converter();
var sh2 = new System.ComponentModel.Int64Converter();
var dec = new System.ComponentModel.DecimalConverter();
var nc0 = new System.ComponentModel.NullableConverter(typeof(Int16?));
var nc1 = new System.ComponentModel.NullableConverter(typeof(Int32?));
var nc2 = new System.ComponentModel.NullableConverter(typeof(Int64?));
var nc3 = new System.ComponentModel.NullableConverter(typeof(decimal?));
var nc4 = new System.ComponentModel.NullableConverter(typeof(DateTime?));
}

Related

How to add custom roslyn analyzer from locally placed DLL?

I have created a Roslyn Analyzer project which generates a nuget package and DLL of it. I want to use that DLL in a standalone code analysis project. How can i do that? For example i have following code:
MSBuildLocator.RegisterDefaults();
var filePath = #"C:\Users\user\repos\ConsoleApp\ConsoleApp.sln";
var msbws = MSBuildWorkspace.Create();
var soln = await msbws.OpenSolutionAsync(filePath);
var errors = new List<Diagnostic>();
foreach (var proj in soln.Projects)
{
var analyzer = //Here i want to load analyzer from DLL present locally.
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(analyzer.GetAnalyzersForAllLanguages());
var res = compWithAnalyzer.GetAllDiagnosticsAsync().Result;
errors.AddRange(res.Where(r => r.Severity == DiagnosticSeverity.Error).ToList());
}
I have tried following
var analyzer = new AnalyzerFileReference("Path to DLL", new AnalyzerAssemblyLoader());
But here AnalyzerAssemblyLoader shows error as it is inaccessible to to its protection level (class is internal).
Kindly suggest me if we can do this.
the .WithAnalyzers() option will allow you to pass an instance of an analyzer. If you're referencing the DLL locally, you can just create the analyzer like you would any other object and pass it to the compilation.
var analyzer = new MyAnalyzer();
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
If you're not referencing the assembly, but want to load it at runtime, you can use the usual System.Reflection based methods to get an instance of the analyzer:
var assembly = Assembly.LoadFrom(#"<path to assembly>.dll");
var analyzers = assembly.GetTypes()
.Where(t => t.GetCustomAttribute<DiagnosticAnalyzerAttribute>() is object)
.Select(t => (DiagnosticAnalyzer) Activator.CreateInstance(t))
.ToArray();
compWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzers));

Renaming models in database with existing data when using RavenDb

Is there any 'easy' way to rename models in RavenDb when the database already has existing data? I have various models which were originally created in another language, and now I would like to rename them to English as the codebase is becoming quite unmaintainable. If I just rename them, then the data won't be loaded because the properties don't match anymore.
I would like the system to automatically do it on first load. Is there any best way how to approach this? My solution would be:
Check if a document exists to determine if the upgrade has been done or not
If upgrade has not been done, execute patch scripts to update fields
Update document to know that the upgrade has been done
I'd recommend you create new documents from the old documents.
This can be done pretty easily using patching via docStore.UpdateByIndex.
Suppose I had an old type name, Foo, and wanted to rename it to the new type name, Bar. And I wanted all the IDs to change from Foos/123 to Bars/123.
It would look something like this:
var patchScript = #"
// Copy all the properties from the old document
var newDoc = {};
for (var prop in this) {
if (prop !== '#metadata') {
newDoc[prop] = this[prop];
}
}
// Create the metadata.
var meta = {};
meta['Raven-Entity-Name'] = newCollection;
meta['Raven-Clr-Type'] = newType;
// Store the new document.
var newId = __document_id.replace(oldCollection, newCollection);
PutDocument(newId, newDoc, meta);
";
var oldCollection = "Foos";
var newCollection = "Bars";
var newType = "KarlCassar.Bar, KarlCassar"; // Where KarlCassar is your assembly name.
var query = new IndexQuery { Query = $"Tag:{oldCollection}" };
var options = new BulkOperationOptions { AllowStale = false };
var patch = new ScriptedPatchRequest
{
Script = patchScript,
Values = new Dictionary<string, object>
{
{ nameof(oldCollection), oldCollection },
{ nameof(newCollection), newCollection },
{ nameof(newType), newType }
}
};
var patchOperation = docStore.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName", query, patch, options);
patchOperation.WaitForCompletion();
Run that code once at startup, and then your app will be able to work with the new name entities. Your old entities are still around - those can be safely deleted via the Studio.

SgmlReader and System.Xml Windows 8

I'm trying to convert HTML stream to XML using SgmlReader for further parsing. This conversion is part of an APP i'm developing for Windows 8 Store. Below is the method that convert Html to XML:-
public static void ConvertToXml(string webResponse)
{
StringWriter sWriter = new StringWriter();
XmlWriter xmlWriter = XmlWriter.Create(sWriter);
SgmlReader sgmlReader = new SgmlReader();
sgmlReader.DocType = "HTML";
sgmlReader.WhitespaceHandling = WhitespaceHandling.All;
sgmlReader.CaseFolding = CaseFolding.ToLower;
sgmlReader.InputStream = new StringReader(webResponse);
sgmlReader.IgnoreDtd = true;
while (!sgmlReader.EOF)
{
xmlWriter.WriteNode(sgmlReader, true);
}
xmlWriter.Flush();
XmlString = sWriter.ToString();
}
The sgmlReader.WhitespaceHandling = WhitespaceHandling.All; is the problem as Xml.WhitespaceHandling is not present. Is there anyother way to do this?
After alot of reading and testing/debugging just found that sgmlReader.WhitespaceHandling = WhitespaceHandling.All is not needed atleast in my case, as sgmlReader.WhitespaceHandling is set to All by default. However i removed sgmlReader.IgnoreDtd = true; and now my Xml file look Normal ;)
Hope this will help someone

Ninject ActivationException on ChildKernel

I'm getting an ActivationException saying there was an error activating IEventBroker. MyDataSource takes an IEventBroker has a parameter. If I don't use the child kernel, there is no issue. What is going on?
var kernel = new StandardKernel();
var childKernel = new ChildKernel(kernel);
var eventBroker = new EventBroker();
childKernel.Bind<IEventBroker>().ToConstant(eventBroker);
var myDS = childKernel.Get<MyDataSource>();
From the ChildKernel readme:
The default behavior of Ninject that classes are bound to themself if
not explicit still exists. But in this case this will be done by the
top most parent. This means that this class can not have any
dependency defined on a child kernel. I strongly suggest to have a
binding for all objects that are resolved by ninject and not to use
this default behavior.
So you need to explicitly bind MyDataSource to self to make it work:
var kernel = new StandardKernel();
var childKernel = new ChildKernel(kernel);
var eventBroker = new EventBroker();
childKernel.Bind<IEventBroker>().ToConstant(eventBroker);
childKernel.Bind<MyDataSource>().ToSelf();
var myDS = childKernel.Get<MyDataSource>();

Serialize an Activity to xaml

I have Googled a bit, and cannot seem to find any examples of Xaml-fying Activities - good, bad, or otherwise!
public static string ToXaml (this Activity activity)
{
// i would use ActivityXamlServices to go from Xaml
// to activity, but how to go other way? documentation
// is slim, and cannot infer proper usage of
// ActivityXamlServices from Xml remarks :S
string xaml = string.Empty;
return xaml;
}
Hints, tips, pointers would be welcome :)
NOTE: so found this. Will work through and update once working. Anyone wanna beat me to the punch, by all means. Better yet, if you can find a way to be rid of WorkflowDesigner, seems odd it is required.
Alright, so worked through this forum posting.
You may Xaml-fy [ie transform an instance to declarative Xaml] a well-known Activity via
public static string ToXaml (this Activity activity)
{
StringBuilder xaml = new StringBuilder ();
using (XmlWriter xmlWriter = XmlWriter.Create (
xaml,
new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true, }))
using (XamlWriter xamlWriter = new XamlXmlWriter (
xmlWriter,
new XamlSchemaContext ()))
using (XamlWriter xamlServicesWriter =
ActivityXamlServices.CreateBuilderWriter (xamlWriter))
{
ActivityBuilder activityBuilder = new ActivityBuilder
{
Implementation = activity
};
XamlServices.Save (xamlServicesWriter, activityBuilder);
}
return xaml.ToString ();
}
Your Xaml may contain certain artifacts, such as references to System.Activities.Presentation namespace appearing as xmlns:sap="...". If this presents an issue in your solution, read the source link above - there is a means to inject directives to ignore unrecognized namespaces.
Will leave this open for a while. If anyone can find a better solution, or improve upon this, please by all means :)
How about XamlServices.Save(filename, activity)?
Based on the other solution (for VS2010B2) and some Reflectoring, I found a solution for VS2010RC. Since XamlWriter is abstract in the RC, the new way to serialize an activity tree is this:
public static string ToXaml (this Activity activity)
{
var xamlBuilder = new StringBuilder();
var xmlWriter = XmlWriter.Create(xamlBuilder,
new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true });
using (xmlWriter)
{
var xamlXmlWriter =
new XamlXmlWriter(xmlWriter, new XamlSchemaContext());
using (xamlXmlWriter)
{
XamlWriter xamlWriter =
ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);
using (xamlWriter)
{
var activityBuilder =
new ActivityBuilder { Implementation = sequence };
XamlServices.Save(xamlWriter, activityBuilder);
}
}
}
return xamlBuilder.ToString();
}