ToString() public method

public ToString ( ) : string
return string
        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();
        }
        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());
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
		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();
            }
        }
Exemplo n.º 6
0
        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 "";
            }
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
0
        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));
		}
Exemplo n.º 9
0
		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);
		}
        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
            }
              }
        }
Exemplo n.º 11
0
        /// <summary> Load a font from a URL
        ///
        /// </summary>
        /// <param name="code">
        /// </param>
        /// <param name="alias">The name used to bind a DefineFont tag to a DefineEditText tag.
        /// </param>
        /// <param name="location">remote url or a relative, local file path
        /// </param>
        /// <param name="style">
        /// </param>
        /// <param name="hasLayout">
        /// </param>
        public FontBuilder(int code, FontManager manager, System.String alias, System.Uri location, int style, bool hasLayout, bool flashType) : this(code, hasLayout, flashType)
        {
            if (manager == null)
            {
                throw new NoFontManagerException();
            }

            if (Trace.font)
            {
                Trace.trace("Locating font using FontManager '" + manager.GetType().FullName + "'");
            }

            bool     useTwips = code != flash.swf.TagValues_Fields.stagDefineFont && code != flash.swf.TagValues_Fields.stagDefineFont2;
            FontFace fontFace = manager.getEntryFromLocation(location, style, useTwips);

            if (fontFace == null)
            {
                throwFontNotFound(alias, null, style, location.ToString());
            }

            if (Trace.font)
            {
                Trace.trace("Initializing font at '" + location.ToString() + "' as '" + alias + "'");
            }

            this.defaultFace = fontFace;

            init(alias);
        }
Exemplo n.º 12
0
        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());
        }
Exemplo n.º 13
0
        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> ();
        }
Exemplo n.º 14
0
        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)
                );
        }
Exemplo n.º 15
0
        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> ());
        }
Exemplo n.º 16
0
        public RewriterResults rewrite(Gadget gadget, MutableContent content)
        {
            if (gadget.getSpec().getModulePrefs().getFeatures().ContainsKey("caja") ||
                "1".Equals(gadget.getContext().getParameter("caja")))
            {
                URI          retrievedUri = gadget.getContext().getUrl();
                UriCallback2 cb           = new UriCallback2(retrievedUri);

                MessageQueue          mq    = new SimpleMessageQueue();
                DefaultGadgetRewriter rw    = new DefaultGadgetRewriter(mq);
                CharProducer          input = CharProducer.Factory.create(
                    new java.io.StringReader(content.getContent()),
                    FilePosition.instance(new InputSource(new java.net.URI(retrievedUri.ToString())), 2, 1, 1));
                java.lang.StringBuilder output = new java.lang.StringBuilder();

                try
                {
                    rw.rewriteContent(new java.net.URI(retrievedUri.ToString()), input, cb, output);
                }
                catch (GadgetRewriteException e)
                {
                    throwCajolingException(e, mq);
                    return(RewriterResults.notCacheable());
                }
                catch (IOException e)
                {
                    throwCajolingException(e, mq);
                    return(RewriterResults.notCacheable());
                }
                content.setContent(tameCajaClientApi() + output.ToString());
            }
            return(null);
        }
Exemplo n.º 17
0
        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();
        }
Exemplo n.º 18
0
        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;
            }
        }
        /// <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 = "******",
            };

            // *** 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);
        }
Exemplo n.º 20
0
		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());
		}
Exemplo n.º 21
0
Arquivo: Wallpaper.cs Projeto: v0l/whp
 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);
 }
Exemplo n.º 22
0
        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 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);
 }
Exemplo n.º 24
0
        // 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);
            }
        }
 /// <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;
 }
Exemplo n.º 26
0
       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;
       }
Exemplo n.º 27
0
        // 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;
        }
        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());
            }
        }
Exemplo n.º 29
0
        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;
            }
        }
Exemplo n.º 30
0
        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
        }
