private async void btnChangeAvater_Tapped(object sender, TappedRoutedEventArgs e) { FileOpenPicker picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); // 选取单个文件 StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var stream = await file.OpenSequentialReadAsync(); await WebProvider.GetInstance().SendPostRequestAsync("http://news-at.zhihu.com/api/4/avatar", stream); string resJosn = await WebProvider.GetInstance().GetRequestDataAsync("http://news-at.zhihu.com/api/4/account"); var UserInfo = JsonConvertHelper.JsonDeserialize <UserInfo>(resJosn); ViewModel.ViewModelLocator.AppShell.UserInfo.Avatar = UserInfo.Avatar; ViewModel.ViewModelLocator.AppShell.UserInfo.Name = UserInfo.Name; ViewModel.ViewModelLocator.AppShell.UserInfo.BoundServices = UserInfo.BoundServices; AppSettings.Instance.UserInfoJson = JsonConvertHelper.JsonSerializer(ViewModel.ViewModelLocator.AppShell.UserInfo); } }
public static string?GetBearer(this HttpRequest instance) { WebProvider.Trace($"Call to {nameof(GetBearer)}."); if (instance == null) { return(null); } if (instance.Headers == null) { WebProvider.Trace(" No headers found in the HTTP request."); return(null); } if (string.IsNullOrEmpty(instance.Headers["Authorization"])) { WebProvider.Trace(" No Authorization header provided."); return(null); } if (!instance.Headers["Authorization"].ToString().Trim().StartsWith("Bearer")) { WebProvider.Trace(" No Bearer token defined."); return(null); } return(instance.Headers["Authorization"].ToString().Replace("Bearer", string.Empty).Trim()); }
public IEnumerable <UpdateInfo> Get() { var longPollServer = (Provider as VKontakteApiProvider).Groups.GetLongPollServer(); var response = WebProvider.SendRequestAndGetJson( $"{longPollServer.Server}?act=a_check&key={longPollServer.Key}&ts={longPollServer.TimeStamp}&wait=25", new NameValueCollection() ); foreach (var eventKeyValuePair in response) { if (eventKeyValuePair.Value is not JArray) { continue; } var array = eventKeyValuePair.Value as JArray; foreach (var ev in array) { var evObject = ev as JObject; if (evObject == null) { continue; } if (evObject.ContainsKey("type") && TypeHandlers.ContainsKey(evObject["type"].ToString())) { yield return(TypeHandlers[evObject["type"].ToString()].Invoke(evObject["object"] as JObject)); } } } }
public AndroidApplicationContext(BaseScreen baseActivity, Settings settings, Action loadComplete) { ApplicationBackground += () => { }; ApplicationRestore += () => { }; GlobalVariables = new Dictionary <string, object>(); _baseActivity = baseActivity; _settings = settings; _loadComplete = loadComplete; LocationProvider = new GpsProvider(_baseActivity); LocationTracker = new GpsTracker(_baseActivity); GalleryProvider = new GalleryProvider(_baseActivity, this); CameraProvider = new CameraProvider(_baseActivity, this); DialogProvider = new DialogProvider(_baseActivity, this); DisplayProvider = new DisplayProvider(); ClipboardProvider = new ClipboardProvider(_baseActivity); EmailProvider = new EmailProvider(_settings, _baseActivity); JokeProviderInternal = new JokeProvider(_baseActivity); LocalNotificationProvider = new LocalNotificationProvider(_baseActivity); WebProvider = new WebProvider(_baseActivity); var builder = new SolutionBuilder(this); builder.Build(); _commonData = ValueStackContext.Current.CreateCommonData("Android"); }
public async Task SinaLogin() { try { string loginInfoJson = AppSettings.Instance.LoginInfoJson; var loginInfo = loginInfoJson != string.Empty ? SocialShare.Weibo.JsonConvertHelper.JsonDeserialize <LoginInfo>(loginInfoJson) : new LoginInfo(); WeiboClient client = new WeiboClient(loginInfo); loginInfo = await client.LoginAsync(); AppSettings.Instance.LoginInfoJson = SocialShare.Weibo.JsonConvertHelper.JsonSerializer(loginInfo); string resJson = await WebProvider.GetInstance().SendPostRequestAsync("http://news-at.zhihu.com/api/4/login", AppSettings.Instance.LoginInfoJson, WebProvider.ContentType.ContentType3); UserInfo userInfo = DataService.JsonConvertHelper.JsonDeserialize <UserInfo>(resJson); if (userInfo != null) { var folder = ApplicationData.Current.LocalFolder; string fileName = System.IO.Path.GetFileName(userInfo.Avatar); var storageFile = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); await new NewsImageDowloader().SaveImage(userInfo.Avatar, storageFile); userInfo.Avatar = $"ms-appdata:///local/{fileName}"; ViewModel.ViewModelLocator.AppShell.UserInfo = userInfo; AppSettings.Instance.UserInfoJson = DataService.JsonConvertHelper.JsonSerializer(userInfo); } } catch (Exception) { //ToastPrompt.ShowToast(ex.Message); } }
/// <summary> /// Clears the current active provider and forces the device data to be /// reloaded from source. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ButtonSettingsRefresh_Command(object sender, CommandEventArgs e) { if (WebProvider.ActiveProvider != null) { WebProvider.Download(); } }
public static string GetBearer(this HttpRequest instance) { WebProvider.Trace($"Call to {nameof(GetBearer)}."); if (instance == null) { return(null); } if (!(instance is DefaultHttpRequest httpRequest)) { WebProvider.Trace(" Invalid HTTP request."); return(null); } if (!(httpRequest.Headers is FrameRequestHeaders headers)) { WebProvider.Trace(" Invalid HTTP request headers."); return(null); } if (StringValues.IsNullOrEmpty(headers.HeaderAuthorization)) { WebProvider.Trace(" No Authorization header provided."); return(null); } if (!headers.HeaderAuthorization.ToString().Trim().StartsWith("Bearer")) { WebProvider.Trace(" No Bearer token defined."); return(null); } return(headers.HeaderAuthorization.ToString().Replace("Bearer", String.Empty).Trim()); }
public IOSApplicationContext(AppDelegate appDelegate, NavigationController controller, ApplicationSettings settings, CustomExceptionHandler exceptionHandler) { ApplicationBackground += () => { }; ApplicationRestore += () => { }; GlobalVariables = new Dictionary <string, object>(); Settings = settings; _controller = controller; _exceptionHandler = exceptionHandler; LocationProvider = new GpsProvider(); LocationTracker = new GPSTracker(); GalleryProvider = new GalleryProvider(controller, this); CameraProvider = new CameraProvider(controller, this); DialogProvider = new DialogProvider(this); DisplayProvider = new DisplayProvider(); ClipboardProvider = new ClipboardProvider(); EmailProvider = new EmailProvider(settings, appDelegate); JokeProviderInternal = new JokeProvider(); LocalNotificationProvider = new LocalNotificationProvider(); WebProvider = new WebProvider(); var builder = new SolutionBuilder(this); builder.Build(); StyleSheetContext.Current.Scale = UIScreen.MainScreen.Scale; }
public JToken SendRequest(string method, Dictionary <string, string> args, bool throwException = true) { if (!args.ContainsKey("access_token")) { args.Add("access_token", AccessToken); } if (!args.ContainsKey("v")) { args.Add("v", API_VERSION); } var response = WebProvider.SendRequestAndGetJson($"https://api.vk.com/method/{method}", args); if (response.ContainsKey("error")) { if (throwException) { throw new VKontakteErrorException( int.Parse(response["error"]["error_code"].ToString()), response["error"]["error_msg"].ToString() ); } return(null); } return(response["response"]); }
public async void LoadContent(long commentId) { string resJosn = await WebProvider.GetInstance().GetRequestDataAsync($"http://news-at.zhihu.com/api/4/comment/{commentId}/replies"); if (resJosn != string.Empty) { NotificationReply = JsonConvertHelper.JsonDeserialize <NotificationReply>(resJosn); } }
public async void LoadContent() { string resJosn = await WebProvider.GetInstance().GetRequestDataAsync("http://news-at.zhihu.com/api/4/notifications"); if (resJosn != string.Empty) { var jsonObj = Windows.Data.Json.JsonObject.Parse(resJosn); Notifications = JsonConvertHelper.JsonDeserialize <List <Notification> >(jsonObj["notifications"].ToString()); } }
public void InitWebView() { if (webView != null) { return; } position = windowRect; Debug.Log("UnityJSWindow: Init: making new WebView"); webView = new WebView(); object p = WebProvider.getView(this); Debug.Log("UnityJSWindow: Init: WebView init: this: " + this + " p: " + p); webView.init(p, new Rect(0, 0, position.width, position.height), false); Debug.Log("UnityJSWindow: Init: WebView defineScript"); webView.defineScript("Bridge", this); webView.allowRightClickMenu(true); webView.setDelegateObject(this); //Debug.Log("UnityJSWindow: Init: WebView showDevTools"); //webView.showDevTools(); string url; if (Bridge.bridge == null) { url = "about:blank"; } else { #if true url = "file://" + Application.dataPath + "/WebGLTemplates/Bridge" + "/bridge.html"; #else "http://localhost/Bridge/bridge.html"; //"http://DonHopkins.com/home/Bridge/bridge.html"; #endif url += "?random=" + Random.value; Debug.Log("UnityJSWindow: Init: url: " + url); } Debug.Log("UnityJSWindow: Init: LoadURL: " + url); LoadURL(url); }
/// <summary> /// The refresh button has been clicked, refresh the data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _buttonRefresh_Click(object sender, EventArgs e) { try { if (AutoUpdate.Download(LicenceKey.Keys) == LicenceKeyResults.Success) { WebProvider.Refresh(); } } catch (Exception ex) { EventLog.Warn(new MobileException("Exception refreshing data.", ex)); } }
/// <summary> /// Returns the javascript for the feature. /// </summary> /// <param name="request">Request the javascript is needed for</param> /// <returns>Javascript to support the feature if present</returns> private static Values GetJavascriptValues(HttpRequest request) { Values values = null; var match = WebProvider.GetMatch(request); if (match != null) { var javascript = match["JavascriptImageOptimiser"]; if (javascript != null && javascript.Count > 0) { values = javascript; } } return values; }
private async void tbEdit_Unchecked(object sender, RoutedEventArgs e) { string userName = tbUserName.Text.Trim(); if (userName != string.Empty && userName != ViewModel.ViewModelLocator.AppShell.UserInfo.Name) { ViewModel.ViewModelLocator.AppShell.UserInfo.Name = userName; string postJosn = "{" + $"\"name\":\"{userName}\"" + "}"; await WebProvider.GetInstance().SendPostRequestAsync("http://news-at.zhihu.com/api/4/name", postJosn, WebProvider.ContentType.ContentType3); AppSettings.Instance.UserInfoJson = JsonConvertHelper.JsonSerializer(ViewModel.ViewModelLocator.AppShell.UserInfo); } }
public void init() { this.position = windowRect; this.view = new WebView(); this.view.init(WebProvider.getView(this), new Rect(0, 22, this.position.width, this.position.height), false); this.view.defineScript("window.unityScriptObject", this); this.view.allowRightClickMenu(true); this.view.setDelegateObject(this); //this.view.loadURL(this.urlText); this.view.loadFile(string.Format(this.urlText, Application.dataPath)); }
/// <summary> /// Returns the javascript for the feature. /// </summary> /// <param name="request">Request the javascript is needed for</param> /// <returns>Javascript to support the feature if present</returns> private static Values GetJavascriptValues(HttpRequest request) { Values values = null; var match = WebProvider.GetMatch(request); if (match != null) { var javascript = match["JavascriptHardwareProfile"]; if (javascript != null && javascript.Count > 0) { values = javascript; } } return(values); }
public JToken SendRequest(string method, NameValueCollection args) { var response = WebProvider.SendRequestAndGetJson($"https://api.telegram.org/bot{AccessToken}/{method}", args); if (!((bool)response["ok"])) { throw new TelegramErrorException( int.Parse(response["error_code"].ToString()), response["description"].ToString() ); } return(response["result"]); }
public ProfileProvider(HttpContext _context) : base(_context) { this.ip = WebProvider.GetIP(_context); this.client = WebProvider.GetClient(_context); HttpCookie _cookie = this.context.Request.Cookies[this.key]; if (_cookie == null) { this.TokenCreate(); } this.TokenActive(); this.current = TokenData(); }
/// <summary> /// Set a static field to quickly determine if property /// value override is supported. /// </summary> /// <param name="application"></param> internal static void Init(HttpApplicationState application) { if (Configuration.Manager.FeatureDetectionEnabled == false || WebProvider.ActiveProvider == null) { _enabled = false; } else { _enabled = WebProvider.GetActiveProvider().DataSet. PropertyValueOverrideProperties.Length > 0; } EventLog.Debug(String.Format( "Property Value Override '{0}'", _enabled)); }
public JToken SendRequest(string method, NameValueCollection args) { args.Add("access_token", AccessToken); args.Add("v", API_VERSION); var response = WebProvider.SendRequestAndGetJson($"https://api.vk.com/method/{method}", args); if (response.ContainsKey("error")) { throw new VKontakteErrorException( int.Parse(response["error"]["error_code"].ToString()), response["error"]["error_msg"].ToString() ); } return(response["response"]); }
/// <summary> /// Set a property in the application state to quickly determine if property /// value override is supported. /// </summary> /// <param name="application"></param> internal static void Init(HttpApplicationState application) { if (Configuration.Manager.FeatureDetectionEnabled == false || WebProvider.ActiveProvider == null) { application[Constants.PropertyValueOverrideFlag] = new bool?(false); } else { application[Constants.PropertyValueOverrideFlag] = new bool?( WebProvider.GetActiveProvider().DataSet. PropertyValueOverrideProperties.Length > 0); } EventLog.Debug(String.Format( "Property Value Override '{0}'", application[Constants.PropertyValueOverrideFlag])); }
/// <summary> /// Returns all the JavaScript for both the Propery Value Override /// feature AND the request provided. /// </summary> /// <param name="request">Request the javascript is needed for</param> /// <returns>Javascript to support the feature if present</returns> private static List <Value> GetJavascriptValues(HttpRequest request) { var javaScriptValues = new List <Value>(); var match = WebProvider.GetMatch(request); if (match != null) { foreach (var property in WebProvider.GetActiveProvider(). DataSet.PropertyValueOverrideProperties) { foreach (var value in match[property]) { javaScriptValues.Add(value); } } } return(javaScriptValues); }
protected async Task <string> GetJsonDataAsync(string url) { //httpClient = new HttpClient(new MyHttpClientHandler()); //System.Diagnostics.Debug.WriteLine("Access Url:" + url); //var response = new HttpResponseMessage(); //try //{ // response = await httpClient.GetAsync(url); // string responseText = await response.Content.ReadAsStringAsync(); // response.EnsureSuccessStatusCode(); // return responseText; //} //catch (Exception) //{ // return string.Empty; //} return(await WebProvider.GetInstance().GetRequestDataAsync(url)); }
public JToken SendMultipartRequest(string method, List <WebMultipartContent> args, bool throwException = false) { var response = WebProvider.SendMultipartRequestAndGetJson($"https://api.telegram.org/bot{AccessToken}/{method}", args); if (!(bool)response["ok"]) { if (throwException) { throw new TelegramErrorException( int.Parse(response["error_code"].ToString()), response["description"].ToString() ); } return(null); } return(response["result"]); }
private string HandleAttachment(User user, IAttachment attachment) { var vkProvider = Provider as VKontakteApiProvider; if (attachment is PhotoAttachment photo) { var url = vkProvider.Photos.GetMessagesUploadServer(user.Id); var jObject = WebProvider.SendMultipartRequestAndGetJson(url, new[] { new WebMultipartContent( "photo", new StreamContent( new MemoryStream(photo.Content ?? GetBytes(photo.Url)))) }); return(vkProvider.Photos.SaveMessagesPhoto(jObject["photo"].ToString(), jObject["server"].ToString(), jObject["hash"].ToString())); } return(""); }
public bool SetCover(byte[] bytes, Crop crop1, Crop crop2) { var jObject = WebProvider.SendMultipartRequestAndGetJson(GetUploadServer(crop1, crop2), new[] { new WebMultipartContent( "photo", new StreamContent( new MemoryStream(bytes))) }); if (jObject.ContainsKey("error")) { throw new VKontakteErrorException( int.Parse(jObject["error"]["error_code"].ToString()), jObject["error"]["error_msg"].ToString() ); } return (jObject.ContainsKey("hash") && SetCover(jObject["hash"].ToString(), jObject["photo"].ToString())); }
internal static void OptimisedImageResponse(HttpContext context) { var size = GetRequiredSize(context); if (size.Width == 0 && size.Height == 0) { var match = WebProvider.GetMatch(context.Request); // Get the screen width and height. int value; if (match["ScreenPixelsWidth"] != null && match["ScreenPixelsWidth"].Count > 0 && int.TryParse(match["ScreenPixelsWidth"][0].ToString(), out value)) { size.Width = value; } if (match["ScreenPixelsHeight"] != null && match["ScreenPixelsHeight"].Count > 0 && int.TryParse(match["ScreenPixelsHeight"][0].ToString(), out value)) { size.Height = value; } // Use the larger of the two values as the width as there is no // way of knowing if the device is in landscape or portrait // orientation. size.Width = Math.Max(size.Width, size.Height); size.Height = 0; } // Ensure the size is not larger than the maximum parameters. ResolveSize(ref size); if (size.Width > 0 || size.Height > 0) { // Get the files and paths involved in the caching. var cachedFileVirtualPath = Image.Support.GetCachedResponseFile(context.Request, size); var cachedFilePhysicalPath = context.Server.MapPath(cachedFileVirtualPath); var cachedFile = new FileInfo(cachedFilePhysicalPath); var sourceFile = context.Server.MapPath(context.Request.AppRelativeCurrentExecutionFilePath); EventLog.Debug(String.Format( "Image processor is responding with image '{0}' of width '{1}' and height '{2}'", sourceFile, size.Width, size.Height)); // If the cached file doesn't exist or is out of date // then create a new cached file and serve this in response // to the request by rewriting the requested URL to the // static file. if (cachedFile.Exists == false || cachedFile.LastWriteTimeUtc < File.GetLastWriteTimeUtc(sourceFile)) { // Check the directory exists? if (cachedFile.Directory.Exists == false) { Directory.CreateDirectory(cachedFile.DirectoryName); } // Shrink the image to the cache file path. Use a bit depth of 32 pixels // as the image cache is not aware of the specific devices bit depth, only // the requested screen size. var processor = new Image.Processor(32); var source = new FileInfo(sourceFile); processor.Width = size.Width; processor.Height = size.Height; using (var cachedStream = new MemoryStream()) { try { // Make sure the source stream is closed when the shrinking // process has been completed. using (var sourceStream = source.OpenRead()) { processor.Shrink( sourceStream, cachedStream); } // Some times the GDI can produce larger files than the original. // Check for this to ensure the image is smaller. if (cachedStream.Length < source.Length) { // Use the cache stream for the new file. using (var fileStream = File.Create(cachedFilePhysicalPath)) { cachedStream.Position = 0; cachedStream.CopyTo(fileStream); } } else { // Copy the original file into the cache to avoid doing // this again in the future. source.CopyTo(cachedFilePhysicalPath); } } catch (Exception ex) { EventLog.Warn(String.Format( "Source file '{0}' generated exception '{1}' shrinking to '{2}' by '{3}'.", sourceFile, ex, processor.Width, processor.Height)); } } } if (File.Exists(cachedFilePhysicalPath)) { context.RewritePath(cachedFileVirtualPath, true); } else { context.RewritePath(context.Request.AppRelativeCurrentExecutionFilePath); } } }
internal WebServicesInfoProviderAttribute(WebProvider iWebProvider) { WebProvider = iWebProvider; }
public void toggleMaximaze() { WebProvider.toggle(this.web); }
public void Send(string message) { WebProvider.callback(this.callback, message); }
//private UISafeEvent<InternetFinderResultEventArgs> _OnResult; //private UISafeEvent<InternetFailedArgs> _OnInternetError; //public event EventHandler<InternetFinderResultEventArgs> OnResult //{ // add { _OnResult.Event += value; } // remove { _OnResult.Event -= value; } //} //public event EventHandler<InternetFailedArgs> OnInternetError //{ // add { _OnInternetError.Event += value; } // remove { _OnInternetError.Event -= value; } //} private void ConnectionDown(InternetFailed ifa, IProgress<InternetFailed> iInternetFailedArgs, WebProvider? Provider = null) { ifa.WebService = Provider; //_OnInternetError.Fire(ifa, true); iInternetFailedArgs.SafeReport(ifa); }