An issue with Image loading by the abolute URI - windows-phone-8

I have this function which returns the Uri.
public static Uri GetAppropriate(string imageName, string basePath = "/Assets/") {
switch (DisplayInformationEx.Default.FriendlyResolution) {
case FriendlyResolution.FullHD:
return new Uri("ms-appx://" + basePath + imageName + ".screen-1080p.jpg", UriKind.Absolute);
case FriendlyResolution.HD:
return new Uri("ms-appx://" + basePath + imageName + ".screen-720p.jpg", UriKind.Absolute);
case FriendlyResolution.WXGA:
return new Uri("ms-appx://" + basePath + imageName + ".screen-wxga.jpg", UriKind.Absolute);
case FriendlyResolution.WVGA:
return new Uri("ms-appx://" + basePath + imageName + ".screen-wvga.jpg", UriKind.Absolute);
default:
throw new InvalidOperationException("Unknown resolution type");
}
}
I have the image with the following path relative to the root of the application: //Assets/SquareBackground.screen-720p.jpg
I don't see the image when I make the following call:
private ImageSource backgroundImage;
public ImageSource BackgroundImage {
get { return backgroundImage; }
set {
backgroundImage = value;
NotifyOfPropertyChange(()=>BackgroundImage);
}
}
protected override void OnViewAttached(object view, object context) {
BackgroundImage = new BitmapImage(ImageChooser.GetAppropriate("SquareBackground"));
}
What am I doing wrong?

new Uri("/Assets/SquareBackground.screen-720p.jpg", UriKind.Relative); is another way to let you use URIs relative to your project root

Related

Html correct filePath for downloading file from Server