Exemplo n.º 31
0
		static ItemBuilder MoreAt(this ItemBuilder dsl, Uri uri)
		{
			return dsl.More(() =>
			{
				Process.Start(uri.ToString());
			}, uri.ToString());
		}
Exemplo n.º 32
0
        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 );
            }
        }
Exemplo n.º 33
0
        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());
        }
Exemplo n.º 34
0
        private uint CreateVersion(string name, uint base_version_id, bool create, bool is_protected)
        {
            System.Uri new_uri      = GetUriForVersionName(name, System.IO.Path.GetExtension(VersionUri(base_version_id).AbsolutePath));
            System.Uri original_uri = VersionUri(base_version_id);
            string     md5_sum      = MD5Sum;

            if (VersionNameExists(name))
            {
                throw new Exception("This version name already exists");
            }

            if (create)
            {
                if ((new Gnome.Vfs.Uri(new_uri.ToString())).Exists)
                {
                    throw new Exception(String.Format("An object at this uri {0} already exists", new_uri.ToString()));
                }

                Xfer.XferUri(
                    new Gnome.Vfs.Uri(original_uri.ToString()),
                    new Gnome.Vfs.Uri(new_uri.ToString()),
                    XferOptions.Default, XferErrorMode.Abort,
                    XferOverwriteMode.Abort,
                    delegate(Gnome.Vfs.XferProgressInfo info) { return(1); });

                //			Mono.Unix.Native.Stat stat;
                //			int stat_err = Mono.Unix.Native.Syscall.stat (original_path, out stat);
                //			File.Copy (original_path, new_path);
                FSpot.ThumbnailGenerator.Create(new_uri).Dispose();
                //
                //			if (stat_err == 0)
                //				try {
                //					Mono.Unix.Native.Syscall.chown(new_path, Mono.Unix.Native.Syscall.getuid (), stat.st_gid);
                //				} catch (Exception) {}
                //
            }
            else
            {
                md5_sum = Photo.GenerateMD5(new_uri);
            }
            highest_version_id++;

            Versions [highest_version_id] = new PhotoVersion(this, highest_version_id, new_uri, md5_sum, name, is_protected);

            changes.AddVersion(highest_version_id);

            return(highest_version_id);
        }
Exemplo n.º 35
0
 public void FailedToGetServiceMethodName(
     System.Fabric.StatefulServiceContext context,
     System.Uri requestUri,
     int interfaceId,
     int methodId,
     System.Exception ex)
 {
     if (this.IsEnabled())
     {
         FailedToGetServiceMethodName(
             context.ServiceName.ToString(),
             context.ServiceTypeName,
             context.ReplicaOrInstanceId,
             context.PartitionId,
             context.CodePackageActivationContext.ApplicationName,
             context.CodePackageActivationContext.ApplicationTypeName,
             context.NodeContext.NodeName,
             requestUri.ToString(),
             interfaceId,
             methodId,
             ex.Message,
             ex.Source,
             ex.GetType().FullName,
             ex.AsJson());
     }
 }
Exemplo n.º 36
0
 public void StopCallService(
     System.Fabric.StatefulServiceContext context,
     System.Uri requestUri,
     string serviceMethodName,
     Microsoft.ServiceFabric.Services.Remoting.ServiceRemotingMessageHeaders serviceMessageHeaders,
     FG.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader customServiceRequestHeader)
 {
     if (this.IsEnabled())
     {
         StopCallService(
             context.ServiceName.ToString(),
             context.ServiceTypeName,
             context.ReplicaOrInstanceId,
             context.PartitionId,
             context.CodePackageActivationContext.ApplicationName,
             context.CodePackageActivationContext.ApplicationTypeName,
             context.NodeContext.NodeName,
             requestUri.ToString(),
             serviceMethodName,
             (serviceMessageHeaders?.InterfaceId ?? 0),
             (serviceMessageHeaders?.MethodId ?? 0),
             customServiceRequestHeader?.GetHeader("userId"),
             customServiceRequestHeader?.GetHeader("correlationId"));
     }
 }
