Set and find control by name - c#

What I have is this and it's working fine:
if (direction.Equals("UR"))
{
UR_Image.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../Family/" + name + "/Image/"+direction+".png", Directory.GetCurrentDirectory())));
}
else if (direction.Equals("UL"))
{
UL_Image.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../Family/" + name + "/Image/"+direction+".png", Directory.GetCurrentDirectory())));
}
What I wish to do is below, written as pseudo code:
direction + _Image.Source = new BitmapImage(new Uri(
String.Format("file:///{0}/../Family/" + name + "/Image/"+direction+".png",
Directory.GetCurrentDirectory())));
How can I implement direction + _Image ?
Direction is a string and UL_Image and UR_Image are image views.

Try the following approach.
YourWindow.xaml
<!-- named controls -->
<Image x:Name="ImageOne" />
<Image x:Name="ImageTheOther" />
YourWindow.xaml.cs
// get image control by name
var control = FindName(string.Format("Image{0}", direction)) as Image;
if (control == null)
return;
// set bitmap once
string path = Path.Combine(Environment.CurrentDirectory, "image.png");
var bitmap = new BitmapImage(new Uri(path));
// assign
control.Source = bitmap;
Where direction is enumeration
public enum Direction
{
One,
TheOther
}

Related

Fast way to check is image exists in assets in Windows Phone

My application for Windows Phone 8.1.
I need to find a way to check image aviability in assets resources in my application.
At first, I had following solution:
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
var folder = await package.GetFolderAsync("Assets\\Makes");
var files = await folder.GetFilesAsync();
var result = files.FirstOrDefault(p => p.Name == imageName);
if (result != null)
{
Uri imageUri = new Uri("ms-appx:///Assets/Makes/" + imageName);
Image img = new Image();
BitmapImage bi = new BitmapImage(imageUri);
img.Source = bi;
btn.Content = img;
}
else
{
TextBlock label = new TextBlock();
label.Text = text;
btn.Content = label;
}
It works. But, unfortunately, very very slow.
Anyway, next part of code working even in case if asset is not existing:
Uri imageUri = new Uri("ms-appx:///Assets/Makes/" + imageName);
BitmapImage bi = new BitmapImage(imageUri);
In case if file not existing, the image is empty, but not null.
Is there are any good way, to check, if image created empty from resource?
Or a really fast way to check existing of packaged resource file?
Thank you

Getting NotSupportedException when trying to set image from isolated storage

