public string ParseResponseSetToRequestXml(int responseSetID) { using (var responseSetRepository = new ResponseSetRepository()) { var responseSet = responseSetRepository.GetResponseSetForUserByID(responseSetID); XDocument resultDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); XElement root = new XElement("data", new XAttribute("id", responseSet.Survey.SystemID), new XAttribute(XNamespace.Xmlns + "orx", Namespaces.JavaRosaMetaDataNamespace)); #region meta tag creation XElement meta = new XElement(Namespaces.JavaRosaMetaDataNamespace + "meta"); root.Add(meta); meta.Add(new XElement(Namespaces.JavaRosaMetaDataNamespace + "instanceID") { Value = responseSet.SystemID, }); meta.Add(new XElement(Namespaces.JavaRosaMetaDataNamespace + "deviceID") { Value = Convert.ToBase64String((byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId")) }); meta.Add(new XElement(Namespaces.JavaRosaMetaDataNamespace + "timeStart") { Value = responseSet.DateSaved.Value.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture) }); meta.Add(new XElement(Namespaces.JavaRosaMetaDataNamespace + "timeEnd") { Value = responseSet.DateModified.Value.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture) }); if (GpsTracker.Instance.UserLocation != null && new SettingsRepository().GetCurrentSettings().IsGpsEnabled) { meta.Add(new XElement(Namespaces.JavaRosaMetaDataNamespace + "geostamp") { Value = string.Format("{0} {1}", GpsTracker.Instance.UserLocation.Latitude, GpsTracker.Instance.UserLocation.Longitude), }); } #endregion foreach (var category in responseSet.Survey.Category) { XElement categoryXElement = new XElement(category.SystemID); foreach (var question in category.Question) { XElement questionXElement = new XElement(question.SystemID); var answer = responseSetRepository.GetQuestionAnswerByQuestionAndResponseSet(question.ID, responseSetID); if (answer != null) { questionXElement.Value = answer.AnswerText; } else { questionXElement.Value = question.Data.GetResult(); } categoryXElement.Add(questionXElement); } root.Add(categoryXElement); } return(root.ToString()); } }
private async void AttemptSaveAsync() { if (!Processing) { Processing = true; AdaptButtonsToState(); GC.Collect(); var lowMemory = false; try { long result = (long)DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit"); lowMemory = result / 1024 / 1024 < 300; } catch (ArgumentOutOfRangeException) { } IBuffer buffer = null; Model.OriginalImage.Position = 0; using (var source = new StreamImageSource(Model.OriginalImage)) using (var segmenter = new InteractiveForegroundSegmenter(source)) using (var annotationsSource = new BitmapImageSource(Model.AnnotationsBitmap)) { segmenter.Quality = lowMemory ? 0.5 : 1; segmenter.AnnotationsSource = annotationsSource; var foregroundColor = Model.ForegroundBrush.Color; var backgroundColor = Model.BackgroundBrush.Color; segmenter.ForegroundColor = Windows.UI.Color.FromArgb(foregroundColor.A, foregroundColor.R, foregroundColor.G, foregroundColor.B); segmenter.BackgroundColor = Windows.UI.Color.FromArgb(backgroundColor.A, backgroundColor.R, backgroundColor.G, backgroundColor.B); using (var effect = new LensBlurEffect(source, new LensBlurPredefinedKernel(Model.KernelShape, (uint)Model.KernelSize))) using (var renderer = new JpegRenderer(effect)) { effect.KernelMap = segmenter; try { buffer = await renderer.RenderAsync(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("AttemptSave rendering failed: " + ex.Message); } } } if (buffer != null) { using (var library = new MediaLibrary()) using (var stream = buffer.AsStream()) { library.SavePicture("lensblur_" + DateTime.Now.Ticks, stream); Model.Saved = true; AdaptButtonsToState(); } } Processing = false; AdaptButtonsToState(); } }
private static string GetDeviceId() { var id = (byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId"); return(BitConverter.ToString(id).Replace("-", string.Empty)); }
private void EnterUnlockCode() { var input = new InputPrompt { Title = "Enter your code", Message = "Please enter the code provided to you:", MessageTextWrapping = TextWrapping.Wrap }; input.Completed += async(sender, args) => { if (args.PopUpResult == PopUpResult.Ok) { var code = args.Result; var url = string.Format("http://scottisafoolws.apphb.com/ScottIsAFool/InTwo/unlock?emailaddress={0}&code={1}", _emailAddress, code); SetProgressBar("Checking code..."); try { if (!_navigationService.IsNetworkAvailable) { Log.Info("No network connection"); return; } Log.Info("Verifying unlock code"); var response = await _httpClient.GetStringAsync(url); if (response.ToLower().Equals("true")) { Log.Info("Verification successful"); var myDeviceId = (byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId"); var deviceIdAsString = Convert.ToBase64String(myDeviceId); FlurryWP8SDK.Api.LogEvent("UnlockCodeSuccessfull", new List <Parameter> { new Parameter("EmailAddress", _emailAddress), new Parameter("DeviceID", deviceIdAsString) }); App.SettingsWrapper.HasRemovedAds = true; Messenger.Default.Send(new NotificationMessage(Constants.Messages.ForceSettingsSaveMsg)); MessageBox.Show("Thanks, ads have now been removed for you.", "Success", MessageBoxButton.OK); _navigationService.GoBack(); } else { MessageBox.Show("The email address and code don't match our records, sorry.", "Not verified", MessageBoxButton.OK); Log.Info("Unable to verify email [{0}] with code [{1}]", _emailAddress, code); } } catch (Exception ex) { MessageBox.Show("There was an error verifying your unlock code, please try again later.", "Error", MessageBoxButton.OK); FlurryWP8SDK.Api.LogError("UnlockCode", ex); Log.ErrorException("UnlockCode", ex); } SetProgressBar(); } }; input.Show(); }
void _timerOfDebug_Tick(object sender, EventArgs e) { xDebugTextBlock.Text = "总内存:" + (long)DeviceExtendedProperties.GetValue("DeviceTotalMemory") / 1024 / 1024 + "当前使用:" + (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage") / 1024 / 1024; }
public static List <Diag> GetDiagnostics() { var list = new List <Diag>(); // Better design: diagnostics can retrieve a value safely. Never // had this fail though. try { string os = Environment.OSVersion.ToString(); os = os.Replace("Windows CE", "Windows Phone"); list.Add(new Diag { Title = "operating system", Value = os }); IAppPlatformVersion iapv = Application.Current as IAppPlatformVersion; if (iapv != null) { string a = "unknown"; if (iapv.AppPlatformVersion == "7.0") { a = "Windows Phone 7"; } else if (iapv.AppPlatformVersion == "7.1") { a = "Windows Phone 7.5"; } list.Add(new Diag("designed for app platform", a)); } IAppInfo iai = Application.Current as IAppInfo; if (iai != null) { list.Add(new Diag("app version", iai.Version)); } list.Add(new Diag("current culture", CultureInfo.CurrentCulture.ToString())); list.Add(new Diag("user interface culture", CultureInfo.CurrentUICulture.ToString())); // DEVICE EXTENDED PROPERTIES! object o; if (DeviceExtendedProperties.TryGetValue("DeviceManufacturer", out o)) { string s = o as string; if (s != null) { list.Add( new Diag( "phone manufacturer", string.Format(CultureInfo.InvariantCulture, "{0}", s) )); } } if (DeviceExtendedProperties.TryGetValue("DeviceName", out o)) { string s = o as string; if (s != null) { // device friendly names =) // and super inefficient code. sweet. var upper = s.ToUpperInvariant(); if (upper == "SGH-I937") { s = "Focus S"; } if (upper == "SGH-I917") { s = "Focus"; } if (upper == "SGH-I917R") { s = "Focus*"; } if (upper.StartsWith("SGH-I1677")) { s = "Focus Flash"; // need to validate. } if (upper == "XDEVICEEMULATOR") { s = "Windows Phone Emulator"; } list.Add( new Diag( "phone model", string.Format(CultureInfo.InvariantCulture, "{0}", s) )); } } list.Add( new Diag( "peak memory use", string.Format(CultureInfo.CurrentCulture, "{0:N} MB", DeviceStatus.ApplicationPeakMemoryUsage / (1024 * 1024)) )); list.Add( new Diag( "available app memory", string.Format(CultureInfo.CurrentCulture, "{0:N} MB", DeviceStatus.ApplicationMemoryUsageLimit / (1024 * 1024)) )); list.Add( new Diag( "reported memory", string.Format(CultureInfo.CurrentCulture, "{0:N} MB", DeviceStatus.DeviceTotalMemory / (1024 * 1024)) )); list.Add(new Diag("web services agent", FourSquareWebClient.ClientInformation)); } catch { } return(list); }
public void LoadDeviceId() { var id = Convert.ToBase64String((byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId")); _serviceClient.SetDeviceId(id); }
/** * Retrieves the values of MoSync System Properties */ public static string getDeviceInfo(string key) { // imei if (key.Equals("mosync.imei")) { string sImei = string.Empty; object objImei; if (Microsoft.Phone.Info.UserExtendedProperties.TryGetValue("ANID", out objImei)) { sImei = (string)objImei; return(sImei); } } // imsi - not available in WP7.1 if (key.Equals("mosync.imsi")) { //TODO } // lang if (key.Equals("mosync.iso-639-1")) { return(System.Globalization.CultureInfo.CurrentCulture.ToString()); } // lantg if (key.Equals("mosync.iso-639-2")) { return(System.Globalization.CultureInfo.CurrentCulture.Name); } // device info if (key.Equals("mosync.device")) { string device = DeviceStatus.DeviceManufacturer + ";" + DeviceStatus.DeviceFirmwareVersion; // + model name return(device); } // device name if (key.Equals("mosync.device.name")) { return(DeviceStatus.DeviceName); } //Note: to get a result requires ID_CAP_IDENTITY_DEVICE // to be added to the capabilities of the WMAppManifest // this will then warn users in marketplace if (key.Equals("mosync.device.UUID")) { byte[] sUUID = null; object uniqueId; if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId)) { sUUID = (byte[])uniqueId; return(BitConverter.ToString(sUUID)); } } // device OS if (key.Equals("mosync.device.OS")) { return(Environment.OSVersion.ToString()); } // device OS version if (key.Equals("mosync.device.OS.version")) { return(Environment.OSVersion.Version.ToString()); } // network connection type if (key.Equals("mosync.network.type")) { return(Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType.ToString()); } // in case of no information return("not available"); }
public static string GetDeviceHardwareVersion() { return(DeviceExtendedProperties.GetValue("DeviceHardwareVersion").ToString()); }
public static void DetermineIsTrail() { App.LastAutoBackupTime = DateTime.Now; HasAds = true; IsPremium = false; #if BETA IsPremium = true; #endif try { EmulatorSettings.Current.IsTrial = IsTrial; } catch (Exception) { } if (CurrentApp.LicenseInformation.ProductLicenses["noads_premium"].IsActive) { HasAds = false; IsPremium = true; return; //no need to check for other 2 licenses } //get information on in-app purchase if (CurrentApp.LicenseInformation.ProductLicenses["removeads"].IsActive) { HasAds = false; } if (CurrentApp.LicenseInformation.ProductLicenses["premiumfeatures"].IsActive) { IsPremium = true; } //check if a promotion code exists if (metroSettings.PromotionCode != null && metroSettings.PromotionCode != "") { byte[] byteCode; try { byteCode = Convert.FromBase64String(metroSettings.PromotionCode); } catch (Exception) { return; } string dataString = Convert.ToBase64String(DeviceExtendedProperties.GetValue("DeviceUniqueId") as byte[]) + "_noads_premium"; // Create byte arrays to hold original, encrypted, and decrypted data. UTF8Encoding ByteConverter = new UTF8Encoding(); byte[] originalData = ByteConverter.GetBytes(dataString); RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(2048); Stream src = Application.GetResourceStream(new Uri("Assets/VBA8publicKey.xml", UriKind.Relative)).Stream; using (StreamReader sr = new StreamReader(src)) { string text = sr.ReadToEnd(); RSAalg.FromXmlString(text); } RSAParameters Key = RSAalg.ExportParameters(false); if (PurchasePage.VerifySignedHash(originalData, byteCode, Key)) { HasAds = false; IsPremium = true; } } }
public static string GetDeviceUniqueId() { return(DeviceExtendedProperties.GetValue("DeviceUniqueId").ToString()); }
public static string GetDeviceName() { return((string)DeviceExtendedProperties.GetValue("DeviceName")); }
public static string GetDeviceManufacturer() { return(DeviceExtendedProperties.GetValue("DeviceManufacturer").ToString()); }
//get device name public static string getDeviceName() { return(DeviceExtendedProperties.GetValue("DeviceName").ToString()); }
public void LogMemoryUsage() { this.Info("Memory usage: {0}", (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage")); }
private static void SendSession(string currentChannelUri) { if (sessionCallInProgress || sessionCallDone) { return; } sessionCallInProgress = true; string adId; var type = Type.GetType("Windows.System.UserProfile.AdvertisingManager, Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"); if (type != null) // WP8.1 devices { adId = (string)type.GetProperty("AdvertisingId").GetValue(null, null); } else // WP8.0 devices, requires ID_CAP_IDENTITY_DEVICE { adId = Convert.ToBase64String((byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId")); } if (currentChannelUri != null && mChannelUri != currentChannelUri) { mChannelUri = currentChannelUri; if (settings.Contains("GameThriveChannelUri")) { settings["GameThriveChannelUri"] = mChannelUri; } else { settings.Add("GameThriveChannelUri", mChannelUri); } settings.Save(); } JObject jsonObject = JObject.FromObject(new { device_type = 3, app_id = mAppId, identifier = mChannelUri, ad_id = adId, device_model = DeviceStatus.DeviceName, device_os = Environment.OSVersion.Version.ToString(), game_version = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Version").Value, language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.ToString(), timezone = TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds.ToString(), sdk = VERSION }); var cli = GetWebClient(); cli.UploadStringCompleted += (senderObj, eventArgs) => { sessionCallInProgress = false; if (eventArgs.Error == null) { sessionCallDone = true; if (fallBackOneSignalSession != null) { Deployment.Current.Dispatcher.BeginInvoke(() => { fallBackOneSignalSession.Dispose(); }); } if (mPlayerId == null) { mPlayerId = (string)JObject.Parse(eventArgs.Result)["id"]; settings.Add("GameThrivePlayerId", mPlayerId); settings.Save(); if (idsAvailableDelegate != null) { idsAvailableDelegate(mPlayerId, mChannelUri); } } } }; string urlString = BASE_URL + "api/v1/players"; if (mPlayerId != null) { urlString += "/" + mPlayerId + "/on_session"; } cli.UploadStringAsync(new Uri(urlString), jsonObject.ToString()); }
/// <summary> /// Resolves the screen resolution and display size. /// </summary> private async void ResolveScreenResolutionAsync() { // Initialise the values ScreenResolution = Resolutions.Unknown; ScreenResolutionSize = new Size(0, 0); double rawPixelsPerViewPixel = 0; double rawDpiX = 0; double rawDpiY = 0; double logicalDpi = 0; double screenResolutionX = 0; double screenResolutionY = 0; await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () => { #if WINDOWS_PHONE_APP DisplayInformation displayInformation = Windows.Graphics.Display.DisplayInformation.GetForCurrentView(); rawPixelsPerViewPixel = displayInformation.RawPixelsPerViewPixel; rawDpiX = displayInformation.RawDpiX; rawDpiY = displayInformation.RawDpiY; logicalDpi = displayInformation.LogicalDpi; screenResolutionX = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Bounds.Width *rawPixelsPerViewPixel; screenResolutionY = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Bounds.Height *rawPixelsPerViewPixel; #elif NETFX_CORE #else object objExtendedProperty; if (DeviceExtendedProperties.TryGetValue("PhysicalScreenResolution", out objExtendedProperty)) { var physicalScreenResolution = (Size)objExtendedProperty; screenResolutionY = (int)physicalScreenResolution.Height; screenResolutionX = (int)physicalScreenResolution.Width; } else { var scaleFactor = Application.Current.Host.Content.ScaleFactor; screenResolutionY = (int)(Application.Current.Host.Content.ActualHeight *scaleFactor); screenResolutionX = (int)(Application.Current.Host.Content.ActualWidth *scaleFactor); } objExtendedProperty = null; if (DeviceExtendedProperties.TryGetValue("RawDpiX", out objExtendedProperty)) { rawDpiX = (double)objExtendedProperty; } if (DeviceExtendedProperties.TryGetValue("RawDpiY", out objExtendedProperty)) { rawDpiY = (double)objExtendedProperty; } // Get PhysicalScreenResolution //if (DeviceExtendedProperties.TryGetValue("PhysicalScreenResolution", out objExtendedProperty)) //{ // var scaleFactor = Application.Current.Host.Content.ScaleFactor; // var screenResolution = (Size)objExtendedProperty; // var width = Application.Current.Host.Content.ActualWidth; // var physicalSize = new Size(screenResolution.Width / rawDpiX, screenResolution.Height / rawDpiY); // var scale = Math.Max(1, physicalSize.Width / DisplayConstants.BaselineWidthInInches); // var idealViewWidth = Math.Min(DisplayConstants.BaselineWidthInViewPixels * scale, screenResolution.Width); // var idealScale = screenResolution.Width / idealViewWidth; // rawPixelsPerViewPixel = idealScale.NudgeToClosestPoint(1); //bucketizedScale // var viewResolution = new Size(screenResolution.Width / rawPixelsPerViewPixel, screenResolution.Height / rawPixelsPerViewPixel); //} #endif }); ScreenResolutionSize = new Size(Math.Round(screenResolutionX), Math.Round(screenResolutionY)); if (screenResolutionY < 960) { ScreenResolution = Resolutions.WVGA; } else if (screenResolutionY < 1280) { ScreenResolution = Resolutions.qHD; } else if (screenResolutionY < 1920) { if (screenResolutionX < 768) { ScreenResolution = Resolutions.HD720; } else { ScreenResolution = Resolutions.WXGA; } } else if (screenResolutionY > 1280) { ScreenResolution = Resolutions.HD1080; } if (rawDpiX > 0 && rawDpiY > 0) { // Calculate screen diagonal in inches. DisplaySizeInInches = Math.Sqrt(Math.Pow(ScreenResolutionSize.Width / rawDpiX, 2) + Math.Pow(ScreenResolutionSize.Height / rawDpiY, 2)); DisplaySizeInInches = Math.Round(DisplaySizeInInches, 1); // One decimal is enough } Debug.WriteLine(DebugTag + "ResolveScreenResolutionAsync(): Screen properties:" + "\n - Raw pixels per view pixel: " + rawPixelsPerViewPixel + "\n - Raw DPI: " + rawDpiX + ", " + rawDpiY + "\n . Logical DPI: " + logicalDpi + "\n - Resolution: " + ScreenResolution + "\n - Resolution in pixels: " + ScreenResolutionSize + "\n - Screen size in inches: " + DisplaySizeInInches); AsyncOperationComplete(); }
//Initialize the default starting properties. Should only be called once by MobileAppTracker. internal MATParameters(string advId, string advKey) { // Initialize Parameters this.advertiserId = advId; this.advertiserKey = advKey; matResponse = null; this.AllowDuplicates = false; this.DebugMode = false; this.ExistingUser = false; this.AppAdTracking = true; this.Gender = MATGender.NONE; // Get Windows AID through Reflection if app on WP8.1 device var type = Type.GetType("Windows.System.UserProfile.AdvertisingManager, Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"); this.WindowsAid = type != null ? (string)type.GetProperty("AdvertisingId").GetValue(null, null) : null; // If app has a Store app id, use it as package name if (CurrentApp.AppId != Guid.Empty) { this.PackageName = CurrentApp.AppId.ToString(); } else { // Fallback is to try to get WMAppManifest ProductID XElement app = XDocument.Load("WMAppManifest.xml").Root.Element("App"); this.AppName = GetValue(app, "Title"); this.AppVersion = GetValue(app, "Version"); string productId = GetValue(app, "ProductID"); if (productId != null) { this.PackageName = Regex.Match(productId, "(?<={).*(?=})").Value; } } byte[] deviceUniqueId = (byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId"); this.DeviceUniqueId = Convert.ToBase64String(deviceUniqueId); this.DeviceBrand = DeviceStatus.DeviceManufacturer; this.DeviceModel = DeviceStatus.DeviceName; this.DeviceCarrier = DeviceNetworkInformation.CellularMobileOperator; Version version = Environment.OSVersion.Version; this.OSVersion = String.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision); this.DeviceScreenSize = GetScreenRes(); // Check if we can restore existing MAT ID or should generate new one if (IsolatedStorageSettings.ApplicationSettings.Contains(MATConstants.SETTINGS_MATID_KEY)) { this.MatId = (string)IsolatedStorageSettings.ApplicationSettings[MATConstants.SETTINGS_MATID_KEY]; } else // Don't have MAT ID, generate new guid { this.MatId = System.Guid.NewGuid().ToString(); SaveLocalSetting(MATConstants.SETTINGS_MATID_KEY, this.MatId); } // Get saved values from LocalSettings if (GetLocalSetting(MATConstants.SETTINGS_PHONENUMBER_KEY) != null) { this.PhoneNumber = (string)GetLocalSetting(MATConstants.SETTINGS_PHONENUMBER_KEY); this.PhoneNumberMd5 = MATEncryption.Md5(this.PhoneNumber); this.PhoneNumberSha1 = MATEncryption.Sha1(this.PhoneNumber); this.PhoneNumberSha256 = MATEncryption.Sha256(this.PhoneNumber); } if (GetLocalSetting(MATConstants.SETTINGS_USEREMAIL_KEY) != null) { this.UserEmail = (string)GetLocalSetting(MATConstants.SETTINGS_USEREMAIL_KEY); this.UserEmailMd5 = MATEncryption.Md5(this.UserEmail); this.UserEmailSha1 = MATEncryption.Sha1(this.UserEmail); this.UserEmailSha256 = MATEncryption.Sha256(this.UserEmail); } this.UserId = (string)GetLocalSetting(MATConstants.SETTINGS_USERID_KEY); if (GetLocalSetting(MATConstants.SETTINGS_USERNAME_KEY) != null) { this.UserName = (string)GetLocalSetting(MATConstants.SETTINGS_USERNAME_KEY); this.UserNameMd5 = MATEncryption.Md5(this.UserName); this.UserNameSha1 = MATEncryption.Sha1(this.UserName); this.UserNameSha256 = MATEncryption.Sha256(this.UserName); } }
//------------------------------------------------------------------------- /// <summary> /// The async method to send session. /// </summary> /// <param name="currentChannelUri">The current channel uri.</param> private static Task <bool> SendSessionAsync(string currentChannelUri) { var taskComplete = new TaskCompletionSource <bool>(); if (!sessionCallInProgress && !sessionCallDone) { sessionCallInProgress = true; string adId; var type = Type.GetType("Windows.System.UserProfile.AdvertisingManager, Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"); if (type != null) // WP8.1 devices { adId = (string)type.GetProperty("AdvertisingId").GetValue(null, null); } else // WP8.0 devices, requires ID_CAP_IDENTITY_DEVICE { adId = Convert.ToBase64String((byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId")); } if (currentChannelUri != null && mChannelUri != currentChannelUri) { mChannelUri = currentChannelUri; if (settings.Contains("GameThriveChannelUri")) { settings["GameThriveChannelUri"] = mChannelUri; } else { settings.Add("GameThriveChannelUri", mChannelUri); } settings.Save(); } JObject jsonObject = JObject.FromObject(new { device_type = 3, app_id = mAppId, identifier = mChannelUri, ad_id = adId, device_model = DeviceStatus.DeviceName, device_os = Environment.OSVersion.Version.ToString(), game_version = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Version").Value, language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.ToString(), timezone = TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds.ToString(), sdk = VERSION }); var webClient = GetWebClient(); webClient.UploadStringCompleted += (s, e) => { bool result = false; if (!e.Cancelled && e.Error == null) { sessionCallDone = true; if (fallBackOneSignalSession != null) { Deployment.Current.Dispatcher.BeginInvoke(() => { fallBackOneSignalSession.Dispose(); }); } // Set player id if new one received or if changed (someone removed the device record on the server). string newPlayerId = (string)JObject.Parse(e.Result)["id"]; if (mPlayerId == null || ((mPlayerId != newPlayerId) && newPlayerId != null)) { mPlayerId = newPlayerId; settings["GameThrivePlayerId"] = mPlayerId; settings.Save(); } if (idsAvailableDelegate != null && mPlayerId != null && mChannelUri != null) { idsAvailableDelegate(mPlayerId, mChannelUri); } result = true; } sessionCallInProgress = false; taskComplete.TrySetResult(result); }; string urlString = BASE_URL + "api/v1/players"; if (mPlayerId != null) { urlString += "/" + mPlayerId + "/on_session"; } webClient.UploadStringAsync(new Uri(urlString), jsonObject.ToString()); } else { taskComplete.TrySetResult(false); } return(taskComplete.Task); }
public static void BeginRecording() { // start a timer to report memory conditions every 3 seconds // timer = new Timer(state => { string c = "unassigned"; try { // } catch (ArgumentOutOfRangeException ar) { var c1 = ar.Message; } catch { c = "unassigned"; } string report = ""; report += Environment.NewLine + "Current: " + (DeviceStatus.ApplicationCurrentMemoryUsage / 1000000).ToString() + "MB\n" + "Peak: " + (DeviceStatus.ApplicationPeakMemoryUsage / 1000000).ToString() + "MB\n" + "Memory Limit: " + (DeviceStatus.ApplicationMemoryUsageLimit / 1000000).ToString() + "MB\n" + "Device Total Memory: " + (DeviceStatus.DeviceTotalMemory / 1000000).ToString() + "MB\n" + "Working Limit: " + Convert.ToInt32((Convert.ToDouble(DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit")) / 1000000)).ToString() + "MB"; Deployment.Current.Dispatcher.BeginInvoke(delegate { Debug.WriteLine(report); }); }, null, TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3)); }
// Do not add any additional code to this method private async void InitializePhoneApplication() { if (phoneApplicationInitialized) { return; } // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new RadPhoneApplicationFrame { // Add default page transitions animations Transition = new RadTransition() { ForwardInAnimation = AnimationService.GetPageInAnimation(), ForwardOutAnimation = AnimationService.GetPageOutAnimation(), BackwardInAnimation = AnimationService.GetPageInAnimation(), BackwardOutAnimation = AnimationService.GetPageOutAnimation(), } }; RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; #if WINDOWS_PHONE_81 RootFrame.Navigating += RootFrameOnNavigating; // Handle contract activation such as returned values from file open or save picker PhoneApplicationService.Current.ContractActivated += CurrentOnContractActivated; #endif // Assign the URI-mapper class to the application frame. RootFrame.UriMapper = new AssociationUriMapper(); // Initialize the application information AppInformation = new AppInformation(); // Initialize the links information LinkInformation = new LinkInformation(); //The next line enables a custom logger, if this function is not used OutputDebugString() is called //in the native library and log messages are only readable with the native debugger attached. //The default behavior of MegaLogger() is to print logs using Debug.WriteLine() but it could //be used to sends log to a file, for example. LogService.SetLoggerObject(new MegaLogger()); //You can select the maximum output level for debug messages. //By default FATAL, ERROR, WARNING and INFO will be enabled //DEBUG and MAX can only be enabled in Debug builds, they are ignored in Release builds LogService.SetLogLevel(MLogLevel.LOG_LEVEL_DEBUG); //You can send messages to the logger using LogService.Log(), those messages will be received //in the active logger LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Example log message"); // Set the ID for statistics MegaSDK.setStatsID(Convert.ToBase64String((byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId"))); // Initialize the main MegaSDK instance MegaSdk = new MegaSDK(AppResources.AppKey, String.Format("{0}/{1}/{2}", AppService.GetAppUserAgent(), DeviceStatus.DeviceManufacturer, DeviceStatus.DeviceName), ApplicationData.Current.LocalFolder.Path, new MegaRandomNumberProvider()); // Initialize the MegaSDK instance for Folder Links MegaSdkFolderLinks = new MegaSDK(AppResources.AppKey, String.Format("{0}/{1}/{2}", AppService.GetAppUserAgent(), DeviceStatus.DeviceManufacturer, DeviceStatus.DeviceName), ApplicationData.Current.LocalFolder.Path, new MegaRandomNumberProvider()); // Initialize the main drive CloudDrive = new CloudDriveViewModel(MegaSdk, AppInformation); // Add notifications listener. Needs a DriveViewModel GlobalDriveListener = new GlobalDriveListener(AppInformation); MegaSdk.addGlobalListener(GlobalDriveListener); // Add a global request listener to process all. MegaSdk.addRequestListener(this); // Add a global transfer listener to process all transfers. GlobalTransferListener = new GlobalTransferListener(); MegaSdk.addTransferListener(GlobalTransferListener); // Initialize the transfer listing MegaTransfers = new TransferQueu(); // Initialize Folders AppService.InitializeAppFolders(); // Set the current resolution that we use later on for our image selection AppService.CurrentResolution = ResolutionHelper.CurrentResolution; // Clear settings values we do no longer use AppService.ClearObsoleteSettings(); // Save the app version information for future use (like deleting settings) AppService.SaveAppInformation(); // Set MEGA red as Accent Color ((SolidColorBrush)Resources["PhoneAccentBrush"]).Color = (Color)Resources["MegaRedColor"]; // Ensure we don't initialize again phoneApplicationInitialized = true; }
//*********************************************************************************************************************** /// <summary> /// Constructeur statique de l'objet <b>DeviceInfos</b> /// </summary> //----------------------------------------------------------------------------------------------------------------------- static DeviceInfos() { //------------------------------------------------------------------------------------------------------------------- #region // ApplicationCulture //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- try { //--------------------------------------------------------------------------------------------------------------- ApplicationCulture = new CultureInfo("fr-FR"); foreach (CustomAttributeData Item in Assembly.GetExecutingAssembly().CustomAttributes) { if (Item.AttributeType == typeof(NeutralResourcesLanguageAttribute)) { foreach (var arg in Item.ConstructorArguments) { if (arg.Value is string) { ApplicationCulture = new CultureInfo((string)arg.Value); } } } } //--------------------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------------------- catch {} //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #endregion //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #region // OsVersion, DeviceName, Manufacturer, UserAgent & DeviceName //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- string UserAgentMask = string.Empty; DeviceInfos.OsVersion = "8.0"; DeviceInfos.DeviceName = "Lumia XXX"; DeviceInfos.Manufacturer = "Nokia"; if (Environment.OSVersion.Version.Major < 8) { UserAgentMask = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS {0};" + " Trident/5.0; IEMobile/9.0; Touch; {1}; {2})"; if (Environment.OSVersion.Version.Minor < 10) { DeviceInfos.OsVersion = "7.0"; DeviceInfos.Version = WindowsPhoneVersion.WP70; } else { DeviceInfos.OsVersion = "7.5"; DeviceInfos.Version = WindowsPhoneVersion.WP71; } } else if (Environment.OSVersion.Version.Major < 10) { UserAgentMask = "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone OS {0};" + " Trident/6.0; IEMobile/10.0; ARM; Touch; {1}; {2})"; if (Environment.OSVersion.Version.Minor < 10) { DeviceInfos.OsVersion = "8.0"; DeviceInfos.Version = WindowsPhoneVersion.WP80; } else { DeviceInfos.OsVersion = "8.1"; DeviceInfos.Version = WindowsPhoneVersion.WP81; } } else { UserAgentMask = "Mozilla/5.0 (Windows Phone {0}; Android 4.2.1; {1}; {2})" + " AppleWebKit/537.36 (KHTML, like Gecko)" + " Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/13.10586"; DeviceInfos.OsVersion = "10.0"; DeviceInfos.Version = WindowsPhoneVersion.WP10; } try { DeviceInfos.Manufacturer = DeviceStatus.DeviceManufacturer.ToTitleCase(); DeviceInfos.DeviceName = DeviceStatus.DeviceName.ToTitleCase(); } catch {} DeviceInfos.UserAgent = string.Format(UserAgentMask, DeviceInfos.OsVersion, DeviceInfos.Manufacturer, DeviceInfos.DeviceName); DeviceInfos.DeviceName = string.Format("{0} {1}", DeviceInfos.Manufacturer, DeviceInfos.DeviceName); //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #endregion //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #region // TextHeight, TitleHeight, ApplicationBar & DeviceType //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- TextHeight = 18; SystemBarHeight = 32; ApplicationBarHeight = 72; ApplicationButtonSize = 48; ApplicationButtonMarging = 12; MinimizedApplicationBarHeight = 30; DeviceType = DeviceType.SmartPhone; //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- try { //--------------------------------------------------------------------------------------------------------------- var AppBar = new ApplicationBar() { Opacity = 0 }; ApplicationBarHeight = AppBar.DefaultSize; //--------------------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------------------- catch {} //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- try { //--------------------------------------------------------------------------------------------------------------- if (!DesignerProperties.IsInDesignTool) { //----------------------------------------------------------------------------------------------------------- var Version81 = new Version(8, 1); //----------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------- if (Environment.OSVersion.Version >= Version81) { //------------------------------------------------------------------------------------------------------- object SizeObject; //------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------- if (DeviceExtendedProperties.TryGetValue("PhysicalScreenResolution", out SizeObject)) { //--------------------------------------------------------------------------------------------------- var screenResolution = (Size)SizeObject; object DpiObjet; //--------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------- if (DeviceExtendedProperties.TryGetValue("RawDpiY", out DpiObjet)) { var Dpi = (double)DpiObjet; if (Dpi > 0) { var ScreenDiagonal = Math.Sqrt( Math.Pow(screenResolution.Width / Dpi, 2) + Math.Pow(screenResolution.Height / Dpi, 2)); if (ScreenDiagonal >= 5) { TextHeight = 16; SystemBarHeight = 24; ApplicationBarHeight = 56; ApplicationButtonSize = 45; ApplicationButtonMarging = 6; MinimizedApplicationBarHeight = 23; DeviceType = DeviceType.Phablet; } } } //--------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------- } //----------------------------------------------------------------------------------------------------------- } //--------------------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------------------- catch {} //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #endregion //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #region // ScaleFactor //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #if WP7 //------------------------------------------------------------------------------------------------------------------- ScaleFactor = Factor.Scale_WVGA; //------------------------------------------------------------------------------------------------------------------- #endif //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #if WP80 //------------------------------------------------------------------------------------------------------------------- try { //--------------------------------------------------------------------------------------------------------------- switch (Application.Current.Host.Content.ScaleFactor) { //----------------------------------------------------------------------------------------------------------- case 100: ScaleFactor = Factor.Scale_WVGA; break; case 150: ScaleFactor = Factor.Scale_720P; break; case 160: ScaleFactor = Factor.Scale_WXGA; break; default: ScaleFactor = Factor.Scale_WVGA; break; //----------------------------------------------------------------------------------------------------------- } //--------------------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------------------- catch {} //------------------------------------------------------------------------------------------------------------------- #endif //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #if WP81 //------------------------------------------------------------------------------------------------------------------- try { //--------------------------------------------------------------------------------------------------------------- switch (Application.Current.Host.Content.ScaleFactor) { //----------------------------------------------------------------------------------------------------------- case 100: ScaleFactor = Factor.Scale_WVGA; break; case 150: ScaleFactor = Factor.Scale_720P; break; case 160: ScaleFactor = Factor.Scale_WXGA; break; case 225: ScaleFactor = Factor.Scale_1080P; break; default: ScaleFactor = Factor.Scale_WVGA; break; //----------------------------------------------------------------------------------------------------------- } //--------------------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------------------- catch {} //------------------------------------------------------------------------------------------------------------------- #endif //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #endregion //------------------------------------------------------------------------------------------------------------------- }
/// <summary> /// Send Nomination for changing pharmacy /// </summary> private void CallSendNominationWebService() { objSignUpViewModel.ProgressBarVisibilty = Visibility.Visible; string apiUrl1 = RxConstants.sendNomination; string deviceUniqueID = string.Empty; try { object deviceID; if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out deviceID)) { byte[] myDeviceID = (byte[])deviceID; deviceUniqueID = Convert.ToBase64String(myDeviceID); } string deviceName = string.Empty; object devicename; if (DeviceExtendedProperties.TryGetValue("DeviceName", out devicename)) { deviceName = devicename.ToString(); } LoginResponse objResponse = App.ObjLgResponse; if (objResponse != null) { SendNominationRequest objInputParameters = new SendNominationRequest { pharmacyid = App.LoginPharId.ToUpper(), deviceid = deviceUniqueID, model = DeviceModel, os = "Windows Phone", pushid = App.ApId, fullname = objResponse.payload.name, firstname = string.Empty, lastname = string.Empty, forename = string.Empty, surname = string.Empty, nhs = objResponse.payload.nhs, birthdate = objResponse.payload.birthdate, address1 = objResponse.payload.address1, address2 = objResponse.payload.address2, postcode = objResponse.payload.postcode, phone = objResponse.payload.phone, mail = objResponse.payload.mail, sex = Convert.ToString(objResponse.payload.sex), pin = App.HashPIN, country = objResponse.payload.country, mode = "old", verifyby = objResponse.payload.verifyby, surgery = new SendNominationRequestSurgery { name = objResponse.payload.surgery.name, address = objResponse.payload.surgery.address }, system_version = "android", app_version = "1.6", branding_version = "MLP" }; WebClient sendNominationswebservicecall = new WebClient(); var uri1 = new Uri(apiUrl1, UriKind.RelativeOrAbsolute); var json = JsonHelper.Serialize(objInputParameters); sendNominationswebservicecall.Headers["Content-type"] = "application/json"; sendNominationswebservicecall.UploadStringCompleted += sendNominationswebservicecall_UploadStringCompleted; sendNominationswebservicecall.UploadStringAsync(uri1, "POST", json); } App.IsChangePharmacy = false; } catch (Exception) { MessageBox.Show("Sorry, Unable to process your request."); } }
/// <summary> /// Gets the current memory usage, in bytes. Returns zero in non-debug mode /// </summary> /// <returns>Current usage</returns> public static long GetCurrentMemoryUsage() { // don't use DeviceExtendedProperties for release builds (requires a capability) return((long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage")); }
private async void AttemptUpdateImageAsync() { if (!Processing) { Processing = true; GC.Collect(); var lowMemory = false; try { long result = (long)DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit"); lowMemory = result / 1024 / 1024 < 300; } catch (ArgumentOutOfRangeException) { } var maxSide = lowMemory ? 2048.0 : 4096.0; Model.OriginalImage.Position = 0; using (var source = new StreamImageSource(Model.OriginalImage)) using (var segmenter = new InteractiveForegroundSegmenter(source)) using (var annotationsSource = new BitmapImageSource(Model.AnnotationsBitmap)) { segmenter.Quality = lowMemory ? 0.5 : 1; segmenter.AnnotationsSource = annotationsSource; var foregroundColor = Model.ForegroundBrush.Color; var backgroundColor = Model.BackgroundBrush.Color; segmenter.ForegroundColor = Windows.UI.Color.FromArgb(foregroundColor.A, foregroundColor.R, foregroundColor.G, foregroundColor.B); segmenter.BackgroundColor = Windows.UI.Color.FromArgb(backgroundColor.A, backgroundColor.R, backgroundColor.G, backgroundColor.B); var info = await source.GetInfoAsync(); double scaler, rotation; var width = info.ImageSize.Width; var height = info.ImageSize.Height; if (width > height) { scaler = maxSide / width; rotation = 90; var t = width; // We're rotating the image, so swap width and height width = height; height = t; } else { scaler = maxSide / height; rotation = 0; } scaler = Math.Max(1, scaler); _bitmap = new WriteableBitmap((int)(width * scaler), (int)(height * scaler)); using (var blurEffect = new LensBlurEffect(source, new LensBlurPredefinedKernel(Model.KernelShape, (uint)Model.KernelSize))) using (var filterEffect = new FilterEffect(blurEffect) { Filters = new[] { new RotationFilter(rotation) } }) using (var renderer = new WriteableBitmapRenderer(filterEffect, _bitmap)) { blurEffect.KernelMap = segmenter; try { await renderer.RenderAsync(); Image.Source = _bitmap; _bitmap.Invalidate(); ConfigureViewport(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("AttemptUpdateImageAsync rendering failed: " + ex.Message); } } } Processing = false; } }