Exemplo n.º 37
0
        private void btnServerListXML_Click(object sender, EventArgs e)
        {
            if (!m_FieldChannelMgr.IsLoadedFieldList)
            {
                MessageBox.Show("fieldlist.xml 을 먼저 선택하십시오!!");
                return;
            }

            openFileDialog_serverlistXML.Title            = TITLE_FIND_SERVERLIST_XML_WND;
            openFileDialog_serverlistXML.Filter           = FILTER_FIND_SERVERLIST_XML;
            openFileDialog_serverlistXML.InitialDirectory = System.Windows.Forms.Application.StartupPath;

            if (openFileDialog_serverlistXML.ShowDialog() == DialogResult.OK)
            {
                System.Environment.CurrentDirectory = Application.StartupPath;

                System.Uri uriAbsolutePath = new Uri(openFileDialog_serverlistXML.FileName);
                System.Uri uriCurrentPath  = new Uri(Application.StartupPath + "\\");

                System.Uri uriRelativePath = uriCurrentPath.MakeRelativeUri(uriAbsolutePath);

                textboxServerListXML.Text = uriRelativePath.ToString();


                m_FieldChannelMgr.LoadServerList(textboxServerListXML.Text);

                BuildFieldList();
            }
        }
Exemplo n.º 38
0
        public void can_use_uri_with_WithUrl()
        {
            var uri = new System.Uri("http://www.mysite.com/foo?x=1");
            var req = new FlurlClient().Request(uri);

            Assert.AreEqual(uri.ToString(), req.Url.ToString());
        }
 public void FailedtoSendMessage(
     System.Uri requestUri,
     CodeEffect.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader header,
     System.Exception ex)
 {
     WebApiServiceEventSource.Current.FailedtoSendMessage(
         _context,
         requestUri,
         header,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "FailedtoSendMessage" },
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.InstanceId.ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "RequestUri", requestUri.ToString() },
         { "User", header?.GetHeader("name") },
         { "CorrelationId", header?.GetHeader("correlation-id") },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
        private string absUri(System.Uri uBase, string sRef)
        {
            if (sRef.IndexOf("://") >= 0)
            {
                return(sRef);
            }
            if (sRef == "")
            {
                return(uBase.ToString());
            }

            string sBase = uBase.Scheme + "://"
                           + uBase.Host + uBase.LocalPath;

            int iPos = sBase.LastIndexOf("/");

            sBase = sBase.Substring(0, iPos);

            if (sRef.Substring(0, 1) != "/")
            {
                sBase = sBase + "/";
            }

            return(sBase + sRef);
        }
