Formatting Html strings to be used in HtmlHelper extensions -MVC - asp.net-mvc-4

I wrote an extension method :
public static string XDropDown(this HtmlHelper helper,string name, string optionLabel,object selectedValue)
{
StringBuilder b = new StringBuilder();
b.AppendFormat("<select name='{0}' id='{0}'>", name);
b.Append("</select>");
return b.ToString();
}
The rendered version :
<select name='CCName' id='CCName'><option value=&quot;BT&quot;>Bhutan</option></select>
and I am using it from a partial view,
it isn't rendered as it's expected,
I know that I can use Tag builders also,
but eager to know weather if this could work somehow or not.

Use the MvcHtmlString as the return type like so:
public static MvcHtmlString XDropDown(
this HtmlHelper helper,
string name,
string optionLabel,
object selectedValue)
{
StringBuilder b = new StringBuilder();
b.AppendFormat("<select name='{0}' id='{0}'>", name);
b.Append("</select>");
return MvcHtmlString.Create(b.ToString());
}

Related

Saving and Loading file definitions while using <generic> version of FileEngine

I've successfully use the SaveToXml and LoadFromXml methods on the ClassBuilder class to store and retrieve the file definitions while using the Standard version of the File Helper Engine.
However I'd really prefer to use the generic version of the File Helper Engine. In other words I'd like to instatiate the engine like so:
var eng = new DelimitedFileEngine<OutputClass>(params....);
OutputClass[] records = eng.ReadFile("Sample.csv");
So my results are strongly typed and not just an array of objects.
Does this save and load functionality exist for the generic file helper engine?
Sure, it works exactly as you'd expect.
[DelimitedRecord("|")]
public class OutputClass
{
public string First { get; set; }
public string Second { get; set; }
}
class Program
{
static void Main(string[] args)
{
var eng = new DelimitedFileEngine<OutputClass>();
// To read from a file use ReadFile()
//OutputClass[] records = eng.ReadFile("Sample.csv");
// Or to read from a string use ReadString()
OutputClass[] records = eng.ReadString("First|Second");
Debug.Assert(records.Length == 1);
Debug.Assert(records[0].First == "First");
Debug.Assert(records[0].Second == "Second");
Console.WriteLine("All OK");
Console.ReadKey();
}
}
Edit:
Based on your comment below, you want to map the results from your XML class to a concrete C# object. The easiest way is to use read into a DataTable and map the fields to the C# object.
var cb = new DelimitedClassBuilder(nameof(OutputClass), "|");
cb.AddField("First", typeof(string));
cb.AddField("Second", typeof(string));
var xmlString = cb.SaveToXmlString();
var outputClass = DelimitedClassBuilder.LoadFromXmlString(xmlString);
var eng = new FileHelperEngine(outputClass.CreateRecordClass());
OutputClass[] records = eng
.ReadStringAsDT("First|Second")
.Rows.OfType<DataRow>()
.Select(x => new OutputClass() {
First = x.Field<string>("First"),
Second = x.Field<string>("Second")
})
.ToArray();

How to replace query parameters into intercalated url?

Hello i am want to know given a an url saved as a string with placeholders.Is there anyway to just replace the spaceholders with the desired values?
public string Constant= #"/main/url/[id]/something/[value]";
public string Replace(int id,string value)
{
string url=Replace(id,value,Constant); // "/main/url/3/something/abc"
}
As you can see the url is intercalated with variables.Is there any class provided by the framework that i could use like:
public class Replacer
{
public string FillUrl(List<object> variables,string url)
{
var fullUrl=Replace(variables,url);
return fullUrl;
}
}
You can use the String.Replace (docs):
Returns a new string in which all occurrences of a specified Unicode
character or String in the current string are replaced with another
specified Unicode character or String.
public string Replace (string oldValue, string newValue);
url = url.Replace("[id]", id.ToString()).Replace('[value]', value);

Rendering html with tag helpers into string variable

