Hi everyone I am developing a universal windows platform game which is compiled from unity. In that game I want to show Microsoft ads(both banner and interstitial).
My problem is in the framework where I load the ads in the framework I don't know.
Can anyone give the solution for this problem?
I mentioned framework below,
Thanks in advance.
- using System;
- using System.Collections.Generic;
- using Windows.ApplicationModel.Activation;
- using Windows.Foundation;
- using Windows.Storage;
- using Windows.UI;
- using Windows.UI.Core;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- using Windows.UI.Xaml.Media;
- using Windows.UI.Xaml.Navigation;
- using System.Diagnostics;
- using UnityPlayer;
- using Windows.Networking.Connectivity;
- using Windows.ApplicationModel.DataTransfer;
- using Microsoft.Advertising.WinRT.UI;
- using Windows.UI.Popups;
- using com.vmax.windows.ads.wp10;
- using com.vmax.windows.ads;
- #if DEBUG
- using store = Windows.ApplicationModel.Store.CurrentAppSimulator;
- using Windows.ApplicationModel.Store;
- using System.Net.NetworkInformation;
- #else
- using store = Windows.ApplicationModel.Store.CurrentApp;
- using Windows.ApplicationModel.Store;
- #endif
- namespace HopTheBall
- {
- ///
- /// An empty page that can be used on its own or navigated to within a Frame.
- ///
- public sealed partial class MainPage : Page
- {
- private WinRTBridge.WinRTBridge _bridge;
- private SplashScreen splash;
- private Rect splashImageRect;
- private WindowSizeChangedEventHandler onResizeHandler;
- //private TypedEventHandler onRotationChangedHandler;
- private const string interstitialTestAdspotId = "8063";
- public static string InApp_ConsumableId = "Beer100";
- public static string InApp_NonConsumableId = "Pong100";
- private string msRemoveAdsId = "adsRemoved";
- private int msRemoveadsValue = 1;
- //App Launch URL
- private string appLaunchUrl = "http://www.windowsphone.com/s?appid=169381fb-0fcb-4f42-852d-a1d1ad49c777";
- private int totalInapItems = 7;
- private string[] ApreciationMessage;
- private Random randomMessage;
- private DataTransferManager dataTransferManager;
- public string shareData;
- public MainPage()
- {
- this.InitializeComponent();
- NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required;
- AppCallbacks appCallbacks = AppCallbacks.Instance;
- // Setup scripting bridge
- _bridge = new WinRTBridge.WinRTBridge();
- appCallbacks.SetBridge(_bridge);
- appCallbacks.RenderingStarted += () => { RemoveSplashScreen(); };
- CustomAdMediator.Visibility = Visibility.Collapsed;
- #if !UNITY_WP_8_1
- appCallbacks.SetKeyboardTriggerControl(this);
- #endif
- appCallbacks.SetSwapChainPanel(GetSwapChainPanel());
- appCallbacks.SetCoreWindowEvents(Window.Current.CoreWindow);
- appCallbacks.InitializeD3DXAML();
- splash = ((App)App.Current).splashScreen;
- GetSplashBackgroundColor();
- OnResize();
- onResizeHandler = new WindowSizeChangedEventHandler((o, e) => OnResize());
- Window.Current.SizeChanged += onResizeHandler;
- #if UNITY_WP_8_1
- onRotationChangedHandler = new TypedEventHandler((di, o) => { OnRotate(di); });
- ExtendedSplashImage.RenderTransformOrigin = new Point(0.5, 0.5);
- var displayInfo = DisplayInformation.GetForCurrentView();
- displayInfo.OrientationChanged += onRotationChangedHandler;
- OnRotate(displayInfo);
- SetupLocationService();
- #endif
- }
- ///
- /// Invoked when this page is about to be displayed in a Frame.
- ///
- /// Event data that describes how this page was reached. The Parameter
- /// property is typically used to configure the page.
- protected override void OnNavigatedTo(NavigationEventArgs e)
- {
- splash = (SplashScreen)e.Parameter;
- OnResize();
- }
- private void OnResize()
- {
- if (splash != null)
- {
- splashImageRect = splash.ImageLocation;
- PositionImage();
- }
- }
- #if UNITY_WP_8_1
- private void OnRotate(DisplayInformation di)
- {
- // system splash screen doesn't rotate, so keep extended one rotated in the same manner all the time
- int angle = 0;
- switch (di.CurrentOrientation)
- {
- case DisplayOrientations.Landscape:
- angle = -90;
- break;
- case DisplayOrientations.LandscapeFlipped:
- angle = 90;
- break;
- case DisplayOrientations.Portrait:
- angle = 0;
- break;
- case DisplayOrientations.PortraitFlipped:
- angle = 180;
- break;
- }
- var rotate = new RotateTransform();
- rotate.Angle = angle;
- ExtendedSplashImage.RenderTransform = rotate;
- }
- #endif
- private void PositionImage()
- {
- var inverseScaleX = 1.0f;
- var inverseScaleY = 1.0f;
- #if UNITY_WP_8_1
- inverseScaleX = inverseScaleX / DXSwapChainPanel.CompositionScaleX;
- inverseScaleY = inverseScaleY / DXSwapChainPanel.CompositionScaleY;
- #endif
- ExtendedSplashImage.SetValue(Canvas.LeftProperty, splashImageRect.X * inverseScaleX);
- ExtendedSplashImage.SetValue(Canvas.TopProperty, splashImageRect.Y * inverseScaleY);
- ExtendedSplashImage.Height = splashImageRect.Height * inverseScaleY;
- ExtendedSplashImage.Width = splashImageRect.Width * inverseScaleX;
- }
- private async void GetSplashBackgroundColor()
- {
- try
- {
- StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///AppxManifest.xml"));
- string manifest = await FileIO.ReadTextAsync(file);
- int idx = manifest.IndexOf("SplashScreen");
- manifest = manifest.Substring(idx);
- idx = manifest.IndexOf("BackgroundColor");
- if (idx < 0) // background is optional
- return;
- manifest = manifest.Substring(idx);
- idx = manifest.IndexOf("\"");
- manifest = manifest.Substring(idx + 1);
- idx = manifest.IndexOf("\"");
- manifest = manifest.Substring(0, idx);
- int value = 0;
- bool transparent = false;
- if (manifest.Equals("transparent"))
- transparent = true;
- else if (manifest[0] == '#') // color value starts with #
- value = Convert.ToInt32(manifest, 16) & 0x00FFFFFF;
- else
- return; // at this point the value is 'red', 'blue' or similar, Unity does not set such, so it's up to user to fix here as well
- byte r = (byte)(value >> 16);
- byte g = (byte)((value & 0x0000FF00) >> 8);
- byte b = (byte)(value & 0x000000FF);
- await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.High, delegate ()
- {
- byte a = (byte)(transparent ? 0x00 : 0xFF);
- ExtendedSplashGrid.Background = new SolidColorBrush(Color.FromArgb(a, r, g, b));
- });
- }
- catch (Exception)
- { }
- }
- public SwapChainPanel GetSwapChainPanel()
- {
- return DXSwapChainPanel;
- }
- public void RemoveSplashScreen()
- {
- try
- {
- AppCallbacks.Instance.InvokeOnAppThread(new AppCallbackItem(() =>
- {
- //Communication Handler
- if (UnityEngine.GameObject.Find("ExternalInterfaceHandler") != null)
- {
- var mvGo = UnityEngine.GameObject.Find("ExternalInterfaceHandler");
- if (mvGo != null)
- {
- var InterfaceHandler = mvGo.GetComponent();
- InterfaceHandler.OnSendRequestEvent += OnRequestFromGame;
- }
- }
- randomMessage = new Random();
- ApreciationMessage = new String[]
- {
- "Fantastic", "Superb", "Awesome", "Great", "Amazing", "Excellent", "magnificent", "Impressive"
- };
- }), false);
- }
- catch (Exception me)
- {
- //System.Diagnostics.Debug.WriteLine("" + me.Message);
- }
- DXSwapChainPanel.Children.Remove(ExtendedSplashGrid);
- if (onResizeHandler != null)
- {
- Window.Current.SizeChanged -= onResizeHandler;
- onResizeHandler = null;
- #if UNITY_WP_8_1
- DisplayInformation.GetForCurrentView().OrientationChanged -= onRotationChangedHandler;
- onRotationChangedHandler = null;
- #endif
- }
- }
- //Application Quit
- private async void ApplicationQuit()
- {
- var dlg = new ContentDialog()
- {
- Title = "Exit",
- Content = "Are You Sure?",
- PrimaryButtonText = "Yes",
- SecondaryButtonText = "No"
- };
- var result = await dlg.ShowAsync();
- if (result == ContentDialogResult.Primary)
- {
- Application.Current.Exit();
- }
- else
- {
- Debug.WriteLine("No");
- }
- }
- public void OnRequestFromGame(eEXTERNAL_REQ_TYPE ReqType, string strData)
- {
- System.Diagnostics.Debug.WriteLine("Request Type---------" + ReqType + " StrData---------" + strData);
- AppCallbacks.Instance.InvokeOnUIThread(new AppCallbackItem(() =>
- {
- switch (ReqType)
- {
- case eEXTERNAL_REQ_TYPE.ApplicationQuit:
- {
- ApplicationQuit();
- }
- break;
- case eEXTERNAL_REQ_TYPE.InAppConsumable:
- {
- ExternalInterfaceHandler.Instance.Receiver("true");
- try
- {
- var mvProductId = InApp_ConsumableId + strData;
- var licence = store.LicenseInformation.ProductLicenses[mvProductId];
- if (licence.IsActive)
- {
- ExternalInterfaceHandler.Instance.Receiver("true");
- mDoPurchaseOrFullfillItem(mvProductId, true, true);
- }
- else
- {
- mDoPurchaseOrFullfillItem(mvProductId, false, true);
- }
- }
- catch (Exception ex)
- {
- ExternalInterfaceHandler.Instance.Receiver("false");
- }
- }
- break;
- case eEXTERNAL_REQ_TYPE.InAppNonConsumable:
- {
- ExternalInterfaceHandler.Instance.Receiver("true");
- try
- {
- var mvProductId = InApp_NonConsumableId + strData;
- var licence = store.LicenseInformation.ProductLicenses[mvProductId];
- if (licence.IsActive)
- {
- ExternalInterfaceHandler.Instance.Receiver("true");
- }
- else
- {
- mDoPurchaseOrFullfillItem(mvProductId, false, false);
- }
- }
- catch (Exception ex)
- {
- ExternalInterfaceHandler.Instance.Receiver("false");
- }
- }
- break;
- case eEXTERNAL_REQ_TYPE.Show_Banner_Top_Ads:
- {
- // Debug.WriteLine("Show_Banner_Top_Ads_Called");
- try
- {
- ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
- //check if net is available or not
- if (InternetConnectionProfile != null)
- {
- if (CustomAdMediator != null)
- {
- CustomAdMediator.VerticalAlignment = VerticalAlignment.Top;
- CustomAdMediator.Visibility = Visibility.Visible;
- }
- else
- {
- CustomAdMediator.VerticalAlignment = VerticalAlignment.Top;
- CustomAdMediator.Visibility = Visibility.Visible;
- }
- }
- }
- catch
- {
- }
- }
- break;
- case eEXTERNAL_REQ_TYPE.Show_Banner_Bottom_Ads:
- {
- // Debug.WriteLine("Show_Banner_Bottom_Ads_Called");
- try
- {
- ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
- //check if net is available or not
- if (InternetConnectionProfile != null)
- {
- if (CustomAdMediator != null)
- {
- CustomAdMediator.VerticalAlignment = VerticalAlignment.Bottom;
- CustomAdMediator.Visibility = Visibility.Visible;
- }
- else
- {
- CustomAdMediator.VerticalAlignment = VerticalAlignment.Bottom;
- CustomAdMediator.Visibility = Visibility.Visible;
- }
- }
- }
- catch
- {
- }
- }
- break;
- case eEXTERNAL_REQ_TYPE.Show_FullScreen_Ads:
- {
- // Debug.WriteLine("Show_FullScreen_Ads_Called");
- try
- {
- ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
- //check if net is available or not
- if (InternetConnectionProfile != null)
- {
- VMAXAdView adView = new VMAXAdView();
- adView.AdspotId = interstitialTestAdspotId;
- adView.UX = AdUX.Interstitial; // To specify banner ads.
- adView.LoadAd();
- adView.ShowAd();
- }
- }
- catch
- {
- }
- }
- break;
- case eEXTERNAL_REQ_TYPE.Hide_Banner_Ads:
- {
- // Debug.WriteLine("Hide_Banner_Ads_Called");
- if (CustomAdMediator != null)
- {
- CustomAdMediator.Visibility = Visibility.Collapsed;
- }
- }
- break;
- //Google Universal Analytics
- case eEXTERNAL_REQ_TYPE.GoogleAnalyticsScreen:
- {
- GoogleAnalytics.EasyTracker.GetTracker().SetStartSession(true);
- GoogleAnalytics.EasyTracker.GetTracker().SendView(strData);
- }
- break;
- case eEXTERNAL_REQ_TYPE.GoogleAnalyticsEvent:
- {
- GoogleAnalytics.EasyTracker.GetTracker().SendEvent(strData, null, null, 0);
- }
- break;
- case eEXTERNAL_REQ_TYPE.sendLiveTileNotify:
- {
- AppCallbacks.Instance.InvokeOnUIThread(new AppCallbackItem(() =>
- {
- UpdateTile(strData);
- }), false);
- }
- break;
- case eEXTERNAL_REQ_TYPE.ShareScore:
- {
- try
- {
- shareData = strData;
- dataTransferManager = DataTransferManager.GetForCurrentView();
- dataTransferManager.DataRequested += new TypedEventHandler(this.OnDataRequested);
- DataTransferManager.ShowShareUI();
- }
- catch
- {
- }
- }
- break;
- case eEXTERNAL_REQ_TYPE.RateApplication:
- {
- try
- {
- ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
- if (InternetConnectionProfile != null) //check if net is available or not
- {
- RateApp();
- }
- }
- catch
- {
- ExternalInterfaceHandler.Instance.Receiver("false");
- }
- }
- break;
- case eEXTERNAL_REQ_TYPE.MoreGames:
- {
- string uriToLaunch = "http://www.windowsphone.com/en-us/store/search?q=dumadu+games+pvt+ltd";
- Uri Url;
- Url = new Uri(uriToLaunch);
- }
- break;
- default:
- break;
- }
- }), false);
- }
- private void SocialMediaShare()
- {
- }
- private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
- {
- Uri appLaunchURI = ValidateAndGetUri(appLaunchUrl);
- string dataPackageText = "Wow! It's " + ApreciationMessage[randomMessage.Next(0, ApreciationMessage.Length)] + " beat my Levels if you can! : " + shareData;
- if (!String.IsNullOrEmpty(dataPackageText))
- {
- DataPackage requestData = e.Request.Data;
- requestData.Properties.Title = "BeerPong TrickShot";
- requestData.SetText(dataPackageText + " Have you tried it ? Go for the link." + appLaunchURI);
- }
- else
- {
- //request.FailWithDisplayText("Enter the text you would like to share and try again.");
- }
- }
- private Uri ValidateAndGetUri(string uriString)
- {
- Uri uri = null;
- try
- {
- uri = new Uri(uriString);
- }
- catch (FormatException)
- {
- }
- return uri;
- }
- private async void RateApp()
- {
- //await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store:reviewapp?appid="+CurrentApp.AppId));
- await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store:reviewapp"));
- }
- private void UpdateTile(string tileData)
- {
- UnityEngine.WSA.Tile liveTile = UnityEngine.WSA.Tile.main;
- liveTile.Update("ms-appx:///Assets/SquareTile.png", "ms-appx:///Assets/Wide310x150Logo.scale-100.png", "ms-appx:///Assets/Square310x310Logo.scale-100.png", tileData); //mwl
- }
- private async void mDoPurchaseOrFullfillItem(string msProductId, bool isRestore, bool itemIsConsumable)
- {
- if (isRestore && itemIsConsumable)
- {
- IReadOnlyList LstProcts = await store.GetUnfulfilledConsumablesAsync();
- for (int i = 0; i <= LstProcts.Count; i++)
- {
- FulfillmentResult result = await store.ReportConsumableFulfillmentAsync(LstProcts[i].ProductId, LstProcts[i].TransactionId);//TransactionId);
- switch (result)
- {
- case FulfillmentResult.Succeeded:
- break;
- case FulfillmentResult.NothingToFulfill:
- case FulfillmentResult.PurchasePending:
- case FulfillmentResult.PurchaseReverted:
- case FulfillmentResult.ServerError:
- // Win8StoreInterfaceHandler._temTextToDisplayInAppRes = "server Error";
- break;
- default:
- break;
- }
- }
- }
- else
- {
- try
- {
- PurchaseResults purchaseResults = await store.RequestProductPurchaseAsync(msProductId);
- switch (purchaseResults.Status)
- {
- case ProductPurchaseStatus.Succeeded:
- {
- if (itemIsConsumable)
- {
- FulfillmentResult result = await store.ReportConsumableFulfillmentAsync(msProductId, purchaseResults.TransactionId);
- switch (result)
- {
- case FulfillmentResult.Succeeded:
- ExternalInterfaceHandler.Instance.Receiver("true");
- break;
- case FulfillmentResult.NothingToFulfill:
- case FulfillmentResult.PurchasePending:
- case FulfillmentResult.PurchaseReverted:
- case FulfillmentResult.ServerError:
- // Win8StoreInterfaceHandler._temTextToDisplayInAppRes = "server Error";
- break;
- default:
- break;
- }
- }
- else
- {
- ExternalInterfaceHandler.Instance.Receiver("true");
- }
- } //success
- break;
- case ProductPurchaseStatus.NotFulfilled:
- {
- FulfillmentResult result = await store.ReportConsumableFulfillmentAsync(msProductId, purchaseResults.TransactionId);
- switch (result)
- {
- case FulfillmentResult.Succeeded:
- ExternalInterfaceHandler.Instance.Receiver("true");
- break;
- case FulfillmentResult.NothingToFulfill:
- case FulfillmentResult.PurchasePending:
- case FulfillmentResult.PurchaseReverted:
- case FulfillmentResult.ServerError:
- // Win8StoreInterfaceHandler._temTextToDisplayInAppRes = "server Error";
- break;
- default:
- break;
- }
- } //success but not full filled
- break;
- case ProductPurchaseStatus.NotPurchased:
- ExternalInterfaceHandler.Instance.Receiver("false");
- break;
- }
- }
- catch (Exception)
- {
- //Win8StoreInterfaceHandler._temTextToDisplayInAppRes = "In not Working";
- }
- }
- }
- #if !UNITY_WP_8_1
- protected override Windows.UI.Xaml.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
- {
- return new UnityPlayer.XamlPageAutomationPeer(this);
- }
- //Interstitial adds setup
- //void MyInterstitialAd_AdReady(object sender, object e)
- //{
- // AdIsReady = true;
- // AdReady();
- //}
- //public static async void AdReady()
- //{
- // var dialog = new MessageDialog("Ad Is Ready To Load");
- // dialog.Commands.Add(new UICommand("ok"));
- // await dialog.ShowAsync();
- //}
- //private void Button_Click(object sender, RoutedEventArgs e)
- //{
- // NewMethod();
- //}
- //private void NewMethod()
- //{
- // myInterstitialAd.RequestAd(AdType.Video, myAppId, myAdUnitId);
- //}
- //private void Button_Click_1(object sender, RoutedEventArgs e)
- //{
- // if (InterstitialAdState.Ready == myInterstitialAd.State)
- // {
- // myInterstitialAd.Show();
- // }
- //}
- #else
- // This is the default setup to show location consent message box to the user
- // You can customize it to your needs, but do not remove it completely if your application
- // uses location services, as it is a requirement in Windows Store certification process
- private async void SetupLocationService()
- {
- AppCallbacks appCallbacks = AppCallbacks.Instance;
- if (!appCallbacks.IsLocationCapabilitySet())
- {
- return;
- }
- const string settingName = "LocationContent";
- bool userGaveConsent = false;
- object consent;
- var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
- var userWasAskedBefore = settings.Values.TryGetValue(settingName, out consent);
- if (!userWasAskedBefore)
- {
- var messageDialog = new Windows.UI.Popups.MessageDialog("Can this application use your location?", "Location services");
- var acceptCommand = new Windows.UI.Popups.UICommand("Yes");
- var declineCommand = new Windows.UI.Popups.UICommand("No");
- messageDialog.Commands.Add(acceptCommand);
- messageDialog.Commands.Add(declineCommand);
- userGaveConsent = (await messageDialog.ShowAsync()) == acceptCommand;
- settings.Values.Add(settingName, userGaveConsent);
- }
- else
- {
- userGaveConsent = (bool)consent;
- }
- if (userGaveConsent)
- { // Must be called from UI thread
- appCallbacks.SetupGeolocator();
- }
- }
- #endif
- }
- }
Sundaram SubramanianPosted Sep 20, 2017, 3:24 AM