Exemplo n.º 41
0
        public async Task <dynamic> httpGet(String address)
        {
            Uri uri = new System.Uri(mainApi + address);

            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            dynamic httpResponseBody = "";

            try
            {
                Debug.WriteLine("HttpGet attempt for: " + uri.ToString());
                //Send the GET request
                httpResponse = await httpClient.GetAsync(uri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                return(httpResponseBody);
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            Debug.WriteLine("HttpGet null");
            return(null);
        }
Exemplo n.º 42
0
        public static string GetDataPath_WWW(string platform)
        {
            string path = null;

            try
            {
                string dataPath = Application.dataPath;
                int    pos      = dataPath.LastIndexOf('/');//如果找到该字符,则为 value 的索引位置;否则如果未找到,则为 -1。
                if (pos != -1)
                {
                    dataPath = dataPath.Remove(pos);
                }

                string fullPath = dataPath + "/" + "AssetBundles/" + platform + "/";

                System.Uri fileUri = new System.Uri(fullPath);
                path = fileUri.ToString();
            }
            catch (System.Exception e)
            {
                Debug.LogException(e);
            }


            return(path);
        }
Exemplo n.º 43
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            bool flag = !string.IsNullOrEmpty(base.Request["isCallback"]) && base.Request["isCallback"] == "true";

            if (flag)
            {
                string verifyCode = base.Request["code"];
                string arg;
                if (!this.CheckVerifyCode(verifyCode))
                {
                    arg = "0";
                }
                else
                {
                    arg = "1";
                }
                base.Response.Clear();
                base.Response.ContentType = "application/json";
                base.Response.Write("{ ");
                base.Response.Write(string.Format("\"flag\":\"{0}\"", arg));
                base.Response.Write("}");
                base.Response.End();
            }
            if (!this.Page.IsPostBack)
            {
                SiteSettings masterSettings = SettingsManager.GetMasterSettings(true);
                this.htmlWebTitle = masterSettings.SiteName;
                System.Uri urlReferrer = this.Context.Request.UrlReferrer;
                if (urlReferrer != null)
                {
                    this.ReferralLink = urlReferrer.ToString();
                }
                this.txtAdminName.Focus();
            }
        }
Exemplo n.º 44
0
 protected void Page_Load(object sender, System.EventArgs e)
 {
     if (!string.IsNullOrEmpty(base.Request["isCallback"]) && base.Request["isCallback"] == "true")
     {
         string verifyCode = base.Request["code"];
         string arg;
         if (!this.CheckVerifyCode(verifyCode))
         {
             arg = "0";
         }
         else
         {
             arg = "1";
         }
         base.Response.Clear();
         base.Response.ContentType = "application/json";
         base.Response.Write("{ ");
         base.Response.Write(string.Format("\"flag\":\"{0}\"", arg));
         base.Response.Write("}");
         base.Response.End();
     }
     if (!this.Page.IsPostBack)
     {
         System.Uri urlReferrer = this.Context.Request.UrlReferrer;
         if (urlReferrer != null)
         {
             this.ReferralLink = urlReferrer.ToString();
         }
         this.txtAdminName.Focus();
         PageTitle.AddSiteNameTitle("后台登录", Hidistro.Membership.Context.HiContext.Current.Context);
     }
 }
Exemplo n.º 45
0
        private static async Task ShowImageInNewWindow(string imageUri, int gridWidth, int gridHeight)
        {
            CoreApplicationView newView = CoreApplication.CreateNewView();
            int newViewId = 0;
            await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                var uri        = new System.Uri(imageUri);
                Grid grd       = new Grid();
                grd.Background = new ImageBrush {
                    ImageSource = new BitmapImage(new Uri(uri.ToString()))
                };

                grd.Height              = gridHeight;
                grd.Width               = gridWidth;
                grd.VerticalAlignment   = VerticalAlignment.Center;
                grd.HorizontalAlignment = HorizontalAlignment.Center;

                Window.Current.Content = grd;
                Window.Current.Activate();

                newViewId = ApplicationView.GetForCurrentView().Id;
            });

            bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
        }
Exemplo n.º 46
0
        private async Task PrimeTeamCache()
        {
            // ---------------------------------------------------------
            // This routine will do an initial fill of the teamCache using 2000-2020,
            // while the splash screen is being displayed.
            // If no internet, this will fail and do nothing.

            try {
                var url = new System.Uri(GFileAccess.client.BaseAddress, $"liveteamrdr/api/team-list/2010/2020");

                List <CTeamRecord>  yearList10;
                HttpResponseMessage response = await GFileAccess.client.GetAsync(url.ToString());

                if (response.IsSuccessStatusCode)
                {
                    yearList10 = await response.Content.ReadAsAsync <List <CTeamRecord> >();
                }
                else
                {
                    throw new Exception($"Error loading initial list of teams\r\nStatus code: {response.StatusCode}");
                }
                DataAccess.TeamCache.AddRange(yearList10);
            }
            catch (Exception ex) {
                // Just do nothing here. Can't show error dialog.
                // CAlert.ShowOkAlert("Error initializing data", ex.Message, "OK", this);
            }
        }
