Cookies not working on mobile browsers (using ASP.NET MVC ) - android

I have an ASP.NET C# MVC4 Web site that I have working wonderfully for the most part. However, when we tested on mobile, the cookies that I am using for authentication would not work. I set the Auth cookie in my controller action but when trying to access them on the next call they are not there. Once again this is ONLY A PROBLEM ON MOBILE. Works fine in desktop versions of IE, Chrome and Firefox. Does not work with Chrome on Android.
Code to write cookie (in controller action):
//Set information into object that can be read out of the cookie later
FormsAuthModel UserDataObj = new FormsAuthModel
{
UserID = dmUser.ID,
PasswordChange = dmUser.PasswordChange
};
string UserData = Convert.ToBase64String(clsShared.Serialize(UserDataObj));
//Create the ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, dmUser.UserName, DateTime.Now, DateTime.Now.AddDays(1), false, UserData, FormsAuthentication.FormsCookiePath);
// Encrypt the ticket
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
Code to read cookie (in Global.asax.cs - Application_PostAuthenticateRequest):
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
try
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
UserDataObj = (FormsAuthModel)clsShared.Deserialize(Convert.FromBase64String(authTicket.UserData), typeof(FormsAuthModel));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//WriteEvent(string.Format("Error deserializing auth ticket - {0}", ex.Message), EventLogEntryType.Error);
}
}
The AuthCookie is always null on the subsequent requests. What the user sees is a login screen, they fill it out and they get redirected right back to the login screen.
I could not find anything in my searches that helped explain why all the mobile requests (my phone, my tablet and other users' phones) would act differently than the desktop browsers.
Any help would be greatly appreciated.
Thanks!!

OK I found a solution although I am not sure why. I changed the cookie creation code as follows and it worked.
//Set information into object that can be read out of the cookie later
FormsAuthModel UserDataObj = new FormsAuthModel
{
UserID = dmUser.ID,
PasswordChange = dmUser.PasswordChange
};
string UserData = Convert.ToBase64String(clsShared.Serialize(UserDataObj));
//Create the ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, dmUser.UserName, DateTime.Now, DateTime.Now.AddDays(1), false, UserData, FormsAuthentication.FormsCookiePath);
// Encrypt the ticket
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie - FIX IS HERE!!!
Response.Cookies[FormsAuthentication.FormsCookieName].Value = encTicket;
//HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
//Response.Cookies.Add(cookie);
Notice that the only change is in adding the cookie by setting the value directly instead of creating a cookie object and adding that to the collection.
i.e. - Response.Cookies["Name"] = Value;
I got the idea from this MS article: https://msdn.microsoft.com/en-us/library/ms178194.aspx.
So does anyone know why this would make a difference? I have used the cookie instance method several times before and never had this problem.

Related

Android Oauth + PHP (Symfony3 + FOS Oauth Server Bundle)

I'm trying to implement oauth authorization into my Android(KitKat based) app.
I've prepared own oauth2 server,based on php (Symfony3 Framework + FOS Oauth Server Bundle).
Now I need to make authorization in android app.
I was wondering on internet and I didn't found any solution which can help me to do authorization. There are a lot of docs, which describes OAUTH using google or other social services, but, as I told, I have my own oauth server.
I was trying to make something in mobile app, and i meet a few problems.
Oauth flow requires to open web-view element in app and accept usage of my web account by my app. This flow works in my server, but i have no idea how to do it in app. I tried to open web view, i was passing auth flow and was getting code, but it is displayed inside webview.
I found method - which catch the moment of web-view load, and in this case - i can catch some params from web-view URL, but my oauth flow in web is under firewall. If i'm not authorized in web - flow will redirect me to login page, and later - after success login - it will offer me accept or deny usage of my account data. So, i can't use onPageFinished or something else.
Other case, i can obtain access_token by passing login,password, client_id,secret and other params. I was thinking to make 2 services in app, first will check locally - if my token is not expired, and if it is - it will run second service - to refresh my token - to make http request to my oauth server(web application). But I meet another problem here.
I'm using Volley library to make http calls. AS I know, volley runs asynchronous requests to web. I was trying to move my request into separate class/service.
But i had problems with nullable context. Ok. I decided to make requests in activity class (not good case of usage, but ok), and there - i meet another problems.
I have defined button, and onClick listener for it.
I want to authenticate user after he'll path login and password into EditText fields and in onClick for sign in button - i'm checking SharedPreferences for client_id, and if it's empty - i want to get new oauth client_id from web, i'm runing new volley request in onCLickListener. The problem is that - i can't obtain response correctly.
My code example.
```
signIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String login = LoginView.getText().toString();
String password = PasswordView.getText().toString();
auth_dialog = new Dialog(LoginActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferences.edit().putString(getString(R.string.oauth_client_id), null).apply();
String clientId = preferences.getString(getString(R.string.oauth_client_id), null);
preferences.edit().putString(getString(R.string.user_login), login).apply();
preferences.edit().putString(getString(R.string.user_password), password).apply();
if(clientId == null){
RequestQueue queue = Volley.newRequestQueue(context);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String url = context.getString(R.string.url) + context.getString(R.string.url_token) + "?";
url += "client_id=" + preferences.getString(context.getString(R.string.oauth_client_id), null) + "&";
url += "client_secret=" + preferences.getString(context.getString(R.string.oauth_client_secret), null) + "&";
url += "grant_type=" + context.getString(R.string.grant_type_password) + "&";
url += "username=" + preferences.getString(context.getString(R.string.user_login), null) + "&";
url += "password=" + preferences.getString(context.getString(R.string.user_password), null);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response){
clientResponse = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Request for getting Token failed", Toast.LENGTH_SHORT).show();
}
});
queue.add(stringRequest);
}
Log.d("VIOO_APP", clientResponse);// THIS IS THE PLACE WHERE ERROR HAPPENS
token = getToken();
Toast.makeText(getApplicationContext(), token.getAccessToken(), Toast.LENGTH_LONG).show();
}
});```
I want to say that all variables are defined - it's jsut the part of code from button onClick Listener. clientResponse variable defined in activity class as Global variable.
Ofcorse, i can put my logic into response statement - when volley got response - do my stuff, but i think - later, my code will be unreadable and it's not good approach in building app structure. It's a total bullshit to make request in response from another request, and so on...
I had good cases, when my request was working in another class.
I saw examples in internet - how some guys tries to make app service - to make requests through volley, but probably, this info is not actual now. Every internet case - which i found - won't work or provide useless info.
I see this challenge like unwinnable. All stuff I try - fails and won't work.
I hope, i explained my problem fully.
Thank you.

Android can't retrieve data from web service using session ID

I'm a beginner of android programming. I had started a test project which is about using an android app to access web service and run function there. I am using ksoap2 to call the web services.
When I want to login to a database through phone and the web service return a session ID to me. But after that, When I want to run other function in service, and I pass it in session ID, it tell me that there is a null object reference. I tried use the session ID again to get back the login details but it shows that the session doesn't point to any session. This is the method which allow me to connect with web services. While for android, I just simply call using ksoap2.
<WebMethod(True)> _
Public Function CompanyConnectionString() As String
Dim lErrCode, lRetCode As Long
Dim sErrMsg As String = ""
Dim sSessionID As String = ""
Dim oCompany As SAPbobsCOM.Company
oCompany = New SAPbobsCOM.Company
// User and other details to connect
oCompany.Server = "xx.x.x.xx" //ip address
oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012
oCompany.DbUserName = "dbUser"
oCompany.DbPassword = "dbPassword"
oCompany.CompanyDB = "CompanyDB"
oCompany.UserName = "User"
oCompany.Password = "Password"
oCompany.LicenseServer = "xx.x.x.xx:xxxxx" // ip
lRetCode = oCompany.Connect
If lRetCode <> 0 Then
oCompany.GetLastError(lErrCode, sErrMsg)
sSessionID = lErrCode & "-" & sErrMsg
Else
sSessionID = Session.SessionID.ToString
Session.Add(sSessionID, oCompany)
''
Cookies.SetCookies(oCompany, "SID")
End If
Return sSessionID
End Function
I found that it might lose the session ID and I can't get back the login details for other functions later. So is that any idea for that? How I gonna do? without this I can't proceed further in my program.
Thank in advance..
Well, the problem had just solved. Me and my friend found out that that is because the sessionID is forgotten due to the max-age=0;. So we add that to our sessionID and it ran.
if (headerKey != null) {
if (headerKey.equals("Set-Cookie")) {
cookieBuilder.append(headerValue + "max-age=86400;");
}
} //headervalue is the sessionID
This will allow the session to stay active for 86400 seconds = 1 day.
So the sessionID can be use for running other function on web service

Google Plus Single Sign On Server Flow - Google_AuthException Error fetching OAuth2 access token, message: 'invalid_grant'

UPDATE 27th January 2013
I have now resolved this, Please check the accepted answer.
I am having trouble to get my refresh token and my access token when using the server side flow between my Android Application and my PHP server.
So I have managed to get my One Time Code by using the below:
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
Bundle appActivities = new Bundle();
appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
"http://schemas.google.com/AddActivity");
String scopes = "oauth2:server:client_id:" + SERVER_CLIENT_ID +
":api_scope:" + SCOPE_STRING;
try {
code = GoogleAuthUtil.getToken(
OneTimeCodeActivity.this, // Context context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
System.out.println(transientEx.printStactTrace());
return "Error";
} catch (UserRecoverableAuthException e) {
// Recover
code = null;
System.out.println(e.printStackTrace());
OneTimeCodeActivity.this.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
System.out.println(authEx.printStackTrace());
return "Error";
} catch (Exception e) {
System.out.println(authEx.printStackTrace());
}
}
Which will then store the token in the variable "code" and I call up the async task as
task.execute();
The code above will always bring up a popup message and throw UserRecoverableAuthException Need Permission that requires the user to grant offline access, which means the above will need to be called twice to retrieve the code and store it in "code"
I am now trying to send this across to my server which is implemented in PHP.
I have used the quick start https://developers.google.com/+/quickstart/php and managed to get that working.
In here, there is a sample signin.php
In here and according to the documentation this already implements a One Time Authorisation Server Side Flow.
So now my problem is sending this One Time Code to the server.
I used the photohunt Android Auth example for this located here.
https://github.com/googleplus/gplus-photohunt-client-android/blob/master/src/com/google/plus/samples/photohunt/auth/AuthUtil.java
I used the "authorization" method of the code and called up signin.php/connect through a post method shown below
$app->post('/connect', function (Request $request) use ($app, $client) {
$token = $app['session']->get('token');
if (empty($token)) {
// Ensure that this is no request forgery going on, and that the user
// sending us this connect request is the user that was supposed to.
if ($request->get('state') != ($app['session']->get('state'))) {
return new Response('Invalid state parameter', 401);
}
// Normally the state would be a one-time use token, however in our
// simple case, we want a user to be able to connect and disconnect
// without reloading the page. Thus, for demonstration, we don't
// implement this best practice.
//$app['session']->set('state', '');
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
->getAttributes();
$gplus_id = $attributes["payload"]["sub"];
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);
}
return new Response($response, 200);
});
Now when I send the code using the above implementation, I get an 500 messages that says the below
Google_AuthException Error fetching OAuth2 access token, message: 'invalid_grant'
in ../vendor/google/google-api-php-client/src/auth/Google_OAuth2.php line 115
at Google_OAuth2->authenticate(array('scope' => 'https://www.googleapis.com/auth/plus.login'), '{ "token":"xxxxxxxx"}') in ../vendor/google/google-api-php-client/src/Google_Client.php line 131
at Google_Client->authenticate('{ "token":"xxxxxxx"}') in ../signin.php line 99
at {closure}(object(Request))
at call_user_func_array(object(Closure), array(object(Request))) in ../vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php line 117
at HttpKernel->handleRaw(object(Request), '1') in ../vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php line 61
at HttpKernel->handle(object(Request), '1', true) in ../vendor/silex/silex/src/Silex/Application.php line 504
at Application->handle(object(Request)) in ../vendor/silex/silex/src/Silex/Application.php line 481
at Application->run() in ../signin.php line 139
Funny enough I have had to worked once where I did receive a 200, but I cannot recreate it.
So I know I have definitely got the implementation wrong, but I have no clue on how to send it and get my refresh token. I can't find anywhere on the web that explains this. Is someone able to help me please.
UPDATE 16 Jan 2014
Using https://www.googleapis.com/oauth2/v1/tokeninfo?access_token= I can see that the token being produced from getToken is valid and is indeed valid for 1 hour.
I can confirm the json formation is correct by changing the way I am inputting into the Post request and if I don't do it properly I get a total failure.
Now I am going deeper into the php and look at this section Google_OAuth2.php line 115 where it is breaking it is throwing a Google_AuthException. The code is below and this is provided in the quick starter pack
/**
* #param $service
* #param string|null $code
* #throws Google_AuthException
* #return string
*/
public function authenticate($service, $code = null) {
if (!$code && isset($_GET['code'])) {
$code = $_GET['code'];
}
if ($code) {
// We got here from the redirect from a successful authorization grant, fetch the access token
$request = Google_Client::$io->makeRequest(new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUri,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)));
if ($request->getResponseHttpCode() == 200) {
$this->setAccessToken($request->getResponseBody());
$this->token['created'] = time();
return $this->getAccessToken();
} else {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
throw new Google_AuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
}
}
$authUrl = $this->createAuthUrl($service['scope']);
header('Location: ' . $authUrl);
return true;
}
I edit the code above to make sure the code, the client id and secret were correct and they were. So that is where I am now, I don't think it is scope issues as well as I hard coded it in the client setup and still does not work. Not too sure.
UPDATE 23rd January
OK, I think it is a time issue. I used https://developers.google.com/+/photohunt/android and base my design on the BaseActivity in the Photohunt using the AuthUtil, and I get invalid grant on my server. How do I move the time back on my server in code. I read somewhere I can do time() - 10 somewhere but not sure where...
It sounds like you may be sending the same authorization code multiple times. On Android GoogleAuthUtil.getToken() caches any tokens that it retrieves including authorization codes.
If you ask for a second code without invalidating the previous code, GoogleAuthUtil will return the same code. When you try to exchange a code on your server which has already been exchanged you get the invalid_grant error. My advice would be to invalidate the token immediately after you retrieve it (even if you fail to exchange the code, you are better off getting a new one than retrying with the old one).
code = GoogleAuthUtil.getToken(
OneTimeCodeActivity.this, // Context context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
GoogleAuthUtil.invalidateToken(
OneTimeCodeActivity.this,
code
);
invalid_grant can be returned for other reasons, but my guess is that caching is causing your problem since you said it worked the first time.
This issue is now resolved. This was due to the implementation on the One Time Code exchange with the server
As specified in the my issue above, I used the photohunt example to do the exchange with my server. The Android code can be found on the below link
https://github.com/googleplus/gplus-photohunt-client-android/blob/master/src/com/google/plus/samples/photohunt/auth/AuthUtil.java
One line 44 it reads this
byte[] postBody = String.format(ACCESS_TOKEN_JSON, sAccessToken).getBytes();
This will only work if on the server side you handle the JSON. I did not.
When calling up $client->authenticate($code); in php, $code had a JSON string and therefore when calling https://accounts.google.com/o/oauth2/token the authorization code was wrong.
So it was easy as I was not sending the code in the right format.
I found this out when digging and testing https://accounts.google.com/o/oauth2/token and created a manual cURL to test the token.
As provided in the Google+ API it was stated that all examples included a One Time Code exchange, but I think the code across all platform are not consistent and one has to double check themselve to make sure everything flows correctly, which was my mistake.

ASP.Net MVC HttpContext.User.Identity is getting lost

I have a really weird scenario that I'm stuck on. I have a ASP.Net MVC 4 app where I'm authenticating a user and creating an authCookie and adding it to the response's cookies then redirecting them to the target page:
if (ModelState.IsValid)
{
var userAuthenticated = UserInfo.AuthenticateUser(model.UserName, model.Password);
if (userAuthenticated)
{
var userInfo = UserInfo.FindByUserName(model.UserName);
//SERIALIZE AUTHENTICATED USER
var serializer = new JavaScriptSerializer();
var serializedUser = serializer.Serialize(userInfo);
var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, serializedUser);
var hash = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash) {Expires = ticket.Expiration};
Response.Cookies.Add(authCookie);
if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/") && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\"))
{
return Redirect(model.ReturnUrl);
}
var url = Url.Action("Index", "Course");
return Redirect(url);
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
This is working just fine in all browsers. I can login and access the secure pages in my app.
My client is requesting an android version of this app. So, I'm trying to figure out how to convert this app into an APK file. My first attempt is to create a simple index.html page with an iframe that targets the application. This works just fine in Firefox and IE 9. However, when accessing the index.html page that contains the iframe that points to the app via Chrome, I get past the login code above and the user gets redirected to the secure controller, but the secure controller has a custom attribute to make sure the user is authenticated:
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated) return;
if (filterContext.HttpContext.Request.Url == null) return;
var returnUrl = filterContext.HttpContext.Request.Url.AbsolutePath;
if (!filterContext.HttpContext.Request.Browser.IsMobileDevice)
{
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + string.Format("?ReturnUrl={0}", returnUrl), true);
}
else
{
filterContext.HttpContext.Response.Redirect("/Home/Home", true);
}
}
}
My app is failing on: filterContext.HttpContext.User.Identity.IsAuthenticated. IsAuthenticated is always false, even though the user was authenticated in the code above.
Keep in mind this only happens when accessing the app via iframe in Chrome. If I access the app directly instead of via iframe, then everything works just fine.
Any ideas?
UPDATE:
My controller extends SecureController. In the constructor of SecureController I have the code that deserializes the user:
public SecureController()
{
var context = new HttpContextWrapper(System.Web.HttpContext.Current);
if (context.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
var serializer = new JavaScriptSerializer();
var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
var ticket = FormsAuthentication.Decrypt(cookie);
CurrentUser = serializer.Deserialize<UserInfo>(ticket.UserData);
}
else
{
CurrentUser = new UserInfo();
}
//if ajax request and session has expired, then force re-login
if (context.Request.IsAjaxRequest() && context.Request.IsAuthenticated == false)
{
context.Response.Clear();
context.Response.StatusCode = 401;
context.Response.Flush();
}
}
First, you should be deriving from AuthorizeAttribute, not an ActionFilterAttribute. Authorization attributes execute before the method is even called at a higher level of the pipeline, while ActionFilters execute much further down, and other attributes can execute before yours.
Secondly, you aren't showing the code you use to decrypt the ticket and set the IPrincipal and IIdentity. Since that's where the problem is, it's odd that you didn't include it.

