I'm using JSON to send data to client. However, the date fields get transformed into a timespan format like /Date(1363807800000)/.
Is there anyway to get rid of it and let server send DateTime values like 2013/7/21 3:44 PM to client?
Think of this,
var data = "/Date(1363807800000)/";
var date = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
var result = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
Then, use this RegEx to validate it,
/ ^ \ d {4} - \ d { 2} - \e{2} \e{2}:\e{2}:\e{2} $ /
Hope this helps...:)
Here is a solution using Json.NET (you can install it via NuGet):
object testObject = new { Name = "TestName", DateTime = DateTime.Now };
string output = JsonConvert.SerializeObject(testObject, new IsoDateTimeConverter());
Console.Write(output);
Output:
"{\"Name\":\"TestName\",\"DateTime\":\"2013-07-21T15:01:56.2872469+03:00\"}"
In case ISO DateTime format does not work well for you, you can write your own DateTimeConverter to use with SerializeObject function.
I wrote once this, maybe you could add the string to your json ?
var getDate = function() {
var date = new Date();
var prefix = "["
+ date.getDate() + "."
+ (date.getMonth() + 1) + "."
+ date.getFullYear() + " "
+ date.toString().split(" ")[4]
+ "]";
return prefix;
};
Related
I've got an issue where I am applying a template to an object and am using a find and replace function to mesh the template in the form of a string of html. The issue is, the height and width of the image are contained in the token so I don't have a way to find and replace as it could vary.
Token value is [ARTICLEIMAGE:150:200]
foreach(var article in articles) {
var articleTemplateValue = _TemplateArticleMarkup;
articleTemplateValue = articleTemplateValue.Replace("[ARTICLEIMAGE:xx:yy]", "<img src=" + article.ArticleImageFolder + "/" + article.ArticleImage + " title=" + article.ArticleTitle + " width="
xx" height="
yy" />");
}
This obviously would not work for every example as the dimensions of the image token will vary. Is there a way to find the token as a StartsWith and then split the dimensions an array on the :. Please let me know if that makes sense as it is a little confusing. Thanks!
Regex will solve this issue for you.
using System.Text.RegularExpressions;
Then change your code as seen below.
foreach (var article in articles)
{
string articleTemplateValue = _TemplateArticleMarkup;
MatchCollection mc = Regex.Matches(articleTemplateValue, #"\[ARTICLEIMAGE\:(\d+)\:(\d+)\]");
if (mc.Count > 0)
{
string toReplace = mc[0].Value;
string xx = mc[0].Groups[1].Value;
string yy = mc[0].Groups[2].Value;
articleTemplateValue = articleTemplateValue.Replace(toReplace, "<img src=\"" + article.ArticleImageFolder + "/" + article.ArticleImage + "\" title=\"" + article.ArticleTitle + "\" width=\"" + xx + "\" height=\"" + yy + "\"/>");
}
}
You can use the Split() command to find the width and the height. A very rough approach follows:
rextester remo
String articleTemplateValue = "[test:40:200]";
Console.WriteLine(articleTemplateValue);
var arr = articleTemplateValue.Split(':');
if (arr.Length == 3) {
var xx = arr[1];
var yy = arr[2].Substring(0, arr[2].Length - 1);
articleTemplateValue = articleTemplateValue.Replace(articleTemplateValue, "<img src="
+ "folder" + "/" + "image" + " title=" + "ArticleTitle" + " width="+ xx + " height= " + yy+ "/>");
Console.WriteLine(articleTemplateValue);
}
Use Regex would do the trick repl.it demo
"\[ARTICLEIMAGE:\d+?:\d+?\]"
\[ escape the [ character. Brackets are special characters in Regex
\d any digit
\d+?: + is 0 or more digits. Until we find a colon :. The ? means non-greedy and is really not needed...
\] escape the closing bracket
var matches = Regex.Match(articleTemplateValue, #"\d+");
var xx = matches;
var yy = matches.NextMatch();
var template = "<img src=" + article.ArticleImageFolder + "/" + article.ArticleImage + " title=" + article.ArticleTitle + " width="
+ xx + " height="
+ yy + " />";
articleTemplateValue = articleTemplateValue = Regex.Replace(articleTemplateValue, #"\[ARTICLEIMAGE:\d+?:\d+?\]", template);
Using
Regex.Match(string, string)
Regex.Replace(string, string)
I trying to display a List into Console
My List code:
var order = new List<Orders>();
order.Add(new Orders { Date = "" + orders[0].date_created, Name = ""+ orders[0].billing.first_name , Adress = ""+ orders[0].shipping.address_1 + " " + orders[0].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[1].date_created, Name = "" + orders[1].billing.first_name, Adress = "" + orders[1].shipping.address_1 + " " + orders[1].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[2].date_created, Name = "" + orders[2].billing.first_name, Adress = "" + orders[2].shipping.address_1 + " " + orders[2].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[3].date_created, Name = "" + orders[3].billing.first_name, Adress = "" + orders[3].shipping.address_1 + " " + orders[3].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[4].date_created, Name = "" + orders[4].billing.first_name, Adress = "" + orders[4].shipping.address_1 + " " + orders[4].shipping.address_2 });
return order;
I have tried to display it like this:
Debug.WriteLine(order.ToString());
and like this:
order.ForEach(i => Debug.WriteLine(i.ToString()));
But gives the warning:
Unreachable code
How I can display the list?
Using Linq, as in your second try is close to the actual printing, you just need to format the string properly instead of simply call ToString method:
order.ForEach(o => Debug.WriteLine("Date: " + o.Date + " Adress: " + o.Adress + "Name: " + o.Name));
And I know it is not the point of the question, but I suggest you to use a ForEach instruction to populate the list too, as it will add more flexibility to your code.
Try this one:
foreach (var item in order)
{
Debug.WriteLine(item.ToString());
}
Or if you have mulitple properties as mentioned above, you can try like this:
foreach (var item in order)
{
Debug.WriteLine("Date : {0}, Name : {1}, Adress : {2}",item.Date.ToString(), item.Name.ToString(), item.Adress.ToString());
}
I have a routine where i prompt the user for a value. In this case the city. They will type in for example LA. I store this value in a variable named inputValue.
Now i need to pass a string to crystal reports that uses this input and i want it to look like this
{member.name} = "LA"
string inputValue = GetInputValue("Enter value for " + fieldName);
string sqlInput = sqlInput.Substring(0, leftPos - 1) + " + inputValue + " + sqlInput.Substring(rightPos + 2);
O thought by using " + inputValue + " would do the trick but it only puts the quotation mark after the input value ex. LA \". What is the proper way to quote this?
" + inputValue + " +
Should be
inputValue +
Thus making
string sqlInput = sqlInput.Substring(0, leftPos - 1) + inputValue +
sqlInput.Substring(rightPos + 2);
Assuming you don't want '"' characters leading and trailing your string.
Then that would be
string sqlInput = sqlInput.Substring(0, leftPos - 1) +"\"" + inputValue + "\"" +
sqlInput.Substring(rightPos + 2);
I have written a code to eliminate the double quotes which is as follows,
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
Also tried with #"""variable""" but was futile, I want to eliminate the \ slash and want my every value to be inside "". Below is my obtained result.
["{series_name : \"Actual\",period_name: \"Q1 / 2013\",period_final_value: \"17\"}","\"{series_name : \\\"Actual\\\",period_name: \\\"Q1 / 2013\\\",period_final_value: \\\"17\\\"}\"","{series_name : \"Actual\",period_name: \"Q2 / 2013\",period_final_value: \"15\"}","\"{series_name : \\\"Actual\\\",period_name: \\\"Q2 / 2013\\\",period_final_value: \\\"15\\\"}\"","{series_name : \"Actual\",period_name: \"Q3 / 2013\",period_final_value: \"13\"}","\"{series_name : \\\"Actual\\\",period_name: \\\"Q3 / 2013\\\",period_final_value: \\\"13\\\"}\"","{series_name : \"Actual\",period_name: \"Q1 / 2013\",period_final_value: \"14.103\"}""]
Below is the code that I write to serialize the string value into JSON format.
modified_listofstrings.Add(resulted_value);
System.IO.File.WriteAllText(#"C:\Json\Json.json", jSearializer.Serialize(resulted_value));
also I tried this method as well
var obj = new
{
series_name = final_resulted_series_name,
period_name,
period_final_value
};
System.IO.File.WriteAllText(#"C:\Json\Json.json",jSearializer.Serialize(obj));
this eliminate backslash but only from first values and the output obtained is
[{"series_name":"Actual","period_name":"Q1 / 2013","period_final_value":"17"},"\"{series_name : \\\"Actual\\\",period_name: \\\"Q1 / 2013\\\",period_final_value: \\\"17\\\"}\"",{"series_name":"Actual","period_name":"Q2 / 2013","period_final_value":"15"},"\"{series_name : \\\"Actual\\\",period_name: \\\"Q2 / 2013\\\",period_final_value: \\\"15\\\"}\"",{"series_name":"Actual","period_name":"Q3 / 2013","period_final_value":"13"},"\"{series_name : \\\"Actual\\\",period_name: \\\"Q3 / 2013\\\",period_final_value: \\\"13\\\"}\""]
I want to eliminate backslash from all the values.
Below is the code which gives me the output,
if (xmlAttributeCollection_for_period != null)
{
var periodid = xmlAttributeCollection_for_period["periodid"];
xmlActions[j] = periodid.Value;
period_final_id = periodid.Value;
string period_name = Client.GetAttributeAsString(sessionId, periodid.Value, "name", "");
var action = xmlAttributeCollection_for_period["value"];
xmlActionsone[j] = action.Value;
period_final_value = action.Value;
values += final_resulted_series_name + ":" + period_name + ":" + period_final_value + ",";
string vals = values.Split(',')[1];
counts = values;
string[] periods = counts.Split(',');
Period1 = periods[j];
// string final_resulted_period_name = Client.GetAttributeAsString(sessionId, resulted_series_id, "name", "");
var obj = new
{
series_name = final_resulted_series_name,
period_name,
period_final_value
};
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
modified_listofstrings.Add(resulted_value);
System.IO.File.WriteAllText(#"C:\Json\Json.json", jSearializer.Serialize(resulted_value));
}
Any Help will be greatly appreciated...
I passed the obj variable to list as follows
modified_listofstrings.Add(obj);
and then serialized the list as below
jSearializer.Serialize(modified_listofstrings)
declaration were as below,
List<object> modified_listofstrings = new List<object>();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
and it gave the desired output
I am trying to output to a text file, with the following C# code. The problem is that my outputted information has a comma at the end of it and this won't work with the program that uses the file after. I'm trying to figure out how to get rid of this comma...
var toFile = Path.Combine(GetTextPath(),
string.Format(heatname + "_{0}.txt", DateTime.Now.ToString("yyyyMMdd")));
string ElementsNum = RoundedValues.Count.ToString();
DateTime dt = System.DateTime.Now;
var year = dt.ToString("yy");
var month = dt.ToString("MM");
var day = dt.ToString("dd");
var minute = dt.ToString("mm");
using (var fs = File.OpenWrite(toFile))
using (TextWriter sw = new StreamWriter(fs))
{
sw.Write("NA" + "," + dt.Hour.ToString() + "," + minute + "," + day + ","
+ month + "," + year + "," + "ALTEST " + "," +
"ALTEST " + "," + heatgrade + " " + "," + " " + "," + heatname + "," +
DT2.Rows[0][3].ToString() + "," + heatgrade + "," + "OE2" + "," + "," +
"," + "," + "," + "," + "," + " " + ElementsNum);
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
}
}
You can use TrimEnd, for example:
var theString = "abcd,";
var trimmedString = theString.TrimEnd(new[]{','});
In your case, if I'm not mistaken, this is where you want it to happen:
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
If so, you can do this:
var pairs = pair.B.ToString() + ", " + pair.A.ToString() + ",";
sw.Write(pairs.Trim().TrimEnd(new[]{','}));
Here is a linqy way to do it. This would use the Aggregate function of linq.
var x = RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b })
.Aggregate("", (old, item) => {
return old + (old == "" ? "" : ", ") +
item.B.ToSTring() + ", " + item.A.ToString();
});
sw.Write(x);
Version two (go go join!) uses linq to make a array of strings containing the pairs and then combine those pairs seperated by a comma using join.
string [] x = RoundedValues.Zip(Elements,
(a, b) => b.ToSTring() + ", " + a.ToString() ).ToArray();
sw.Write(String.Join(", ",x));
It might be that the following would work, but I'm not where I can test it ... this sure looks sexy (mostly because it is one line and everyone loves one line solutions):
sw.Write(String.Join(", ",
RoundedValues.Zip(Elements,
(a, b) => b.ToSTring() + ", " + a.ToString() )
));
Which would replace
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
}
Another option is to use the StringBuilder.
...
StringBuilder sb = new StringBuilder();
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sb.AppendFormat("{0}, {1},", pair.B, pair.A);
}
sw.Write(sb.ToString().TrimEnd(new[] { ' ', ',' });