How to pass a Date object from Flex to a JSP Servlet? - apache-flex

I am passing some parameters as POST to a Servlet from my Flex WebApplication. I am able to pass and retrieve strings properly.
I used new Date().getTime() in my flex code and tried passing the timestamp variable hoping to parse it at the servlet and convertit into a java.util.Date object. But i am getting a NumberFormatException when i try to parse the variable from the string that i got from request.getParameter.
Any solutions?

I think you are not converting String to long in Java IF so Please try
String strDateinmilliseconds = request.getAttribute("FlexMilliseconds");
long dateinmilliseconds = Long.valueOf(strDateinmilliseconds);
Date resultdate = new Date(dateinmilliseconds);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
System.out.println(sdf.format(resultdate));
Hopes that helps

Related

Input string not in Correct format error while using the Google currency Conversion API

My application is in Asp.Net MVC3 coded in C#.Net.
Im using google Currency Conversion API for getting the conversion.
Google Currency Conversion API
Im passing the From Currency and To Currency values and the amount to my Controller.
Below is my C# code.
WebClient web = new WebClient();
string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", CurrenctCurr.ToUpper(), DestinationCurr.ToUpper(), TotCurrentPay);
string response = web.DownloadString(url);
Regex regex = new Regex("rhs: \\\"(\\d*.\\d*)");
Match match = regex.Match(response);
decimal rate = Convert.ToDecimal(match.Groups[1].Value);
Im getting an error on line
decimal rate = Convert.ToDecimal(match.Groups[1].Value.ToString());
The error is Input string not in Correct format.There is no inner exception to it.
I tried it to convert to toString()
decimal rate = Convert.ToDecimal(match.Groups[1].Value.ToString());
Also i tried to take the value of match in a string variable and then try doing a SubString logic on it.But its not working either
string test = match.ToString();
test=test.substring(0,test.Indexof("""));
There is a single Quotation ("),so im trying to take the value of string till ".
Suggest how can i solve the issue.Or what else can i try in the right direction.
Try this for getting url.
Uri uri = new Uri(string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", CurrenctCurr.ToUpper(), DestinationCurr.ToUpper(), TotCurrentPay));
string url = uri.AbsoluteUri + uri.Fragment;
string response = web.DownloadString(url);

ExtJs 4 Displaying WCF DateTime

I can't figure out how convert the datetime that wcf outputs into a datetime that ExtJs can use. I have found lots of articles about this but they are all for ExtJs 3 and I couldn't get it to work with 4.
I did find this code but I don't know how I could use it to convert everything in my JsonStore.
//this method is used to convert the MS JSON date format to the ExtJS Grid Date Column Value
function dateFormatter(dt) {
/// <summary>this method is used to convert the MS JSON date format to the ExtJS Grid Date Column Value</summary>
/// <param name="dt">Actual JSON Date Value</param>
try {
//microsoft JSON date format needs to convert into Javascript date
var newdata = dt.replace(/\/Date\((-?[0-9]+)([+-][0-9]+)?\)\//g, "new Date($1)");
newdata = eval('(' + newdata + ')');
return newdata.format('m/d/Y');
}
catch (e) {
return dt;
}
}
Unlike Ext JS 3, Ext JS 4 does not extend the native Date object. Instead it provides Ext.Date. So instead of:
date.format('m/d/Y');
you would instead use:
Ext.Date.format(date, 'm/d/Y');
Additionally using eval() is a really bad idea most of the time. This code is no exception.
And if you drop eval, the try-catch is also not needed.
Finally, a function that both parses a date and converts it to another format seems to be doing too much. Often you will want to display the same date in different formats in different parts of your app. Therefore I would rather just have a function that parses the WCF date format into JavaScript Data object. And then use convert the Date object into particular string format at the very place where it's needed.
Removing all extraneous stuff, this is what I get:
function parseWcfDate(dt) {
var milliseconds = dt.replace(/\/Date\((-?[0-9]+)([+-][0-9]+)?\)\//, "$1");
return new Date(parseInt(milliseconds, 10));
}
Anyway, all this is too much trouble... Ext JS has built-in support for parsing WCF formatted dates:
Ext.Date.parse("/Date(1234567894560)/", "MS");
Also see:
How to handle json DateTime returned from WCF Data Services (OData)
How do I format a Microsoft JSON date?
Use JSON.NET with JavaScriptDateConverter.

sending Json array failed

I am building a JSON/WCF app and need to send an array of objects back to the server. For some reason it is not accepting the array. Using script manager I can get data fine.
var month = $("#ddlStartMonth").val();
var year = $("#ddlStartYear").val();
var items = JSON.stringify(calendarItems);
WebService.SaveCalendar(items, new Date(year, month, 01).toDateString(), new Date(year, month, 01).toDateString(), Submit, onPageError);
I have tried with and without the JSON stringify. The function onPageError is activated and the only error info it produces is "The server method 'SaveCalendar' failed". Yet the breakpoint on the first line of the web method is not activated.
<OperationContract()>
<WebGet(ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.WrappedRequest)>
<WebMethod(EnableSession:=True)>
Public Function SaveCalendar(ByVal _jsonImages As String()(), ByVal _selectedMonth As String, ByVal _selectedYear As String) As Boolean
Dim _calenderItems As New List(Of CalenderItem)
'_calenderItems = New JavaScriptSerializer().Deserialize(Of List(Of CalenderItem))(_jsonImages)
HttpContext.Current.Session("calenderItems") = _calenderItems
HttpContext.Current.Session("selectedMonth") = New Date(_selectedMonth)
HttpContext.Current.Session("selectedYear") = New Date(_selectedYear)
Return True
End Function
Any Ideas?
I've had similar issues working with MVC. I think .NET's deserializer actually expects that the object it is passed will be a JSON object rather than an array (i.e. it should always start with "{" and end with "}". You could:
Create a POCO class to act as your DTO which simply has a List/Array of CalenderItems inside of it, or
Use a more "lenient" deserializer like Newtonsoft's JSON.NET
Of course this second option would only work if you can somehow convince WCF to run the method in the first place. Looking at your code again, though, I'm wondering if your declaring _jsonImages as a double-array of strings might be causing some difficulty.

Flex - Date serialization

Does anyone know how to get actionscript to render a null date value '000:00:00T00:00:00'? I am calling a web service that expects date fields in the SOAP xml. I need some of these dates to serialize as null and I can't see how to produce null. The closest value I can get is '1899-11-30T00:00:00Z'. Below is the code I am using:
var dateStr:String = "0000-00-00T00:00:00+";
var emptyDate:Date = DateUtil.parseW3CDTF(dateStr);
newReqData.DateTimeInit = emptyDate;
You can probably do it with a date formatter. You'll have to create a Date object but if you pass it to the DateFormatter, you can set the format to pretty much whatever you like. Here's the reference and I would recommend looking at the "Other Text" area:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/formatters/DateFormatter.html
var d:Date=new Date();
d.setTime(-62167226400000);
Alert.show(d.toString());
or as said Shawn Yale, read this.

Parse a JSON query response string in ASP.NET

Hey guys I have the following code working which is sending a GET Request and receiving JSON Response.
Now I can basically go
GetWeatherByLocation(53.3, -6.28);
and the method returns
{"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"}
I was now wondering how can I retrieve the values for
URL
Name
from the string returned
THanks a lot
Im using ASP.NET 2 this is my calling code
public static string GetWeatherByLocation(double lat, double lng)
{
string formattedUri = String.Format(CultureInfo.InvariantCulture,
FindNearbyWeatherUrl, lat, lng);
HttpWebRequest webRequest = GetWebRequest(formattedUri);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
return jsonResponse;
}
Your calling code is in javascript, i guess. Just use the response as a javascript object, because the json format is a notation for a javascript object. You can access its properties directly:
var returningValue = {"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"} ;
alert(returningValue.status);
alert(returningValue.url);
alert(returningValue.name);
edit: if you want to parse json in .net you can see this question where somebody explains how to parse the object using JavaScriptSerializer from System.Web.Extensions.dll
edit 2: if your version of .net doesn't let you play with this .dll i'd recommend looking into json.net previous releases, notably the last 2.0 release. But you should have access to the dll since it appeared in .net 2.0, albeit in the AJAX framework if my memory is good...
It's possible to parse your object by hand, but i'd really recommend using a library instead. If you want to do it by hand, you're in a complex world...

Resources