Exemplo n.º 47
0
        public static string CombineUris(string baseUrl, string relativeUrl)
        {
            try
            {
                if (string.IsNullOrEmpty(baseUrl))
                {
                    return(relativeUrl);
                }
                if (string.IsNullOrEmpty(relativeUrl))
                {
                    return(baseUrl);
                }

                Uri baseUri     = new System.Uri(baseUrl, UriKind.Absolute);
                Uri relativeUri = new System.Uri(relativeUrl, UriKind.Relative);

                if (!baseUri.ToString().EndsWith("/"))
                {
                    string modifiedBaseUrl = baseUrl + "/";
                    baseUri = new System.Uri(modifiedBaseUrl, UriKind.Absolute);
                }

                return(new Uri(baseUri, relativeUri).ToString());
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
                return(baseUrl + relativeUrl);
            }
        }
 public void FailedToEnumeratePartitions(
     System.Uri serviceUri,
     System.Exception ex)
 {
     WebApiServiceEventSource.Current.FailedToEnumeratePartitions(
         _context,
         serviceUri,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "FailedToEnumeratePartitions" },
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.InstanceId.ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "ServiceUri", serviceUri.ToString() },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
Exemplo n.º 49
0
 public void RecieveServiceMessageFailed(
     System.Fabric.StatefulServiceContext context,
     System.Uri requestUri,
     string serviceMethodName,
     Microsoft.ServiceFabric.Services.Remoting.ServiceRemotingMessageHeaders serviceMessageHeaders,
     FG.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader customServiceRequestHeader,
     System.Exception ex)
 {
     if (this.IsEnabled())
     {
         RecieveServiceMessageFailed(
             context.ServiceName.ToString(),
             context.ServiceTypeName,
             context.ReplicaOrInstanceId,
             context.PartitionId,
             context.CodePackageActivationContext.ApplicationName,
             context.CodePackageActivationContext.ApplicationTypeName,
             context.NodeContext.NodeName,
             requestUri.ToString(),
             serviceMethodName,
             (serviceMessageHeaders?.InterfaceId ?? 0),
             (serviceMessageHeaders?.MethodId ?? 0),
             customServiceRequestHeader?.GetHeader("userId"),
             customServiceRequestHeader?.GetHeader("correlationId"),
             ex.Message,
             ex.Source,
             ex.GetType().FullName,
             ex.AsJson());
     }
 }
 public void RecieveWebApiRequestFailed(
     System.Fabric.StatelessServiceContext context,
     System.Uri requestUri,
     string payload,
     string correlationId,
     string userId,
     System.Exception exception)
 {
     if (this.IsEnabled())
     {
         RecieveWebApiRequestFailed(
             context.ServiceName.ToString(),
             context.ServiceTypeName,
             context.InstanceId,
             context.PartitionId,
             context.CodePackageActivationContext.ApplicationName,
             context.CodePackageActivationContext.ApplicationTypeName,
             context.NodeContext.NodeName,
             requestUri.ToString(),
             payload,
             correlationId,
             userId,
             exception.Message,
             exception.Source,
             exception.GetType().FullName,
             exception.AsJson());
     }
 }
Exemplo n.º 51
0
 public void FailedToGetServiceMethodName(
     System.Uri requestUri,
     int interfaceId,
     int methodId,
     System.Exception ex)
 {
     TitleActorServiceEventSource.Current.FailedToGetServiceMethodName(
         _context,
         requestUri,
         interfaceId,
         methodId,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "FailedToGetServiceMethodName" },
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.ReplicaOrInstanceId.ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "RequestUri", requestUri.ToString() },
         { "InterfaceId", interfaceId.ToString() },
         { "MethodId", methodId.ToString() },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