I'm currently localising a ASP.NET Core Razor Pages application.
I use the "old" way of localising, with a compiled ResX file, and in my cshtml I use
<h3>#Global.Access</h3>
"Global" being the resource file,
"Access" being the key to the resource string.
I prefer to use this approach over an injected localizer:
#localiser["Access"]
Because this allows me to identify missing strings in the resource file during compile time.
Now, I have a resource string with a placeholder:
StringWithPlaceholder: "You can visit {0} for more information"
When I use following code in the cshtml everything works:
#{
var linkvariable = "blabla";
}
#string.Format(Global.StringWithPlaceHolder, linkvariable);
But if I replace the href by the asp-page tag helper, the tag helper is not rendered.
#{
linkvariable = "<a asp-page=\"my-page\">blabla</a>";
}
How could I resolve this?
To get the result of a tag helper into a string variable, you can do this:
#{
Func<string, Microsoft.AspNetCore.Html.IHtmlContent> Hyperlink = #<a asp-area="Area" asp-controller="Controller">#item</a>;
string value = Html.ToHtmlString(Hyperlink("Link text"));
}
The argument to that Func - a Templated Razor delegate - is a Dynamic object, so you could easily have a generic hyperlink template and pass it an object with Controller, Action, Area etc.
The ToHtmlString() extension method looks like this:
public static string ToHtmlString(this IHtmlHelper source, IHtmlContent htmlContent)
{
var sb = new StringBuilder();
using (TextWriter tw = new StringWriter(sb))
{
var encoder = (HtmlEncoder?)source.ViewContext.HttpContext.RequestServices.GetService(typeof(HtmlEncoder)) ?? HtmlEncoder.Default;
htmlContent.WriteTo(tw, encoder);
}
return sb.ToString();
}
From there, it's easy to use String.Format to render your localised hyperlink.
A more succinct alternative which avoids the variable is this:
#Html.Raw(Html.StringFormat("Click {0} to proceed", #<a asp-area="Area" asp-controller="Controller">here</a>))
The StringFormat extension method:
public static string StringFormat(this IHtmlHelper source, string format, params Func<dynamic, IHtmlContent>[] formatArgs)
{
var stringFormatArgs = new List<string>();
foreach (var item in formatArgs)
{
var sb = new StringBuilder();
using (TextWriter tw = new StringWriter(sb))
{
var encoder = (HtmlEncoder?)source.ViewContext.HttpContext.RequestServices.GetService(typeof(HtmlEncoder)) ?? HtmlEncoder.Default;
item("").WriteTo(tw, encoder);
stringFormatArgs.Add(sb.ToString());
}
}
return string.Format(format, args: stringFormatArgs.ToArray());
}

Creating JSON without quotes

A library is using Map to use some extra information. This map eventually is being converted a JSON object and I need to set request information to display for debugging purposes as this:
map.put("request", requestString);
I am considering to use Jackson specifically to create a JSON without quotes and want to set as requestString.
I am building necessary information regarding Request and building a Map including request headers, parameters, method etc.
Jackson is creating perfectly valid JSON with quotes but when I set this generated value inside map, It is displayed ugly because of having escaped quotes.
So Jackson is creating this:
{
method : "POST",
path : "/register"
}
When I set this in map, it turns to this:
{
method : \"POST\",
path : \"/register\"
}
Consider this as a huge map including all parameters and other information about request.
What I would like to want this:
{
method : POST,
path : /register
}
I know that this is not a valid JSON but I am using this as a String to a Map which is accepting String values.
public class UnQuotesSerializer extends NonTypedScalarSerializerBase<String>
{
public UnQuotesSerializer() { super(String.class); }
/**
* For Strings, both null and Empty String qualify for emptiness.
*/
#Override
public boolean isEmpty(String value) {
return (value == null) || (value.length() == 0);
}
#Override
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeRawValue(value);
}
#Override
public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
return createSchemaNode("string", true);
}
#Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
if (visitor != null) visitor.expectStringFormat(typeHint);
}
}
and
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule("UnQuote");
module.addSerializer(new UnQuotesSerializer());
objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.registerModule(module);
This is generating without quotes strings.
The following test passes (Jackson 2.5.0)
#Test
public void test() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Map map = new HashMap();
map.put("method", "POST");
map.put("request", "/register");
String s = mapper.writeValueAsString(map);
Map map2 = mapper.readValue(s, Map.class);
Assert.assertEquals(map, map2);
}
so your pseudo JSON without quotes does not seem the way to go

C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly

