Clickable URL in Windows Phone Message box - windows-phone-7

I want to display an URL in my message box that the user can click and navigate to on Wp7 mango. Is this Possible? If yes how do i implement it ?
My message box is coded as below:
public static void customizedMessageBox(int messageboxtype, string title, string text, IEnumerable<string> buttons, int focusbutton, MessageBoxIcon icon, AsyncCallback callback, object state)
{
if (!Guide.IsVisible)
{
try
{
ProgressBarControl.dismissProgressBar();
Guide.BeginShowMessageBox(" ", text, buttons, focusbutton, MessageBoxIcon.None, callback, state);
messageboxType = messageboxtype;
}
catch (GuideAlreadyVisibleException ex)
{
Logger.log("MsgBox", "Exception : messageboxtype: " + messageboxtype
+ "\n" + ex.Message + "\n" + ex.StackTrace);
}
}
//return messageboxtype;
}
public static void OnMessageBoxClosed(IAsyncResult ar)
{
int? dialogResult = Guide.EndShowMessageBox(ar);
Game game;
try
{
Logger.log("MsgBox", "result: " + dialogResult + " msg type: " + messageboxType);
switch (messageboxType)
{ case 7:
//ERROR E4000 case
switch (dialogResult)
{
case 0:
string url;
//url = CacheManager.getInstance().getApplicationSettings(CacheManager.APP_APK_UPGRADE_URI);
url = DataManager.URL_VALUE;
if (Utils.isNullString(url))
{
//url = CacheManager.getInstance().getUpgradeURL();
}
WebBrowserTask browse = new WebBrowserTask();
browse.URL = url;
browse.Show();
break;
default:
//delete data from the DB
ProgressBarControl.displayProgressBar(0, 10, AppResources.DOWNLOADING);
try
{
//byte[] data = (byte[])CacheManager.getInstance().getPersistanceData(Utils.MINOR_UPGRADE_DATA);
byte[] data = (byte[])CacheManager.getInstance().getDataFromDataFile();
if (data != null && data.Length > 0)
{
DataManager.getInstance().processMyWidgetResponse(data);
DataManager.getInstance().refresUI();
}
}
catch (Exception ex)
{
}
finally
{
//CacheManager.getInstance().deletaFromApplicationCache(Utils.MINOR_UPGRADE_DATA);
}
break;
}
break;
default:
break;
}
}
catch (Exception ex)
{
Logger.log(TAG, ex.Message);
}
finally
{
ProgressBarControl.dismissProgressBar();
}
}
I am calling the messagebox like this:-
UIListen.customizedMessageBox(Utils.ERROR_CODE_E4000, ERROR_FORCE_REGISTRATION, responseHeaders[HEADER_URL_NAME, 1], Utils.valuesOk, 0);

take a look a this: http://coding4fun.codeplex.com/
explore different kind of custom dialogs\message boxed he made. You can take this as ref and make your own or you can directly use the existing one.

consider showing a custom screen or xaml page which gives user the correct options. You can provide whatever options you want. Buttons etc .

Related

How can I share an event handler?

