public void Execute(ClientContext ctx, string library, Uri url, string description) { Logger.Verbose($"Started executing {nameof(AddLinkToLinkList)} for url '{url}' on library '{library}'"); var web = ctx.Web; var links = web.Lists.GetByTitle(library); var result = links.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(result); ctx.ExecuteQuery(); var existingLink = result .ToList() .Any(l => { var u = (FieldUrlValue)l.FieldValues["URL"]; return u.Url == url.ToString() && u.Description == description; }); if (existingLink) { Logger.Warning($"Link '{url}' with description '{description}' already exists"); return; } var newLink = links.AddItem(new ListItemCreationInformation()); newLink["URL"] = new FieldUrlValue { Url = url.ToString(), Description = description }; newLink.Update(); ctx.ExecuteQuery(); }
public static string GetSizedImageUrl(Uri ImageUrl, int Width, int Height) { if (!ImageUrl.IsNullOrEmpty()) { if (!ImageUrl.ToString().Contains("gravatar.com") || !ImageUrl.ToString().Contains("castroller.com")) { return String.Format("{0}/{2}/{3}/{1}", Config.SizedBaseUrl, ImageUrl.ToString().Replace("http://", "").Replace("//", "DSLASH"), Width, Height); } else { var min = Math.Min(Width, Height); ImageUrl = new Uri(ImageUrl.ToString().Replace("IMAGESIZE", min.ToString())); int defaultLocation = ImageUrl.ToString().IndexOf("d="); string defaultUrl = ImageUrl.ToString().Substring(defaultLocation + 2); return ImageUrl.ToString().Replace(defaultUrl, HttpUtility.UrlEncode(defaultUrl)); // string noDefault = ImageUrl.ToString().Substring(0, ImageUrl.ToString().IndexOf("&d=")); // return String.Format("{0}&d={1}", noDefault, HttpUtility.UrlEncode(defaultUrl)); } } else { return ""; } }
protected override void OnAppLinkRequestReceived(Uri uri) { var appDomain = "http://" + AppName.ToLowerInvariant() + "/"; if (!uri.ToString().ToLowerInvariant().StartsWith(appDomain)) return; var url = uri.ToString().Replace(appDomain, ""); var parts = url.Split('/'); if (parts.Length == 2) { var isPage = parts[0].Trim().ToLower() == "gallery"; if (isPage) { string page = parts[1].Trim(); var pageForms = Activator.CreateInstance(Type.GetType(page)); var appLinkPageGallery = pageForms as AppLinkPageGallery; if (appLinkPageGallery != null) { appLinkPageGallery.ShowLabel = true; (MainPage as MasterDetailPage)?.Detail.Navigation.PushAsync((pageForms as Page)); } } } base.OnAppLinkRequestReceived(uri); }
public override Object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } if (s_appStreamResolver == null) { Debug.Assert(false, "No IApplicationResourceStreamResolver is registered on the XmlXapResolver."); throw new XmlException(SR.Xml_InternalError, string.Empty); } if (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream) || ofObjectToReturn == typeof(Object)) { // Note that even though the parameter is called absoluteUri we will only accept // relative Uris here. The base class's ResolveUri can create a relative uri // if no baseUri is specified. // Check the argument for common schemes (http, file) and throw exception with nice error message. Stream stream; try { stream = s_appStreamResolver.GetApplicationResourceStream(absoluteUri); } catch (ArgumentException e) { throw new XmlException(SR.Xml_XapResolverCannotOpenUri, absoluteUri.ToString(), e, null); } if (stream == null) { throw new XmlException(SR.Xml_CannotFindFileInXapPackage, absoluteUri.ToString()); } return stream; } else { throw new XmlException(SR.Xml_UnsupportedClass, string.Empty); } }
public static void Set(Uri uri) { if (!Directory.Exists("C:\\WHP\\imgs")) { Directory.CreateDirectory("C:\\WHP\\imgs"); } string path = uri.ToString().Substring(uri.ToString().LastIndexOf("/") + 1); string text = Path.Combine("C:\\WHP\\imgs", path); if (!File.Exists(text)) { try { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri.ToString()); httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36"; using (Stream responseStream = httpWebRequest.GetResponse().GetResponseStream()) { using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.ReadWrite)) { responseStream.CopyTo(fileStream); fileStream.Flush(); } } } catch { return; } } Wallpaper.SystemParametersInfo(20, 0, text, 3); }
/// <summary> /// Create a IWebProxy Object which can be used to access the Internet /// This method will check the configuration if the proxy is allowed to be used. /// Usages can be found in the DownloadFavIcon or Jira and Confluence plugins /// </summary> /// <param name="url"></param> /// <returns>IWebProxy filled with all the proxy details or null if none is set/wanted</returns> public static IWebProxy CreateProxy(Uri uri) { IWebProxy proxyToUse = null; if (config.UseProxy) { proxyToUse = WebRequest.DefaultWebProxy; if (proxyToUse != null) { proxyToUse.Credentials = CredentialCache.DefaultCredentials; if (LOG.IsDebugEnabled) { // check the proxy for the Uri if (!proxyToUse.IsBypassed(uri)) { Uri proxyUri = proxyToUse.GetProxy(uri); if (proxyUri != null) { LOG.Debug("Using proxy: " + proxyUri.ToString() + " for " + uri.ToString()); } else { LOG.Debug("No proxy found!"); } } else { LOG.Debug("Proxy bypass for: " + uri.ToString()); } } } else { LOG.Debug("No proxy found!"); } } return proxyToUse; }
public static void getHrefs(string url) { // try to fetch href values from a webpage try { // Create an instance of HtmlWeb HtmlAgilityPack.HtmlWeb htmlWeb = new HtmlWeb(); // Creating an instance of HtmlDocument and loading the html source code into it. HtmlAgilityPack.HtmlDocument doc = htmlWeb.Load(url); // Adding the crawled url to the list of crawled urls VisitedPages.Add(url); // For each HTML <a> tag found in the document foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) { // Extract the href value from the <a> tag Uri l = new Uri(baseUrl, link.Attributes["href"].Value.ToString()); // check if the href value does not exist in the list or the queue and if it is a page of the url the user entered. if (!LinkQueue.Contains(l.ToString()) && !VisitedPages.Contains(l.ToString()) && l.Host.ToString() == baseUrl.Host.ToString()) { // Add the href value to the queue to get scanned. LinkQueue.Enqueue(l.ToString()); } } } catch { // return if anything goes wrong return; } }
public static CookieContainer GetUriCookieContainer(Uri uri) { CookieContainer l_Cookies = null; // Determine the size of the cookie int l_Datasize = 8192 * 16; StringBuilder l_CookieData = new StringBuilder(l_Datasize); if (!InternetGetCookieEx(uri.ToString(), null, l_CookieData, ref l_Datasize, InternetCookieHttponly, IntPtr.Zero)) { if (l_Datasize < 0) return null; // Allocate stringbuilder large enough to hold the cookie l_CookieData = new StringBuilder(l_Datasize); if (!InternetGetCookieEx(uri.ToString(), null, l_CookieData, ref l_Datasize, InternetCookieHttponly, IntPtr.Zero)) return null; } if (l_CookieData.Length > 0) { l_Cookies = new CookieContainer(); l_Cookies.SetCookies(uri, l_CookieData.ToString().Replace(';', ',')); } return l_Cookies; }
private static void Navigate(Uri source) { if (Deployment.Current.Dispatcher.CheckAccess()) Application.Current.Host.NavigationState = source.ToString(); else Deployment.Current.Dispatcher.InvokeAsync(() => Application.Current.Host.NavigationState = source.ToString()); }
/// <summary> /// Runs an HttpClient issuing a POST request against the controller. /// </summary> static async void RunClient() { var handler = new HttpClientHandler(); handler.Credentials = new NetworkCredential("Boris", "xyzxyz"); var client = new System.Net.Http.HttpClient(handler); var bizMsgDTO = new BizMsgDTO { Name = "Boris", Date = DateTime.Now, User = "Boris.Momtchev", }; // *** POST/CREATE BizMsg Uri address = new Uri(_baseAddress, "/api/BizMsgService"); HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), bizMsgDTO); // Check that response was successful or throw exception // response.EnsureSuccessStatusCode(); // BizMsg result = await response.Content.ReadAsAsync<BizMsg>(); // Console.WriteLine("Result: Name: {0}, Date: {1}, User: {2}, Id: {3}", result.Name, result.Date.ToString(), result.User, result.Id); Console.WriteLine(response.StatusCode + " - " + response.Headers.Location); // *** PUT/UPDATE BizMsg var testID = response.Headers.Location.AbsolutePath.Split('/')[3]; bizMsgDTO.Name = "Boris Momtchev"; response = await client.PutAsJsonAsync(address.ToString() + "/" + testID, bizMsgDTO); Console.WriteLine(response.StatusCode); // *** DELETE BizMsg response = await client.DeleteAsync(address.ToString() + "/" + testID); Console.WriteLine(response.StatusCode); }
public virtual SvgElement GetElementById(Uri uri) { if (uri.ToString().StartsWith("url(")) uri = new Uri(uri.ToString().Substring(4).TrimEnd(')'), UriKind.Relative); if (!uri.IsAbsoluteUri && this._document.BaseUri != null && !uri.ToString().StartsWith("#")) { var fullUri = new Uri(this._document.BaseUri, uri); var hash = fullUri.OriginalString.Substring(fullUri.OriginalString.LastIndexOf('#')); SvgDocument doc; switch (fullUri.Scheme.ToLowerInvariant()) { case "file": doc = SvgDocument.Open<SvgDocument>(fullUri.LocalPath.Substring(0, fullUri.LocalPath.Length - hash.Length)); return doc.IdManager.GetElementById(hash); case "http": case "https": var httpRequest = WebRequest.Create(uri); using (WebResponse webResponse = httpRequest.GetResponse()) { doc = SvgDocument.Open<SvgDocument>(webResponse.GetResponseStream()); return doc.IdManager.GetElementById(hash); } default: throw new NotSupportedException(); } } return this.GetElementById(uri.ToString()); }
internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false) { Core.AuthenticationManager authManager = new Core.AuthenticationManager(); string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string configFile = Path.Combine(appDataFolder, "OfficeDevPnP.PowerShell\\tokencache.dat"); FileTokenCache cache = new FileTokenCache(configFile); var context = authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache); var connectionType = ConnectionType.OnPrem; if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM")) { connectionType = ConnectionType.O365; } if (skipAdminCheck == false) { if (IsTenantAdminSite(context)) { connectionType = ConnectionType.TenantAdmin; } } return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()); }
public static string EncodeUri(Uri uri) { if (!uri.IsAbsoluteUri) { var uriString = uri.IsWellFormedOriginalString() ? uri.ToString() : Uri.EscapeUriString(uri.ToString()); return EscapeReservedCspChars(uriString); } var host = uri.Host; var encodedHost = EncodeHostname(host); var needsReplacement = !host.Equals(encodedHost); var authority = uri.GetLeftPart(UriPartial.Authority); if (needsReplacement) { authority = authority.Replace(host, encodedHost); } if (uri.PathAndQuery.Equals("/")) { return authority; } return authority + EscapeReservedCspChars(uri.PathAndQuery); }
public static void AddParametersToCommand(ICommand command, Uri uri) { try { NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(uri.Query); foreach (string key in nameValueCollection.Keys) { if (key == null || string.IsNullOrWhiteSpace(key)) { object[] str = new object[1]; str[0] = uri.ToString(); throw new DataServiceException(0x190, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.BadRequest, Resources.InvalidQueryParameterMessage, str)); } else { string[] values = nameValueCollection.GetValues(key); if ((int)values.Length == 1) { string str1 = values[0]; if (!string.IsNullOrWhiteSpace(str1)) { string str2 = key.Trim(); if (str2.StartsWith("$", StringComparison.OrdinalIgnoreCase)) { continue; } try { command.AddParameter(str2, str1.Trim(), true); } catch (ArgumentException argumentException1) { ArgumentException argumentException = argumentException1; object[] objArray = new object[1]; objArray[0] = uri.ToString(); throw new DataServiceException(0x190, string.Empty, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.BadRequest, Resources.InvalidQueryParameterMessage, objArray), string.Empty, argumentException); } } else { object[] objArray1 = new object[1]; objArray1[0] = uri.ToString(); throw new DataServiceException(0x190, ExceptionHelpers.GetExceptionMessage(Resources.InvalidQueryParameterMessage, objArray1)); } } else { object[] objArray2 = new object[1]; objArray2[0] = uri.ToString(); throw new DataServiceException(0x190, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.BadRequest, Resources.InvalidQueryParameterMessage, objArray2)); } } } } catch (Exception exception) { TraceHelper.Current.UriParsingFailed(uri.ToString()); throw; } }
public void Subscribe(Uri address, IEnumerable<string> messageTypes, DateTime? expiration) { if (address == null || messageTypes == null) return; using (var tx = NewTransaction()) using (var session = this.store.OpenSession()) { foreach (var messageType in messageTypes) { var type = messageType; var subscription = session.Query<Subscription>() .Where(s => s.Subscriber == address.ToString() && s.MessageType == type) .SingleOrDefault(); if (subscription == null) { subscription = new Subscription(address.ToString(), messageType, expiration); session.Store(subscription); } else subscription.Expiration = expiration; } session.SaveChanges(); tx.Complete(); } }
protected async Task Launch(Uri appToAppUri, Uri webFallbackUri) { #if WINDOWS_PHONE || NETFX_CORE #if WINDOWS_PHONE bool canLaunch = string.Equals(DeviceStatus.DeviceManufacturer, "Nokia", StringComparison.OrdinalIgnoreCase) || string.Equals(DeviceStatus.DeviceManufacturer, "Microsoft", StringComparison.OrdinalIgnoreCase); #else bool canLaunch = true; #endif if (canLaunch) { // Append the clientId if one has been supplied... if (!string.IsNullOrEmpty(this.ClientId)) { if (appToAppUri.ToString().Contains("?")) { appToAppUri = new Uri(appToAppUri.ToString() + "&client_id=" + this.ClientId); } else { appToAppUri = new Uri(appToAppUri.ToString() + "?client_id=" + this.ClientId); } } await Windows.System.Launcher.LaunchUriAsync(appToAppUri); return; } #endif #if WINDOWS_PHONE WebBrowserTask web = new WebBrowserTask(); web.Uri = webFallbackUri; web.Show(); #endif }
private ITransferRequest DownloadAsyncViaBackgroundTranfer(Uri serverUri, Uri phoneUri) { try { var request = new BackgroundTransferRequest(serverUri, phoneUri); request.Tag = serverUri.ToString(); request.TransferPreferences = TransferPreferences.AllowCellularAndBattery; int count = 0; foreach (var r in BackgroundTransferService.Requests) { count++; if (r.RequestUri == serverUri) return new WindowsTransferRequest(r); if (r.TransferStatus == TransferStatus.Completed) { BackgroundTransferService.Remove(r); count--; } // Max 5 downloads if (count >= 5) return null; } BackgroundTransferService.Add(request); PersistRequestToStorage(request); return new WindowsTransferRequest(request); } catch (InvalidOperationException) { return GetRequest(serverUri.ToString()); } }
static ItemBuilder MoreAt(this ItemBuilder dsl, Uri uri) { return dsl.More(() => { Process.Start(uri.ToString()); }, uri.ToString()); }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public static void ProcessQueueMessage( [QueueTrigger(SiteModificationManager.StorageQueueName)] SiteModificationData request, TextWriter log) { Uri url = new Uri(request.SiteUrl); //Connect to the OD4B site using App Only token string realm = TokenHelper.GetRealmFromTargetUrl(url); var token = TokenHelper.GetAppOnlyAccessToken( TokenHelper.SharePointPrincipal, url.Authority, realm).AccessToken; using (var ctx = TokenHelper.GetClientContextWithAccessToken( url.ToString(), token)) { // Set configuration object properly for setting the config SiteModificationConfig config = new SiteModificationConfig() { SiteUrl = url.ToString(), JSFile = Path.Combine(Environment.GetEnvironmentVariable("WEBROOT_PATH"), "Resources\\OneDriveConfiguration.js"), ThemeName = "Garage", ThemeColorFile = Path.Combine(Environment.GetEnvironmentVariable("WEBROOT_PATH"), "Resources\\Themes\\Garage\\garagewhite.spcolor"), ThemeBGFile = Path.Combine(Environment.GetEnvironmentVariable("WEBROOT_PATH"), "Resources\\Themes\\Garage\\garagebg.jpg"), ThemeFontFile = "" // Ignored in this case, but could be also set }; new SiteModificationManager().ApplySiteConfiguration(ctx, config); } }
public Task<RecivedId> Add(string body, Uri embed, int linkId, int precedentCommentId = -1) { if (embed == null) throw new ArgumentNullException(nameof(embed)); if (string.IsNullOrWhiteSpace(embed.ToString())) throw new ArgumentException("Argument is null or whitespace", nameof(body)); if (string.IsNullOrWhiteSpace(body)) throw new ArgumentException("Argument is null or whitespace", nameof(body)); var parameters = GetApiParameterSet(); var methodParameters = new SortedSet<StringMethodParameter> { new StringMethodParameter("param1", linkId) }; if (precedentCommentId != -1) methodParameters.Add(new StringMethodParameter("param2", precedentCommentId)); var postParameters = new SortedSet<PostParameter> { new StringPostParameter("body", body), new StringPostParameter("embed", embed.ToString()) }; return Client.CallApiMethodWithAuth<RecivedId>( new ApiMethod(ApiV1Constants.CommentsAdd, HttpMethod.Post, parameters, methodParameters, postParameters) ); }
// This function returns cookie data based on a uniform resource identifier public static CookieContainer GetUriCookieContainer(Uri uri) { // First, create a null cookie container CookieContainer cookies = null; // Determine the size of the cookie var datasize = 8192 * 16; var cookieData = new StringBuilder(datasize); // Call InternetGetCookieEx from wininet.dll if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero)) { if (datasize < 0) return null; // Allocate stringbuilder large enough to hold the cookie cookieData = new StringBuilder(datasize); if (!InternetGetCookieEx( uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero)) return null; } // If the cookie contains data, add it to the cookie container if (cookieData.Length > 0) { cookies = new CookieContainer(); cookies.SetCookies(uri, cookieData.ToString().Replace(';', ',')); } // Return the cookie container return cookies; }
internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false) { Core.AuthenticationManager authManager = new Core.AuthenticationManager(); if (realm == null) { realm = GetRealmFromTargetUrl(url); } var context = authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret); context.ApplicationName = Properties.Resources.ApplicationName; context.RequestTimeout = requestTimeout; var connectionType = ConnectionType.OnPrem; if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM")) { connectionType = ConnectionType.O365; } if (skipAdminCheck == false) { if (IsTenantAdminSite(context)) { connectionType = ConnectionType.TenantAdmin; } } return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()); }
public static IGithubServiceManagement CreateServiceManagementChannel(Uri remoteUri, string username, string password) { WebChannelFactory<IGithubServiceManagement> factory; if (_factories.ContainsKey(remoteUri.ToString())) { factory = _factories[remoteUri.ToString()]; } else { factory = new WebChannelFactory<IGithubServiceManagement>(remoteUri); factory.Endpoint.Behaviors.Add(new GithubAutHeaderInserter() {Username = username, Password = password}); WebHttpBinding wb = factory.Endpoint.Binding as WebHttpBinding; wb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; wb.Security.Mode = WebHttpSecurityMode.Transport; wb.MaxReceivedMessageSize = 10000000; if (!string.IsNullOrEmpty(username)) { factory.Credentials.UserName.UserName = username; } if (!string.IsNullOrEmpty(password)) { factory.Credentials.UserName.Password = password; } _factories[remoteUri.ToString()] = factory; } return factory.CreateChannel(); }
public override object GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) { if (Message != null) { Console.WriteLine(Message + absoluteUri + " (role=" + role + ")"); } if (absoluteUri.ToString().EndsWith(".txt")) { MemoryStream ms = new MemoryStream(); StreamWriter tw = new StreamWriter(ms); tw.Write("<uri>"); tw.Write(absoluteUri); tw.Write("</uri>"); tw.Flush(); return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length); } if (absoluteUri.ToString().EndsWith("empty.xslt")) { String ss = "<transform xmlns='http://www.w3.org/1999/XSL/Transform' version='2.0'/>"; MemoryStream ms = new MemoryStream(); StreamWriter tw = new StreamWriter(ms); tw.Write(ss); tw.Flush(); return new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length); } else { return null; } }
public ActionResult List(Uri url, int? index, int? size, int replyTo = 0) { if (url == null) return HttpNotFound(); var formattedUrl = url.ToString().ToLower(); var total = 0; if (index.HasValue && size.HasValue) { var modelResult = App.Get().FindComments(url.ToString(), out total, index.Value - 1, size.Value, replyTo); var userNames = modelResult.Select(u => u.UserName).ToArray(); var profiles = App.Get().DataContext.Where<UserProfile>(u => userNames.Contains(u.UserName)).ToList(); var result = new { Total = total, Model = modelResult.Select(m => m.ToObject(profiles, Request.ApplicationPath)) }; return Content(JsonConvert.SerializeObject(result, new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }), "application/json", System.Text.Encoding.UTF8); } else { var results = App.Get().FindComments(url.ToString(), replyTo); var userNames = results.Select(u => u.UserName).ToArray(); var profiles = App.Get().DataContext.Where<UserProfile>(u => userNames.Contains(u.UserName)).ToList(); return Content(JsonConvert.SerializeObject(results.Select(m => m.ToObject(profiles, Request.ApplicationPath)), new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }), "application/json", System.Text.Encoding.UTF8); } //return Json(App.Get().FindComments(url.ToString()).Select(m => m.ToObject()), JsonRequestBehavior.AllowGet); }
public static void SubmitResult(Uri testVaultServer, string session, string project, string buildname, string testgroup, string testname, TestOutcome outcome, bool personal) { try { using ( var client = new WebClient() ){ client.BaseAddress = testVaultServer.ToString(); client.CachePolicy = new System.Net.Cache.RequestCachePolicy( System.Net.Cache.RequestCacheLevel.NoCacheNoStore ); client.Headers.Add("Content-Type", "text/xml"); var result = new TestResult() { Group = new TestGroup() { Name = testgroup, Project = new TestProject() { Project = project } }, Name = testname, Outcome = outcome, TestSession = session, IsPersonal = personal, BuildID = buildname, }; var xc = new XmlSerializer(result.GetType()); var io = new System.IO.MemoryStream(); xc.Serialize( io, result ); client.UploadData( testVaultServer.ToString(), io.ToArray() ); } } catch ( Exception e ) { Console.Error.WriteLine( e ); } }
public Task<object> LoadContentAsync(Uri uri, CancellationToken cancellationToken) { if (cached.ContainsKey(uri.ToString())) { return Task<object>.Factory.StartNew(delegate() { UnitOperationView unitOperationView = null; cached.TryGetValue(uri.ToString(), out unitOperationView); return unitOperationView; }); } else { foreach (var unit in Core.Instance.Units) { if (unit.Uri.Equals(uri)) { return Task<object>.Factory.StartNew(delegate() { UnitOperationView unitOperationView = null; ManualResetEvent continueEvent = new ManualResetEvent(false); MainThread.EnqueueTask(delegate() { unitOperationView = new UnitOperationView(unit); cached.Add(unit.Uri.ToString(), unitOperationView); continueEvent.Set(); }); continueEvent.WaitOne(); return unitOperationView; }); } } } return defaultContentLoader.LoadContentAsync(uri, cancellationToken); }
public static IEnumerable<Item> GetItems(string query) { Items.Clear (); if (string.IsNullOrEmpty (prefs.URLs)) { RequestTrackerItem defitem = new RequestTrackerItem ( "No Trackers Configured", "Please use the GNOME Do Preferences to add some RT sites", "FAIL{0}"); Items.Add (defitem); } else { string[] urlbits = prefs.URLs.Split('|'); for (int i = 0; i < urlbits.Length; i++) { string name = urlbits[i]; string uri = urlbits[++i]; Uri url; try { url = new System.Uri(uri); } catch (System.UriFormatException) { continue; } string description = string.Format (url.ToString (), query); Items.Add (new RequestTrackerItem (name, description, url.ToString ())); } } return Items.OfType<Item> (); }
public IInboundTransport GetInboundTransport(Uri uri) { string key = uri.ToString().ToLowerInvariant(); IInboundTransport transport; if (_inboundTransports.TryGetValue(key, out transport)) return transport; string scheme = uri.Scheme.ToLowerInvariant(); ITransportFactory transportFactory; if (_transportFactories.TryGetValue(scheme, out transportFactory)) { try { ITransportSettings settings = new TransportSettings(new EndpointAddress(uri)); transport = transportFactory.BuildInbound(settings); _inboundTransports.Add(uri.ToString().ToLowerInvariant(), transport); return transport; } catch (Exception ex) { throw new TransportException(uri, "Failed to create inbound transport", ex); } } throw new TransportException(uri, "The {0} scheme was not handled by any registered transport.".FormatWith(uri.Scheme)); }
protected void Page_Load(object sender, EventArgs e) { // TODO: update this with the URL of the Office 365 site that contains the libraries with photos Uri sharePointSiteUrl = new Uri("https://****.sharpoint.com/"); // if the refresh code is in the URL, cache it if (Request.QueryString["code"] != null) { TokenCache.UpdateCacheWithCode(Request, Response, sharePointSiteUrl); } // if haven't previously obtained an refresh token, get an authorization token now if (!TokenCache.IsTokenInCache(Request.Cookies)) { Response.Redirect(TokenHelper.GetAuthorizationUrl(sharePointSiteUrl.ToString(), "Web.Read List.Read")); } else { // otherwise, get the access token from ACS string refreshToken = TokenCache.GetCachedRefreshToken(Request.Cookies); string accessToken = TokenHelper.GetAccessToken( refreshToken, "00000003-0000-0ff1-ce00-000000000000", sharePointSiteUrl.Authority, TokenHelper.GetRealmFromTargetUrl(sharePointSiteUrl) ).AccessToken; // use the access token to get a CSOM client context & get values from SharePoint using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(sharePointSiteUrl.ToString(), accessToken)) { context.Load(context.Web); context.ExecuteQuery(); // get contents from specified list } } }