Taking screenshot of windows phone 7.5 and sending over through TCP - windows-phone-7

i am stuck on how to take a screenshot of my windows phone 7.5 and sending it over TCP. i have no experience in doing socket program and I/O and am doing what i can through tutorials over the internet. This is what i have done.
From the codes below i am stuck in how i can send the writeableBitMap over TCP encoded as a Jpeg periodically running in the WP7.5 background, whereby a program on a desktop will receive it as a jpeg image so it can be displayed creating a windows phone to desktop streaming effect.
my mainPage of my windows phone 7.5 application using a library i have created from a tutorial for taking care of the sockets connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone;
using System.Windows.Media;
using System.IO;
namespace helloworld
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
SocketLibrary.socketLib sl = new SocketLibrary.socketLib();
private string hostIP = "127.0.0.1";
public MainPage()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, RoutedEventArgs e)
{
bool retVal;
retVal = sl.EstablishTCPConnection(hostIP);
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
var ms = new MemoryStream();
// Send the picture.
bmpCurrentScreenImage.SaveJpeg(ms, bmpCurrentScreenImage.PixelWidth, bmpCurrentScreenImage.PixelHeight, 0, 90);
ms.Seek(0, SeekOrigin.Begin);
retVal = sl.Send(ms);
sl.CloseSocket();
}
}
}
the socket library
namespace SocketLibrary
{
public class socketLib
{
Socket s = null;
static ManualResetEvent done = new ManualResetEvent(false);
private Int16 portNo = 3334;
public socketLib()
{
}
public bool EstablishTCPConnection(string host)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new DnsEndPoint(host, portNo);
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
done.Reset();
s.ConnectAsync(socketEventArg);
return done.WaitOne(10000);
}
public bool Send(MemoryStream data)
{
byte[] msData = data.ToArray();
if (s != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = s.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
socketEventArg.SetBuffer(msData, 0, msData.Length);
done.Reset();
s.SendAsync(socketEventArg);
return done.WaitOne(10000);
}
return false;
}
public void CloseSocket()
{
if (s != null)
{
s.Close();
}
}
}
}

check this
http://www.charlespetzold.com/blog/2011/05/Windows-Phone-Screen-Shots.html
http://blog.galasoft.ch/archive/2010/12/28/taking-a-screenshot-from-within-a-silverlight-wp7-application.aspx

Related

ASP.NET Boilerplate background jobs abandoned

I am using asp.net boilerplate and running a background job that posts data to an external API.
The post is happening correctly but the background job is still been abandoned instead of deleting it from the backgroundjobs table.
Is there a way to force a successful job execution and only abandon it if it fails.
Code Below
using Abp.Reflection.Extensions;
using EErx.Middleware.RestAPIClient.Dto;
using Erx.Middleware.Configuration;
using Erx.Middleware.Models;
using Erx.Middleware.RestAPIClient.Dto;
using Erx.Middleware.TCPCommunicator.Models;
using Microsoft.Extensions.Configuration;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
namespace Erx.Middleware.TCPCommunicator.Jobs
{
public class PDStatusUpdateJob : BackgroundJob<PDUpdateJobArgs>, ITransientDependency
{
private readonly Log _log;
private readonly IConfigurationRoot _appConfiguration;
private readonly IRepository<DispenseMessageHeader, long> _dispenseMessageHeaderRepository;
private readonly IRepository<DispenseMessageScript, long> _dispenseMessageScriptRepository;
private readonly IObjectMapper _objectMapper;
public PDStatusUpdateJob(
Log log,
IRepository<DispenseMessageHeader, long> dispenseMessageHeaderRepository,
IRepository<DispenseMessageScript, long> dispenseMessageScriptRepository,
IObjectMapper objectMapper
)
{
_log = log;
_dispenseMessageHeaderRepository = dispenseMessageHeaderRepository;
_dispenseMessageScriptRepository = dispenseMessageScriptRepository;
_objectMapper = objectMapper;
_appConfiguration = AppConfigurations.Get(
typeof(TcpCommunicatorModule).GetAssembly().GetDirectoryPathOrNull()
);
}
[UnitOfWork]
public override void Execute(PDUpdateJobArgs args)
{
try
{
var output = new PDDispenseMessageDto();
var scriptOutput = new List<PDDispenseMessageScriptDto>();
var headerRecord = _dispenseMessageHeaderRepository.FirstOrDefault(x => x.MessageGuid == args.MessageGuid);
var dispenseMessage = _objectMapper.Map(headerRecord, output);
var scripts = _dispenseMessageScriptRepository.GetAllIncluding(p => p.Items).Where(x => x.DispenseMessageHeaderId == headerRecord.Id).ToList();
dispenseMessage.Scripts = _objectMapper.Map(scripts, scriptOutput);
var request = new RestRequest(Method.POST);
var requestMsg = dispenseMessage.ToJsonString(true);
var client = new RestClient(_appConfiguration.GetValue<string>("PDUpdateAPI"))
{
Timeout = -1,
RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
};
request.AddHeader("Authorization", "Basic " + GenerateToken());
request.AddHeader("EntityDescription", "ERX");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json; charset=utf-8", requestMsg, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
if (response.ErrorMessage != null)
{
_log.Logger.Error(response.ErrorMessage);
}
}
catch (Exception e)
{
_log.Logger.Error(e.Message);
}
}
public static string GenerateToken()
{
var encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes("somestring"));
return encoded;
}
}
}

