Download ParseObject from Parse and Display - c#

I am developing and application in xamarin for android. There are two buttons one for uploading the Parse object and another one for downloading the object and display Image. Uploading button is working properly. But I am facing two main Problem
First: I am getting a null value in my IEnumerable object. I have attached a screenshot of my breakpoint value.
Second: When I am trying to display the object I am getting an error. I have attached a screenshot of the error shown
Upload Button:
upbutton.Click += async delegate {
try {
byte[] myfile = System.IO.File.ReadAllBytes (path);
ParseFile file = new ParseFile ("imgfl.png", myfile);
await file.SaveAsync ();
// link your file object to your Parse object
ParseObject gameScore = new ParseObject ("GameScore");
gameScore ["score"] = 0001;
gameScore ["playerName"] = " Bob";
gameScore ["image"] = file;
await gameScore.SaveAsync ();
} catch (Exception e) {
System.Console.WriteLine (e);
}
};
Download Button:
downbutton.Click+= async delegate {
var query = from GameScore in ParseObject.GetQuery("GameScore")
orderby GameScore.CreatedAt descending
select GameScore;
IEnumerable<ParseObject> results = await query.FindAsync();
//I am getting a null object result here
foreach (var obj in results)
{
ParseFile img = obj.Get<ParseFile>("image");
_imageView.SetImageURI(img.Url);
//error here
}
};

One of your GameScore rows probably doesn't have the image property set, for that row you'll get a null result in your img variable.
Also note that in your Download Button code, you're going to get every single row and keep calling _imageView.SetImageURI(img.Url) line for each one, potentially replacing the value over and over again.
You might want to be doing a FirstAsync() call instead of FindAsync() if you are going to want just a single row.

Related

C# MongoDB : Chunk file does not upload following a prior deletion

I'm having a bit of a problem with an update feature designed to compare two images, and if different, delete the existing image and data from Mongo, and replace it with a new copy. The problem is, individually, each component works. The loading feature will successfully upload an image and Bson Document. The delete method will successfully (seemingly) remove them; the document, the fs.files entry, and the fs.chunks entry.
However, when the entry is deleted and then proceeds to upload the new image, only the fs.files entry and the BsonDocument will be pushed to the server. The actual image is left off.
I'm running MongoDB 3.2.6 for Windows.
The replace block followed by the upload block
if (newMD5.Equals(oldMD5) == false)
{
Debug.WriteLine("Updating image " + fileWithExt);
BsonValue targetId = docCollection.FindOne(Query.EQ("id", fileNoExt))["_id"];
deleteImageEntry(Query.EQ("_id", new ObjectId(targetId.ToString())));
//continues to upload replacement
} else
{
continue;
}
}
//create new entry
uploadInfo = mongoFileSystem.Upload(memStream, fileFs);
BsonDocument entry = new BsonDocument();
entry.Add("fileId", uploadInfo.Id);
entry.Add("id", fileNoExt);
entry.Add("filename", fileFs);
entry.Add("user", "");
//appends to image collection
var newItemInfo = docCollection.Save(entry);
And the delete method
public static bool deleteImageEntry(IMongoQuery query)
{
MongoInterface mongo = new MongoInterface();
try
{
var docCollection = mongo.Database.GetCollection("employees");
var imageCollection = mongo.Database.GetCollection<EmployeeImage>("employees");
var toDelete = docCollection.FindOne(query);
BsonValue fileId = toDelete.GetValue("fileId");
mongo.Gridfs.DeleteById(fileId);
WriteConcernResult wresult = imageCollection.Remove(query);
}
catch (Exception e)
{
Debug.WriteLine("Image could not be deleted \n\r" + e.Message);
return false;
}
return true;
}
Sorry the code is messy, I've doing a lot a guerrilla testing to try and find a reason for this. Similar code has worked in other parts of the program.
Well this is embarrassing. After a few more hours of debugging it turned out to be the MD5.ComputerHash() function was setting the memStream iterator to the end, and so there was no data being uploaded. Using memStream.Position = 0; solved the problem.

Adding Image MediaType programatically Umbraco 7.1