Code below is working well as long as I have class ClassSameAssembly in same assembly as class Program.
But when I move class ClassSameAssembly to a separate assembly, a RuntimeBinderException (see below) is thrown.
Is it possible to resolve it?
using System;
namespace ConsoleApplication2
{
public static class ClassSameAssembly
{
public static dynamic GetValues()
{
return new
{
Name = "Michael", Age = 20
};
}
}
internal class Program
{
private static void Main(string[] args)
{
var d = ClassSameAssembly.GetValues();
Console.WriteLine("{0} is {1} years old", d.Name, d.Age);
}
}
}
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Name'
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at ConsoleApplication2.Program.Main(String[] args) in C:\temp\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 23
I believe the problem is that the anonymous type is generated as internal, so the binder doesn't really "know" about it as such.
Try using ExpandoObject instead:
public static dynamic GetValues()
{
dynamic expando = new ExpandoObject();
expando.Name = "Michael";
expando.Age = 20;
return expando;
}
I know that's somewhat ugly, but it's the best I can think of at the moment... I don't think you can even use an object initializer with it, because while it's strongly typed as ExpandoObject the compiler won't know what to do with "Name" and "Age". You may be able to do this:
dynamic expando = new ExpandoObject()
{
{ "Name", "Michael" },
{ "Age", 20 }
};
return expando;
but that's not much better...
You could potentially write an extension method to convert an anonymous type to an expando with the same contents via reflection. Then you could write:
return new { Name = "Michael", Age = 20 }.ToExpando();
That's pretty horrible though :(
You could use [assembly: InternalsVisibleTo("YourAssemblyName")] to make you assembly internals visible.
I ran into a similair problem and would like to add to Jon Skeets answer that there is another option. The reason I found out was that I realized that many extension methods in Asp MVC3 uses anonymous classes as input to provide html attributes (new {alt="Image alt", style="padding-top: 5px"} =>
Anyway - those functions use the constructor of the RouteValueDictionary class. I tried that myself, and sure enough it works - though only the first level (I used a multi-level structure). SO - in code this would be:
object o = new {
name = "theName",
props = new {
p1 = "prop1",
p2 = "prop2"
}
}
SeparateAssembly.TextFunc(o)
//In SeparateAssembly:
public void TextFunc(Object o) {
var rvd = new RouteValueDictionary(o);
//Does not work:
Console.WriteLine(o.name);
Console.WriteLine(o.props.p1);
//DOES work!
Console.WriteLine(rvd["name"]);
//Does not work
Console.WriteLine(rvd["props"].p1);
Console.WriteLine(rvd["props"]["p1"]);
SO... What is really going on here? A peek inside the RouteValueDictionary reveals this code (values ~= o above):
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
object obj2 = descriptor.GetValue(values);
//"this.Add" would of course need to be adapted
this.Add(descriptor.Name, obj2);
}
SO - using TypeDescriptor.GetProperties(o) we would be able to get the properties and values despite the anonymous type being constructed as internal in a separate assembly! And of course this would be quite easy to extend to make it recursive. And to make an extension method if you wanted.
Hope this helps!
/Victor
Here is a rudimentary version of an extension method for ToExpandoObject that I'm sure has room for polishing.
public static ExpandoObject ToExpandoObject(this object value)
{
// Throw is a helper in my project, replace with your own check(s)
Throw<ArgumentNullException>.If(value, Predicates.IsNull, "value");
var obj = new ExpandoObject() as IDictionary<string, object>;
foreach (var property in value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
obj.Add(property.Name, property.GetValue(value, null));
}
return obj as ExpandoObject;
}
[TestCase(1, "str", 10.75, 9.000989, true)]
public void ToExpandoObjectTests(int int1, string str1, decimal dec1, double dbl1, bool bl1)
{
DateTime now = DateTime.Now;
dynamic value = new {Int = int1, String = str1, Decimal = dec1, Double = dbl1, Bool = bl1, Now = now}.ToExpandoObject();
Assert.AreEqual(int1, value.Int);
Assert.AreEqual(str1, value.String);
Assert.AreEqual(dec1, value.Decimal);
Assert.AreEqual(dbl1, value.Double);
Assert.AreEqual(bl1, value.Bool);
Assert.AreEqual(now, value.Now);
}
Below solution worked for me in my console application projects
Put this [assembly: InternalsVisibleTo("YourAssemblyName")]
in \Properties\AssemblyInfo.cs of the separate project with function returning dynamic object.
"YourAssemblyName" is the assembly name of calling project. You can get that through Assembly.GetExecutingAssembly().FullName by executing it in calling project.
A cleaner solution would be:
var d = ClassSameAssembly.GetValues().ToDynamic();
Which is now an ExpandoObject.
Remember to reference:
Microsoft.CSharp.dll
ToExpando extension method (mentioned in Jon's answer) for the brave ones
public static class ExtensionMethods
{
public static ExpandoObject ToExpando(this object obj)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(obj))
{
var value = propertyDescriptor.GetValue(obj);
expando.Add(propertyDescriptor.Name, value == null || new[]
{
typeof (Enum),
typeof (String),
typeof (Char),
typeof (Guid),
typeof (Boolean),
typeof (Byte),
typeof (Int16),
typeof (Int32),
typeof (Int64),
typeof (Single),
typeof (Double),
typeof (Decimal),
typeof (SByte),
typeof (UInt16),
typeof (UInt32),
typeof (UInt64),
typeof (DateTime),
typeof (DateTimeOffset),
typeof (TimeSpan),
}.Any(oo => oo.IsInstanceOfType(value))
? value
: value.ToExpando());
}
return (ExpandoObject)expando;
}
}
If you're already using Newtonsoft.Json in your project (or you're willing to add it for this purpose), you could implement that horrible extension method Jon Skeet is referring to in his answer like this:
public static class ObjectExtensions
{
public static ExpandoObject ToExpando(this object obj)
=> JsonConvert.DeserializeObject<ExpandoObject>(JsonConvert.SerializeObject(obj));
}