how to bind dynamically image to the windows phone image control - windows-phone-7.1

I am consuming .net web-service in my windows phone app.
Here I binding XML data to the controls,I am unable to display image.
C#:
eSchooltrack.ServiceReference5.EST_WebServicesSoapClient obj = new EST_WebServicesSoapClient();
obj.GetLoginUserDetailsCompleted+=new EventHandler<GetLoginUserDetailsCompletedEventArgs>(obj_GetLoginUserDetailsCompleted);
obj.GetLoginUserDetailsAsync(loginid);
}
private void obj_GetLoginUserDetailsCompleted(object sender, eSchooltrack.ServiceReference5.GetLoginUserDetailsCompletedEventArgs e)
{
XElement xmlNews = XElement.Parse(e.Result.ToString());
image1.Source=GetImage(xmlNews.Element("ProfileImage").Value);
}

depending upon the return type of the GetImage function
1) if its BitmapImage, then it should work, else the Image its returning is null
2) if its Uri do image1.Source=new BitmapImage(GetImage(xmlNews.Element("ProfileImage").Value));
3) if its a string do image1.Source=new BitmapImage(new Uri(GetImage(xmlNews.Element("ProfileImage").Value)));
I hope it helps. Do note, if still the image is not being displayed, you should check the returning value of the function != null before assigning it.

Related

IronResponse calls an JsObjectImpl object, but I cant find class docs on it

I was trying to parse the return of an IronAjax success handler and set the response to an instance of Map. It seems to not like that.
My HTML Markup is:
<iron-ajax id="myAjaxId" auto
url="http://localhost:12345/test_server/v1/daily"
handle-as="json"
on-response="handleResponse" on-error="handleError"></iron-ajax>
My Dart Code is:
void handleResponse(CustomEventWrapper cew, IronRequest ir){
print("inside handleResponse");
var data = ir.response; // <-- is type JsObjectImpl
print("data");
print(data);
if (data == null) return;
print ("About to set rows");
List<Map> rows = data.containsKey("data") ? data["data"] : [];
print("Variables are Set locally");
$['myDatagrid'].render();
}
#reflectable
String camelToFormal (String input){
String out;
RegExp regex = new RegExp("([A-Z])");
out = input[0].toUpperCase() + input.substring(1).replaceAllMapped(regex, (Match m) => " ${m[1]}");
return out;
}
#reflectable
void handleError(CustomEventWrapper cew, IronRequest ir){
print("____Error:____");
print(ir.response);
}
The Error I get is:
type 'JsObjectImpl' is not a subtype of type 'Map' of 'other'.
I wasnt sure if I need to run convert over it, even though the return type set by IronAjax was json
So, since ir.response will either be set or null, i check if it is null first. the var data line in responseHandler currently sets is, but i have also attempted to do something like: Map data = new Map.from(ir.response); which fails as well.
Even though this is said to be handled as JSON, and is returning a jslint confirmed objected, it seems to have issues to convert it to a proper map instance.
According to Polymer IronRequest at: https://elements.polymer-project.org/elements/iron-ajax?active=iron-request
it says that responseis *, the parsed response body. Am I mistaken as to how this is properly set up, or am I missing something?
You could try Object instead of map on the property and then use convertToDart. Not sure this results in a Map but worth a try I guess. See also Polymer 1.0 - iron-list - selection

Change returned object value after action execution in Web API

In ASP.Net Web API, the action returned object will be converted to XML or JSON automatically - is there a way to add additional process to the returned object before it gets converted?
What I want to achieve is to wrap returned object into a generic APIResponse (another class) type which has an object Property called Data that will be assigned with whatever the original returned object is.
for example:
public Books[] FindBooks(string keyword)
{
..
return new Books[] {new Book(){Name="ASP.NET"}};
}
This will return JSON of book array by default, however I want to wrap the result into an object called APIResponse, so the returned object becomes:
new APIResponse(){
Data = //the Book[] array return from the action method
}
By doing this, I will be able to keep the freedom of returning normal business objects in Web API however always return the same object type in JSON format when the front-end Ajax requests.
I believe it can be done in a way however I'm not familiar with the Web API life cycle, can any way give some guide on this?
Thank you.
I fixed it by creating a custom MediaTypeFormatter however simply inheriting from JSON formatter which have already got all what I need, here is the very simple code I added, which resolved all issues I have!!!
public class APIResponseMediaFomatter : JsonMediaTypeFormatter
{
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
ResponseMessage wrappedValue = null;
if (type != typeof(ResponseMessage) || (value != null && value.GetType() != typeof(ResponseMessage)))
wrappedValue = new ResponseMessage(value);
return base.WriteToStreamAsync(typeof(ResponseMessage), wrappedValue, writeStream, content, transportContext);
}
}
Cheers!
Interestingly, Web API already works exactly how you describe. It already has generic request and response classes that can hold your object payload. Just do the following,
public HttpResponseMessage FindBooks(string keyword)
{
...
var books = new Books[] {new Book(){Name="ASP.NET"}};
var content = new ObjectContent<Book[]>(books,new JsonMediaTypeFormatter());
return new HttpResponseMessage { Content = content);
}
There is no need to re-invent your own generic response object that can hold metadata and data, HTTP has already done that for you.
Why dont you return your wrapper object APIResponse from WebAPI
public APIResponse FindBooks(string keyword)
{
var books = new Books[] {new Book(){Name="ASP.NET"}};
return new APIResponse {Data= books };
}
Just use an action filter, and modify the response content inside it:
public class ApiResponseWrapperActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// Check that the response is an object content
var objectContent = actionExecutedContext.Response.Content as ObjectContent;
if (objectContent != null)
{
// Wrap the returned value in the ApiResponse
objectContent.Value = new ApiResponse() { Data = objectContent.Value };
}
}
Apply the filter to the whole API (in global config) or a whole controller (attribute applied to the controller class) or to the desired methods (attribute in each method).
If you're returning something that it's not an object (a custom response) it will skip the wrapping.

