Get error "InvalidRequest" when use AdMob in WP8 - windows-phone-8

I'm really confusing ! I get this error randomly, Sometime the code worked (yesterday code went okay) but sometime not (today it returned "InvalidRequest" error).
I put this code in every page of my app
public MainPage()
{
InitializeComponent();
DataContext = App.MyModel;
LoadAd();
}
void LoadAd()
{
AdView av = new AdView()
{
AdUnitID = "ca-app-pub-...‏‏‏‏‏",
Format = AdFormats.Banner,
VerticalAlignment = System.Windows.VerticalAlignment.Top,
HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
};
av.FailedToReceiveAd += av_FailedToReceiveAd;
LayoutRoot.Children.Add(av);
AdRequest ar = new AdRequest();
ar.ForceTesting = true;
av.LoadAd(ar);
}
void av_FailedToReceiveAd(object sender, AdErrorEventArgs e)
{
Debug.WriteLine(e.ErrorCode.ToString());
}

I have found out that this error is mostly due to incorrect ad unit ids.
Check your adid, and make sure that its correct and doesnt have any space

Related

Multiple calls to MessageDialog cause crash under Windows Phone 8.1

I develop an Universal App that uses MVVM-Light. I call WebServices from the ViewModels, and I throw the exceptions encountered by the calls at the WebServices to the ViewModels: TimeOut, Wrong URL, Server Exception, ...
I have created a class "ExceptionsMsgHelper.cs" which centralizes the messages displayed for each of these exceptions through MessageDialog.
My HomePage is based on a Pivot that containing several datas: some WebServices are called asynchronously. I so meet a crash if I show an Exception in a MessageDialog through the class "ExceptionsMsgHelper.cs", whereas a previous Exception is also showed in another MessageDialog.
Here is a part of my original class:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
await msgbox.ShowAsync();
}
}
=> If I call twice the "msgbox.ShowAsync()", I get the "System.UnauthorizedAccessException" Exception: with message "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
I've so looked for solutions in order to fix it:
use a "Dispatcter", like it is recommended here (WinRT - MessageDialog.ShowAsync will throw UnauthorizedAccessException in my custom class)
The code is:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await msgbox.ShowAsync();
});
}
}
=> But I always meet the same exception.
use a "IAsyncOperation" command to close the previous MessageDialog, like recommended here (MessageDialog ShowAsync throws accessdenied exception on second dialog)
With this code:
public class ExceptionsMsgHelper
{
private static IAsyncOperation<IUICommand> messageDialogCommand = null;
public async static Task<bool> ShowDialog(MessageDialog dlg)
{
// Close the previous one out
if (messageDialogCommand != null)
{
messageDialogCommand.Cancel();
messageDialogCommand = null;
}
messageDialogCommand = dlg.ShowAsync();
await messageDialogCommand;
return true;
}
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await ShowDialog(msgbox);
});
}
}
=> But in this case too, I always get the same exception.
use an extension to queue up messagedialogs, like describing here (Multiple MessageDialog app crash)
The code is now:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
await MessageDialogExtensions.ShowAsyncQueue(msgbox);
}
}
public static class MessageDialogExtensions
{
private static TaskCompletionSource<MessageDialog> _currentDialogShowRequest;
public static async Task<IUICommand> ShowAsyncQueue(this MessageDialog dialog)
{
if (!Window.Current.Dispatcher.HasThreadAccess)
{
throw new InvalidOperationException("This method can only be invoked from UI thread.");
}
while (_currentDialogShowRequest != null)
{
await _currentDialogShowRequest.Task;
}
var request = _currentDialogShowRequest = new TaskCompletionSource<MessageDialog>();
var result = await dialog.ShowAsync();
_currentDialogShowRequest = null;
request.SetResult(dialog);
return result;
}
private static IAsyncOperation<IUICommand> messageDialogCommand = null;
public async static Task<bool> ShowDialog(this MessageDialog dlg)
{
// Close the previous one out
if (messageDialogCommand != null)
{
messageDialogCommand.Cancel();
messageDialogCommand = null;
}
messageDialogCommand = dlg.ShowAsync();
await messageDialogCommand;
return true;
}
#endregion
}
=> And this works for me.
But like says it's author, it's probably not the best solution:
Close existing dialog when you need to open a new one. This is the simplest option and possibly the best, although you risk cancelling a dialog that might be somehow important depending on what your dialogs are about.
Queue up dialogs so the old ones don't get dismissed, but the new ones show up after the old ones were dismissed. This one will make sure all dialogs are closed by the user, but that could be a problem if your app can somehow start showing hundreds of dialogs.
Only open a new one if there isn't one already displayed. Now this risks that a newer message is not shown, which sounds more problematic than the first option.
=> I would like to understand why I can't apply one the 2 first solutions that seems to be more adapted
Ofcourse you can't show 2 or more message dialog at the same time (windows phone limits). Moreover MesssageDialog on Windows Phone 8.1 has probably bug and can't be closed.
If closing previous dialog will be solution for you, try to use ContentDialog instead MessageDialog. Check my answer in this topic: Closing MessageDialog programatically in WP 8.1 RT
I think it solve your problem.

