Esempio n. 1
0
        static void Main(string[] args)
        {
            Console.WriteLine("ymir2xml converter by xenor");
            Console.WriteLine("Copyright (c) 2012 - All Rights reserved.");
            Console.WriteLine("-----------------------------------------");

            args = new string[] { "group.txt" };

            if (args.Length == 0)
            {
                Console.WriteLine("Drag and drop files to the executable to begin.");
            }
            else
            {
                foreach (string filename in args)
                {
                    string relFilename = filename;
                    try
                    {
                        relFilename = new Uri(System.IO.Directory.GetCurrentDirectory() + @"\").MakeRelativeUri(new Uri(filename)).ToString();
                    }
                    catch { }

                    if (relFilename.Substring(relFilename.Length - 3, 3) == "xml")
                    {
                        Console.WriteLine("parse xml file");
                        parseXML(filename);
                    }
                    else if ((relFilename.Length >= 4 && relFilename.Substring(0, 4) == "boss") || (relFilename.Length >= 3 && relFilename.Substring(0, 3) == "npc") || (relFilename.Length >= 5 && relFilename.Substring(0, 5) == "regen") || (relFilename.Length >= 5 && relFilename.Substring(0, 5) == "stone"))
                    {
                        Console.WriteLine("parse regen file");
                        parseRegenfile(filename);
                    }
                    else if (relFilename.Length >= 11 && relFilename.Substring(0, 11) == "group_group")
                    {
                        Console.WriteLine("parse group_group file");
                        parseGroupGroupfile(filename);
                    }
                    else if (relFilename.Length >= 5 && relFilename.Substring(0, 5) == "group")
                    {
                        Console.WriteLine("parse group file");
                        parseGroupfile(filename);
                    }
                    else if (relFilename.Length >= 7 && (relFilename.Substring(0, 7) == "Setting" || relFilename.Substring(0, 7) == "setting"))
                    {
                        Console.WriteLine("parse settings file");
                        parseSetting(filename);
                    }
                    else
                    {
                        Console.WriteLine(relFilename + " - Unknown filetype");
                    }
                }
            }

            Console.WriteLine("done");
            Console.ReadKey();
        }
Esempio n. 2
0
        private string MakeURLPretty(string url)
        {
            var lowURL = url.ToLower();
            
            if (lowURL.StartsWith("http://www"))
            {
                // Everything's good.
            }
            else if (lowURL.StartsWith("http://"))
            {
                var s = url.Split(new string[] { "//" }, StringSplitOptions.None);
                url = s[0] + "//www." + s[1];
            }
            else if (lowURL.StartsWith("www"))
            {
                url = "http://" + url;
            }
            else
            {
                url = "http://www." + url;
            }

            url = new Uri(url).ToString();

            if (url.EndsWith("/"))
            {
                url = url.Substring(0, url.Length - 1);
            }

            return url;
        }
Esempio n. 3
0
        public static string AbsolutoParaRelativo(string de, string para, string inicio)
        {
            string path = new Uri(para).MakeRelativeUri(new Uri(de)).ToString();
            path = path.Substring(path.LastIndexOf(inicio), path.Length - path.LastIndexOf(inicio));

            return "~" + path;
        }
 /// <summary>
 /// 取得媒體ID
 /// </summary>
 /// <param name="Url">網址</param>
 /// <returns>媒體ID</returns>
 private string GetMediaId(string Url) {
     string result = new Uri(Url).Segments.Last<string>();
     try {
         result = result.Substring(0, result.IndexOf("_"));
     } catch { }
     return result;
 }
Esempio n. 5
0
        static void Main(string[] args)
        {
            CTHReader cth = new CTHReader();

            if (ConfigurationManager.AppSettings["passwordPrompt"] == "true")
            {
                Console.WriteLine("Please provide user name to connect to the site:");
                cth.UserName = Console.ReadLine();

                Console.WriteLine("Please provide the password:"******"outputFilePrefix"];

            string outputLocation = ConfigurationManager.AppSettings["outputLocation"];
            string siteUrl = new Uri(ConfigurationManager.AppSettings["siteUrl"]).ToString();

            if (siteUrl.EndsWith("/"))
            {
                siteUrl = siteUrl.Substring(0, siteUrl.Length - 1);
            }

            Console.WriteLine(cth.ProcessCTH(siteUrl, outputLocation, CTHReader.CTHQueryMode.CTHAndSiteColumns));
            //doit();
            //tidyUpXMLDoc();
            //queryXMLProcess();
        }
        public static string GetLayoutHtml(CommonViewModel model, string page, IEnumerable<string> stylesheets, IEnumerable<string> scripts)
        {
            if (model == null) throw new ArgumentNullException("model");
            if (page == null) throw new ArgumentNullException("page");
            if (stylesheets == null) throw new ArgumentNullException("stylesheets");
            if (scripts == null) throw new ArgumentNullException("scripts");

            var applicationPath = new Uri(model.SiteUrl).AbsolutePath;
            if (applicationPath.EndsWith("/")) applicationPath = applicationPath.Substring(0, applicationPath.Length - 1);

            var pageUrl = "assets/app." + page + ".html";

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(model, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() });

            var additionalStylesheets = BuildTags("<link href='{0}' rel='stylesheet'>", applicationPath, stylesheets);
            var additionalScripts = BuildTags("<script src='{0}'></script>", applicationPath, scripts);

            return LoadResourceString("Thinktecture.IdentityServer.Core.Views.Embedded.Assets.app.layout.html",
                new
                {
                    siteName = model.SiteName,
                    applicationPath,
                    pageUrl,
                    model = json,
                    stylesheets = additionalStylesheets,
                    scripts = additionalScripts
                });
        }
Esempio n. 7
0
 public static void CreateImageFolder(this string itemName)
 {
     var path = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
     var mainPath = path.Substring(0, path.IndexOf("bin", 0));
     var imgPath = string.Format(@"{0}\Content\images\item\{1}", mainPath, itemName);
     if (!Directory.Exists(imgPath))
         Directory.CreateDirectory(imgPath);
 }
 private string BuildHost(string website)
 {
     var host = new Uri(website, UriKind.Absolute).Host;
     if (host.Contains("www."))
     {
         host = host.Substring(4);
     }
     return host;
 }
Esempio n. 9
0
        private static string PathFromUri(string uri)
        {
            string baseUri = new Uri(uri).PathAndQuery;
            if (baseUri.StartsWith("/"))
            {
                baseUri = baseUri.Substring(1);
            }

            return baseUri;
        }
Esempio n. 10
0
        private static string GetDomain(IConfiguration settings)
        {
            var domain = new Uri(settings.GetSiteRoot(false)).DnsSafeHost;

            if (domain.IndexOf(':') >= 0)
            {
                domain = domain.Substring(0, domain.IndexOf(':'));
            }

            return domain;
        }
Esempio n. 11
0
 public Compiler()
 {
     configFileName = "config.cpp";
     stdLibPath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
     stdLibPath = stdLibPath.Substring(0, stdLibPath.LastIndexOf('\\')) + "\\stdLibrary\\";
     addFunctionsClass = true;
     outputFolderCleanup = true;
     printOutMode = 0;
     flagDefines = new List<PPDefine>();
     SqfCall.readSupportInfoList();
     includedFiles = new List<string>();
 }
Esempio n. 12
0
        public static void TransformRobocode()
        {
            var w = new Uri("http://robocode.sourceforge.net/docs/robocode/allclasses-noframe.html").ToWebString();

            var zip = new ZIPFile();

            var o = 0;
            while (o >= 0)
            {
                const string pregfix = "<A HREF=\"";
                var i = w.IndexOf(pregfix, o);
                if (i >= 0)
                {
                    var j = w.IndexOf("\"", i + pregfix.Length);

                    if (j >= 0)
                    {
                        var type = w.Substring(i + pregfix.Length, j - (i + pregfix.Length));

                        const string suffix = ".html";

                        if (type.EndsWith(suffix))
                        {
                            o = j + 1;

                            type = type.Substring(0, type.Length - suffix.Length).Replace("/", ".");

                            Console.WriteLine(type);

                            zip.Add(type.Replace(".", "/") + ".cs",
                                new DefinitionProvider(
                                    type
                                //        "robocode.BattleRules"
                                //        //"java.net.InetSocketAddress"
                                //        //"java.net.ServerSocket"
                                //        //"java.nio.channels.ServerSocketChannel"
                                , k => k.ToWebString()).GetString()
                            );

                        }
                        else o = -1;
                    }
                    else o = -1;
                }
                else o = -1;
            }

            using (var ww = new BinaryWriter(File.OpenWrite("Robocode.zip")))
            {
                zip.WriteTo(ww);
            }
        }
        private bool FindPath(string rawUrl, out string foundUri)
        {
            foundUri = new Uri(rawUrl, UriKind.Relative).NormalizedPathAndQuery();
            if (_contentState.Storage.ContainsKey(foundUri))
                return true;

            int pos;
            char[] args = new char[] {'?', '&'};
            while((pos = foundUri.LastIndexOfAny(args)) > 0) //not possible to find index zero, i.e. '/?'
            {
                foundUri = foundUri.Substring(0, pos);
                if (_contentState.Storage.ContainsKey(foundUri))
                    return true;
            }
            return false;
        }
Esempio n. 14
0
        public bool BeforeRequest(Session session, Rule rule)
        {
            Console.WriteLine(String.Format("Request ({0}) cached due to the rule: {1}", session.hostname, rule.Name));

            // TODO:
            // Cache-Control - Expires, MaxAge (private)
            // Age?
            //
            var querystring = new Uri(session.fullUrl).Query;
            var startindex = querystring.IndexOf("&url=");
            var length = querystring.IndexOf("&ei", startindex) - startindex;
            var url = querystring.Substring(startindex, length);
            session.fullUrl = Uri.UnescapeDataString(url);

            return false;
        }
Esempio n. 15
0
 public override void LoadPlaylist(string fpath)
 {
     ItemsPaths = new ArrayList();
     //
     try
     {
         XmlReaderSettings settings = new XmlReaderSettings();
         settings.XmlResolver = null;
         settings.DtdProcessing = DtdProcessing.Ignore;
         settings.ValidationType = ValidationType.None;
         using (XmlReader reader = XmlReader.Create(fpath, settings))
         {
             CheckFileType(reader);
             while (reader.ReadToFollowing("key"))
             {
                 reader.ReadStartElement("key");
                 if (reader.ReadString().ToLower().Equals("location"))
                 {
                     reader.ReadEndElement();
                     reader.ReadStartElement("string");
                     string str = new Uri(reader.ReadString().Trim()).LocalPath;
                     if (str.StartsWith(@"\\localhost\")) str = str.Substring(12);
                     ItemsPaths.Add(str);
                     reader.ReadEndElement();
                 }
                 else
                     reader.ReadEndElement();
             }
         }
     }
     catch (IOException)
     {
         throw new Exception("Error occured during the file reading process!");
     }
     catch (XmlException)
     {
         throw new Exception("Error occured during the file parsing process!");
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Adds a trailing slash to the URI if it does not already have one.
        /// </summary>
        public static Uri EnsureTrailingSlash(this Uri uri)
        {
            if (!uri.IsAbsoluteUri)
            {
                // Temporarily turn relative URIs into absolute ones for appending the slash
                const string prefix = "http://fake:80/";
                string resolvedWithFakeBase = new Uri(new Uri(prefix), uri).EnsureTrailingSlash().OriginalString;
                return new Uri(resolvedWithFakeBase.Substring(uri.OriginalString.StartsWith("/")
                    ? prefix.Length - 1
                    : prefix.Length), UriKind.Relative);
            }

            var builder = new UriBuilder
            {
                Scheme = uri.Scheme,
                Host = uri.Host,
                Port = uri.Port,
                // Add trailing slash to path while preserving query parameters
                Path = uri.AbsolutePath.EndsWith("/") ? uri.AbsolutePath : uri.AbsolutePath + "/",
                Query = uri.Query.TrimStart('?')
            };
            return new Uri(builder.ToString(), UriKind.Absolute);
        }
Esempio n. 17
0
        private async Task<List<ImageLink>> GetImgurImageOrAlbumFromUrl(Post post, string outputPath, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();
            var links = new List<ImageLink>();

            OutputLine($"\tGetting links from post: {post.Title}", true);

            var url = new Uri(post.Url.ToString()).GetLeftPart(UriPartial.Path).Replace(".gifv", ".gif");

            url = url.StartsWith("http://") ? url : "http://" + url.Substring(url.IndexOf(post.Url.DnsSafeHost, StringComparison.Ordinal));

            var name = Path.GetInvalidFileNameChars().Aggregate(post.AuthorName, (current, c) => current.Replace(c, '-'));

            var filepath = outputPath + "\\";

            if (_allAuthorsPosts)
                filepath += post.AuthorName;
            else
                filepath += post.SubredditName + "\\" + name;

            var filename = filepath + $"\\{name}_{post.SubredditName}_{post.Id}";

            var extention = GetExtention(url);

            if (!string.IsNullOrEmpty(extention))
            {
                OutputLine($"\tAdding Link {url}", true);
                links.Add(new ImageLink(post, url, filename));
                return links;
            }

            string htmlString = await GetHtml(url, token);
            if (string.IsNullOrWhiteSpace(htmlString)) return links;

            var caroselAlbum = htmlString.Contains(@"data-layout=""h""");

            if (caroselAlbum)
            {
                htmlString = await GetHtml(url + "/all", token);
                if (string.IsNullOrWhiteSpace(htmlString)) return links;
            }

            var gridAlbum = htmlString.Contains(@"data-layout=""g""");

            if (caroselAlbum && !gridAlbum) return links;

            var regPattern = new Regex(@"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", RegexOptions.IgnoreCase);

            var matchImageLinks = regPattern.Matches(htmlString);

            OutputLine($"\tFound {matchImageLinks.Count} image(s) from link.", true);

            foreach (Match m in matchImageLinks)
            {
                token.ThrowIfCancellationRequested();
                var imgurl = m.Groups[1].Value.Replace(".gifv", ".gif");

                if (!imgurl.Contains("imgur.com")) continue;

                if (gridAlbum)
                    imgurl = imgurl.Remove(imgurl.LastIndexOf('.') - 1, 1);
                var domain = new Uri(imgurl).DnsSafeHost;
                imgurl = imgurl.StartsWith("http://") ? imgurl : "http://" + imgurl.Substring(imgurl.IndexOf(domain, StringComparison.Ordinal));

                links.Add(new ImageLink(post, imgurl, filename));
            }

            return links;
        }
Esempio n. 18
0
		private MimeType[] GetAcceptedTypes(MimeTypes registeredMimes)
		{
			var mimeTypes = new List<MimeType>();
			var originalUrl = Request.Uri.GetLeftPart(UriPartial.Authority) + Request.Url;
			var lastSegment = new Uri(originalUrl).Segments.Last();
			
			if (lastSegment.Contains(".") && (lastSegment.LastIndexOf(".") < lastSegment.Length - 1))
			{
				var extension = lastSegment.Substring(lastSegment.LastIndexOf(".") + 1);
				var mimeType = registeredMimes.GetMimeTypeForExtension(extension);

				if (mimeType != null)
					mimeTypes.Add(mimeType);
			}

			mimeTypes.AddRange(AcceptType.Parse(AcceptHeader, registeredMimes));			
			
			return mimeTypes.Distinct().ToArray();
		}
Esempio n. 19
0
        public ActionResult MetaGenerator(string domain, string page)
        {
            domain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port).ToLower();

            var host = new System.Uri(domain).Host;
            int index = host.LastIndexOf('.'), last = 3;
            while (index > 0 && index >= last - 3)
            {
                last = index;
                index = host.LastIndexOf('.', last - 1);
            }

            var res = host.Substring(index + 1);

            res = "~/Views/Shared/" + (res == "localhost" ? "gestionestampa.com" : res);

            try
            {
                TempData["MetaTitle"] = HttpContext.GetLocalResourceObject(res, page.ToLower() + "Title") + " - PapiroStar ";
                TempData["MetaDescription"] = HttpContext.GetLocalResourceObject(res, page.ToLower() + "Description");
                TempData["MetaKeyword"] = HttpContext.GetLocalResourceObject(res, page.ToLower() + "Keyword");
                TempData["MetaRobots"] = HttpContext.GetLocalResourceObject(res, page.ToLower() + "Robots") == null ? "index,follow" : HttpContext.GetLocalResourceObject(res, page.ToLower() + "Robots");
            }
            catch (Exception)
            {
                TempData["MetaTitle"] = "PapiroStar";
                TempData["MetaDescription"] = "";
                TempData["MetaKeyword"] = "";
                TempData["MetaRobots"] = "noindex, nofollow";
            }
            return null;
        }
Esempio n. 20
0
        public List <double> PhishingIndexes(string URL)
        {
            List <double> indexes = new List <double>();

            string newURL = "";
            Uri    uriURL;

            if (Uri.IsWellFormedUriString(URL, UriKind.Absolute) == false)                      // Prideda https:// jei jo nėra
            {
                newURL = "https://" + URL;
                uriURL = new Uri(newURL);
            }
            else
            {
                newURL = URL;
                uriURL = new Uri(URL);
            }

            string[] parts      = uriURL.Authority.Split('.');                                  // Domena sudalina dalimis
            int      digitCount = 0;

            if (parts.Length >= 4)
            {
                for (int i = 0; i < 4; i++)
                {
                    if (System.Text.RegularExpressions.Regex.IsMatch(parts[i], @"^\d+$"))       // Tikrina ar domeno dalis yra skaičius
                    {
                        digitCount++;
                    }
                }
            }

            if (digitCount == 4)                                                                // Ar naudojamas IP adresas
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            if (newURL.Length >= 75)                                                            // Ar adresas ilgesnis nei 75 simboliai
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            if (newURL.Contains('@'))                                                           // Ar adresas turi @ simbolį
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            string path = uriURL.AbsolutePath;                                                  // Ar naudojamas peradresavimas su //
            string str  = "";

            if (path.Length >= 2)
            {
                str = path.Substring(0, 2);
            }
            if (str == "//")
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            if (uriURL.Authority.Contains('-'))                                                 // Ar domene naudojamas –
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            var host = new System.Uri(newURL).Host;
            int index = host.LastIndexOf('.'), last = 3;

            while (index > 0 && index >= last - 3)                                              // Randa subdomena
            {
                last  = index;
                index = host.LastIndexOf('.', last - 1);
            }
            var domain   = host.Substring(index + 1);
            int dotCount = 0;

            for (int i = 0; i < domain.Length; i++)
            {
                if (domain[i] == '.')
                {
                    dotCount++;
                }
            }
            if (dotCount > 2)                                                                   // Ar taškų skaičius subdomene yra didesnis nei 2
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            if (uriURL.Authority == "bit.ly")                                                   // Ar adresas yra sutrumpintas naudojant „TinyURL“
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            int[] goodPorts = { 21, 22, 23, 80, 443, 445, 1433, 1521, 3306, 3389 };             // Standartiški portai
            if (goodPorts.Contains(uriURL.Port) == false)                                       // Ar naudojamas nestandartiškas portas
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            if (newURL.Contains("mail()") || newURL.Contains("mailto:"))                        // Ar naudojamas duomenų persiuntimas į paštą (ar yra „mail()“ arba „mailto:“)
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            if (uriURL.Authority.Contains("https"))                                             // Ar domene yra „https“
            {
                indexes.Add(1);
            }
            else
            {
                indexes.Add(-1);
            }

            indexes.Add(-1);

            return(indexes);
        }
        private string generateLocalEpisodeFileName(PodcastEpisodeModel podcastEpisode)
        {
            // Parse the filename of the logo from the remote URL.
            string localPath = new Uri(podcastEpisode.EpisodeDownloadUri).LocalPath;
            string podcastEpisodeFilename = localPath.Substring(localPath.LastIndexOf('/') + 1);

            podcastEpisodeFilename = PodcastSubscriptionsManager.sanitizeFilename(podcastEpisodeFilename);
            podcastEpisodeFilename = String.Format("{0}_{1}", DateTime.Now.Millisecond, podcastEpisodeFilename);

            string localPodcastEpisodeFilename = App.PODCAST_DL_DIR + "/" + podcastEpisodeFilename;
            Debug.WriteLine("Found episode filename: " + localPodcastEpisodeFilename);

            return localPodcastEpisodeFilename;
        }
        /// <summary>
        /// Create a new SourceLineNumberCollection from a URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>The new SourceLineNumberCollection.</returns>
        public static SourceLineNumberCollection FromUri(string uri)
        {
            if (null == uri || 0 == uri.Length)
            {
                return null;
            }

            string localPath = new Uri(uri).LocalPath;

            // make the local path really look like a normal local path
            if (localPath.StartsWith(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                localPath = localPath.Substring(1);
            }
            localPath = localPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

            return new SourceLineNumberCollection(localPath);
        }
 private static string GetTrippinWebRoot(string serviceName)
 {
     var codeBase = new Uri(typeof(TrippinServiceFixture).Assembly.CodeBase).LocalPath;
     var parentPathLength = codeBase.IndexOf(EigenString) + EigenString.Length;
     return Path.Combine(codeBase.Substring(0, parentPathLength), serviceName);
 }
Esempio n. 24
0
 /// <summary>
 /// Returns the correct root url
 /// </summary>
 /// <param name="req"></param>
 /// <param name="apiName"></param>
 /// <param name="apiVersion"></param>
 /// <returns></returns>
 protected static string GetRootUrl(HttpRequestMessage req, string apiName, string apiVersion)
 {
     var url = new Uri(req.RequestUri, req.GetRequestContext().VirtualPathRoot).ToString();
     url = url.EndsWith("/") ? url.Substring(0, url.Length - 1) : url;
     return url;
 }
        /// <summary>
        /// Builds the model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="page">The page.</param>
        /// <param name="stylesheets">The stylesheets.</param>
        /// <param name="scripts">The scripts.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// model
        /// or
        /// stylesheets
        /// or
        /// scripts
        /// </exception>
        protected object BuildModel(CommonViewModel model, string page, IEnumerable<string> stylesheets, IEnumerable<string> scripts)
        {
            if (model == null) throw new ArgumentNullException("model");
            if (stylesheets == null) throw new ArgumentNullException("stylesheets");
            if (scripts == null) throw new ArgumentNullException("scripts");
            
            var applicationPath = new Uri(model.SiteUrl).AbsolutePath;
            if (applicationPath.EndsWith("/")) applicationPath = applicationPath.Substring(0, applicationPath.Length - 1);

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(model, Newtonsoft.Json.Formatting.None, settings);

            var additionalStylesheets = BuildTags("<link href='{0}' rel='stylesheet'>", applicationPath, stylesheets);
            var additionalScripts = BuildTags("<script src='{0}'></script>", applicationPath, scripts);

            return new {
                siteName = Microsoft.Security.Application.Encoder.HtmlEncode(model.SiteName),
                applicationPath,
                model = Microsoft.Security.Application.Encoder.HtmlEncode(json),
                page,
                stylesheets = additionalStylesheets,
                scripts = additionalScripts
            };
        }
 private static string GetRootSolutionDirectoryPath()
 {
     var codebase = new Uri(typeof(NestDeployer).Assembly.CodeBase).AbsolutePath;
      return codebase.Substring(0, codebase.IndexOf(kRootSolutionName) + kRootSolutionName.Length);
 }
Esempio n. 27
0
        private HttpWebResponse Download (SafeUri uri, int nb_retries)
        {
            Hyena.ThreadAssist.AssertNotInMainThread ();

            while (true) {
                try {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create (uri.AbsoluteUri);
                    request.UserAgent = Banshee.Web.Browser.UserAgent;
                    request.KeepAlive = false;
                    request.Timeout = 5 * 1000;
                    request.AllowAutoRedirect = true;

                    // Parse out and set credentials, if any
                    string user_info = new Uri (uri.AbsoluteUri).UserInfo;
                    if (!String.IsNullOrEmpty (user_info)) {
                        string username = String.Empty;
                        string password = String.Empty;
                        int cIndex = user_info.IndexOf (":");
                        if (cIndex != -1) {
                            username = user_info.Substring (0, cIndex);
                            password = user_info.Substring (cIndex + 1);
                        } else {
                            username = user_info;
                        }
                        request.Credentials = new NetworkCredential (username, password);
                    }

                    var response = (HttpWebResponse)request.GetResponse ();
                    if (response.StatusCode == HttpStatusCode.GatewayTimeout) {
                        throw new WebException ("", WebExceptionStatus.Timeout);
                    }
                    return response;
                } catch (WebException e) {
                    if (e.Status == WebExceptionStatus.Timeout && nb_retries > 0) {
                        nb_retries--;
                        Log.InformationFormat ("Playlist download from {0} timed out, retrying in 1 second...", uri.AbsoluteUri);
                        System.Threading.Thread.Sleep (1000);
                    } else {
                        throw;
                    }
                }
            }
        }
Esempio n. 28
0
        public WEBDAV(string url, Dictionary<string, string> options)
        {
            Uri u = new Uri(url);

            if (!string.IsNullOrEmpty(u.UserInfo))
            {
                m_userInfo = new System.Net.NetworkCredential();
                if (u.UserInfo.IndexOf(":") >= 0)
                {
                    m_userInfo.UserName = u.UserInfo.Substring(0, u.UserInfo.IndexOf(":"));
                    m_userInfo.Password = u.UserInfo.Substring(u.UserInfo.IndexOf(":") + 1);
                }
                else
                {
                    m_userInfo.UserName = u.UserInfo;
                    if (options.ContainsKey("ftp-password"))
                        m_userInfo.Password = options["ftp-password"];
                }
            }
            else
            {
                if (options.ContainsKey("ftp-username"))
                {
                    m_userInfo = new System.Net.NetworkCredential();
                    m_userInfo.UserName = options["ftp-username"];
                    if (options.ContainsKey("ftp-password"))
                        m_userInfo.Password = options["ftp-password"];
                }
            }

            m_useIntegratedAuthentication = Utility.Utility.ParseBoolOption(options, "integrated-authentication");
            m_forceDigestAuthentication = Utility.Utility.ParseBoolOption(options, "force-digest-authentication");
            m_useSSL = Utility.Utility.ParseBoolOption(options, "use-ssl");

            m_url = (m_useSSL ? "https" : "http") + url.Substring(u.Scheme.Length);
            if (!m_url.EndsWith("/"))
                m_url += "/";

            m_path = new Uri(m_url).PathAndQuery;
            if (m_path.IndexOf("?") > 0)
                m_path = m_path.Substring(0, m_path.IndexOf("?"));

            m_path = System.Web.HttpUtility.UrlDecode(m_path);
            m_rawurl = (m_useSSL ? "https://" : "http://") + u.Host + m_path;

            int port = u.Port;
            if (port <= 0)
                port = m_useSSL ? 443 : 80;

            m_rawurlPort = (m_useSSL ? "https://" : "http://") + u.Host + ":" + port + m_path;
            m_sanitizedUrl = (m_useSSL ? "https://" : "http://") + u.Host + m_path;
            m_reverseProtocolUrl = (m_useSSL ? "http://" : "https://") + u.Host + m_path;
            options.TryGetValue("debug-propfind-file", out m_debugPropfindFile);
        }
        private static string PathFromUri(string uri)
        {
            if (String.IsNullOrEmpty(uri))
            {
                return String.Empty;
            }

            string baseUri = new Uri(uri).PathAndQuery;
            if (baseUri.StartsWith("/"))
            {
                baseUri = baseUri.Substring(1);
            }

            return baseUri;
        }
Esempio n. 30
0
        private async Task AddFromUrl(string url)
        {
            var uriDrag = new Uri(url).AbsolutePath;
            var jiraRef = uriDrag.Substring(uriDrag.LastIndexOf("/") + 1);
            var todaysDate = DateTime.Now.Date;
            var dayTimers = ModelHelpers.Gallifrey.JiraTimerCollection.GetTimersForADate(todaysDate).ToList();

            if (dayTimers.Any(x => x.JiraReference == jiraRef))
            {
                ModelHelpers.Gallifrey.JiraTimerCollection.StartTimer(dayTimers.First(x => x.JiraReference == jiraRef).UniqueId);
                ModelHelpers.RefreshModel();
                ModelHelpers.SelectRunningTimer();
            }
            else
            {
                //Validate jira is real
                try
                {
                    ModelHelpers.Gallifrey.JiraConnection.GetJiraIssue(jiraRef);
                }
                catch (NoResultsFoundException)
                {
                    await DialogCoordinator.Instance.ShowMessageAsync(ModelHelpers.DialogContext, "Invalid Jira", $"Unable To Locate That Jira.\n\nJira Ref Dropped: '{jiraRef}'");
                    return;
                }

                //show add form, we know it's a real jira & valid
                var addTimer = new AddTimer(ModelHelpers, startDate: todaysDate, jiraRef: jiraRef, startNow: true);
                await ModelHelpers.OpenFlyout(addTimer);
                if (addTimer.AddedTimer)
                {
                    ModelHelpers.SetSelectedTimer(addTimer.NewTimerId);
                }
            }
        }
Esempio n. 31
0
 public static string GetFormattedTitle(SoundPlayerInfo playerInfo)
 {
     string title = playerInfo.Name;
     if ((playerInfo.IsWeb) && (playerInfo.UserEditedName == false))
     {
         string domainName = new Uri(playerInfo.UrlOrCommandLine).Host;
         if (domainName.StartsWith("www."))
             domainName = domainName.Substring(4);
         title = domainName + ": " + playerInfo.Name;
     }
     return title;
 }
Esempio n. 32
0
        /// <summary>
        /// Initializes the name of the running service.
        /// </summary>
        private static void InitializeRunningServiceName()
        {
            try
            {
                // Usually, the application run into IIS, so HttpContext is initialized.
                HttpContext context = HttpContext.Current;
                if (context != null && context.Request != null)
                {
                    RunningServiceName = context.Request.ApplicationPath.Trim('/');
                }
                else
                {
                    string path = new System.Uri(typeof(ServiceConfiguration).Assembly.CodeBase).LocalPath;

                    // In case that we run into the debugger of Visual studio, web site might be located into a temporary folder.
                    string tempAspNetFiles = Path.Combine(Path.GetTempPath(), "Temporary ASP.NET Files" + Path.DirectorySeparatorChar);

                    if (path.StartsWith(tempAspNetFiles, StringComparison.OrdinalIgnoreCase))
                    {
                        path = path.Substring(tempAspNetFiles.Length);

                        char firstChar  = path[0];
                        int  foundIndex = path.IndexOfAny(new char[] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar }, 0);

                        if (foundIndex > 0)
                        {
                            path = path.Substring(0, foundIndex);
                        }
                    }
                    else
                    {
                        // Run in the context of automated tests.
                        string[] pathSplitted = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                        int      index        = pathSplitted.Length;
                        if (index > 1)
                        {
                            index -= 2;
                            if (index > 1 && (string.Equals(pathSplitted[index], "Debug", StringComparison.OrdinalIgnoreCase) ||
                                              string.Equals(pathSplitted[index], "Release", StringComparison.OrdinalIgnoreCase)))
                            {
                                index--;
                            }
                            if (index > 1 && string.Equals(pathSplitted[index], "bin", StringComparison.OrdinalIgnoreCase))
                            {
                                index--;
                            }
                        }
                        else
                        {
                            index = 0;
                        }

                        path = pathSplitted[index];
                    }

                    if (!string.IsNullOrEmpty(path))
                    {
                        RunningServiceName = path;
                    }
                    else
                    {
                        RunningServiceName = "PIS.Ground.Core";
                    }
                }
            }
            catch
            {
                RunningServiceName = "PIS.Ground.Core";
            }
        }