Assignation of string with accents to another string, replaces them with "ó" - c#

I have a list of elements, and one of those elements field is a string value that contains an spanish-accented text which I see ok in the list.
Once I enter de Detail page for one of those elements, the accents are shown like this ó
I have a string variable that contains the original Spanish-Accented text, and I assign that value to the new view.
Example:
string a = "facturación";
view.Document = a;
and the field a of the class view is declared like this:
string Document { get; set; }
when I do a quickwatch over "a" I see "facturación".
when I do a quickwatch over "view.Document" y see "facturación"
what can I do?
Thanks in advance!

Found the error!
The property was re-defined like this:
public string Document
{
get
{
return HttpUtility.HtmlEncode(txtDocument.Text);
}
set
{
txtDocument.Text = HttpUtility.HtmlEncode(value);
}
}
So the HtmlEncoding was the thing that was messing up with my string.
Thanks anyway!

The reason this happens is that the view is escaping the string before rendering it. Use
<%= Server.HtmlDecode(mystring) %> in your view to render the string un-escaped.

Related

Smartly replace strings

I am working with JSON API. As c# doesn't accept characters like - (minus) or . (point), I had to replace each character by _ (underscore). The replacement happens when the JSON response is received as a string so that every attribute name containing a - or a . will have it replaced by a _ , then every attribute name will be the same as the attributes names in the class it will be deserialized into.
To make it clearer, here are some examples:
I recieve the following JSON : { "id": 1, "result": [ { "data": [ { "adm-pass": ""}]}
In the class I want to deserialize into I have this attribute : public String adm_pass {get; set;}
So I replace the minus with an underscore so that the NewtonSoft parser can deserialize it accordingly.
My problem is that I sometimes I get some negative integers in my JSON. So if I do the string replacement in: {"beta" : -1}, I get a parsing exception since the -1 (integer here) becomes _1 and cannot be deserialized properly and raises an exception.
Is there a way to replace the string smartly so I can avoid this error?
For example if - is followed by an int it's not replaced.
If this way does not exist, is there a solution for this kind of problems?
Newtonsoft allows you to specify the exact name of the JSON property, which it will use to serialize/deserialize.
So you should be able to do this
[JsonProperty("adm-pass")]
public String adm_pass { get; set; }
This way you are not restricted to name your properties exactly as the JSON property names. And in your case, you won't need to do a string replace.
Hope this helps.
You'll have to check that you are replacing the key and not the value, maybe by using a regex like http://regexr.com/3d471
Regex could work as wlalele suggests.
But I would create a new object like this:
Create a new object:
var sharpObj = {};
loop through the objects as properties as described here:
Iterate through object properties
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
In the // do stuff section, create a property on sharpObj with the desired string replacements and set the property to the same value.
var cleanProperty = cleanPropertyName(property);
sharpObj[cleanProperty] = orginalObject[property];
Note: I assume you can figure out the cleanPropertyName() method or similar.
Stringify the object
var string = JSON.stringify(sharpObj);
You can substring to check whether the next character is an integer, this can adapt into your code easily as you already find a character, as such you could do
int a;
if(int.TryParse(adm_pass.Substring(adm_pass.IndexOf("-") + 1,1),out a))
{
//Code if next character is an int
}
else
{
adm_pass = adm_pass.Replace("-","_");
}
This kind of code can be looped until there are no remaining hyphens/minuses

Outputting formatted code to view in asp.net MVC

I am hoping there is a solution to this,
I have an example MVC application, and I want to output formatted snippets of code to the browser
Something like the following
ViewBag.PageSource = "
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
[RegularExpression("[a-zA-Z0-9]{2,64}", ErrorMessage = "username must contain letters or numbers only, and be between 2 and 64 characters long ")]
public string UserName { get; set; }
}
";
Is this sort of thing possible ?
I have a modal popup in the main layout file and I wanted this to contain the source (model/controller) snippets for each view, by placing it in a viewbag variable in each view
Don't try to do this at the controller. That's what the view is for.
code.google.com & Stackoverflow use Code-Prettify.
You can then use it with the pre tags:
<pre class="prettyprint">
public class RegisterViewModel<br/>
{<br/>
[Required]<br/>
[Display(Name = "User name")]<br/>
[RegularExpression("[a-zA-Z0-9]{2,64}", ErrorMessage = "username must contain letters or numbers only, and be between 2 and 64 characters long ")]<br/>
public string UserName { get; set; }<br/>
<br/>
}<br/>
</pre>
Yes, anything is possible. Add the # sign in front of first " and multi-line strings will work.
Then you need to do something about the tabs. You could use <pre> tag or replace tabs with a fixed-width div.
If snippet is dynamicly generated you have to use JavaScript formatted.
For example
SyntaxHighlighter is good client-side solution:
http://alexgorbatchev.com/SyntaxHighlighter/
In other case take a look here
Jon Skeet provides a code formatter for public use:
http://csharpindepth.com/CodeFormatterTool.aspx
UPDATE
Seems to me that SO use this https://code.google.com/p/google-code-prettify/
For HTML5 you should use <pre><code>//your code here</code></pre>.

Passing parameters though url?

I am trying to test a call to my one of my functions.
This is called from outside of my website an acts like a Webservice.
To test im trying to pass the parameters though my url.
http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails=[{property_details_address_address1{TagValue:'Test'},{ImageBase64:''}}]?Id=4785
My code in my service:
public void UploadValuationDetails(Dictionary<string, ValuationDetails> JsonResult, int Id)
{
DatabaseHelper DBH = new DatabaseHelper();
foreach (var item in JsonResult)
{ //(ValuationId , TagName , TagValue , ImageBase64)
DBH.WSValuationDetailUpdate(Id, item.Key, item.Value.TagValue, item.Value.ImageBase64);
}
}
ValuationDetails class:
public class ValuationDetails
{
public string TagValue { get; set; }
public string ImageBase64 { get; set; }
}
Edit Changed ? for the second parameter to &:
> http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails={'property_details_address_address1':[{TagValue:'Test',ImageBase64:''}]}&Id=4785
After changing my url to the one above a break point was hit but the values were incorrect.
Edit 2 Trying to get the correct values in the json result.
I think i'm closer:
http://localhost:0000/APIService/UploadValuationDetails?JsonResult={TagName:"property_details_address_address1",ValuationDetails:{TagValue:"Test","ImageBase64:""}}]&Id=4785
But now my jsonResult = 0
You should use an ampersand (&) to separate multiple query string parameters. As you have it, you're using ?, so "?Id=4785" is being interpreted as part of the value for the ValuationDetails parameter.
Corrected:
this is correct ┐
↓
http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails=
[{property_details_address_address1{TagValue:'Test'},{ImageBase64:''}}]&Id=4785
↑
but this should be fixed ┘
I think it is better to Encode the JSON too.
Since the moment you will have for instance in side your data an ? or & you will get an exception too.
Your URL string looks improperly formatted.
For the separator of the URL and the parameters you would use ?.
But to separate parameters use &
http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails=[{property_details_address_address1{TagValue:'Test'},{ImageBase64:''}}]&Id=4785
Your JSON is invalid.
I've worked with it a bit, but it still needs input from you.
[
{
"property_details_address_address1": {
"TagValue": "Test"
},
"needs_a_name_here": {
"ImageBase64": ""
}
}
]
Notice that i've put quotes around the names. And your second object also requires a name.
I used JSONLint to validate and create the proper json

Check if HtmlString is whitespace in C#

I've got a wrapper that adds a header to a field whenever it has a value. The field is actually a string which holds HTML from a tinymce textbox.
Requirement: the header should not display when the field is empty or just whitespace.
Issue: whitespace in html is rendered as <p> </p>, so technically it's not an empty or whitespace value
I simply can't !String.IsNullOrWhiteSpace(Model.ContentField.Value) because it does have a value, albeit whitespace html.
I've tried to convert the value onto #Html.Raw(Model.ContentField.Value) but it's of a type HtmlString, so I can't use String.IsNullOrWhiteSpace.
Any ideas? Thanks!
You can use HtmlAgilityPack, something like this:
HtmlDocument document = new HtmlDocument();
document.LoadHtml(Model.ContentField.Value);
string textValue = HtmlEntity.DeEntitize(document.DocumentNode.InnerText);
bool isEmpty = String.IsNullOrWhiteSpace(textValue);
What I eventually did (because I didn't want to add a 3rd party library just for this), is to add a function in a helper class that strips HTML tags:
const string HTML_TAG_PATTERN = "<.*?>";
public static string StripHTML(string inputString)
{
return Regex.Replace
(inputString, HTML_TAG_PATTERN, string.Empty);
}
After which, I combined that with HttpUtility.HtmlDecode to get the inner value:
var innerContent = StringHelper.StripHTML(HttpUtility.HtmlDecode(Model.ContentField.Value));
That variable is what I used to compare. Let me know if this is a bad idea.
Thanks!
I had similar question as your title, but in my case the html string was empty. So I ended up doing the following:
HtmlString someString = new HtmlString("");
string.IsNullOrEmpty(someString.ToString());
Might be obvious, but didn't realize it at first.

How to read dicom tag value using openDicom.net in C#?

I'm reading dicom tags using openDicom.net like this:
string tag = "";
string description = "";
string val_rep = "";
foreach (DataElement elementy in sq)
{
tag = elementy.Tag.ToString();
description = elementy.VR.Tag.GetDictionaryEntry().Description;
val_rep = elementy.VR.ToString();
}
How can I read dicom tag values?
the value.ToString() method isn't implemented. Implement your own method in Value.cs and you will get a value for "Value".
For example (only strings and numeric values):
public override string ToString()
{
return valueList[0].ToString();
}
I'm assuming that sq is a Sequence...
I've not worked with openDicom, but I'm pretty sure what you're doing there isn't going to yield the results you want.
You have a single tag, description, and val_rep variable, but you're filling them using a foreach, meaning the last DataElement in the Sequence will be the only values you retrieve. You would achieve the same effect by using:
string tag = sq[sq.Count - 1].Tag.ToString();
string description = sq[sq.Count -1].VR.Tag.GetDictionaryEntry().Description;
string val_rep = sq[sq.Count - 1].VR.ToString();
Thus retrieving the last set of values from the Sequence. I believe you'll find that if you step through the foreach as it executes, it will be loading all the different DataElements contained in your DICOM file.
Feel free to return a comment or post more information in your original post if I'm way off base here.
The tag value is retrieved as an array of generic object from the 'Value' member in 'DataElement' using the 'ToArray()' overriding method in the 'Value' class.
cniDicomTagList = new List<CNIDicomTag>();
foreach (DataElement element in sq)
{
string tag = element.Tag.ToString();
string description = element.VR.Tag.GetDictionaryEntry().Description;
object[] valueArr = element.Value.ToArray();
cniDicomTagList.Add(new CNIDicomTag(tag, description, valueArr));
}

Categories

Resources