Windows phone 8 AdMob ReceiveAd not working

I have made unity application, and I have exported it to visual studio so I can add Google AdMob. I just want to show interstitial ad when ad loads. I am using latest Google.dll file ver:6.5.13.0. Here is my code:
//Google AdMob begin
private InterstitialAd interstitialAd;
AdRequest adRequest;
Boolean interstitialApploaded = false;
int test = 0;
//Google AdMob end
// Constructor
public MainPage()
{
var bridge = new UnityBridge();
UnityApp.SetBridge(bridge);
InitializeComponent();
bridge.Control = DrawingSurfaceBackground;
interstitialAd = new InterstitialAd("my interstitial ID");
interstitialAd.ReceivedAd += OnAdReceived;
interstitialAd.FailedToReceiveAd += OnFailedToReceiveAd;
interstitialAd.DismissingOverlay += OnDismissingOverlay;
adRequest = new AdRequest();
adRequest.ForceTesting = true;
interstitialAd.LoadAd(adRequest);
}
//Google AdMob BEGIN
private void OnDismissingOverlay(object sender, AdEventArgs e)
{
Debug.WriteLine("Ad dismissed.");
interstitialAd.LoadAd(adRequest);
}
private void OnFailedToReceiveAd(object sender, AdErrorEventArgs e)
{
Debug.WriteLine("Ad failed to load!!!!");
interstitialApploaded = false;
test = 1;
}
private void OnAdReceived(object sender, AdEventArgs e)
{
Debug.WriteLine("Ad loaded. Have fun!");
interstitialApploaded = true;
test = 2;
interstitialAd.ShowAd();
}
Now, the problem is that I am not getting any of the Debug.Writeline messages. So I guess ReceiveAd is not working.
Any thoughts?
Thank you.
Your code seems to be Right, check your internet connection and Capabilities that are needed for Ad-loading and try after removing adRequest.ForceTesting = true; that is for test Ad Interstitial.
You have to add the advertise through Unity with its advertisers there will be always an exception if you try to change the exported .sln file from Unity

Wait until async operation ends Windows Phone

