I am not able to integrate the adcontrol in my windows phone 8 app.
In windows phone 8, the microsoft advertising sdk is already provided in the reference and hence have not downloaded the same.
Below is the code snippet I have used:
// Constructor
public MainPage()
{
InitializeComponent();
// ApplicationID = "test_client", AdUnitID = "Image480_80",
AdControl adControl = new AdControl("test_client", // ApplicationID
"Image480_80", // AdUnitID
true); // isAutoRefreshEnabled
// Make the AdControl size large enough that it can contain the image
adControl.Width = 480;
adControl.Height = 80;
Grid grid = (Grid)this.LayoutRoot.Children[1];
grid.Children.Add(adControl);
}
I have also added various capabilities as mentioned in this link:
Windows phone ads not working
But still I am having no luck...At one place I read you need to have internet connection in order for adcontrol to be visible. Is it true?.
Anyways require help on the same.
Thanks In Advance!!!...
Solution:
Issue that I have found in your question is of capabilities, Keep one thing in mind that there is a change in capabilities from windows phone-7 to windows phone-8.
Capabilities that you have added are according to windows phone-7(as you mentioned from link).
You can find required capabilities at: http://msdn.microsoft.com/en-us/library/advertising-mobile-windows-phone-manifest-capabilities(v=msads.20).aspx
Sample:
public MainPage()
{
InitializeComponent();
AdControl adCntrl = new AdControl();
adCntrl.Height = 80;
adCntrl.Width = 480;
adCntrl.ApplicationId = "test_client";
adCntrl.AdUnitId = "Image480_80";
ContentPanel.Children.Add(adCntrl);
}
with Capabilities:
<Capabilities>
<Capability Name="ID_CAP_IDENTITY_USER"/>
<Capability Name="ID_CAP_MEDIALIB_PHOTO"/>
<Capability Name="ID_CAP_NETWORKING"/>
<Capability Name="ID_CAP_PHONEDIALER"/>
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
<Capability Name="ID_CAP_MEDIALIB_AUDIO"/>
<Capability Name="ID_CAP_MEDIALIB_PLAYBACK"/>
<Capability Name="ID_CAP_SENSORS"/>
</Capabilities>
Assuming that you did all the rest of the requirement stuff correctly and downloaded the Microsoft Ads SDK and added it in to the reference
Top of the main page
using Microsoft.Advertising.Mobile.UI;
In MainPage class initialize these
Grid adGrid = new Grid();
StackPanel adStackPanel = new StackPanel();
AdControl adControl = new AdControl("test_client", "Image480_80", true);
In Constructor do this
adControl.Width = 480;
adControl.Height = 80;
adStackPanel.Children.Insert(0, adControl);
adGrid.Children.Insert(0, adStackPanel);
adGrid.HorizontalAlignment = HorizontalAlignment.Right;
adGrid.VerticalAlignment = VerticalAlignment.Bottom;
this.DrawingSurfaceBackground.Children.Insert(0, adGrid);
//Optional
adControl.ErrorOccurred += adControl_ErrorOccurred;
void adControl_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
{
try
{
AdControl ad = (AdControl)sender;
Dispatcher.BeginInvoke(() =>
{
// MessageBox.Show(e.Error.ToString());
Debug.WriteLine(
"error in ad control '" + ad.Name + "': " + e.Error.Message);
Debug.WriteLine("ad control '" + ad.Name + "' visibility = " + ad.Visibility);
});
}
catch (Exception evnt)
{
Debug.WriteLine("oh no! " + evnt.Message);
}
}
Related
I have a strange behaviour in my Xamarin.Forms app on the WinPhone client.
My MainPage is a NavigationPage. And when I navigate to the second page and turn the phone to landscape (also happens on the other way), the page shows a black area on the right side. It seems that the height and width properties don't get re-calculated on the device orientation change.
To reproduce this, just create a new Xamarin.Forms Blank App (Visual Studio 2013 template), Update the Xamarin.Forms nuget to the newest verson (in my case: 2.0.0.6490), and add the following to the App-Constructor:
var second = new ContentPage
{
BackgroundColor = Color.Green,
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
XAlign = TextAlignment.Center,
Text = "Second Page"
}
}
}
};
var button = new Button {Text = "Show Second"};
button.Clicked += async (sender, args) => { await ((NavigationPage) MainPage).PushAsync(second); };
var firstpage = new ContentPage
{
BackgroundColor = Color.Blue,
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
XAlign = TextAlignment.Center,
Text = "First Page"
},
button
}
}
};
// The root page of your application
MainPage = new NavigationPage(firstpage);
Is this a bug in Xamarin.Forms? Or miss I just something? Thanks in advance
I cant see any existing filed bugs on this. If it is easily reproducible as described, then create a small repro project and submit to bugzilla.xamarin.com. It will be a xf regression bug.
Thanks #Joehl - I obviously am not too great at searching bugzilla on my mobile. As mentioned this is the bug report: https://bugzilla.xamarin.com/show_bug.cgi?id=36477
In Windows Phone 8 I was able to create a Shell Tile with the following:
StandardTileData newTileData = new StandardTileData
{
BackgroundImage = new Uri("/Images/my_tile_medium.png", UriKind.Relative),
Title = "My Tile Title",
BackTitle = "My Tile Back",
BackBackgroundImage = new Uri("/Images/my_tile_medium_back.png", UriKind.Relative),
};
ShellTile.Create(MyAppPages.MainPage("Name=MyAppTile"), newTileData);
This no longer works in Windows Phone 8.1. How can I programatically create a tile with Windows Phone 8.1
In WP8.1 Runtime you can use SecondaryTile, for example:
SecondaryTile tileData = new SecondaryTile()
{
TileId = "MyTileID",
DisplayName = "MyTilesTitle",
Arguments = "Some arguments"
};
tileData.VisualElements.Square150x150Logo = new Uri("uri to image");
tileData.VisualElements.ShowNameOnSquare150x150Logo = true;
await tileData.RequestCreateAsync();
Some guide you can also find here at MSDN.
There are quite a few Windows Phone 8.1 apps (e.g. Clock hub, Analog Clock Tile, etc.) which allow you to pin an analog clock on the main screen.
I am trying to do the same by following this sample which shows me how to update an XML document every minute.
But if I am going to create an analog clock tile then it needs to be an image.
I have tried to use XamlRenderingBackgroundTask with RenderTargetBitmap to generate the image, this bit works. What I am not sure is how can I update this image every minute.
Any help wold be greatly appreciated!
I took the sample you provided and modified it to generate a custom image live tile every minute.
I've tested it on my phone and it seems to be working OK. You might need to do more testing such as memory usage testing to make sure it doesn't go over the cap (maybe can reduce planTill to 30 minutes to generate less tiles in the loop?).
The UserControl xml file SquareFrontTile1.xml
<Border Height="360" Width="360" Background="#00b2f0" xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'>
<TextBlock Text="{0}" HorizontalAlignment="Left" VerticalAlignment="Top" Foreground="White" FontSize="50.667" />
</Border>
The code
public static async void UpdateAsync(BackgroundTaskDeferral deferral)
{
TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
IReadOnlyList<ScheduledTileNotification> plannedUpdated = tileUpdater.GetScheduledTileNotifications();
string language = GlobalizationPreferences.Languages.First();
CultureInfo cultureInfo = new CultureInfo(language);
DateTime now = DateTime.Now;
DateTime planTill = now.AddHours(1);
DateTime updateTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0).AddMinutes(1);
if (plannedUpdated.Count > 0)
updateTime = plannedUpdated.Select(x => x.DeliveryTime.DateTime).Union(new[] { updateTime }).Max();
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
StorageFile file = await folder.GetFileAsync("SquareFrontTile1.xml");
string xml = await Windows.Storage.FileIO.ReadTextAsync(file);
string startXml = string.Format(xml, now.ToString(cultureInfo.DateTimeFormat.ShortTimePattern));
XmlDocument tileDocumentNow = await GetTileXmlDocument(startXml);
TileNotification notification = new TileNotification(tileDocumentNow) { ExpirationTime = now.AddMinutes(1) };
tileUpdater.Update(notification);
for (var startPlanning = updateTime; startPlanning < planTill; startPlanning = startPlanning.AddMinutes(1))
{
Debug.WriteLine(startPlanning);
Debug.WriteLine(planTill);
try
{
string updateXml = string.Format(xml, startPlanning.ToString(cultureInfo.DateTimeFormat.ShortTimePattern));
XmlDocument updatedTileDocument = await GetTileXmlDocument(updateXml);
ScheduledTileNotification scheduledNotification = new ScheduledTileNotification(updatedTileDocument, new DateTimeOffset(startPlanning)) { ExpirationTime = startPlanning.AddMinutes(1) };
tileUpdater.AddToSchedule(scheduledNotification);
Debug.WriteLine("schedule for: " + startPlanning);
}
catch (Exception e)
{
Debug.WriteLine("exception: " + e.Message);
}
}
deferral.Complete();
}
private static async Task<XmlDocument> GetTileXmlDocument(string xml)
{
Border tileUIElement = XamlReader.Load(xml) as Border;
string liveTileImageName = string.Format("UpdatedLiveTile_{0}.png", DateTime.Now.Ticks.ToString());
if (tileUIElement != null)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(tileUIElement, 150, 150);
IBuffer pixels = await rtb.GetPixelsAsync();
DataReader dReader = Windows.Storage.Streams.DataReader.FromBuffer(pixels);
byte[] data = new byte[pixels.Length];
dReader.ReadBytes(data);
var outputFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFileAsync(liveTileImageName, Windows.Storage.CreationCollisionOption.ReplaceExisting);
var outputStream = await outputFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
BitmapEncoder enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream);
enc.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, 150, 150, 96, 96, data);
await enc.FlushAsync();
}
var tileDocument = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Image);
var tileImageAttributes = tileDocument.GetElementsByTagName("image");
XmlElement tmp = tileImageAttributes[0] as XmlElement;
tmp.SetAttribute("src", liveTileImageName);
return tileDocument;
}
I am not going to fully answer the question since I am myself trying to get this working at present. However I will set you in right direction. I have done this in past with windows 8.
What you need to do is create Tile Updater and schedule tiles updates every so often.. in this case one every minute. The tile schema chosen can have be image or text or a combination of both.
you can find the TileSchema catalogue here
http://msdn.microsoft.com/en-us/library/windows/apps/hh761491.aspx
and details of Tile Schema here
http://msdn.microsoft.com/en-us/library/windows/apps/br212859.aspx
Here is a Windows 8 sample
http://code.msdn.microsoft.com/windowsapps/scheduled-notifications-da477093
Here is a snippet from my code which isn't working correctly so far.. tile is blank
TileUpdater updater = TileUpdateManager.CreateTileUpdaterForApplication();
XmlDocument document = new XmlDocument();
document.LoadXml(str2);
ScheduledTileNotification notification2 = new ScheduledTileNotification(document, new DateTimeOffset(time4));
notification2.ExpirationTime = (new DateTimeOffset?((DateTimeOffset)time4.AddMinutes(1.0)));
ScheduledTileNotification notification = notification2;
updater.AddToSchedule(notification);
Once I finish this, I will write up a blog post and add a link here
I have created a repro project that tries to do this from within sample app (not background task).
http://1drv.ms/1nai8nn
The sample work for me, I add to Windows Phone Silverlight 8.1. You must change Notification Services from MPN to WNS in WMAppManifest.xml and add Background task, tick System event, Timer in Package.appxmanifest (Declarations tab).
#Justin XL: your code not work for me, error in line
Border tileUIElement = XamlReader.Load(xml) as Border;
Error: The application called an interface that was marshalled for a different thread.
My windows 8 phone app programatically add an image (as a pin) to a specific coordinataion in map using mapoverlay. And now i would like to add a tooltip to the image (pin) after tapping on it. Does anyone know how to fix this?
pinIMG = new Image();
pinIMG.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Assets/pin.png", UriKind.Relative));
MapOverlay myLocationOverlay = new MapOverlay();
myLocationOverlay.Content = pinIMG;
myLocationOverlay.PositionOrigin = new Point(0.5, 0.5);
myLocationOverlay.GeoCoordinate = new GeoCoordinate(57.724611, 12.938945);
MapLayer myLocationLayer = new MapLayer();
myLocationLayer.Add(myLocationOverlay);
MyMap.Layers.Add(myLocationLayer);
Instead of adding an Image to the MapOverlay, consider adding an ExpanderView control that expands to add additional data. You'll need to download the Windows Phone Toolkit to get the ExpanderView control. While you're at it you might want to switch over to using Map Extensions Pushpins to get databinding support.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
MapLayer myLayer = new MapLayer();
MapOverlay myOverlay = new MapOverlay()
{
GeoCoordinate = new GeoCoordinate(-17, 133)
};
ExpanderView expander = new ExpanderView();
expander.Header = new Image()
{
Source = new BitmapImage(new Uri("Assets/ApplicationIcon.png", UriKind.Relative)),
Width = 200
};
expander.ItemsSource = new[]
{
new TextBlock{ Text = "HELLO"}
};
;
myOverlay.Content = expander;
myLayer.Add(myOverlay);
myMap.Layers.Add(myLayer);
}
When we run this sample we can see the following icon over australia:
And once we click ti we can see our "Hello" text show up:
A few ceavets: the code sample above is terrible. ExpanderView is meant to use both ItemSource and IteTemplate for multiple items databinding. Using it for a single item isn't great. The above code sample is also terrible since it creates UI elements in C# code whereas using Map Extensions could have placed this code in XAML.
I would like to use Air to build for PC, Mac, Android, Ios.
Is it possible to do this from a single code base as Adobe Suggests.
Or will I need to maintain 4 separate builds?
Some guidance would be appreciated.
Regards
C
I have been able to maintain a single code base to date. I have done things like the following:
private function getHostName() : void
{
if (NativeProcess.isSupported)
{
var OS : String = Capabilities.os.toLocaleLowerCase();
var file : File;
if (OS.indexOf('win') > -1)
{
// Executable in windows
file = new File('C:\\Windows\\System32\\hostname.exe');
}
else if (OS.indexOf('mac') > -1 )
{
// Executable in mac
}
else if (OS.indexOf('linux'))
{
// Executable in linux
}
var nativeProcessStartupInfo : NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = file;
var process : NativeProcess = new NativeProcess();
process.addEventListener(NativeProcessExitEvent.EXIT, onExitError);
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutput);
process.start(nativeProcessStartupInfo);
process.closeInput();
}
}
private function onOutput(event : ProgressEvent) : void
{
var strHelper : StringHelper = new StringHelper();
formStationID.text = event.target.standardOutput.readUTFBytes(event.target.standardOutput.bytesAvailable);
formStationID.text = strHelper.trimBack(formStationID.text, "\n");
formStationID.text = strHelper.trimBack(formStationID.text, "\r");
}
private function onExitError(event : NativeProcessExitEvent) : void
{
}
To take care of native calls. Other than the native calls I have found few things that can't be written generically, but of those, the above approach should work with any part of the code set as well.