Im a bit new to Umbraco, and i have to say i like it a lot.
But now i'm stuck on something simple i think. I Created a protected page that is only visible to members on my website. Where the member is able to upload multiple files at once. This is al working like a charm. First i created the upload form for multiple images then i created the SurfaceController to handle the submit. Also working like a charm.
My ActionResult on my SurfaceController receives an IEnumerable<HttpPostedFileBase> called files which is good. I see all my images that i'm posting with my form. But here comes the problem.
While looping over my files I try to create a Media (Image type) using the MediaService.CreateMedia giving my filename and parentid and the mediaType (Image).
But when i try to set the umbracoFile value on my just created media item i will get the following exception:
An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Umbraco.Core.dll
Additional information: The best overloaded method match for
'Umbraco.Core.Models.ContentBase.SetPropertyValue(string, string)'
has some invalid arguments
I hope someone can tell my what i'm doing wrong. Below is my code i'm using
[HttpPost]
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
bool success = false;
//Get logged in member and look for the mediafolderID
var member = Services.MemberService.GetByUsername(HttpContext.User.Identity.Name);
var mediaFolderID = member.GetValue<int>("mediaFolderID");
//Get mediafolder
var mediaFolder = Services.MediaService.GetById(mediaFolderID);
try
{
// Create a media item from each file uploaded
foreach (var file in files)
{
var fileName = file.FileName; // Assumes no path information, just the file name
var ext = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
if (!UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles.Contains(ext))
{
var mediaType = global::Umbraco.Core.Constants.Conventions.MediaTypes.File;
if (UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.Contains(ext))
{
mediaType = global::Umbraco.Core.Constants.Conventions.MediaTypes.Image;
}
var f = Services.MediaService.CreateMedia(fileName, mediaFolderID, mediaType);
// Assumes the file.InputStream is a Stream - you may have to do some extra work here...
f.SetValue(global::Umbraco.Core.Constants.Conventions.Media.File,(Stream)file.InputStream); // Real magic happens here.
Services.MediaService.Save(f);
}
}
success = true;
}
catch (Exception ex)
{
// On error show message
ViewData["exceptionMessage"] = ex.Message;
success = false;
}
// On success redirect to current page and show successmessage
ViewData["success"] = success;
if (success)
{
return RedirectToCurrentUmbracoPage();
}
return CurrentUmbracoPage();
}
Instead of f.SetValue(global::Umbraco.Core.Constants.Conventions.Media.File, (Stream)file.InputStream); you should just use the HttpPostedFileBase: f.SetValue(global::Umbraco.Core.Constants.Conventions.Media.File, file);
Some other notes:
Check that the file has a length and is not null: file != null && file.ContentLength > 0
You're not using your mediaFolder variable anywhere, can be removed.
Not sure why you'd need global::Umbraco.Core, consider adding using Umbraco.Core; and use Constants.Conventions.MediaTypes.Image etc.
Check that you really need to rely on DisallowedUploadFiles - I'm pretty sure that's checked during CreateMedia

Select multiple image files using fileupload control(ASP.net C#) and save it in database in one click.

I am able to select multiple files using fileupload control but when I try to save it to a database it's giving me an "Object reference not set to an instance of an object" error.
if (FileUpload1.HasFiles)
{
foreach (HttpPostedFile uploaded in FileUpload1.PostedFiles)
{
bindata = new BinaryReader(uploaded.InputStream);
ImageByteArray = bindata.ReadBytes(uploaded.ContentLength);
// byte array is sent to a method
dbmt.SaveImageToDB(ImageByteArray);
}
}
And the following is my code for the SaveImageToDB method
public void SaveImageToDB(byte[] ImageByteArray)
{
try
{
scon.Open();
scm.Connection = scon;
scm.CommandType = CommandType.StoredProcedure;
scm.CommandText = "SaveProfileImage";
SqlParameter paramImgArray = scm.Parameters.Add("#ImgBody", SqlDbType.Image,0);
paramImgArray.Direction = ParameterDirection.Input;
paramImgArray.Value = ImageByteArray;
scm.ExecuteNonQuery();
}
catch( SqlException sqx )
{
throw sqx;
}
}
Set The Property AllowMultiple = True in fileupload control.
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),
uploadedFile.FileName));
listofuploadedfiles.Text += String.Format("{0}<br/>", uploadedFile.FileName);
}
}
}
I understand that it is giving an error in the said method, but on which line inside that method is giving this error?
I assume that the method you have given here is complete (i.e. there is no code which you have deleted before pasting it here), so i guess there are only 2 objects which could be null and those are "scon" and "scm". Put a breakpoint on the line "scon.Open();" and on line "scm.Connection = scon;". Once the execution stops on each of these lines, hover your mouse over "scon" and then over "scm". I guess either one of them will be null.
Hope this helps.
The problem was my object. It was not instantiated correctly. I was accessing a class within appcode called DBmiddleTier to access a database and write the image file. Here is what I did wrong: DBMiddleTier dbmt; <-----"WRONG". Here is what I did to correct the problem DBMiddleTier dbmt = new DBMiddleTier();

ListView returns null on selected items that should contain data