Exemplo n.º 52
0
        /// <summary>
        /// Loads from URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns>OpmlDocument</returns>
        public static OpmlDocument Load(System.Uri url)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            string opmlXml = string.Empty;

            using (Stream opmlStream = DownloadManager.GetFeed(url.ToString()))
            {
                using (XmlTextReader reader = new XmlTextReader(opmlStream))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.LocalName.Equals("opml", StringComparison.OrdinalIgnoreCase))
                        {
                            opmlXml = reader.ReadOuterXml();
                            break;
                        }
                    }
                }
            }

            return(Load(opmlXml));
        }
Exemplo n.º 53
0
        public static void RedirectToMainStoreUrl(long storeId, System.Uri requestedUrl, MerchantTribeApplication app)
        {
            Accounts.Store store = app.AccountServices.Stores.FindById(storeId);
            if (store == null)
            {
                return;
            }
            app.CurrentStore = store;

            string host         = requestedUrl.Authority;
            string relativeRoot = "http://" + host;

            bool secure = false;

            if (requestedUrl.ToString().ToLowerInvariant().StartsWith("https://"))
            {
                secure = true;
            }
            string destination = app.StoreUrl(secure, false);

            string pathAndQuery = requestedUrl.PathAndQuery;

            // Trim starting slash because root URL already has this
            pathAndQuery = pathAndQuery.TrimStart('/');

            destination = System.IO.Path.Combine(destination, pathAndQuery);

            // 301 redirect to main url
            if (System.Web.HttpContext.Current != null)
            {
                System.Web.HttpContext.Current.Response.RedirectPermanent(destination);
            }
        }
Exemplo n.º 54
0
 public void ServiceClientFailed(
     System.Fabric.StatefulServiceContext context,
     System.Uri requestUri,
     FG.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader customServiceRequestHeader,
     System.Exception ex)
 {
     if (this.IsEnabled())
     {
         ServiceClientFailed(
             context.ServiceName.ToString(),
             context.ServiceTypeName,
             context.ReplicaOrInstanceId,
             context.PartitionId,
             context.CodePackageActivationContext.ApplicationName,
             context.CodePackageActivationContext.ApplicationTypeName,
             context.NodeContext.NodeName,
             requestUri.ToString(),
             customServiceRequestHeader?.GetHeader("userId"),
             customServiceRequestHeader?.GetHeader("correlationId"),
             ex.Message,
             ex.Source,
             ex.GetType().FullName,
             ex.AsJson());
     }
 }