I am trying to parse some pois from a xml download from a server and I saw that it is done after the program continues in the main thread. I haven't found a way to solve it because I need it.
using System.Threading;
namespace XML_Parser
{
class XMLParserPOI_Wiki
{
private static XMLParserPOI_Wiki objSingle = new XMLParserPOI_Wiki();
public static XMLParserPOI_Wiki ObjSingle
{
get { return objSingle; }
set { objSingle = value; }
}
private List<POI> places;
public List<POI> Places
{
get { return places; }
}
private XMLParserPOI_Wiki()
{
}
public void parseWikitude(string url)
{
places = new List<POI>();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(url));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
XNamespace ns = "http://www.opengis.net/kml/2.2";
XNamespace ns2 = "http://www.openarml.org/wikitude/1.0";
var placemarkers = xdoc.Root.Descendants(ns + "Placemark");
places =
(from query in xdoc.Root.Descendants(ns + "Placemark")
select new POI
(
...
)).ToList();
System.Diagnostics.Debug.WriteLine("Lista");
System.Diagnostics.Debug.WriteLine(places.Count);
}
}
}
}
In my main class:
XMLParserPOI_Wiki parserXML = XMLParserPOI_Wiki.ObjSingle;
parserXML.parseWikitude("http://myurl.php");
System.Diagnostics.Debug.WriteLine("Lista de pois");
System.Diagnostics.Debug.WriteLine(parserXML.Places.Count);
for (int i = 0; i < parserXML.Places.Count; i++)
{
System.Diagnostics.Debug.WriteLine(parserXML.Places[i].getName());
}
It prints Lista de POis and 0, before Lista and X (number of pois)
I guess I should freeze main thread but I tried a couple of times with some examples and they didn't work.
Can you point me to any tutorial about this? More than get an answer I want to understand how to deal with this kind of operations
First of all, you don't want to block (freeze) the UI thread EVER!
This is called asynchronous programming. There are two things you can do to solve your problem (I recommend option 2!):
Use the classic callback model. You basically call some long operation on a background thread and give a function to it, to execute when the long operation is done. Here's how to do it in your case.
At the end of the HttpsCompleted method, invoke what you need on the UI Thread using:
Deployment.Current.Dispatcher.BeginInvoke(delegate() {
//The code here will be invoked on the UI thread
});
If you want to make the parseWikitude method reusable, you should pass an Action to it. This way you can call it from multiple places and tell it what to do on the UI thread when the parsing is done. Something like this:
public void parseWikitude(string url, Action callback) {
places = new List<POI>();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(url), callback);
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
...
var callback = (Action)e.UserState;
Deployment.Current.Dispatcher.BeginInvoke(callback);
}
}
//And then when you use it, you do it like that
parserXML.parseWikitude("http://myurl.php", delegate() {
//The code here will be executed on the UI thread, after the parsing is done
});
Use the (rather) new asnyc pattern in .NET. You should read about this, as it is one of the best features of .NET if you ask me. :) It basically does the callback thing automatically and makes the code a lot easier to read/maintain/work-with. Once you get used to it, that is.
Here's an example:
public Task<List<POI>> parseWikitude(string url) {
TaskCompletionSource<List<POI>> resultTaskSource = new TaskCompletionSource<List<POI>>();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(url), resultTaskSource);
return resultTaskSource.Task;
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
//If needed, run the code here in a background thread
//...
var resultTaskSource = (TaskCompletionSource<List<POI>>)e.UserState;
resultTaskSource.SetResult(places);
}
}
//And when you need to use it, do it like that (note, this must be invoked in an async method!)
var places = await parser.parseWikitude("http://myurl.php");
//The code here will be executed on the same thread when the parsing is done, but the thread will not be blocked while the download is happening.
So, these are the two ways you can handle it. Option one is old-school, classic and easy. Option two is the new and cool way of doing async stuff. It really is a must-know. Simplifies a lot of things once you get used to it.
P.S. Sorry if I got carried away. :D

Infinite wait loading remote image into BitmapImage() in Background Agent

I have a valid URL for a remote JPEG which I'm trying to load in the background. But I find I never get control back after invoking the BitmapImage() constructor. My question is, should this approach work, or should I pitch it all, load up BcpAsync project from NuGet and start working with WebClient asynch methods?
A sample URL for which it fails is
http://image.weather.com/images/maps/current/garden_june_720x486.jpg
It is valid. .UpdateAsync() references it from AppViewModel.Instance, it's not explicitly referenced here.
Here's the background agent:
protected override async void OnInvoke(ScheduledTask task)
{
AppViewModel.LoadData();
await AppViewModel.Instance.RemoteImageProxy.UpdateAsync();
AppViewModel.Instance.ImageUrl = AppViewModel.Instance.RemoteImageProxy.LocalFileUri;
AppViewModel.Instance.UpdateCount++;
PinnedTile.Update();
}
AppViewModel.SaveData();
#if DEBUG
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(AppViewModel.Instance.BgAgentInterval));
#endif
NotifyComplete();
}
Here's the invoked method:
public Task<double> UpdateAsync() {
LastCheckedTime = DateTime.UtcNow;
CompletionTask = new TaskCompletionSource<double>();
// Not usually called on UI thread, not worth optimizing for that case here.
Deployment.Current.Dispatcher.BeginInvoke(() => { //todo determine whether System.Windows.Deployment.Dispatcher can be called from main app, or just bgAgent.
HelperImageControl = new Image();
HelperImageControl.Loaded += im_Loaded;
HelperImageControl.ImageFailed += im_ImageFailed;
HelperImageControl.ImageOpened += im_ImageOpened;
// breakpoint here
HelperImageControl.Source = new BitmapImage(SourceUri);
// stepping over the function, control does not return here. Nor are any of the above events fired.
});
return CompletionTask.Task; // this will be completed in one of the subsequent control events...
}
You need to call CompletionTask.SetResult(); to return control back to the caller method.
This works (I'm returning 100 in case of successful download because you set the task to return double).
TaskCompletionSource<double> CompletionTask;
public Task<double> UpdateAsync()
{
CompletionTask = new TaskCompletionSource<double>();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var HelperImageControl = new Image();
var bmp = new BitmapImage();
bmp.ImageOpened += bmp_ImageOpened;
bmp.ImageFailed += bmp_ImageFailed;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = new Uri("http://image.weather.com/images/maps/current/garden_june_720x486.jpg", UriKind.Absolute);
HelperImageControl.Source = bmp;
});
return CompletionTask.Task;
}
void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
CompletionTask.SetException(e.ErrorException);
}
void bmp_ImageOpened(object sender, RoutedEventArgs e)
{
CompletionTask.SetResult(100);
}