java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#

I've read several related posts and even posted and answer here but it seems like I was not able to solve the problem.
I have 3 Activities:
Act1 (main)
Act2
Act3
When going back and forth Act1->Act2 and Act2->Act1 I get no issues
When going Act2->Act3 I get no issues
When going Act3->Act2 I get occasional crashes with the following error: java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#.... This is a ListView cursor.
What I tried:
1. Adding stopManagingCursor(currentCursor);to the onPause() of Act2 so I stop managing the cursor when leaving Act2 to Act3
protected void onPause()
{
Log.i(getClass().getName() + ".onPause", "Hi!");
super.onPause();
saveState();
//Make sure you get rid of the cursor when leaving to another Activity
//Prevents: ...Unable to resume activity... trying to requery an already closed cursor
Cursor currentCursor = ((SimpleCursorAdapter)getListAdapter()).getCursor();
stopManagingCursor(currentCursor);
}
When returning back from Act3 to Act2 I do the following:
private void populateCompetitorsListView()
{
ListAdapter currentListAdapter = getListAdapter();
Cursor currentCursor = null;
Cursor tournamentStocksCursor = null;
if(currentListAdapter != null)
{
currentCursor = ((SimpleCursorAdapter)currentListAdapter).getCursor();
if(currentCursor != null)
{
//might be redundant, not sure
stopManagingCursor(currentCursor);
// Get all of the stocks from the database and create the item list
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
((SimpleCursorAdapter)currentListAdapter).changeCursor(tournamentStocksCursor);
}
else
{
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
}
}
else
{
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
}
startManagingCursor(tournamentStocksCursor);
//Create an array to specify the fields we want to display in the list (only name)
String[] from = new String[] {StournamentConstants.TblStocks.COLUMN_NAME, StournamentConstants.TblTournamentsStocks.COLUMN_SCORE};
// and an array of the fields we want to bind those fields to (in this case just name)
int[] to = new int[]{R.id.competitor_name, R.id.competitor_score};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter tournamentStocks = new SimpleCursorAdapter(this, R.layout.competitor_row, tournamentStocksCursor, from, to);
//tournamentStocks.convertToString(tournamentStocksCursor);
setListAdapter(tournamentStocks);
}
So I make sure I invalidate the cursor and use a different one. I found out that when I go Act3->Act2 the system will sometimes use the same cursor for the List View and sometimes it will have a different one.
This is hard to debug and I was never able to catch a crashing system while debugging. I suspect this has to do with the time it takes to debug (long) and the time it takes to run the app (much shorter, no pause due to breakpoints).
In Act2 I use the following Intent and expect no result:
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this, ActivityCompetitorDetails.class);
intent.putExtra(StournamentConstants.App.competitorId, id);
intent.putExtra(StournamentConstants.App.tournamentId, mTournamentRowId);
startActivity(intent);
}
Moving Act1->Act2 Act2->Act1 never gives me trouble. There I use startActivityForResult(intent, ACTIVITY_EDIT); and I am not sure - could this be the source of my trouble?
I would be grateful if anyone could shed some light on this subject. I am interested in learning some more about this subject.
Thanks,D.
I call this a 2 dimensional problem: two things were responsible for this crash:
1. I used startManagingCursor(mItemCursor); where I shouldn't have.
2. I forgot to initCursorAdapter() (for autocomplete) on onResume()
//#SuppressWarnings("deprecation")
private void initCursorAdapter()
{
mItemCursor = mDbHelper.getCompetitorsCursor("");
startManagingCursor(mItemCursor); //<= this is bad!
mCursorAdapter = new CompetitorAdapter(getApplicationContext(), mItemCursor);
initItemFilter();
}
Now it seems to work fine. I hope so...
Put this it may work for you:
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
orderCursor.requery();
}
This also works
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
startManagingCursor(Cursor);
}

Accessing encoded stream in OpenRasta

