Capture image with MediaStreamSource - windows-phone-8

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);
}
}

Related

IN ASP.NET web application I want to convert a youtube links to MP3 file

i want to just convert youtube links to MP3 file in asp.net.I have research about that and do the code but the code gives exception like below:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. how to resolve that
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string url = TextBox1.Text;
var source = #"C:\Users\Dipak";
var youtube = YouTube.Default;
var vid = youtube.GetVideo(url);
File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
var inputFile = new MediaFile { Filename = source + vid.FullName };
var outputFile = new MediaFile { Filename = $"{source + vid.FullName}.mp3" };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
}
catch (Exception exception)
{
}
}
I have found this types of code in Stack overflow but won't work

Clear image cache created by <Image>

If I have an element like this in a Windows Store or Windows Phone application:
<Image Source="{Binding UrlToWebServer}" />
the image is cached locally. This is great. But how do I remove all cached images on disc from code?
You just have to set the imagesource to NULL
Something like this:
BitmapImage bitmapImage = myimage.Source as BitmapImage;
bitmapImage.UriSource = null;
myimage.Source = null;
This works for me. Here you can find mor infos handling images (section Image Caching for example).
Hi it´s a little bit late to answer this question but you can use this class to delete the cache of a specific files or all if you want
this is the class helper
class CacheCleanup : IDisposable
{
private DispatcherTimer cleanCacheTimer;
public CacheCleanup(TimeSpan? cleanInterval = null)
{
if (!cleanInterval.HasValue)
cleanInterval = TimeSpan.FromMinutes(0.2);
cleanCacheTimer = new DispatcherTimer();
cleanCacheTimer.Interval = cleanInterval.Value;
cleanCacheTimer.Tick += CleanCacheTimer_Tick;
cleanCacheTimer.Start();
}
private void CleanCacheTimer_Tick(object sender, object e)
{
try
{
StorageFolder localDirectory = ApplicationData.Current.LocalFolder;
string[] tmpCacheDirectories = Directory.GetDirectories(localDirectory.Path + "\\..\\ac\\inetcache");
foreach (string dir in tmpCacheDirectories)
{
string[] tmpCacheFilesPng = Directory.GetFiles(dir, "*.png");
foreach (string file in tmpCacheFilesPng)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted png: " + file);
}
catch (Exception) { }
}
string[] tmpCacheFilesJpg = Directory.GetFiles(dir, "*.jpg");
foreach (string file in tmpCacheFilesJpg)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted jpg: " + file);
}
catch (Exception) { }
}
}
}
catch (Exception ex) { Debug.WriteLine("ERROR CLEANING CACHE: " + ex.Message); }
}
public void Dispose()
{
if (cleanCacheTimer != null)
{
cleanCacheTimer.Stop();
cleanCacheTimer = null;
}
}
}
and this is the way how you can call this class in some part of your c# code
CacheCleanup cacheCleanup = new CacheCleanup();

Accurate Windows phone 8.1 geolocation?

Im working with windows phone 8.1 geolocation. The problem that I currently have is that my code only shows the first numbers of my coordinate. Example: If the coordinate is "41.233" the app only shows "41.00" . I need it to be as accurate as possible. In case it matters, im using windows phone 8.1 emulator to try the app, not an actual phone.
My code:
public sealed partial class MainPage : Page
{
bool shouldSend = false;
DispatcherTimer timer = new DispatcherTimer();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private async Task GetLocation()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromSeconds(1),
timeout: TimeSpan.FromSeconds(10)
);
LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
LatLonTxt.Text = LatitudeTxt.Text + ", " + LongitudeTxt.Text;
var speed = geoposition.Coordinate.Speed.ToString();
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"http://proyecto-busways.rhcloud.com/colectivos?p=lta123&l=80&d=moyano&lat=" + LatitudeTxt.Text + "&lon=" + LongitudeTxt.Text + "&v=" + speed + "&Accion=Agregar");
request.ContinueTimeout = 4000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//To obtain response body
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
{
result = streamRead.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if ((uint)ex.HResult == 0x80004004)
{
// the application does not have the right capability or the location master switch is off
}
//else
{
// something else happened acquring the location
}
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private async void StartSending_Click(object sender, RoutedEventArgs e)
{
await GetLocation();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
StartSending.IsEnabled = false;
}
async void timer_Tick(object sender, object e)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Visible;
await GetLocation();
}
private void EndSending_Click(object sender, RoutedEventArgs e)
{
timer.Tick -= timer_Tick;
timer.Stop();
StartSending.IsEnabled = true;
EndSending.IsEnabled = false;
}
private void GPS_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(ContactPage));
}
}
Thanks for your help!
Did you try out the Geolocator.DesiredAccuracyInMeters property?
geolocator.DesiredAccuracyInMeters = 3;
Reference & Sample
In this point LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
You indicated that you have 0.00 decimals, for more accuracy you should put 0.000000

How to convert .aspx to Image in asp.net with forms authentication