private void ExitAndSave(object sender, EventArgs e)
{
foreach (Form form in MdiChildren)
{
if (form is TextForm tf)
{
tf.BringToFront();
DialogResult dr = MessageBox.Show("Do you want to save your document?", "Save document?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
//counter++;
var textBoxValue = tf.FetchTextBoxValue();
//string filePath = $"{DateTime.Now.Ticks.ToString()}.txt";
string filePath = $"composition{DateTime.Now.Ticks.ToString()}.txt";
File.WriteAllText(filePath, textBoxValue);
}
if (dr == DialogResult.No)
{
continue;
}
}
else if (form is ImageDocumentForm)
{
MessageBox.Show("Please note that only text documents can be saved.", "Advisory:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Close();
}
This code works fine. I need it to be called when the user exits the program. I'm not able to assign this event to the form closing event in the design view.
Your event argument needs to be of the form FormClosingEventArgs e
Change that and try again.

pull images from twitter API on processing 3

I am quite new to this so please bear with me. I am trying to use a keyword search to pull images from twitter using twitter4j. I want it to show the images positioned randomly on the screen in a loop.
This code I have below is a combination of different ones I have found online. Its currently finding tweets using these keywords and showing them in the console, however, it is not displaying them on the screen and I’m not sure why…
Another thing is that I think it is doing a live stream from twitter so pulling tweets immediately at the time the code is run, so I am not getting lots of results when I put in an obscure keyword, I want it to search for the last 100 tweets with images using the keyword so that I get more results
I’d really appreciate all the help I can get! thank you
///////////////////////////// Config your setup here! ////////////////////////////
// { site, parse token }
String imageService[][] = {
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://img.ly",
"<img alt=\"\" id=\"the-image\" src=\""
},
{
"http://lockerz.com/",
"<img id=\"photo\" src=\""
},
{
"http://instagr.am/",
"<meta property=\"og:image\" content=\""
} {
"http://pic.twitter.com",
"<img id
};
// This is where you enter your Oauth info
static String OAuthConsumerKey = KEY_HERE;
static String OAuthConsumerSecret = SECRET_HERE;
static String AccessToken = TOKEN_HERE;
static String AccessTokenSecret = TOKEN_SECRET_HERE;
cb.setIncludeEntitiesEnabled(true);
Twitter twitterInstance = new TwitterFactory(cb.build()).getInstance();
// if you enter keywords here it will filter, otherwise it will sample
String keywords[] = {
"#hashtag" //sample keyword!!!!!!!!
};
///////////////////////////// End Variable Config ////////////////////////////
TwitterStream twitter = new TwitterStreamFactory().getInstance();
PImage img;
boolean imageLoaded;
void setup() {
frameRate(10);
size(800, 600);
noStroke();
imageMode(CENTER);
connectTwitter();
twitter.addListener(listener);
if (keywords.length == 0) twitter.sample();
else twitter.filter(new FilterQuery().track(keywords));
}
void draw() {
background(0);
if (imageLoaded) image(img, width / 5, height / 5);
//image(loadImage((status.getUser().getImage())), (int)random(width*.45), height-(int)random(height*.4));
}
// Initial connection
void connectTwitter() {
twitter.setOAuthConsumer(OAuthConsumerKey, OAuthConsumerSecret);
AccessToken accessToken = loadAccessToken();
twitter.setOAuthAccessToken(accessToken);
}
// Loading up the access token
private static AccessToken loadAccessToken() {
return new AccessToken(AccessToken, AccessTokenSecret);
}
// This listens for new tweet
StatusListener listener = new StatusListener() {
//#Override
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
//#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
//#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
//#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
//#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
//#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
public void onStatus(Status status) {
String imgUrl = null;
String imgPage = null;
// Checks for images posted using twitter API
if (status.getMediaEntities() != null) {
imgUrl = status.getMediaEntities()[0].getMediaURL().toString();
}
// Checks for images posted using other APIs
else {
if (status.getURLEntities().length > 0) {
if (status.getURLEntities()[0].getExpandedURL() != null) {
imgPage = status.getURLEntities()[0].getExpandedURL().toString();
} else {
if (status.getURLEntities()[0].getDisplayURL() != null) {
imgPage = status.getURLEntities()[0].getDisplayURL().toString();
}
}
}
if (imgPage != null) imgUrl = parseTwitterImg(imgPage);
}
if (imgUrl != null) {
println("found image: " + imgUrl);
// hacks to make image load correctly
if (imgUrl.startsWith("//")) {
println("s3 weirdness");
imgUrl = "http:" + imgUrl;
}
if (!imgUrl.endsWith(".jpg")) {
byte[] imgBytes = loadBytes(imgUrl);
saveBytes("tempImage.jpg", imgBytes);
imgUrl = "tempImage.jpg";
}
println("loading " + imgUrl);
img = loadImage(imgUrl);
imageLoaded = true;
}
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
public void onException(Exception ex) {
ex.printStackTrace();
}
// Twitter doesn't recognize images from other sites as media, so must be parsed manually
// You can add more services at the top if something is missing
String parseTwitterImg(String pageUrl) {
for (int i = 0; i < imageService.length; i++) {
if (pageUrl.startsWith(imageService[i][0])) {
String fullPage = ""; // container for html
String lines[] = loadStrings(pageUrl); // load html into an array, then move to container
for (int j = 0; j < lines.length; j++) {
fullPage += lines[j] + "\n";
}
String[] pieces = split(fullPage, imageService[i][1]);
pieces = split(pieces[1], "\"");
return (pieces[0]);
}
}
return (null);
}

MediaFormat options, the KEY_ROTATION is not work

The current image is encoded and stored in the output buffer as it is.
However, Samsung (Galaxy S6(Nouga), 7(Nouga), 8(Nouga)) KEY_ROTATION option works well,
This option does not work on the Google reference phone (Pixel 2 XL -> Oreo, Nexus 5 -> Lollipop).
In other words, while the KEY_ROTATION option works well on the Samsung device, the value output to the output buffer is rotated,
This option does not work on Google reference phones.
The surface created by encoderSurface () serves as an input buffer
Check the output buffer through onOutputBufferAvailable of MediaCodec.Callback.
Anyone who knows the reason needs help.
Here is the code I wrote.
private final MediaCodec.Callback _mediaCodecCallback = new MediaCodec.Callback() {
#Override
public void finalize(){
}
#Override
public void onInputBufferAvailable(#NonNull MediaCodec mediaCodec, int i) {
}
#Override
public void onOutputBufferAvailable(#NonNull MediaCodec mediaCodec, int i, #NonNull MediaCodec.BufferInfo bufferInfo) {
ByteBuffer buffer = mediaCodec.getOutputBuffer(i);
byte[] outData = new byte[bufferInfo.size];
buffer.get(outData);
mediaCodec.releaseOutputBuffer(i, false);
switch (bufferInfo.flags) {
case MediaCodec.BUFFER_FLAG_CODEC_CONFIG:
if(DEBUG_LOG) {
Log.v(TAG, "CONFIG FRAME");
}
_configFrame = new byte[bufferInfo.size];
System.arraycopy(outData, 0, _configFrame, 0, outData.length);
break;
case MediaCodec.BUFFER_FLAG_KEY_FRAME:
// I Frame;
if(DEBUG_LOG) {
Log.v(TAG, "I FRAME" +
", SIZE = " + bufferInfo.size + ", " + currentDateandTime);
}
try {
_outputFrame.reset();
_outputFrame.write(_configFrame);
_outputFrame.write(outData);
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
// P Frame;
if(DEBUG_LOG) {
Log.v(TAG, "P FRAME" +
", SIZE = " + bufferInfo.size);
}
break;
}
}
//
public boolean initialize(int width,int height) {
try {
_mediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
} catch (IOException e) {
e.printStackTrace();
return false;
}
MediaCodecInfo codec = selectCodec(MIME_TYPE);
if (codec == null) {
return false;
}
MediaCodecInfo.CodecCapabilities cap = codec.getCapabilitiesForType(MIME_TYPE);
MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRateInfo.getInstance().getBitRate()); // 300000
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
mediaFormat.setInteger(MediaFormat.KEY_ROTATION, 90);
// in under API 21, not use MediaFormat.KEY_ROTATION, but use "rotation-degrees"
// This does not work on a Google reference phone.
_mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
_surface = _mediaCodec.createInputSurface();
_mediaCodec.setCallback(_mediaCodecCallback);
_mediaCodec.start();
Log.d(TAG,"Encoder Start SUCCESS");
return true;
}
public Surface encoderSurface() {
//Return the value of this function and use it as the input surface.
return _surface;
}
please Help me ..

Transferring assets : Error code 4005 ASSET_UNAVAILABLE

This is driving me crazy. I wrote a code quite a while ago that was working, and opened it again and it happens that I am not able to transfer my assets from the mobile to the wearable device.
public Bitmap loadBitmapFromAsset(Asset asset) {
if (asset == null) {
throw new IllegalArgumentException("Asset must be non-null");
}
// convert asset into a file descriptor and block until it's ready
Log.d(TAG, "api client" + mApiClient);
DataApi.GetFdForAssetResult result = Wearable.DataApi.getFdForAsset(mApiClient, asset).await();
if (result == null) {
Log.w(TAG, "getFdForAsset returned null");
return null;
}
if (result.getStatus().isSuccess()) {
Log.d(TAG, "success");
} else {
Log.d(TAG, result.getStatus().getStatusCode() + ":" + result.getStatus().getStatusMessage());
}
InputStream assetInputStream = result.getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
// decode the stream into a bitmap
return BitmapFactory.decodeStream(assetInputStream);
}
And this is the code from which I call the loadBitmapFrom Asset method.
DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
ArrayList<DataMap> dataMaps = dataMap.getDataMapArrayList("dataMaps");
ArrayList<String> names = new ArrayList<>();
ArrayList<String> permalinks = new ArrayList<>();
ArrayList<Asset> images = new ArrayList<>();
for (int i = 0 ; i < dataMaps.size() ; i++) {
Log.d(TAG, dataMaps.get(i).getString("name"));
names.add(dataMaps.get(i).getString("name"));
permalinks.add(dataMaps.get(i).getString("permalink"));
images.add(dataMaps.get(i).getAsset("image"));
}
editor.putInt("my_selection_size", names.size());
for (int i=0; i <names.size() ; i++) {
editor.putString("my_selection_name_" + i, names.get(i));
editor.putString("my_selection_permalink_" + i, permalinks.get(i));
Log.d(TAG, "asset number " + i + " " + images.get(i));
Bitmap bitmap = loadBitmapFromAsset(images.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
editor.putString("my_selection_image_" + i, encoded);
}
And on the mobile side :
private void sendData(PutDataMapRequest dataMap) {
PutDataRequest request = dataMap.asPutDataRequest();
request.setUrgent();
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mApiClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
com.orange.radio.horizon.tools.Log.d(TAG, "api client : " + mApiClient);
if (dataItemResult.getStatus().isSuccess()) {
com.orange.radio.horizon.tools.Log.d(TAG, "message successfully sent");
} else if (dataItemResult.getStatus().isInterrupted()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (interrupted)");
} else if (dataItemResult.getStatus().isCanceled()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (canceled)");
}
}
});
Log.d(TAG, "Sending data to android wear");
}
class ConfigTask extends AsyncTask<String, Void, String> {
ArrayList<WatchData> mitems;
int mType;
public ConfigTask(ArrayList<WatchData> items, int type)
{
mitems = items;
mType = type;
}
protected String doInBackground(String... str)
{
DataMap dataMap;
ArrayList<DataMap> dataMaps = new ArrayList<>();
Bitmap bitmap = null;
for (int i = 0 ; i < mitems.size() ; i++) {
dataMap = new DataMap();
URL url = null;
try {
url = new URL(mitems.get(i).mUrlSmallLogo);
Log.d(TAG, "url : " + url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Asset asset = createAssetFromBitmap(bitmap);
dataMap.putAsset("image", asset);
dataMap.putString("name", mitems.get(i).mName);
dataMap.putString("permalink", mitems.get(i).mPermalink);
dataMaps.add(dataMap);
}
PutDataMapRequest request = null;
switch (mType) {
case 0 :
request = PutDataMapRequest.create(SELECTION_PATH);
break;
case 1 :
request = PutDataMapRequest.create(RADIOS_PATH);
break;
case 2 :
request = PutDataMapRequest.create(PODCASTS_PATH);
break;
}
request.getDataMap().putDataMapArrayList("dataMaps", dataMaps);
request.getDataMap().putString("", "" + System.currentTimeMillis()); //random data to refresh
Log.d(TAG, "last bitmap : " + bitmap);
Log.d(TAG, "===============================SENDING THE DATAMAP ARRAYLIST==================================");
sendData(request);
return "h";
}
protected void onPostExecute(String name)
{
}
}
When executing that code, I see the following error happening :
02-02 14:47:59.586 7585-7601/? D/WearMessageListenerService﹕ 4005:ASSET_UNAVAILABLE
I saw that related thread Why does Wearable.DataApi.getFdForAsset produce a result with status 4005 (Asset Unavailable)? but it didn't really help me
I recently had the same problem... I solved it by updating the Google play service, and adding the same signing configuration to both the app and the wearable module. If it doesn't work on the first build go to "invalidate caches / restart" in files and it should work.

Code to execute if a navigation fails

Hello I have no idea where I should start looking. I add few prop (before that my code run fine), then I get
System.Diagnostics.Debugger.Break();
so then I comment that changes, but that didn't help.
Could you suggest me where I should start looking for solution?
MyCode:
namespace SkydriveContent
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
FilesManager fileManager = new FilesManager();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void signInButton1_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Signed in.";
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetAsync("/me/skydrive/files/");
fileManager.CurrentFolderId = "/me/skydrive/files/";
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
//Gdy uda nam się podłaczyc do konta skydrive
if (e.Error == null)
{
signInButton1.Visibility = System.Windows.Visibility.Collapsed;
infoTextBlock.Text = "Hello, signed-in user!";
List<object> data = (List<object>)e.Result["data"];
fileManager.FilesNames.Clear();
filemanager.filesnames.add("..");
foreach (IDictionary<string,object> item in data)
{
File file = new File();
file.fName = item["name"].ToString();
file.Type = item["type"].ToString();
file.Url = item["link"].ToString();
file.ParentId = item["parent_id"].ToString();
file.Id = item["id"].ToString();
fileManager.Files.Add(file);
fileManager.FilesNames.Add(file.fName);
}
FileList.ItemsSource = fileManager.FilesNames;
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
}
private void FileList_Tap(object sender, GestureEventArgs e)
{
foreach (File item in fileManager.Files)
{
if (item.fName == FileList.SelectedItem.ToString() )
{
switch (item.Type)
{
case "file":
MessageBox.Show("Still in progress");
break;
case "folder":
fileManager.CurrentFolderId = item.ParentId.ToString();
client.GetAsync(item.Id.ToString() + "/files");
break;
default:
MessageBox.Show("Coś nie działa");
break;
}
}
else if (FileList.SelectedItem.ToString() == "..")
{
client.GetAsync(fileManager.CurrentFolderId + "/files");
}
}
}
}
}
Running stop at that line.
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
You should check all of the URLs you have both in the XAML and code. When you get to the NavigationFailed function, it means that the phone tried to navigate to some page that did not existed. We would be able to help more if you could tell what were you doing when the app threw the exception.
System.Diagnostics.Debugger.Break();
usually happens because of an Uncaught Exception.
Either post the code which started giving problems, or the stack trace when you encounter this problem.
No one can tell anything without actually seeing what you are doing.

Resources