Exemplo n.º 55
0
        public StringBuilder GetSvr()
        {
            Type type = this.GetType();

            System.Uri url = HttpContext.Current.Request.Url;

            string script = GetScriptTemplete();

            script = script.Replace("%H_DESC%", "通过jQuery.ajax完成服务端函数调用");
            script = script.Replace("%H_DATE%", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            script = script.Replace("%URL%", url.Query.Length > 0?url.ToString().Replace(url.Query, ""):url.ToString());
            script = script.Replace("%CLS%", type.Name);

            StringBuilder scriptBuilder = new StringBuilder(script);

            MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            foreach (MethodInfo m in methods)
            {
                ResponseAnnotationAttribute resAnn = this.GetAnnation(m.Name);

                scriptBuilder.AppendLine("/*----------------------------------------------------------------------------");
                scriptBuilder.AppendLine("功能说明:" + resAnn.Desc);
                scriptBuilder.AppendLine("附加说明:缓存时间 " + resAnn.CacheDuration.ToString() + " 秒");
                scriptBuilder.AppendLine("         输出类型 " + resAnn.ResponseFormat.ToString());
                scriptBuilder.AppendLine("----------------------------------------------------------------------------*/");

                string func = GetFunctionTemplete(m, resAnn.ResponseFormat);
                scriptBuilder.AppendLine(func);
            }

            return(scriptBuilder);
        }
Exemplo n.º 56
0
 /// <summary>
 /// Gets the script neccessary to open the dialog.
 /// </summary>
 /// <remarks>
 /// <p>
 /// When deriving from this class, you generally want to implement the publi GetDialogOpenScript by calling this method with the proper url and features.
 /// </p>
 /// </remarks>
 protected virtual String GetDialogOpenScript(System.Uri url, NameValueCollection features)
 {
     System.Text.StringBuilder theScript = new System.Text.StringBuilder();
     theScript.Append("MetaBuilders_DialogWindow_OpenDialog('");
     theScript.Append(url.ToString());
     theScript.Append("', '");
     theScript.Append(this.ClientID);
     if (this.Resizable)
     {
         theScript.Append("', 'resizable=1");
     }
     else
     {
         theScript.Append("', 'resizable=0");
     }
     if (features["resizable"] != null)
     {
         features.Remove("resizable");
     }
     foreach (String key in features.AllKeys)
     {
         theScript.Append(",");
         theScript.Append(key);
         theScript.Append("=");
         theScript.Append(features[key]);
     }
     theScript.Append("')");
     return(theScript.ToString());
 }
Exemplo n.º 57
0
        /// <summary>
        /// Post the events to the Elasticsearch _bulk API for faster inserts
        /// </summary>
        /// <typeparam name="T">Type/item being inserted. Should be a list of events</typeparam>
        /// <param name="uri">Fully formed URI to the ES endpoint</param>
        /// <param name="items">List of logEvents</param>
        public void PostBulk <T>(Uri uri, T items)
        {
            System.Diagnostics.Debug.WriteLine(uri.ToString());

            var httpWebRequest = RequestFor(uri);

            var postBody = new StringBuilder();

            // For each logEvent, we build a bulk API request which consists of one line for
            // the action, one line for the document. In this case "create" and then the doc
            // Since we're appending _bulk to the end of the Uri, ES will default to using the
            // index and type already specified in the Uri segments
            foreach (var item in (IEnumerable <logEvent>)items)
            {
                postBody.AppendLine("{\"index\" : {} }");
                postBody.AppendLine(item.ToJson());
            }

            using (var streamWriter = GetRequestStream(httpWebRequest))
            {
                streamWriter.Write(postBody.ToString());
                streamWriter.Flush();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                var errorBody    = GetErrorBody(httpResponse);
                httpResponse.Close();

                if ((int)httpResponse.StatusCode > 203)
                {
                    throw new WebException(
                              "Failed to post {0} to {1}. Response: {2} {3}"
                              .With(postBody.ToString(), uri, httpResponse.StatusCode, errorBody));
                }
            }
        }
 public void CallActorFailed(
     System.Fabric.StatelessServiceContext context,
     System.Uri requestUri,
     string actorMethodName,
     FG.ServiceFabric.Actors.Remoting.Runtime.ActorMessageHeaders actorMessageHeaders,
     FG.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader customServiceRequestHeader,
     System.Exception ex)
 {
     if (this.IsEnabled())
     {
         CallActorFailed(
             context.ServiceName.ToString(),
             context.ServiceTypeName,
             context.InstanceId,
             context.PartitionId,
             context.CodePackageActivationContext.ApplicationName,
             context.CodePackageActivationContext.ApplicationTypeName,
             context.NodeContext.NodeName,
             requestUri.ToString(),
             actorMethodName,
             (actorMessageHeaders?.InterfaceId ?? 0),
             (actorMessageHeaders?.MethodId ?? 0),
             actorMessageHeaders?.ActorId.ToString(),
             customServiceRequestHeader?.GetHeader("userId"),
             customServiceRequestHeader?.GetHeader("correlationId"),
             ex.Message,
             ex.Source,
             ex.GetType().FullName,
             ex.AsJson());
     }
 }
        public ActionResult Delete(string id)
        {
            System.Uri uri = System.Web.HttpContext.Current.Request.UrlReferrer;
            notificationService.Delete(id);

            return(Redirect(uri.ToString()));
        }
Exemplo n.º 60
0
    public override bool SetDefaultDeviceProfile(System.Uri uri)
    {
        bool result = false;

        CallObjectMethod(ref result, activityListener, "setDefaultDeviceProfile", uri.ToString());
        return(result);
    }