I have done the function to save a file to a Folder in Server, **I am now trying to get the file back from Server by using HTML download, but haven't found the way to get the correct filepath yet.
After stored a file in a Folder in Server, saved filePath in DB by using Entity Framework, I retrieved file from DB with filePath = /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png. But this filePath doesn't work right.
Click here to download
//file.Path = /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png
I got an error: Failed - No file
Take a look at create FilePath path in SaveFile code in Controller:
private void SaveFile(HttpPostedFileBase file)
{
string serverPath = "\\VisitReportAttachments";
if (file!= null)
{
if (!Directory.Exists(serverPath))
{
Directory.CreateDirectory(serverPath);
}
var fileName = Guid.NewGuid()+ Path.GetExtension(file.FileName);
var path = Path.Combine("\\", new DirectoryInfo(serverPath).Name, fileName);
path = relativePath.Replace(#"\", "/"); //this path is stored to DB
....
//As I mentioned: save file to Server is done. I simply post the code that create the filepath in SQL DB while file is storing to Server*
}
}
FilePath is stored in DB like: /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png
Need help!
Found out the solution by using Server.MapPath to Map the filePath to the correct Path.
Instead of using downloadable Link in HTML View, I create Download function in Controller:
[HttpPost]
[Authorize]
public ActionResult DownloadAttachment()
{
return Json(true);
}
[HttpGet]
public ActionResult Download(Guid? attachmentId)
{
var visitAttachment = _visitAttachmentService.FindOne(x => x.Id == attachmentId);
try
{
var serverPath = Server.MapPath(visitAttachment.Path);
byte[] fileBytes = System.IO.File.ReadAllBytes(serverPath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
}
catch
{
return File(Encoding.UTF8.GetBytes(""), System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
}
}
Call this method in View:
#file.AttachmentName
<script>
function Download(attachmentId) {
var url = '/Visits/DownloadAttachment';
$.post(url,
{
// FilePath: filePath
},
function (data) {
var response = JSON.parse(data);
window.location = '/Visits/Download?attachmentId=' + attachmentId;
},
"json");
}
</script>
It works perfectly now.
Your private string SaveFile(HttpPostedFileBase file) method should return a NewFile model object that reflects the entity in your database. private NewFile SaveFile(HttpPostedFileBase file)
public class NewFile
{
public int NewFileId { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
}
You will need do something similar to the following code when you save the File:
using (var db = new YourDbContext())
{
var newFile = new NewFile { FileName = fileName, FilePath = path };
var savedFile = db.Add(newFile);
db.SaveChanges();
return savedFile; // here is the object you can return to the view and access
// its properties
}
private string SaveFile(HttpPostedFileBase file)
{
if (file == null)
return string.Empty;
string saveFolder = "VisitReportAttachments";
string fileName = fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
string serverFolderPath = AppDomain.CurrentDomain.BaseDirectory + "/" + saveFolder;
string savePath = serverFolderPath + "/" + fileName;
if (!Directory.Exists(serverFolderPath))
Directory.CreateDirectory(serverFolderPath);
file.SaveAs(savePath);
return Url.Content($"~/{saveFolder}/{fileName}");
}
You have not shored file in folder.
Add below line in code
file.SaveAs(serverPath + file.FileName);
So your C# code will be like
private string SaveFile(HttpPostedFileBase file)
{
string serverPath = "\\VisitReportAttachments";
if (file!= null)
{
if (!Directory.Exists(serverPath))
{
Directory.CreateDirectory(serverPath);
}
var fileName = Guid.NewGuid()+ Path.GetExtension(file.FileName);
var path = Path.Combine("\\", new DirectoryInfo(serverPath).Name, fileName);
file.SaveAs(serverPath + file.FileName);
path = relativePath.Replace(#"\", "/");
return path;
}
return string.Empty;
}

I want to create highchart widget by Eclipse RAP and i follow "RAP/Custom Widgets FAQ",but there is error?

i want to create some highchart widget by Eclipse RAP ,and i follow the official guide like this
handlejs:
var CKEDITOR_BASEPATH = "rwt-resources/";
(function(){
'use strict';
rap.registerTypeHandler( "rap.sunline.HighCharts", {
factory : function( properties ) {
var parent = rap.getObject( properties.parent );
// var element = document.createElement( "div" );
// parent.append( element );
// $(element).html("askldfjaskljdk");
return {};
}
});
}());
widget.java:
public class HightChartComposite extends Composite {
private static final String RESOURCES_PATH = "resources/";
private static final String REGISTER_PATH = "hightcharts/";
private static final String[] RESOURCE_FILES = { "jquery-2.1.0.min.js", "highcharts.js","ChartPaintListener.js" };
private static final String REMOTE_TYPE = "rap.sunline.HightCharts";
private final RemoteObject remoteObject;
private final OperationHandler operationHandler = new AbstractOperationHandler() {
#Override
public void handleSet(JsonObject properties) {
// JsonValue textValue = properties.get("text");
// if (textValue != null) {
// text = textValue.asString();
// }
}
};
public HightChartComposite(Composite parent, int style) {
super(parent, style);
registerResources();
loadJavaScript();
Connection connection = RWT.getUISession().getConnection();
remoteObject = connection.createRemoteObject(REMOTE_TYPE);
remoteObject.setHandler(operationHandler);
remoteObject.set("parent", WidgetUtil.getId(this));
}
private void registerResources() {
ResourceManager resourceManager = RWT.getResourceManager();
boolean isRegistered = resourceManager.isRegistered(REGISTER_PATH + RESOURCE_FILES[0]);
if (!isRegistered) {
try {
for (String fileName : RESOURCE_FILES) {
register(resourceManager, fileName);
}
} catch (IOException ioe) {
throw new IllegalArgumentException("Failed to load resources", ioe);
}
}
}
private void loadJavaScript() {
JavaScriptLoader jsLoader = RWT.getClient().getService(JavaScriptLoader.class);
ResourceManager resourceManager = RWT.getResourceManager();
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "jquery-2.1.0.min.js"));
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "highcharts.js"));
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "ChartPaintListener.js"));
}
private void register(ResourceManager resourceManager, String fileName) throws IOException {
ClassLoader classLoader = HightChartComposite.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(RESOURCES_PATH + fileName);
try {
resourceManager.register(REGISTER_PATH + fileName, inputStream);
} finally {
inputStream.close();
}
}
// //////////////////
// overwrite methods
#Override
public void setLayout(Layout layout) {
throw new UnsupportedOperationException("Cannot change internal layout of CkEditor");
}
}
the error is occur:
Uncaught Error: Operation "create" on target "r6" of type "null" failed:
No Handler for type rap.sunline.HightCharts
Properties:
parent = w5
and i have a question about this , what differents from extends Canvas and Composite;
You forget to implement setters in your javascript code.
The created object is stored by the framework under its object id. This object has to implement setter methods that match the properties defined in the handler, which will then be called when the server sends a set operation for a given property.