Asp.net-core api response WaitingForActivision

Can someone point me into the right direction what I am doing wrong in this Api call? I am getting an odd error that I don’t know what it means. The api call should work as I tested it using VBA and I get a response with the payload. Also any feedback is welcomed.
Id = 190, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" - this is the response I am getting back from it
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Xml.Linq;
namespace BarcodeScanner.Classes
{
public class Api : IDisposable
{
private readonly TimeSpan _timeout;
private HttpClient _httpClient;
private HttpClientHandler _httpClientHandler;
private readonly string _baseUrl;
private readonly string _credentials;
private const string MediaTypeXml = "application/xml";
public Api(string baseUrl, string authToken, TimeSpan? timeout = null)
{
_baseUrl = NormaliseBaseUrl(baseUrl);
_credentials = Base64Encode(authToken);
_timeout = timeout ?? TimeSpan.FromSeconds(90);
}
public async Task<string> GetAsync(string url)
{
EnsureHttpClientCreated();
using (var response = await _httpClient.GetAsync(url).ConfigureAwait(continueOnCapturedContext: false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
public void Dispose()
{
_httpClientHandler?.Dispose();
_httpClient?.Dispose();
}
private void CreateHttpClient()
{
_httpClientHandler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
};
_httpClient = new HttpClient(_httpClientHandler, false)
{
Timeout = _timeout
};
if (!string.IsNullOrWhiteSpace(_baseUrl))
{
_httpClient.BaseAddress = new Uri(_baseUrl);
}
_httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + _credentials);
}
private void EnsureHttpClientCreated()
{
if (_httpClient == null)
{
CreateHttpClient();
}
}
//call the api
try
{
using (var client = new Api(requestUrl, authToken))
{
var response = client.GetAsync(requestUrl);
}
}
catch (Exception err)
{
throw new Exception("Something went wrong: ", err);
}

While navigating to Register Player details screen, throws object reference error in Xamarin.Forms

On click on the Register_OnClicked button in the Xamarin.Forms app, system throws System.NullReferenceException: Object reference not set to an instance of an object This button will allow app to navigate to Player Register details screen from where the system save data. Could someone please advise about the cause of the error? I couldn't figure out the reason for that error yet, have restarted the app, perform the clean buildoperation, but still the same.
Database library using : sqlite-net-pcl
//MainPage.xaml.cs details
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
public async void NavigateButton_OnClicked(object sender, EventArgs e)
{
var tabbedPage = new TabbedPage();
tabbedPage.Children.Add(new Home("Welcome"+' '+emailEntry.Text+' '+",have a nice day!"));
tabbedPage.Children.Add(new Map());
tabbedPage.Children.Add(new Settings());
await Navigation.PushAsync(tabbedPage);
}
public async void Register_OnClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new Register());
}
}
Register.xaml.cs details where the saving of Player details:
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Linq;
namespace soccerapp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Register : ContentPage
{
public SQLiteConnection conn;
public Register()
{
InitializeComponent();
conn = DependencyService.Get<Isqlite>().GetConnection();
conn.CreateTable<PlayerDetails>();
}
public void RegisterSave_OnClicked(object sender, EventArgs e)
{
PlayerDetails playerDetails = new PlayerDetails();
playerDetails.FullName = fullNameEntry.Text;
playerDetails.Mobile = mobileEntry.Text;
playerDetails.SoccerPosition = soccerpostionEntry.Text;
playerDetails.Email = emailRegister.Text;
playerDetails.Password = passwordEntry.Text;
int x = 0;
try
{
x = conn.Insert(playerDetails);
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
DisplayAlert("Registration", "Player Registered Successfully", "Cancel");
}
else
{
DisplayAlert("Registration Failled!!!", "Please try again", "ERROR");
}
}
}
}
SQlite Connection class created and return connection:
public class SQliteDroid : Isqlite
{
public SQLiteConnection GetConnection()
{
var dbase = "soccerpep";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(dbpath, dbase);
var connection = new SQLiteConnection(path);
return connection;
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nZ8GZ.png
Error details from Debug > Windows > Call Stack add below;
0xFFFFFFFFFFFFFFFF in System.Diagnostics.Debugger.Mono_UnhandledException_internal C#
0x1 in System.Diagnostics.Debugger.Mono_UnhandledException C#
0x20 in Android.Runtime.DynamicMethodNameCounter.43 C#
0x12 in System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw C#
0x6 in System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0 C#
0xC in Android.App.SyncContext. C#
0xE in Java.Lang.Thread.RunnableImplementor.Run C#
0xA in Java.Lang.IRunnableInvoker.n_Run C#
0x11 in Android.Runtime.DynamicMethodNameCounter.43 C#
Debug through the Constructor for your Register page, and the GetConnection method of your SqliteDroid class.
I've seen hard-to-find errors like this when the Dependency Injection fails. This could be either because of an error in GetConnection, or because SqliteDroid has not been registered in your DependencyService.

Weird and Annoying IsolatedStorageError

Update
I added the piece of code/function that normally throws the error.
can someone please help.
Before I begin, I have spent over 20+ hours researching this issue.
I am developing a windows phone app and I keep getting a lot of IsolatedStorage Exceptions, especially "Operation not supported on IsolatedStorageFileStream".
The Scenario
I have an object that has a ProfilePictureUrl as a property, every time I create an instance of the object I download the profile image from the web, then I will store that image to the Isolated storage.
Sample Code
foreach(String url in urls)
{
var profile = new MyClass()
{
ProfilePictureURL = url
};
profile.DownloadProfilePictureToLocalStorage(() =>
{
completed(profile);
}, (ex) => { incomplete(ex); });
}
The Code that throws the Exception
if (isoFile.FileExists(saveAs))
isoFile.DeleteFile(saveAs);
using (var isoFileStream = isoFile.CreateFile(saveAs))
{
var width = wb.PixelWidth;
var height = wb.PixelHeight;
Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
This is inside the DownloadImageToIsolatedStorage function in the LocalStorageManager class.
Here is the class that manages my IsolatedStorage storing
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Media.Imaging;
namespace Classes.Managers
{
public delegate void GetImageCompletedDelegate(BitmapImage bmp);
public delegate void GetImageNotCompletedDelegate(Exception ex);
public delegate void SaveImageCompletedDelegate();
public delegate void SaveImageNotCompletedDelegate(Exception ex);
public delegate void DeleteImageCompletedDelegate();
public delegate void DeleteImageNotCompletedDelegate(Exception ex);
class LocalStorageManager
{
private static readonly LocalStorageManager _instance = new LocalStorageManager();
public static LocalStorageManager Instance
{
get
{
return _instance;
}
}
private bool m_IsBusy;
public bool IsBusy
{
get { return m_IsBusy; }
private set { m_IsBusy = value; }
}
private void GetImageFromIsolatedStorage(String name, GetImageCompletedDelegate completed, GetImageNotCompletedDelegate notCompleted)
{
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
BitmapImage img = new BitmapImage();
if (isoFile.FileExists(name))
{
using (IsolatedStorageFileStream fileStream = isoFile.OpenFile(name, FileMode.Open, FileAccess.Read))
{
img.SetSource(fileStream);
}
}
completed(img);
}
}
catch (Exception ex) { notCompleted(ex); }
}
public void DownloadImageToIsolatedStorage(String url, string saveAs, SaveImageCompletedDelegate completed, SaveImageNotCompletedDelegate notCompleted)
{
try
{
this.IsBusy = true;
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.BeginGetResponse((callback) =>
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(callback);
var bi = new BitmapImage();
bi.SetSource(response.GetResponseStream());
var wb = new WriteableBitmap(bi);
if (isoFile.FileExists(saveAs))
isoFile.DeleteFile(saveAs);
using (var isoFileStream = isoFile.CreateFile(saveAs))
{
var width = wb.PixelWidth;
var height = wb.PixelHeight;
Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
this.IsBusy = false;
completed();
}
});
}, null);
}
catch (Exception e) { this.IsBusy = false; notCompleted(e); }
}
public void MoveFile(String source, String destination)
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(source))
{
isoFile.MoveFile(source, destination);
}
}
}
private void WriteImageStreamToIsolatedStorage(Stream imageStream, string saveAs, SaveImageCompletedDelegate completed, SaveImageNotCompletedDelegate notCompleted)
{
try
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(saveAs))
isolatedStorage.DeleteFile(saveAs);
var fileStream = isolatedStorage.CreateFile(saveAs);
imageStream.CopyTo(fileStream);
fileStream.Close();
/*
BitmapImage bmp = null;
bmp.SetSource(imageStream);
var writeableBMP = new WriteableBitmap(bmp);
writeableBMP.SaveJpeg(fileStream, writeableBMP.PixelWidth, writeableBMP.PixelHeight, 0, 100);
fileStream.Close();*/
}
completed();
}
catch (Exception ex) { notCompleted(ex); }
}
private void DeleteImageFromIsolatedStorage(string imageName, DeleteImageCompletedDelegate completed, DeleteImageNotCompletedDelegate notCompleted)
{
try
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(imageName))
isolatedStorage.DeleteFile(imageName);
completed();
}
}
catch (Exception e) { notCompleted(e); }
}
}
}
Here is the class for my objects
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.Runtime.Serialization;
using System.IO.IsolatedStorage;
using System.Net;
namespace Classes.Model
{
public class MyClass : INotifyPropertyChanged
{
private string m_ProfilePictureURL;
public string ProfilePictureURL
{
get { return m_ProfilePictureURL; }
set
{
if (m_ProfilePictureURL == value)
return;
m_ProfilePictureURL = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("ProfilePictureURL"));
}
}
[IgnoreDataMember]
public BitmapImage LocalProfilePicture
{
get
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(isoFile.OpenFile("ProfilePic_" + this.UUID, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite));
return bitmapImage;
}
catch (Exception ex)
{
isoFile.Dispose();
return null;
}
}
}
}
public void DownloadProfilePictureToLocalStorage(SaveImageCompletedDelegate completed, SaveImageNotCompletedDelegate notCompleted)
{
// Wait till its no longer busy
while (LocalStorageManager.Instance.IsBusy) ;
if (!String.IsNullOrWhiteSpace(this.ProfilePictureURL) && !String.IsNullOrWhiteSpace(this.UUID))
{
LocalStorageManager.Instance.DownloadImageToIsolatedStorage(this.ProfilePictureURL, "ProfilePic_" + this.UUID, () =>
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("LocalProfilePicture"));
completed();
}, (ex) => { notCompleted(ex); });
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}

