I couldn't see this method as extension method in MainWindow.xaml.cs , why
In MainWindow ,
I added :
using WpfApplication1_WPF.Classes;
please, advise me.
This is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.CompilerServices;
using System.Data.Objects;
namespace WpfApplication1_WPF.Classes
{
public static class Extensions
{
//1-Convert the user input to hash
public static String Hashed(String dataToHash)
{
//Convert dataToHash to byte array
byte[] plainTextBytes = Encoding.Unicode.GetBytes(dataToHash);
//Computer hash of bytes using SHA256 (256 bit hash value)
//Convert text to hash by using ComputerHash function in SHA256Managed algorithm
byte[] hash = new SHA256Managed().ComputeHash(plainTextBytes);
//Return hashed bytes as encoded string
//[convert hash byte to string to be saved in DB]
return Convert.ToBase64String(hash);
}
}
}
Add the following to the signarure
public static String Hashed(this String dataToHash)
You need the this in front of the input param.
Related
I have a .NET Core application that is using dotliquid. From the try online it looks like I can bind a property of an object that is inside an array. Like {{user.tasks[0].name}} where tasks is a collection of task object and name is property of the task.
I have JSON model that would be the input to the template. I don't know the JSON structure during the design time. So I am converting JSON string into ExpandoObject.
However, this does not work when I bind property of an object that is inside an array.
Demo NETFiddle
public class Program
{
public static void Main()
{
// this does not work
var modelString = "{\"States\": [{\"Name\": \"Texas\",\"Code\": \"TX\"}, {\"Name\": \"New York\",\"Code\": \"NY\"}]}";
var template = "State Is:{{States[0].Name}}";
Render(modelString,template);
//this works
modelString = "{\"States\": [\"Texas\",\"New York\"]}";
template = "State Is:{{States[0]}}";
Render(modelString,template);
}
private static void Render(string modelString, string template)
{
var model = JsonConvert.DeserializeObject<ExpandoObject>(modelString);
var templateModel = Hash.FromDictionary(model);
var html = Template.Parse(template).Render(templateModel);
Console.WriteLine(html);
}
}
You should parse as Dictionary<string, IEnumerable<ExpandoObject>> but not ExpandoObject.
using System;
using DotLiquid;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Dynamic;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// this does not work when binding a property of an object that is inside collection and when use dictionary
var modelString = "{\"States\": [{\"Name\": \"Texas\",\"Code\": \"TX\"}, {\"Name\": \"New York\",\"Code\": \"NY\"}]}";
var template = "State Is:{{Name}}";
RenderFromDictionary(modelString, template);
}
private static void RenderFromDictionary(string modelString, string template)
{
var Stats = JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<ExpandoObject>>>(modelString);
foreach (ExpandoObject expandoObject in Stats["States"])
{
var templateModel = Hash.FromDictionary(expandoObject);
var html = Template.Parse(template).Render(templateModel);
Console.WriteLine(html);
}
}
}
Test Result:
I hope somebody could help me on this one. I am implementing an Azure Function where I am trying to serialise an XML message into .Net object. This is the code that I am currently using:
public static void Run(string input, TraceWriter log)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(App));
// more code here....
}
public class App
{
public string DataB { get; set; }
}
However, I always got this error:
2017-01-17T12:21:35.173 Exception while executing function: Functions.ManualXmlToJson. mscorlib: Exception has been thrown by the target of an invocation. System.Xml: Identifier 'Submission#0' is not CLS-compliant.
Parameter name: ident.
I have tried with XmlAttributes, without them. I added the buildOptions:warningsAsErrors as false in project.json file but nothing happens. And to be honest, I ran out of ideas because this code is actually working in an App Console.
I guess is some parameter of something, I would really appreciate if somebody can suggest me how to fix it.
Thanks!
Your best option here will be to factor the class you're attempting to serialize into a separate class library and reference that from your function.
If you implement your App class above in a different assembly, your function code would look like the following:
#r "<yourassemblyname>.dll"
using System;
using <YourClassNamespace>;
public static void Run(string input, TraceWriter log)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(App));
}
The code above assumes a private assembly reference, where you upload your assembly to a bin folder, inside of your function folder.
You can find more about external references here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#referencing-external-assemblies
I'm opening an issue to address the CLS compliant name so this is not as confusing:
https://github.com/Azure/azure-webjobs-sdk-script/issues/1123
Another option worth trying (which would minimize the changes you'd need to make to your code) is to use the DataContractSerializer instead. You can find more information here.
Here is a quick sample of a function using the DataContractSerializer (with your type above):
#r "System.Runtime.Serialization"
using System;
using System.Xml;
using System.Runtime.Serialization;
public static void Run(string input, TraceWriter log)
{
string xml = WriteObject(new App { DataB = "Test"});
log.Info(xml);
}
[DataContract(Name = "App")]
public class App
{
[DataMember]
public string DataB { get; set; }
}
public static string WriteObject(App app)
{
using (var output = new StringWriter())
using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
{
var serializer = new DataContractSerializer(typeof(App));
serializer.WriteObject(writer, app);
return output.GetStringBuilder().ToString();
}
}
I'm learning antlr. I've gotten it working with Java but can't get anything to work in C#. I've created the simplest case I can find using an example from The Definitive Antlr Book and I'm still getting problems.
Here is my code and my grammar. I've hardcoded "hello parr" as the input and get
line 1:6 mismatched input 'parr' expecting ID
PreParser.g4
grammar PreParser;
import PreParseLex;
r: 'hello' ID;
PreParserLex.g4
lexer grammar PreParseLex;
ID: [a-z]+;
WS: [ \t\r\n]+ -> skip ;
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
namespace PreparseApp
{
class Program
{
static void Main(string[] args)
{
string expression = "hello parr";
AntlrInputStream input = new AntlrInputStream(expression);
PreParseLex lexer = new PreParseLex(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
PreParserParser parser = new PreParserParser(tokens);
IParseTree tree = parser.r();
Console.WriteLine("Done");
}
}
}
I don't understand why 'parr' doesn't ID. Ideas?
Sam Harwell answered this question. I used the wrong class for the lexer in C#. I needed to use PreParseLexer rather than PreParseLex. See his full response.
I have a cxf JAX-RS service which looks something like the one below. When I submit a request with requested type "application/xml" I would expect that cxf automatically converts my return value into xml. This works for the method getData, but not for the other 2 methods. The other 2 methods return a simple String representation of the return value such as 2.0 or true. How do I get cxf to return a XML document for all 3 methods?
#WebService
#Consumes("application/xml")
#Produces("application/xml")
public interface MyServiceInterface {
final static String VERSION = "2.0";
#WebMethod
#GET
#Path("/version")
String getVersion();
#WebMethod
#GET
#Path("/data/{user}")
Data[] getData(#PathParam("user") String username) throws IOException;
#WebMethod
#GET
#Path("/user/{user}")
boolean doesUserExist(#PathParam("user") String username);
}
The issue is that neither String nor boolean has a natural representation as an XML document; XML requires an outer element, and neither CXF nor JAXB (the XML binding layer) knows what it should be.
The simplest method is to return the basic type inside a little JAXB-annotated wrapper:
#XmlRootElement
public class Version {
#XmlValue
public String version;
}
#XmlRootElement
public class UserExists {
#XmlValue
public boolean exists;
}
#WebService
#Consumes("application/xml")
#Produces("application/xml")
public interface MyServiceInterface {
final static String VERSION = "2.0";
#WebMethod
#GET
#Path("/version")
// TYPE CHANGED BELOW!
Version getVersion();
#WebMethod
#GET
#Path("/data/{user}")
Data[] getData(#PathParam("user") String username) throws IOException;
#WebMethod
#GET
#Path("/user/{user}")
// TYPE CHANGED BELOW!
UserExists doesUserExist(#PathParam("user") String username);
}
The other way of doing this would be to register providers that know how to convert strings and booleans into XML, but that's messy and affects your whole application in unexpected ways and you really shouldn't do that for simple types, OK?
Note: All sample code is greatly simplified.
I have a DLL defined as:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
namespace RIV.Module
{
public interface IModule
{
StringWriter ProcessRequest(HttpContext context);
string Decrypt(string interactive);
string ExecutePlayerAction(object ParamObjectFromFlash);
void LogEvent(object LoggingObjectFromFlash);
}
}
Now, outside of my solution, other developers can define concrete classes and drop them into the BIN folder of my app. Maybe something like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RIV.Module;
namespace RIV.Module.Greeting
{
public class Module : IModule
{
public System.IO.StringWriter ProcessRequest(System.Web.HttpContext context)
{
//...
}
public string Decrypt(string interactive)
{
//...
}
public string ExecutePlayerAction(object ParamObjectFromFlash)
{
//...
}
public void LogEvent(object LoggingObjectFromFlash)
{
//...
}
}
}
Now, in my app I would need to know that a new Module was available (I am guessing via web.config or something along those lines) and then be able to call it based off of some trigger in the database Campaign table (which maps to the module to use for that specific campaign).
I am trying to instantiate it this way:
var type = typeof(RIV.Module.Greeting.Module);
var obj = (RIV.Module.Greeting.Module)Activator.CreateInstance(type);
However, the compiler belches because a reference was never set to RIV.Module.Greeting.dll!
What am I doing wrong?
You need to use more reflection:
Load the assembly by calling Assembly.Load
Find the type by calling someAssembly.GetType(name) or searching someAssembly.GetTypes()
Pass the Type instance to Activator.CreateInstance
Cast it to your interface.
Instead of typeof(RIV.Module.Greeting.Module), try using
var type = Type.GetType("RIV.Module.Greeting.Module, RIV.Module.Greeting");
(i.e. load the type by specifying its assembly-qualified name as string) and casting to IModule.
This approach requires you to know the exact class and assembly names of the modules (as you wrote, they could be stored in web.config).
Alternatively, you could go for a completely dynamic plugin approach:
establish a convention that all module assemblies should be named "RIV.Module.XYZ"
scan the bin directory for matching DLLs
for each DLL, load it (e.g. Assembly.Load) and scan for types implementing IModule
instantiate all found types and cast to IModule