I'm trying to set image for my tile in the background agent for my application:
ShellTile t = ShellTile.ActiveTiles.First();
if (t != null)
{
var filePath = Path.Combine("Tiles", "test1.jpg");
StandardTileData tile = new StandardTileData();
tile.Title = "Title text here";
tile.BackgroundImage = new Uri(#"isostore:\" + filePath, UriKind.Absolute);
t.Update(tile);
}
but then on t.Update(tile) it throws NotSupportedException :-( Isnt the path ("isostore:\") correct?
new Uri(#"isostore:" + filePath, UriKind.Absolute);
Without the backslash.

Cannot delete file in C#.net windows application

I am first creating Bitmap image file and saving it to some temp location. Later using that file to read in BitmapImage object to compare it with other file. Once comparison is done, I want to delete file but then it throws exception that file is being used by another process. How can I delete this file?
Here is my code:
private void btnLogin_Click(object sender, EventArgs e)
{
string strPath = AppDomain.CurrentDomain.BaseDirectory;
GC.Collect();
if (txtLoginImage.Text != "")
{
string strFileName = txtLoginImage.Text.Substring(txtLoginImage.Text.LastIndexOf('\\') + 1);
Bitmap MainImg = new System.Drawing.Bitmap(txtLoginImage.Text);
Bitmap NewImage = ConvertToGrayScale(MainImg);
NewImage.Save(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" + strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
NewImage.Dispose();
Uri SourceUri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" + strFileName);
BitmapImage source = new BitmapImage();
source.UriSource = SourceUri;
IrisSystem.Class.BLL.User_BLL ubll = new IrisSystem.Class.BLL.User_BLL();
DataSet dsUserData= ubll.getlist();
bool isMatchFound = false;
if (dsUserData != null && dsUserData.Tables.Count > 0)
{
foreach (DataRow item in dsUserData.Tables[0].Rows)
{
Uri TargetUri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Grayscale\\" + item["GrayScaleImgName"]);
BitmapImage Target = new BitmapImage(TargetUri);
if (source.IsEqual(Target))
{
IrisSystem.frmHome frm= new IrisSystem.frmHome();
frm.strFullName = item["FullName"].ToString();
frm.ShowDialog();
Form.ActiveForm.Close();
isMatchFound = true;
break;
}
Target = null;
}
if (!isMatchFound)
MessageBox.Show("Invalid Credential..","Invalid Operation");
}
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" + strFileName);
}
else
MessageBox.Show("Please select image", "Login Error");
}
You need to make sure that your Bitmap objects are disposed properly.
You are not disposing the MainImg object. you need to use using {} block to make sure that objects are disposed properly.
Replace This:
Bitmap MainImg = new System.Drawing.Bitmap(txtLoginImage.Text);
Bitmap NewImage = ConvertToGrayScale(MainImg);
NewImage.Save(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\"
+ strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
NewImage.Dispose();
With This:
using(Bitmap MainImg = new System.Drawing.Bitmap(txtLoginImage.Text))
using(Bitmap NewImage = ConvertToGrayScale(MainImg))
{
NewImage.Save(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\Temp\\" +
strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
}
EDIT:
Replace This:
BitmapImage source = new BitmapImage();
source.UriSource = SourceUri;
With This:
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = SourceUri;
source.EndInit();

Check if the image resource is null

I Working on Windows Phone 8 application.
string Image = "/MyData/" + myObject.ImageName + "big.png";
BitmapImage bmp = new BitmapImage(new Uri(Image , UriKind.Relative));
MyImage.Source = bmp;
I have a image in the folder MyData/, i have 2 sets of images like <imagename>big.png,<imagename>small.png.
So here what is happening is i want to check if <imagename>big.png exists in the location or not, if not pick <imagename>small.png.
How to do it ?
EDIT
I solved it myself, here is how.
File.Exists("path to file") here path should be `folderName/filenames` and not `/folderName/filenames`
Thanks for everyone who helped me.
string image = "/MyData/" + myObject.ImageName + "/big.png";
string fileName = Path.GetFileName(image);
if(!string.IsNullOrEmpty(fileName))
{
MessageBox.Show("File Exist -"+fileName);
}
else
{
MessageBox.Show("No File Exist -");
}
BitmapImage bmp = new BitmapImage(new Uri(image , UriKind.Relative));
if(bmp==null)
{
image = "/MyData/" + myObject.ImageName + "/small.png";
bmp = new BitmapImage(new Uri(image , UriKind.Relative));
}
MyImage.Source = bmp;

Is it possible to render a view from Bing Maps to a WriteableBitmap?

Case: Windows Phone 7 (Mango) application.
I have a list of (hundreds of ) items, containing a geocoordinate. Each item's parameter data is used to render an image, and these images are displayed in a listbox.
Is it possible to render a WP7 Map element to a writeablebitmap? If not, is it possible to disable UI gestures from the map element, so it at least behaves like a static image?
If you just want a static image of a map I would recommend using the Static Map API for Bing maps instead of a Map control for each list item.
The static map API also lets you specify the image size so the download size to the phone can be reduced.
If you still want to use the Bing Map control, you can disable UI gestures by setting IsHitTestVisible to false, like this in XAML:
<my:Map IsHitTestVisible="False" />
Try the example suggested in comment from GFTab
For making it static, you can try IsHitTestVisible="False"
Here is how I made a secondary tile from the areay currenly visible in the application:
private void pinCurrentMapCenterAsSecondaryTile() {
try {
var usCultureInfo = new CultureInfo("en-US");
var latitude = map.Center.Latitude.ToString(usCultureInfo.NumberFormat);
var longitude = map.Center.Longitude.ToString(usCultureInfo.NumberFormat);
var zoom = map.ZoomLevel.ToString(usCultureInfo.NumberFormat);
var tileParam = "Lat=" + latitude + "&Lon=" + longitude + "&Zoom=" + zoom;
if (null != App.CheckIfTileExist(tileParam)) return; // tile for exactly this view already exists
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) {
var fileName = "/Shared/ShellContent/" + tileParam + ".jpg";
if (store.FileExists(fileName)) {
store.DeleteFile(fileName);
}
// hide pushpins and stuff
foreach (var layer in map.Children.OfType<MapLayer>()) {
layer.Visibility = Visibility.Collapsed;
}
using (var saveFileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store)) {
var wb = new WriteableBitmap(173, 173);
b.Render(
map,// the map defined in XAML
new TranslateTransform {
// use the transformation to clip the center of the current map-view
X = -(map.ActualWidth - 173)/2,
Y = -(map.ActualHeight - 173)/2,
});
wb.Invalidate();
wb.SaveJpeg(saveFileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
foreach (var layer in map.Children.OfType<MapLayer>()) {
layer.Visibility = Visibility.Visible;
}
}
ShellTile.Create(
new Uri("/MainPage.xaml?" + tileParam, UriKind.Relative),
new StandardTileData {
BackTitle = "ApplicationName",
Count = 0,
// You can only load images from the web or isolated storage onto secondary tiles
BackgroundImage = new Uri("isostore:/Shared/ShellContent/" + tileParam + ".jpg", UriKind.Absolute),
});
} catch (Exception e) {
// yeah, this is 7331!!11elfelf
}
}

Categories