How to send SharedObject Array data to PHP WS for DB Query (Flex)

I am currently developing an Android application using Flex 4.5.1 and I am having an issue when trying to pass data that I have stored in a SharedObject array to my Web Service for a Database query. the code below shows how I am storing the data in the SharedObject:
var so:SharedObject = SharedObject.getLocal("app");
public var prefsArray:ArrayCollection = new ArrayCollection(so.data.prefs);
protected function prefs_btn_click(event:MouseEvent):void
{
prefsArray.source.push(getFrsByIDResult.lastResult.id);
so.data.prefs = [prefsArray];
var flushStatus:String = so.flush();
if (flushStatus != null) {
switch(flushStatus) {
case SharedObjectFlushStatus.PENDING:
so.addEventListener(NetStatusEvent.NET_STATUS,
onFlushStatus);
break;
case SharedObjectFlushStatus.FLUSHED:
trace("success");
break;
}
}
}
protected function onFlushStatus(event:NetStatusEvent):void
{
trace(event.info.code);
}
I have tested the SharedObject to see if the information is being entered into it correctly and all seems fine. Now I have used the code below in order to retrieve the data from the SharedObject and try and send it to the PHP web Service to run the DB query.
var so:SharedObject = SharedObject.getLocal("app");
var arrCol:ArrayCollection = new ArrayCollection(so.data.prefs);
var str:String = new String(arrCol.toString());
protected function list_creationCompleteHandler(event:FlexEvent):void
{
getPrefsByprefIdsResult.token = prefsService.getPrefsByPrefIds(so.data.prefs);
}
I have tested the Webservice in Flex and have it configured to recieve an Array of Ints (int[]) and it works when i run a test operation on it with two dummy values. However when I try to use the code above to pass the Web Service the Shared Object data I get this error:
TypeError: Error #1034: Type Coercion failed: cannot convert []#97e97e1 to mx.collections.ArrayCollection.
at views::**************/list_creationCompleteHandler()[C:\Users\Jack\Adobe Flash Builder 4.5\****************\src\views\*******************.mxml:25]
at views::*********************/__list_creationComplete()[C:\Users\Jack\Adobe Flash Builder 4.5\****************\src\views\***************.mxml:94]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:13128]
at mx.core::UIComponent/set initialized()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:1818]
at mx.managers::LayoutManager/validateClient()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1090]
at mx.core::UIComponent/validateNow()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:8067]
at spark.components::ViewNavigator/commitNavigatorAction()[E:\dev\4.5.1\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1878]
at spark.components::ViewNavigator/commitProperties()[E:\dev\4.5.1\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1236]
at mx.core::UIComponent/validateProperties()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:8209]
at mx.managers::LayoutManager/validateProperties()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:597]
at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:783]
at mx.managers::LayoutManager/doPhasedInstantiationCallback()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1180]
I have replaced certain filenames and locations with *'s to protect the work i am doing, but can someone please help me with this issues as I believe it has to be something simple???
Thanks
ok so let me explain in more detail. This is being designed for an Android app like I said, but image what I am trying to do is to store Bookmarks persistently using the Local Shared Object.
The first chunck of code you see above is designed to create the LSO attribute for the bookmark i want to create and imagine that there can be more than one bookmark set at different times like in a web browser. The only way i could find to do this was to store these items/details in an array which I retrieve and then update before saving back to the LSO and saving.
The second piece of code related to imagine a "Bookmarks Page" with a list of all the content that I have bookmarked. Now what I wanted to happen was thta I would be able to call up the LSO attribute which held the id's of the bookmarks and then load up thier details in a list format.
I have managed to create the LSO and store the bookmark deatils in and allow them to be updated and entries added. Also I have made sure that the PHP code that I have pulls back all the database objects relating to the array of id's and this has been tested using flex. The only thing that I cant seem to do is to pass the id's to the PHP web service file. The code in the Web Service file is below if that helps:
public function getPrefsByPrefIds($PrefIds) {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE $this->tablename.id IN(" .implode(",", $PrefIds). ")");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->id, $row->name, $row->desc);
while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->id, $row->name, $row->desc);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $rows;
}
Yes I had already tried that but thanks. I have made some more progress on my own as I have been experimenting with the different types of objects that can be stored in SharedObjects. I have managed to get the solution part working with this code:
This code is designed to capture the boomark info and store it in an arrayCollection before transferring it to a bytesArray and saving
var so:SharedObject = SharedObject.getLocal("app");
public var prefArray:ArrayCollection = new ArrayCollection(so.data.prefs);
protected function prefs_btn_click(event:MouseEvent):void
{
prefArray.source.push(getCompaniesByIDResult.lastResult.id);
so.data.prefs = [prefArray];
var bytes:ByteArray = new ByteArray();
bytes.writeObject(prefArray);
so.data.ac = bytes;
var flushStatus:String = so.flush();
if (flushStatus != null) {
switch(flushStatus) {
case SharedObjectFlushStatus.PENDING:
so.addEventListener(NetStatusEvent.NET_STATUS,
onFlushStatus);
break;
case SharedObjectFlushStatus.FLUSHED:
trace("success");
break;
}
}
}
protected function onFlushStatus(event:NetStatusEvent):void
{
trace(event.info.code);
}
This next code is the designed to retrieve that information from the SahredObjects bytesArray and put it back into an Array Collection
var so:SharedObject = SharedObject.getLocal("app");
var ba:ByteArray = so.data.ac as ByteArray;
var ac:ArrayCollection;
protected function list_creationCompleteHandler(event:FlexEvent):void
{
ba.position = 0;
ac = ba.readObject() as ArrayCollection;
getPrefsByPrefIdsResult.token = prefsService.getPrefsByPrefIds(ac);
}
however as I have said this works in a small way only as if I store only one Bookmark (id) for an item and then go to the bookmarks list the details for that bookark are successfully retrieved, however if I save more than one Bookmark(2 or more id's) the page will not load the details, i do not get an error but I believe it is hanging because it is looking for say id's "1,2" instead of "1" and "2" but i dont know why this is or how to resolve this. I appreciate the advice I have been given but am finding it hard there is no one who can help me with this issue and I am having to do various experiemnts with the code. Can someone please help me with this I would really appreciate it :-) Thanks

Categories

Resources