I have a need to access the encoded stream in OpenRasta before it gets sent to the client. I have tried using a PipelineContributor and registering it before KnownStages.IEnd, tried after KnownStages.IOperationExecution and after KnownStages.AfterResponseConding but in all instances the context.Response.Entity stream is null or empty.
Anyone know how I can do this?
Also I want to find out the requested codec fairly early on yet when I register after KnowStages.ICodecRequestSelection it returns null. I just get the feeling I am missing something about these pipeline contributors.
Without writing your own Codec (which, by the way, is really easy), I'm unaware of a way to get the actual stream of bytes sent to the browser. The way I'm doing this is serializing the ICommunicationContext.Response.Entity before the IResponseCoding known stage. Pseudo code:
class ResponseLogger : IPipelineContributor
{
public void Initialize(IPipeline pipelineRunner)
{
pipelineRunner
.Notify(LogResponse)
.Before<KnownStages.IResponseCoding>();
}
PipelineContinuation LogResponse(ICommunicationContext context)
{
string content = Serialize(context.Response.Entity);
}
string Serialize(IHttpEntity entity)
{
if ((entity == null) || (entity.Instance == null))
return String.Empty;
try
{
using (var writer = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(writer))
{
Type entityType = entity.Instance.GetType();
XmlSerializer serializer = new XmlSerializer(entityType);
serializer.Serialize(xmlWriter, entity.Instance);
}
return writer.ToString();
}
}
catch (Exception exception)
{
return exception.ToString();
}
}
}
This ResponseLogger is registered the usual way:
ResourceSpace.Uses.PipelineContributor<ResponseLogger>();
As mentioned, this doesn't necessarily give you the exact stream of bytes sent to the browser, but it is close enough for my needs, since the stream of bytes sent to the browser is basically just the same serialized entity.
By writing your own codec, you can with no more than 100 lines of code tap into the IMediaTypeWriter.WriteTo() method, which I would guess is the last line of defense before your bytes are transferred into the cloud. Within it, you basically just do something simple like this:
public void WriteTo(object entity, IHttpEntity response, string[] parameters)
{
using (var writer = XmlWriter.Create(response.Stream))
{
XmlSerializer serializer = new XmlSerializer(entity.GetType());
serializer.Serialize(writer, entity);
}
}
If you instead of writing directly to to the IHttpEntity.Stream write to a StringWriter and do ToString() on it, you'll have the serialized entity which you can log and do whatever you want with before writing it to the output stream.
While all of the above example code is based on XML serialization and deserialization, the same principle should apply no matter what format your application is using.

Difficulties to send File to view using FileContentResult action method

I need to display in image on the view this way
<img src = <% = Url.Action("GetImage", "Home", new { productID })%>
This is the action which's supposed to supply data
public FileContentResult GetImage(int ID)
{
var img = db.Images.Where(p => p.ID == ID).First();
return File(img.ImageData, img.ImageMimeType);
}
This example comes from Pro ASPNET.NET MVC (Steven Sanderson/APress). I'm getting the following error: The best overload method match for System.Web.Mvc.Controller.File(string, string) has some invalid argument. Cannot convert from System.Data.Linq.Binary to string.
Yet, the intellisense's telling me that there's an overload method (byte[] filecontents, string fileType).But, when I write the above code, I get the error. Am I missing something?
EDIT
Thanks for the answer. I've experienced a similar problem while uploading the image file. Here's my action method
public ActionResult AddImage(HttpPostedFileBase image)
{
if(image != null)
{
var img = new Image();//This Image class has been
//created by the DataContext
img.ImageMimeType = image.ImageMimeType
img.ImageData = new byte[image.ContentLength];
image.InputStream.Read(img.ImageData, 0, image.ContentLength);
}
}
I get error for the last line "image.InputStream.Read(myImage.ImageData, 0, image.ContentLength);" It's saying that it can't convert System.Data.Linq.Binary to Byte[]
What I did was (i) to create a new class, called ImageDataClass, (ii) do the above operation against that class, (iii) do the explicit conversion from ImageDataClass to Image, and (iv) save to the DB using Linq.
I don't think it should be that complicate. Is there any way to make it work using simply an extension method such as ToArray as for the other case???
Thanks for helping
There is an overload for File() that takes a byte array, but you are trying to pass in a type of System.Data.Linq.Binary, not a byte array. However, there is a method on Binary to convert to a byte array.
Try this:
public FileContentResult GetImage(int ID)
{
var img = db.Images.Where(p => p.ID == ID).First();
return File(img.ImageData.ToArray(), img.ImageMimeType);
}
The reason the compile error mentions "string" is purely because it can't work out which overload you were trying for, so it just picks one, in this case string, and then reports the type conversion error.
[EDIT: in response to OP edit]
You should be able to try something like this:
public ActionResult AddImage(HttpPostedFileBase image)
{
if(image != null)
{
var img = new Image();//This Image class has been
//created by the DataContext
img.ImageMimeType = image.ImageMimeType
var imageData = new byte[image.ContentLength];
image.InputStream.Read(imageData, 0, image.ContentLength);
img.ImageData = new System.Data.Linq.Binary(imageData);
}
}
Remember that although System.Data.Linq.Binary is probably just a byte array underneath, or is at least intended to represent byte data, it is not itself of type byte[]; you still have to convert to and from (a similar situation to System.IO.MemoryStream)

Resources