Capture image with MediaStreamSource

Im using a MediaStreamSource to use the camera... everything works, except when I try to capture the image!
I think the problem is the object MediaStreamSource
public class CameraStreamSourceModel : MediaStreamSource
{
private MemoryStream _cameraStream = null; // here I've the stream from camera
...
public async void CapturePhoto()
{
// Save the image as a jpeg to the camera roll
MediaLibrary library = new MediaLibrary();
string filename = AppResources.ApplicationTitle + "_" + DateTime.Now.ToString("G");
Picture pic = library.SavePicture(filename, _cameraStream); //Here I've the exception
}
}
The exception is
System.InvalidOperationException: An unexpected error has occurred.
I've enabled ID_CAP_MEDIALIB_PHOTO.
I am sure the code to save image works because i can save static stream in media library, but not stream from camera!
Can anyone help me? Thank you
You could simply use a camera_capture_task
CameraCaptureTask cameraCaptureTask;
public Transaction()
{
InitializeComponent();
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
}
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
pic.Source = bmp;
pic_name = "" + DateTime.Now.Month + "" + DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second+".jpeg";
SaveToIsolatedStorage(e.ChosenPhoto, "" + pic_name);
}
}

WebClient event firing order

I'm new to WP7 app development and I'm having trouble passing parameters to an API on a website.
It's my understanding that the onNavigatedTo() is fired first when a page is open on the WP7, however when I try to grab the parameters the webClient_DownloadStringCompleted() is fired first.
public partial class Ranks : PhoneApplicationPage
{
private WebClient webClient;
private string pageType;
private string pagePosition;
public Ranks()
{
InitializeComponent();
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string myJsonString = e.Result;
List<PlayerDetails> dataSource = new List<PlayerDetails>();
//load into memory stream
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myJsonString)))
{
//parse into jsonser
var ser = new DataContractJsonSerializer(typeof(PlayerDetails[]));
PlayerDetails[] obj = (PlayerDetails[])ser.ReadObject(ms);
foreach (PlayerDetails plyr in obj)
{
dataSource.Add(plyr);
}
playerList.ItemsSource = dataSource;
}
}
Whenever the URI string is built it's missing the parameters 'pageType' and 'pagePosition'
Any help would be greatly appreciated!
The class constructor will always get called before OnNavigatedTo. you should move that code from the constructor, and into OnNavigatedTo (or Loaded).
I'm guessing that you have that code in the constructor because you only want it to happen once per page load (i.e. not when the user navigates Back onto the page). If that's the case, you can check the NavigationMode.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.New)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
}

MonoTouch get location & capture map image like contacts

As the title, I'm confused with how to capture maps with MonoTouch, and how to get the location. As step by:
CLLocationManager locationManager = new CLLocationManager ();
locationManager.UpdatedLocation += UpdatedLocationEvent;
locationManager.Delegate = new MyLocationDelegate ();
locationManager.StartUpdatingLocation ();
class MyLocationDelegate : CLLocationManagerDelegate
{
public MyLocationDelegate () : base()
{
}
public override void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
{
Console.WriteLine ("newLocation " + newLocation.VerticalAccuracy + " " + newLocation.HorizontalAccuracy);
Console.WriteLine ("oldLocation " + oldLocation.VerticalAccuracy + " " + oldLocation.HorizontalAccuracy);
}
public override void Failed (CLLocationManager manager, NSError error)
{
Console.WriteLine ("Failed to find location");
}
}
It doesn't work. Please help me.
You have not configured the kind of events that you get, you are missing a line like this:
locationManager = new CLLocationManager () {
DesiredAccuracy = CLLocation.AccuracyBest,
Delegate = new MyCLLocationManagerDelegate (callback),
DistanceFilter = 1000f
};
if (CLLocationManager.LocationServicesEnabled)
locationManager.StartUpdatingLocation ();