Render report quality EMF versus PDF

I'm having difficulties rendering a SSRS serverreport and printing it from code.
Although rendering succeeds and the report is printed, the results in quality in the graphics are poor. The report itself has a high res 6kx1k GIF image for the logo.
I've made image below to illustrate the difference between rendering using EMF versus PDF:
As you can see the font look great (no pixallation) and when rendering in PDF logo look good. However the EMF version has poor quality as you can see on the edges in the logo.
Anyone came across this and solved it?
I'm running SQL Server 2008R2 SP2 (10.50.4000)
Code to render the report using EMF
public List<byte[]> Render()
{
// Setting credentials and reporting services uri
ReportExecutionService reportService = new ReportExecutionService
{
Credentials = _credentials,
Url = Settings.Default.ReportingService
};
// Prepare report parameter.
ExecutionHeader execHeader = new ExecutionHeader();
reportService.ExecutionHeaderValue = execHeader;
reportService.LoadReport(_report, null);
reportService.SetExecutionParameters(_parameters.ToArray(), "en-us");
// Render
bool startup = true;
List<byte[]> streams = new List<byte[]>();
int numberOfPages = 0;
byte[] result = null;
while (startup || result.Length > 0)
{
startup = false;
string devInfo = String.Format(#"<DeviceInfo><OutputFormat>EMF</OutputFormat><PrintDpiX>150</PrintDpiX><PrintDpiY>150</PrintDpiY><StartPage>{0}</StartPage></DeviceInfo>", numberOfPages + 1);
string encoding, mimeType, extension;
string[] streamIDs = null;
Warning[] warnings = null;
result = reportService.Render("IMAGE", devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
if (result.Length > 0)
{
streams.Add(result);
}
numberOfPages++;
}
return streams;
}
Here's the printdocument implementation
public class PrintReport : PrintDocument
{
private int _currentPage;
private List<byte[]> _pages;
public PrintReport()
{
}
public List<byte[]> Pages
{
get { return _pages; }
set { _pages = value; }
}
protected override void OnBeginPrint(PrintEventArgs e)
{
base.OnBeginPrint(e);
_currentPage = 0;
}
protected override void OnPrintPage(PrintPageEventArgs e)
{
base.OnPrintPage(e);
Stream pageToPrint = new MemoryStream(_pages[_currentPage]);
pageToPrint.Position = 0;
// Load each page into a Metafile to draw it.
using (Metafile pageMetaFile = new Metafile(pageToPrint))
{
Rectangle adjustedRect = new Rectangle(
e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
e.PageBounds.Width,
e.PageBounds.Height);
// Draw a white background for the report
e.Graphics.FillRectangle(Brushes.White, adjustedRect);
// Draw the report content
e.Graphics.DrawImage(pageMetaFile, adjustedRect);
// Prepare for next page. Make sure we haven't hit the end.
_currentPage++;
e.HasMorePages = _currentPage < _pages.Count;
}
}
protected override void OnQueryPageSettings(QueryPageSettingsEventArgs e)
{
e.PageSettings = (PageSettings)PrinterSettings.DefaultPageSettings.Clone();
}
}
Try replacing "150" with the desired dpi in the snippet below copied from devInfo, it should help. Changing it to "300" solved my similar issue.
<PrintDpiX>150</PrintDpiX><PrintDpiY>150</PrintDpiY>
Note that it can be frustrating to change this in your reports as the report viewer rendering engine will still show with 150 dpi when previewing your reports, so you will need to test your layouts using your code for testing after each update to the rdl.