I have tried this code
public System.Drawing.Bitmap CaptureWebPage(string URL)
{
// create a hidden web browser, which will navigate to the page
System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
// we don't want scrollbars on our image
web.ScrollBarsEnabled = false;
// don't let any errors shine through
web.ScriptErrorsSuppressed = true;
// let's load up that page!
web.Navigate(URL);
// wait until the page is fully loaded
while (web.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(1500); // allow time for page scripts to update
// the appearance of the page
// set the size of our web browser to be the same size as the page
int width = web.Document.Body.ScrollRectangle.Width;
int height = web.Document.Body.ScrollRectangle.Height;
web.Width = width;
web.Height = height;
// a bitmap that we will draw to
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
// draw the web browser to the bitmap
web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));
return bmp; // return the bitmap for processing
}
protected void btnConvert_Click(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(CaptureWebPage(txtUrl.Text));
Response.ContentType = "image/jpeg";
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
bitmap.Dispose();
bitmap.Dispose();
Response.End();
}
I am able to capture google.com,but not able to capture images of our web site since it contains form authentication so it redirects me to login page and login page is captured.Please help to pass through authentication.Can we use sessions,cookies or anything with the WebBrowser to valid it Or something.Please suggest.
Try on the intended page on your website :
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
Page.RenderControl(new HtmlTextWriter(sw));
and then use the HTML in the string builder to render the page like the example below (Reference : Convert HTML string to image) :
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
var source = #"
<!DOCTYPE html>
<html>
<body>
<p>An image from W3Schools:</p>
<img
src=""http://www.w3schools.com/images/w3schools_green.jpg""
alt=""W3Schools.com""
width=""104""
height=""142"">
</body>
</html>";
StartBrowser(source);
Console.ReadLine();
}
private static void StartBrowser(string source)
{
var th = new Thread(() =>
{
var webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.DocumentCompleted +=
webBrowser_DocumentCompleted;
webBrowser.DocumentText = source;
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
static void
webBrowser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = (WebBrowser)sender;
using (Bitmap bitmap =
new Bitmap(
webBrowser.Width,
webBrowser.Height))
{
webBrowser
.DrawToBitmap(
bitmap,
new System.Drawing
.Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"filename.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}

Use Google Map in Blackberry application

Can anyone tell me how to use Google maps in blackberry application development instead of Blackberry map?
Recently I had an idea to use Google Maps website from Browser.Field but it's not possible since GMaps are based on JavaScript and it's badly supported by Blackberry native Browser.
Actually there are 2 ways of using Google Maps on Blackberry:
install Google Maps Mobile application (see example of use)
use Google Static Maps API to generate and send image on device request. This will require server-side implementation and Sign Up for the Google Maps API
Here is a little example:
The Form to view the Google Maps Static image:
public class frmMap extends Form implements CommandListener {
Command _back;
MIDlet midlet;
Form dis;
public frmMap(String title, ImageItem img, MIDlet m, Form d){
super(null);
this.midlet = m;
this.dis = d;
_back = new Command("Back", Command.BACK, 1);
addCommand(_back);
append(img);
setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if(c == _back){
Display.getDisplay(midlet).setCurrent(dis);
}
}
}
The class inet class to download the static image:
public class INETclass implements Runnable {
private String _location = null;
private HttpConnection inet;
private Pispaal _m;
public String url = null;
public INETclass(String location, Pispaal m){
_location = location;
_m = m;
}
public void run() {
try
{
//Setup the connection
inet = (HttpConnection)Connector.open(url);
inet.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
int rc = inet.getResponseCode();
//Responsecode controleren
if(rc == HttpConnection.HTTP_OK){
//Open input stream to read the respone
DataInputStream is = new DataInputStream(inet.openInputStream());
StringBuffer sb = new StringBuffer();
int ch;
long len = -1;
byte[] buffer = null;
if(_location == null){
len = is.available();
}
if(len != -1){
if(_location == null){
buffer = IOUtilities.streamToBytes(is);
}else{
while((ch = is.read()) != -1){
sb.append((char)ch);
}
}
}
is.close();
if(_location == null){
_m.OnINETComplete(buffer);
}else{
_m.Alert(sb.toString());
}
}else{
_m.Alert("URL " + url + " geeft response code: " + rc);
try
{
inet.close();
}catch(Exception e){
_m.Alert("Error: " + e.getMessage());
}
}
}
catch(Exception e)
{
_m.Alert("Error: " + e.getMessage());
System.out.println("Error: " + e.getMessage());
}
finally
{
try
{
if(inet != null){ inet.close(); }
Thread.currentThread().join(); //Making sure this thread dies
}catch(Exception e){
_m.Alert("Error: " + e.getMessage());
System.out.println("Error: " + e.getMessage());
}
}
}
}
The Button action that starts the download and the callback action that loads the form to view the image
public void commandAction(Command c, Displayable d) {
synchronized(c){
String loc = _location.getText();
if(loc.indexOf(",") > 0){
//if(c == _strCommand){
//INETclass inet = new INETclass(loc, this);
//Thread tInet = new Thread(inet);
//tInet.start();
//Alert("Locatie word doorgestuurd. Even geduld");
//}else
if(c == _mapView){
INETclass inet = new INETclass(null, this);
inet.url = "http://www.qeueq.com/gmap.php?location=" + this.lat + "," + this.lon + "&size=" + this.width + "x" + this.height + ";deviceside=true";
Thread tInet = new Thread(inet);
tInet.start();
}
}else{
Alert("GPS locatie is nog niet beschikbaar.");
}
}
}
public void UpdateLocation(double lat, double lon){
String location = lat + "," + lon;
this.lat = lat;
this.lon = lon;
synchronized(location){
_location.setText(location);
INETclass inet = new INETclass(location, this);
Thread tInet = new Thread(inet);
tInet.start();
}
}
Refine and edit the code so it fits your needs. Took me some time to get it right.
It is possible now to use Google Maps instead of BlackBerry maps with our own data like in the image.
If you're looking to use google maps to show your own locations/markers you can invoke google maps using ApplicationDescriptor from your application. Check for google maps on device using CodeModuleManager.getModuleHandle("GoogleMaps"); it returns an integer where non zero means it is available. Then you can add locations in your KML file, you can even customize location pointers using KML file tags.
The example as linked by Max allows a single marker only. So a KML file becomes necessary if multiple markers are to be added.
You may look at the simple tutorial here for beginners.