I have code which takes in data from Flickrs Rest service and populates a ListView. This code works fine and when I run my app I can search for photos and be displayed a list of them. However I want to then get a single photos data but when I try to access this data from the ListView it's completely empty (Iv debugged it and it just contains null entries). I don't have a lot of experience with C# so could anyway advise me as to why I would be getting null results?
private async void ParseFlickrResponse(HttpResponseMessage response)
{
XDocument xml = XDocument.Parse(await response.Content.ReadAsStringAsync());
var photos = from results in xml.Descendants("photo")
select new FlickrImage
{
ImageId = results.Attribute("id").Value.ToString(),
FarmId = results.Attribute("farm").Value.ToString(),
ServerId = results.Attribute("server").Value.ToString(),
Secret = results.Attribute("secret").Value.ToString(),
Title = results.Attribute("title").Value.ToString()
};
FlickrListView.ItemsSource = photos;
}
EDITED
Current code:
enter code here:
private async void ParseFlickrResponse(HttpResponseMessage response)
{
XDocument xml = XDocument.Parse(await response.Content.ReadAsStringAsync());
var photos = from results in xml.Descendants("photo").ToList()
select new FlickrImage
{
ImageId = results.Attribute("id").Value.ToString(),
FarmId = results.Attribute("farm").Value.ToString(),
ServerId = results.Attribute("server").Value.ToString(),
Secret = results.Attribute("secret").Value.ToString(),
Title = results.Attribute("title").Value.ToString()
};
FlickrListView.ItemsSource = new ObservableCollection<FlickrImage>(photos);
}
private void GetPhotoSource(object sender, ItemClickEventArgs e)
{
int inx = FlickrListView.SelectedIndex;
// FlickrImage t = lst.First();
FlickrImage t = lst.ElementAt(inx);
MyImage.Source = new BitmapImage(new Uri(t.ImageUrl.ToString(), UriKind.Absolute));
}
Try adding a .ToList() at the end of your LINQ.
*EDIT (comments summary)
You are handling ItemClick event which seems to be raised before the selection properties on the ListViewBase change. Since these are not updated at this point - you can check e.ClickedItem and cast it to FlickrImage to get your clicked item.
If you do want to work with selection properties - you should be handling the SelectionChanged event.

strange behavior of XamlReader.Load()?

I've got a very strange issue while parsing an external XAML file. The pre-history is that I want to load an external XAML file with content to process. But I want to load as many different files as I want. That happens by unloading the old and loading the new one.
My issue is:
When I load a xaml the first time, everything is good, all as it should be.
But when I load the same xaml the second time, every entry of the object im Loading is there twice. If I run this again, every object is there three times and so on...
To debug the project yourself, download it here. The function starts at line 137 in the file "Control Panel.xaml.cs". I realy don't know what this is. Is it my fault or simply a bug? If yes, is there a workaround?
/// <summary>
/// Load a xaml file and parse it
/// </summary>
public void LoadPresentation()
{
this.Title = "Control Panel - " + System.IO.Path.GetFileName(global.file);
System.IO.FileStream XAML_file = new System.IO.FileStream(global.file, System.IO.FileMode.Open);
try
{
System.IO.StreamReader reader = new System.IO.StreamReader(XAML_file);
string dump = reader.ReadToEnd(); //This is only for debugging purposes because of the strange issue...
XAML_file.Seek(0, System.IO.SeekOrigin.Begin);
presentation = (ResourceDictionary)XamlReader.Load(XAML_file);
//Keys the resourceDictionary must have to be valid
if (presentation["INDEX"] == null || presentation["MAIN_GRID"] == null || presentation["CONTAINER"] == null || presentation["LAYOUTLIST"] == null)
{
throw new Exception();
}
//When this list is loaded, every item in it is there twice or three times or four... Why????
TopicList Index = null;
Index = (TopicList)presentation["INDEX"];
for (int i = 0; i < topics.Count; )
{
topics.RemoveAt(i);
}
foreach (TopicListItem item in Index.Topics)
{
topics.Insert(item.TopicIndex, (Topic)presentation[item.ResourceKey]);
}
lv_topics.SelectedIndex = 0;
selectedIndex = 0;
}
catch
{
System.Windows.Forms.MessageBox.Show("Failed to load XAML file \"" + global.file + "\"", "Parsing Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
presentation = null;
}
finally
{
XAML_file.Close();
}
}
Edit:
I have tried to serialize the object that was read from the XamlReader and in the output was nowhere any childelement... But if I pull the object out of the dictionary, the children are all there (duplicated and triplicated, but there).
I have already tried to clear the list over
topics.Clear();
and
topics=new ObservableCollection<TopicListItem>();
lv_topics.ItemsSource=topics;
Try Index.Topics.Clear() after loading the Topics into your topics object. That appears to get rid of the duplication.
//When this list is loaded, every item in it is there twice or three times or four... Why????
TopicList Index = null;
Index = (TopicList)presentation["INDEX"];
topics.Clear();
foreach (TopicListItem item in Index.Topics)
{
topics.Insert(item.TopicIndex, (Topic)presentation[item.ResourceKey]);
}
Index.Topics.Clear(); //Adding this will prevent the duplication
lv_topics.SelectedIndex = 0;
selectedIndex = 0;
In the code post topics is not declared in LoadPresentation() so naturally it will have any prior values.
I know you said you tried topics=new ObservableCollection(); but please try again. And put that IN LoadPresentation()
public void LoadPresentation()
{
ObservableCollection<TopicListItem> topics = new ObservableCollection<TopicListItem>()
I would pass filename
public void LoadPresentation(string fileName)
I get you may need to use topics outside LoadPresentation but this is debugging. If you need topics outside the return it.
public ObservableCollection<TopicListItem> LoadPresentation(string fileName)
If that does not fix it I would put a try catch block on the XAML_file.Close(); to see if something weird is not going on.

Categories

Resources