WCF datetime format - ios

I developed WCF service that contains so many methods and these methods return json format. My main problem is when i have datacontract member has datetime type i get in json like this /Date(1233846970110-0500)/ which is causing me issue in IOS application. How can i write a global method that converts to MM/dd/yyyy format for very call. I tried to different methods but none works when i test it, always returns the same above format.
I tried in global.ascx like this but like
private void RegisterRoutes()
{
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var config = HttpHostConfiguration.Create().Configuration;
config.OperationHandlerFactory.Formatters.Clear();
config.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));
var httpServiceFactory = new HttpServiceHostFactory
{
OperationHandlerFactory = config.OperationHandlerFactory,
MessageHandlerFactory = config.MessageHandlerFactory
};
RouteTable.Routes.Add(new ServiceRoute("VWPM_Srv", httpServiceFactory, typeof(IVWPM_Srv)));
}

If you want to send an MM/dd/yyyy formatted string. You just make the property a string and assign the date in the MM/dd/yyyy format.
However you can also make ios accept the dates wfc send you:
json-serialized-date-passed-between-ios-and-wcf-and-vice-versa

Related

Getting error while parsing string to datetime?

Getting error while parsing string to datetime.
string datestring = "111815";
DateTime date = Convert.ToDateTime(datestring);
I also tried using, Parse, ExactParse with/without culture specificinfo.
I'm still getting the error:
String was not recognized as a valid DateTime.
Please suggest the correct solution.
You just need to specify the right format string when you call ParseExact. In your case, it looks like this is month-day-year, without any separators, and with a 2-digit year (blech). So you'd parse it like this:
using System;
using System.Globalization;
class Test
{
static void Main()
{
DateTime dt = DateTime.ParseExact("111815", "MMddyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
}
}
If you're in control of the format at all, I'd strongly recommend yyyy-MM-dd instead of this ambiguous (due to the 2-digit years) and US-centric (due to month/day/year) format.

Overriding Joda DateTime toString in Groovy

So I'm using the JodaTime plugin in a grails project I'm implementing and I really don't like that it spits out the ISO8601 date format when I do a toString. I've been constantly putting toString and passing in the default.date.format from the messages file, but that's cumbersome. The majority of cases I just want it to do that automatically. So naturally it makes sense to take advantage of Groovy's fabulous metaprogramming to override toString on the DateTime class. But alas it doesn't work. Hence this discussion:
http://jira.codehaus.org/browse/GROOVY-4210
So according to said discussion, if our class implements an interface to implement the toString method we need to override the interface's metaclass. Looking at the joda code base, DateTime implements the ReadableDateTime interface which in turn inherits from ReadableInstant which is where the method signature is defined. The actual implementation is done 4 classes up in the class hierarchy for DateTime (DateTime inherits from BaseDateTime inherits from AbstractDateTime inherits from AbstractInstant which implements toString without parameters). With me so far?
So in theory this means I should override either the ReadableDateTime interface which doesn't actually have the toString signature or the ReadableInstant one which does. The following code to override toString on ReadableDateTime does nothing.
ReadableDateTime.metaClass.toString = { ->
delegate.toString(messageSource.getMessage(
'default.date.format', null, LCH.getLocale()))
}
So then trying with ReadableInstant:
ReadableInstant.metaClass.toString = { ->
delegate.toString(messageSource.getMessage(
'default.date.format', null, LCH.getLocale()))
}
also does not have the desired result for the DateTime.toString method. However, there are some interesting affects here. Take a look at the following code:
def aiToString = AbstractInstant.metaClass.getMetaMethod("toString", [] as Class[])
def adtToString = AbstractDateTime.metaClass.getMetaMethod("toString", [] as Class[])
def bdtToString = BaseDateTime.metaClass.getMetaMethod("toString", [] as Class[])
def dtToString = DateTime.metaClass.getMetaMethod("toString", [] as Class[])
def date = new DateTime()
println "ai: ${aiToString.invoke(date)} "
println "adt: ${adtToString.invoke(date)} "
println "bdt: ${bdtToString.invoke(date)} "
println "dt: ${dtToString.invoke(date)} "
The first 3 methods show my date formatted just how I'd like it. The last one is still showing the ISO8601 formatted date. I thought maybe the JodaTime plugin for grails might be overriding the toString and they do add a few methods to these interfaces but nothing to do with toString. At this point, I'm at a loss. Anyone have ideas?
Thanks
You cann't override DateTime#toString(), becouse DateTime class is final
public final class DateTime
But if you want another date format, you can use toString(org.joda.time.format.DateTimeFormatter)
for example
def date = new DateTime();
date.toString(ISODateTimeFormat.basicDate()); // format yyyyMMdd

Wire format for OpenRasta array bindings (urlencoded and multipart/formdata)

The wire format for binding arrays and dictionaries in OpenRasta seems to be ":index" like this:
class X
{
public int[] Data { get; set; }
}
which serializes to (with two array items 5 and 12):
Data:0=5&Data:1=12
Is it possible to change this format to:
Data[0]=5&Data[1]=12
Thanks, Jørn
You can try and replace the IPathManager with a custom one that supports that format. Alternatively, feel free to add support for that format too and send a pull request to openrasta-core.

Biztalk mapping Date to String

I'm working on a biztalk project and use a map to create the new message.
Now i want to map a datefield to a string.
I thought i can do it on this way with an Function Script with inline C#
public string convertDateTime(DateTime param)
{
return System.Xml.XmlConvert.ToString(param,ÿyyyMMdd");
}
But this doesn't work and i receive an error. How can i do the convert in the map?
It's a Biztalk 2006 project.
Without the details of the error you are seeing it is hard to be sure but I'm quite sure that your map is failing because all the parameters within the BizTalk XSLT engine are passed as strings1.
When I try to run something like the function you provided as inline C# I get the following error:
Object of type 'System.String' cannot be converted to type 'System.DateTime'
Replace your inline C# with something like the following:
public string ConvertDateTime(string param1)
{
DateTime inputDate = DateTime.Parse(param1);
return inputDate.ToString("yyyyMMdd");
}
Note that the parameter type is now string, and you can then convert that to a DateTime and perform your string format.
As other answers have suggested, it may be better to put this helper method into an external class - that way you can get your code under test to deal with edge cases, and you also get some reuse.
1 The fact that all parameters in the BizTalk XSLT are strings can be the source of a lot of gotchas - one other common one is with math calculations. If you return numeric values from your scripting functoids BizTalk will helpfully convert them to strings to map them to the outbound schema but will not so helpfully perform some very random rounding on the resulting values. Converting the return values to strings yourself within the C# will remove this risk and give you the expected results.
If you're using the mapper, you just need a Scripting Functiod (yes, using inline C#) and you should be able to do:
public string convertDateTime(DateTime param)
{
return(param.ToString("YYYYMMdd");
}
As far as I know, you don't need to call the System.Xml namespace in anyway.
I'd suggest
public static string DateToString(DateTime dateValue)
{
return String.Format("{0:yyyyMMdd}", dateValue);
}
You could also create a external Lib which would provide more flexibility and reusability:
public static string DateToString(DateTime dateValue, string formatPicture)
{
string format = formatPicture;
if (IsNullOrEmptyString(formatPicture)
{
format = "{0:yyyyMMdd}";
}
return String.Format(format, dateValue);
}
public static string DateToString(DateTime dateValue)
{
return DateToString(dateValue, null);
}
I tend to move every function I use twice inside an inline script into an external lib. Iit will give you well tested code for all edge cases your data may provide because it's eays to create tests for these external lib functions whereas it's hard to do good testing on inline scripts in maps.
This blog will solve your problem.
http://biztalkorchestration.blogspot.in/2014/07/convert-datetime-format-to-string-in.html?view=sidebar
Regards,
AboorvaRaja
Bangalore
+918123339872
Given that maps in BizTalk are implemented as XSL stylesheets, when passing data into a msxsl scripting function, note that the data will be one of types in the Equivalent .NET Framework Class (Types) from this table here. You'll note that System.DateTime isn't on the list.
For parsing of xs:dateTimes, I've generally obtained the /text() node and then parse the parameter from System.String:
<CreateDate>
<xsl:value-of select="userCSharp:GetDateyyyyMMdd(string(s0:StatusIdChangeDate/text()))" />
</CreateDate>
And then the C# script
<msxsl:script language="C#" implements-prefix="userCSharp">
<![CDATA[
public System.String GetDateyyyyMMdd(System.String p_DateTime)
{
return System.DateTime.Parse(p_DateTime).ToString("yyyyMMdd");
}
]]>

ASP.NET MVC: dealing with Version field

I have a versioned model:
public class VersionedModel
{
public Binary Version { get; set; }
}
Rendered using
<%= Html.Hidden("Version") %>
it gives:
<input id="Version" name="Version" type="hidden" value=""AQID"" />
that looks a bit strange. Any way, when the form submitted, the Version field is always null.
public ActionResult VersionedUpdate(VersionedModel data)
{
...
}
How can I pass Version over the wire?
EDIT:
A naive solution is:
public ActionResult VersionedUpdate(VersionedModel data)
{
data.Version = GetBinaryValue("Version");
}
private Binary GetBinaryValue(string name)
{
return new Binary(Convert.FromBase64String(this.Request[name].Replace("\"", "")));
}
Related posts I found.
Link
Suggests to turn 'Binary Version' into 'byte[] Version', but some commenter noticed:
The problem with this approach is that
it doesn't work if you want to use the
Table.Attach(modified, original)
overload, such as when you are using a
disconnected data context.
Link
Suggests a solution similar to my 'naive solution'
public static string TimestampToString(this System.Data.Linq.Binary binary)
{ ... }
public static System.Data.Linq.Binary StringToTimestamp(this string s)
{ ... }
http://msdn.microsoft.com/en-us/library/system.data.linq.binary.aspx
If you are using ASP.Net and use the
SQL Server "timestamp" datatype for
concurrency, you may want to convert
the "timestamp" value into a string so
you can store it (e.g., on a web
page). When LINQ to SQL retrieves a
"timestamp" from SQL Server, it stores
it in a Binary class instance. So you
essentially need to convert the Binary
instance to a string and then be able
to convert the string to an equivalent
Binary instance.
The code below provides two extension
methods to do this. You can remove the
"this" before the first parameter if
you prefer them to be ordinary static
methods. The conversion to base 64 is
a precaution to ensure that the
resultant string contains only
displayable characters and no escape
characters.
public static string ConvertRowVersionToString(this Binary rowVersion) {
return Convert.ToBase64String(rowVersion.ToArray());
}
public static Binary ConvertStringToRowVersion(this string rowVersion) {
return new Binary(Convert.FromBase64String(rowVersion));
}
I think the problem with not seeing it in the bound model on form submission is that there is no Convert.ToBinary() method available to the model binary to restructure the data from a string to it's binary representation. If you want to do this, I think that you'll need to convert the value by hand. I'm going to guess that the value you are seeing is the Base64 encoding of the binary value -- the output of Binary.ToString(). In that case, you'll need to convert it back from Base64 to a byte array and pass that to the Binary() constructor to reconstitute the value.
Have you thought about caching the object server-side, instead? This could be a little tricky as well as you have to detach the object from the data context (I'm assuming LINQ) or you wouldn't be able to reattach it to a different data context. This blog entry may be helpful if you decide to go that route.
You may need to use binding to get a strongly-typed parameter to your action method.
Try rendering using:
<%=Html.Hidden("VersionModel.Version")%>
And defining your action method signature as:
public ActionResult VersionedUpdate([Bind(Prefix="VersionModel")] VersionedModel data)
{
...
}
This post http://forums.asp.net/p/1401113/3032737.aspx#3032737 suggests to use
LinqBinaryModelBinder from http://aspnet.codeplex.com/SourceControl/changeset/view/21528#338524.
Once registered
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(Binary), new LinqBinaryModelBinder());
}
the binder will automatically deserialize Version field
public ActionResult VersionedUpdate(VersionedModel data)
{ ... }
rendered this way:
<%= Html.Hidden("Version") %>
(See also http://stephenwalther.com/blog/archive/2009/02/25/asp.net-mvc-tip-49-use-the-linqbinarymodelbinder-in-your.aspx)
There are many ways like here
byte[] b = BitConverter.GetBytes(DateTime.Now.Ticks);//new byte [(DateTime.Now).Ticks];
_store.Version = new System.Data.Linq.Binary(b)
(make sure you bind exclude your version),
But the best way is to let the DB handle it...
There are many ways like here
byte[] b = BitConverter.GetBytes(DateTime.Now.Ticks);//new byte [(DateTime.Now).Ticks]; _store.Version = new System.Data.Linq.Binary(b)
(make sure you bind exclude your version),
But the best way is to let the DB handle it...

Resources