How to make back button return to the system Windows Phone

I have a small app there is 3 seconds intro page, then the content page. When I push back button I go back to the intro screen, but I think I should go back to the system. How to do it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ServiceModel.Syndication;
using System.Xml;
using Microsoft.Phone.Tasks;
namespace RSS {
public partial class FeedPage : PhoneApplicationPage {
public FeedPage() {
InitializeComponent();
this.Loaded += new RoutedEventHandler(PhonePage1_Loaded);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
clearBackStack();
base.OnNavigatedTo(e);
}
void clearBackStack() {
while (this.NavigationService.BackStack.Any()) {
this.NavigationService.RemoveBackEntry();
}
}
void PhonePage1_Loaded(object sender, RoutedEventArgs e) {
// clearBackStack();
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("http://www.carmagazine.co.uk/Shared/Handlers/RssHandler.ashx?&N=190&Ns=P_Publication_Date|1&?"));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
SyndicationFeed feed;
try {
using (XmlReader reader = XmlReader.Create(e.Result)) {
feed = SyndicationFeed.Load(reader);
lista.ItemsSource = feed.Items;
}
} catch (WebException we) { MessageBox.Show("Internet connection is down.");}
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e) {
WebBrowserTask webBrowserTask = new WebBrowserTask();
String url = (String)((Button)sender).Tag;
webBrowserTask.Uri = new Uri(url);
webBrowserTask.Show();
}
}
}
You should clear the BackStack in the OnNavigateTo method of your content page
while (this.NavigationService.BackStack.Any())
{
this.NavigationService.RemoveBackEntry();
}
The following code is the best practice for the back button key press.
protected override void OnBackKeyPress(CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
base.OnBackKeyPress(e);
}
This ensures that your application will exit and return to the main screen on pressing the BackKey.

Resources