public void TestProgramMain()
        {
            Assembly a = typeof(Commands).Assembly;
            StringWriter sout = new StringWriter(), serr = new StringWriter();
            TextWriter saveout = Console.Out;
            Console.SetOut(sout);
            TextWriter saveerr = Console.Error;
            Console.SetError(serr);
            try
            {
                AppDomain.CurrentDomain.ExecuteAssembly(a.Location, 
#if NET20 || NET35
                    AppDomain.CurrentDomain.Evidence,
#endif
                    new string[] { "Config" });
            }
            finally
            {
                Console.SetOut(saveout);
                Console.SetError(saveerr);
            }

            string result = new StreamReader(a.GetManifestResourceStream(typeof(Commands).Namespace + ".CmdTool.config")).ReadToEnd();
            Assert.AreEqual(sout.ToString().Trim(), result.Trim());
        }
Exemple #2
0
        private void GenerateLink()
        {
            // helper function to clean up code
            // MakeURL() returns the Adfly API url
            string url = MakeURL();

            try
            {
                // create a new HttpWebRequest for the Adfly url
                HttpWebRequest wRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse();

                // read the response
                string sResult = new StreamReader(wResponse.GetResponseStream()).ReadToEnd();

                // check for error
                if (sResult.ToLower() != "error")
                {
                    // update status and display the adfly link
                    UpdateStatus("Link generated", sResult.Trim());
                }
                else
                    UpdateStatus("Error");
            }
            catch (Exception ex)
            {
                // display any errors and set the status
                MessageBox.Show(ex.Message);
                UpdateStatus("Error");
            }
        }
Exemple #3
0
        public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams)
        {
            foreach (var packageStream in inputStreams)
            {
                var isSymbolPackage = packageStream.StreamName.EndsWith(".symbols.nupkg");
                var args = new List<string>(new[] {
                    "push",
                    packageStream.StreamName,
                    isSymbolPackage ? this.symbolApiKey : this.apiKey
                });

                if (!isSymbolPackage && this.serverUrl != null) args.AddRange(new[] { "-Source", this.serverUrl });
                if (isSymbolPackage && this.symbolServerUrl != null) args.AddRange(new[] { "-Source", this.symbolServerUrl });

                if (this.timeout.HasValue) args.AddRange(new[] { "-Timeout", this.timeout.Value.TotalSeconds.ToString() });
                args.Add("-NonInteractive");

                var resultStreams = PvcUtil.StreamProcessExecution(PvcNuGet.NuGetExePath, Directory.GetCurrentDirectory(), args.ToArray());

                string outLine;
                var outStreamReader = new StreamReader(resultStreams.Item1);
                while ((outLine = outStreamReader.ReadLine()) != null)
                {
                    Console.WriteLine(outLine);
                }

                var errOutput = new StreamReader(resultStreams.Item2).ReadToEnd();
                if (errOutput.Trim().Length > 0)
                    throw new PvcException("NuGet Push Error: " + errOutput);
            }

            return new PvcStream[] { };
        }
        public void Join(string userAccessToken, string gameId, string secondPlayerName)
        {
            var response = HttpWebRequester.CreatePOST(userAccessToken, GlobalConstants.JoinServiceUri, null);

            var responseAsString =  new StreamReader(response.GetResponseStream()).ReadToEnd();
            if (gameId.CompareTo(responseAsString.Trim('\"')) == 0)
            {
                // if join is successfull
                Clients.All.join(gameId, secondPlayerName);
            }

            //if join is noy successfull
            //Clients.Client(Context.ConnectionId).join(GlobalConstants.JoinUnsuccessfull);
        }
Exemple #5
0
        public static string DecryptFile(string strInFile)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

            //A 64 bit key and IV is required for this provider.
            //Set secret key For DES algorithm.
            DES.Key = ASCIIEncoding.ASCII.GetBytes(KEY);

            //Set initialization vector.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(KEY);

            //Create a file stream to read the encrypted file back.
            FileStream fileInEncrypted = new FileStream(strInFile, FileMode.Open,FileAccess.Read);

            //Create a DES decryptor from the DES instance.
            ICryptoTransform desdecrypt = DES.CreateDecryptor();

            //Create crypto stream set to read and do a DES decryption transform on incoming bytes.
            CryptoStream cryptostreamDecr = new CryptoStream(fileInEncrypted, desdecrypt, CryptoStreamMode.Read);

            string strContent = new StreamReader(cryptostreamDecr).ReadToEnd();
            return strContent.Trim();
        }
Exemple #6
0
        public string GetPublicIp()
        {
            try
            {
                var httpRequest = (HttpWebRequest) WebRequest.Create("http://icanhazip.com");

                httpRequest.Method = "GET";
                httpRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                httpRequest.KeepAlive = false;
                httpRequest.Timeout = 15000;

                var httpResponse = (HttpWebResponse) httpRequest.GetResponse();

                var response = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();

                return response.Trim().Replace("\n", string.Empty);
            }
            catch (Exception ex)
            {
                _log.Error("GetPublicIp failed", ex);
            }
            return null;
        }
 private XmlNode ParseResponseStream(Stream stream)
 {
     var body = new StreamReader(stream).ReadToEnd();
     if (body.Trim() == "")
     {
         return new XmlDocument();
     }
     else
     {
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(body);
         if (doc.ChildNodes.Count == 1) return doc.ChildNodes[0];
         return doc.ChildNodes[1];
     }
 }
Exemple #8
0
        public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams)
        {
            var nupkgFiles = new List<string>();
            var nupkgFilesCreated = 0;
            FileSystemWatcher watcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), "*.nupkg");
            FileSystemEventHandler eventHandler = (object s, FileSystemEventArgs e) =>
            {
                if (!nupkgFiles.Contains(e.FullPath))
                    nupkgFiles.Add(e.FullPath);
            };

            watcher.Created += eventHandler;
            watcher.Changed += eventHandler;

            watcher.EnableRaisingEvents = true;

            foreach (var nuStream in inputStreams)
            {
                var args = new List<string>(new[]{
                    "pack",
                    nuStream.StreamName
                });

                if (this.basePath != null) args.AddRange(new[] { "-BasePath", this.basePath });
                if (this.version != null) args.AddRange(new[] { "-Version", this.version });
                if (this.exclude != null) args.AddRange(new[] { "-Exclude", this.exclude });
                if (this.defaultExcludes == false) args.Add("-NoDefaultExcludes");
                if (this.packageAnalysis == false) args.Add("-NoPackageAnalysis");
                if (this.includeReferencedProjects) args.Add("-IncludeReferencedProjects");
                if (this.excludeEmptyDirectories) args.Add("-ExcludeEmptyDirectories");
                if (this.createSymbolsPackage) args.Add("-Symbols");
                if (this.buildProject) args.Add("-Build");
                if (this.minClientVersion != null) args.AddRange(new[] { "-MinClientVersion", this.minClientVersion });
                if (this.properties != null) args.AddRange(new[] { "-Properties", this.properties });
                args.Add("-NonInteractive");

                var resultStreams = PvcUtil.StreamProcessExecution(PvcNuGet.NuGetExePath, Directory.GetCurrentDirectory(), args.ToArray());

                string outLine;
                var outStreamReader = new StreamReader(resultStreams.Item1);
                while ((outLine = outStreamReader.ReadLine()) != null)
                {
                    Console.WriteLine(outLine);
                }

                var errOutput = new StreamReader(resultStreams.Item2).ReadToEnd();
                if (errOutput.Trim().Length > 0)
                {
                    throw new PvcException("NuGet Pack Error: " + errOutput);
                }
                else
                {
                    nupkgFilesCreated++;
                }
            }

            // wait for the watch to catch all the files created
            while (nupkgFiles.Count != (nupkgFilesCreated * (this.createSymbolsPackage ? 2 : 1))) { }

            var nupkgStreams = nupkgFiles.Select(x => new PvcStream(() => new FileStream(x, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)).As(x, Path.Combine(Directory.GetCurrentDirectory(), x)));
            return nupkgStreams;
        }
        public string SendPost(Dictionary<string, string> data)
        {
            string res = null;
            byte[] postData = null;
            Stream webpageStream;
            HttpWebRequest _webRequest = null;

            try
            {
                postData = preparePostData(data);
            }
            catch (Exception e)
            {
                _cw("Prepairing post data error: " + e.Message);
                _cw("Exception data: " + e.Data);

                return res;
            }

            try
            {
                _webRequest = (HttpWebRequest) WebRequest.Create(PostUrl);
            }
            catch (Exception e)
            {
                _cw("Socket create error: " + e.Message);
                _cw("Exception data: " + e.Data);

                return res;
            }

            _webRequest.Method = "POST";
            _webRequest.ContentType = "application/x-www-form-urlencoded";
            _webRequest.ContentLength = postData.Length;
            _webRequest.Timeout = 2000;

            try
            {
                webpageStream = _webRequest.GetRequestStream();
                webpageStream.Write(postData, 0, postData.Length);
                webpageStream.Close();
            }
            catch (Exception e)
            {
                _cw("Writing http request error: " + e.Message);
                _cw("Exception data: " + e.Data);

                return res;
            }

            _cw("Post request sent");

            try
            {
                var response = (HttpWebResponse)_webRequest.GetResponse();
                res = new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception e)
            {
                _cw("Getting http response error: " + e.Message);
                _cw("Exception data: " + e.Data);

                return res;
            }

            res = res.Trim(' ', ' ', '\n', '\r');

            return res;
        }
Exemple #10
0
    /// <summary>
    /// 实时航班查询接口
    /// </summary>
    public ArrayList GlobalFlight(string fromCode, string toCode, string airLineCode, string cls, int num, string goTime)
    {
        //string url = aifeServerUrl + globalFlightUrl + _account + cls + "/" + fromCode + "/" + toCode + "/" + airLineCode + "/" + num + "/" + goTime;
        string url = "http://data.faredata.cn/ticketWebService.do?method=globalFlight&account=fyjp&cls=Y&fromCode=" + fromCode + "&toCode=" + toCode + "&airLineCode=" + airLineCode + "&mnum=1&goTime=" + goTime;

        ArrayList flgihts = new ArrayList();

        try{
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 15000;
            WebResponse response     = request.GetResponse();
            string      responseText = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
            //解析返回字符串
            string[] flightArray = responseText.Trim().Split('@');            //舱位分隔符 @


            //只用一个舱位数据
            foreach (string flightText in flightArray)
            {
                //cache ticket 插入ticket信息
                string  ticketId = null;
                string  sql      = "insert into FY_Aifei_Ticket (fromCity,toCity,airline,fromTime) values ('" + fromCode + "','" + toCode + "','" + airLineCode + "','" + goTime + "') select ID=@@identity";
                DataSet dsTicket = SqlHelper.ExecuteDataset(SqlHelper.ConnString_select, CommandType.Text, sql);
                if (dsTicket != null)
                {
                    ticketId = dsTicket.Tables[0].Rows[0]["ID"].ToString();
                }

                ArrayList flight = new ArrayList();
                //转机分割符 *
                string[] relayArray = flightText.Split('*');

                int flightNum = 1;
                foreach (string relayText in relayArray)
                {
                    string[] flightOptions = relayText.Split('^');
                    if (flightOptions.Length == 9)
                    {
                        AiFeiFlightEntity affe = new AiFeiFlightEntity();

                        affe.airlineCode = flightOptions[0];
                        affe.flightNum   = flightOptions[1];
                        affe.fromAirport = flightOptions[2];
                        affe.toAirport   = flightOptions[3];
                        affe.toTime      = flightOptions[4];
                        affe.arriveTime  = flightOptions[5];
                        affe.airplan     = flightOptions[6];
                        affe.seats       = Convert.ToInt32(flightOptions[7]);
                        affe.isRelay     = Convert.ToInt32(flightOptions[8]);

                        //cache 舱位信息
                        if (ticketId != null && !ticketId.Trim().Equals("") && !ticketId.Trim().Equals("0"))
                        {
                            sql = "insert into FY_Aifei_Flights (airline,flightNum,toAirport,fromAirport,toTime,arriveTime,airplan,seats,num,ticketid) values ('" + affe.airlineCode + "','" + affe.flightNum + "','" + affe.toAirport + "','" + affe.fromAirport + "','" + affe.toTime + "','" + affe.arriveTime + "','" + affe.airplan + "','" + affe.seats + "','" + flightNum + "','" + ticketId + "')";
                            SqlHelper.ExecuteDataset(SqlHelper.ConnString_select, CommandType.Text, sql);
                        }
                        flightNum++;

                        flight.Add(affe);
                    }
                }
                flgihts.Add(flight);
                return(flgihts);
            }
        }catch (Exception e) {
            return(flgihts);
        }

        return(flgihts);
    }
Exemple #11
0
        public static bool GetUpdate(bool autoCheck)
        {
            UpdateInfo ui = null;
            string ini = PortableSettingsProvider.GetApplicationIniFile("Update");
            if (!File.Exists(ini))
            {
                CopyableMessageBox.Show(
                    "Problem checking for update" + (autoCheck ? " - will try again later" : "") + "\n"
                    + ini + " - not found"
                    , PortableSettingsProvider.ExecutableName + " AutoUpdate"
                    , CopyableMessageBoxButtons.OK
                    , CopyableMessageBoxIcon.Error);
                return true;
            }
            try
            {
                string url = new StreamReader(ini).ReadLine();
                if (url == null)
                    throw new IOException(ini + " - failed to read url");
                url = url.Trim();
                try
                {
                    using (ObjectCloner.Splash splash = new ObjectCloner.Splash("Checking for updates..."))
                    {
                        splash.Show();
                        Application.DoEvents();
                        ui = new UpdateInfo(url);
                    }
                }
                catch (System.Net.WebException we)
                {
                    if (we != null)
                    {
                        CopyableMessageBox.Show(
                            "Problem checking for update" + (autoCheck ? " - will try again later" : "") + "\n"
                            + (we.Response != null ? "\nURL: " + we.Response.ResponseUri : "")
                            + "\n" + we.Message
                            , PortableSettingsProvider.ExecutableName + " AutoUpdate"
                            , CopyableMessageBoxButtons.OK
                            , CopyableMessageBoxIcon.Error);
                        return true;
                    }
                }
            }
            catch (IOException ioe)
            {
                CopyableMessageBox.Show(
                    "Problem checking for update" + (autoCheck ? " - will try again later" : "") + "\n"
                    + ioe.Message
                    , PortableSettingsProvider.ExecutableName + " AutoUpdate"
                    , CopyableMessageBoxButtons.OK
                    , CopyableMessageBoxIcon.Error);
                return true;
            }

            if (UpdateApplicable(ui, autoCheck))
            {
                int dr = CopyableMessageBox.Show(
                    String.Format("{0}\n{3}\n\nCurrent version: {1}\nAvailable version: {2}",
                    ui.Message, Version.CurrentVersion, ui.AvailableVersion, ui.UpdateURL)
                    , PortableSettingsProvider.ExecutableName + " update available"
                    , CopyableMessageBoxIcon.Question
                    , new List<string>(new string[] { "&Visit link", "&Later", "&Skip version", }), 1, 2
                    );

                switch (dr)
                {
                    case 0: System.Diagnostics.Process.Start(ui.UpdateURL); break;
                    case 2: pgmSettings.AULastIgnoredVsn = ui.AvailableVersion; pgmSettings.Save(); break;
                }
                return true;
            }
            return false;
        }
Exemple #12
0
        private bool postData(string postURL, string data2Post, out string responseData, int retryCounter)
        {
            responseData = "";
            int num = 0;
            byte[] bytes = null;
            bool flag = false;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postURL);
            HttpWebResponse response = null;
            ServicePointManager.CertificatePolicy = new CertPolicy();
            if (data2Post == "")
            {
                responseData = "Nothing to post!";
                LogMessage ("No data to post");
                return false;
            }
            num = 30000;
            try
            {
                request.Method = "POST";
                request.UserAgent = "SinaptIQ WebBot";
                request.ContentType = "application/xml; charset=utf-8";
                request.ContentLength = data2Post.Length;
                request.KeepAlive = true;
                request.Timeout = num;
                LogMessage ("URL: " + postURL);

                    LogMessage ("Trying to read certificate to post to MDURL;");
                    try
                    {
                        X509Certificate2 sSLCertificate = this.GetSSLCertificate(this.txtCertLocation.Text , this.txtCertPassword.Text );
                        request.ClientCertificates.Add(sSLCertificate);
                        LogMessage("Certificate read successful;");
                    }
                    catch (Exception exception)
                    {
                        responseData = exception.Message;
                        LogMessage("Certificate read failed;" + responseData.ToString());
                        flag = false;
                    }

                if (data2Post != null)
                {
                    LogMessage("data2Post is not null");
                    bytes = Encoding.UTF8.GetBytes(data2Post);
                    request.ContentLength = bytes.Length;
                    LogMessage("    Before get Request Stream");

                    Stream requestStream = request.GetRequestStream();
                    LogMessage("    After get Request Stream");
                    LogMessage("    Before Write Byte");
                    requestStream.Write(bytes, 0, bytes.Length);

                    requestStream.Close();
                    LogMessage("    After Write Byte");
                    LogMessage("Data sent: " + data2Post);
                }
                else
                {
                    request.ContentLength = 0L;
                }
                LogMessage("   Before Get Response");
                response = (HttpWebResponse)request.GetResponse();
                LogMessage("   After Get Response");
                LogMessage("    Before Get ResponseData");
                responseData = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                LogMessage("   After Get ResponseData");
                responseData = responseData.Trim();
                LogMessage ("Data received: " + responseData);
                flag = true;
            }
            catch (Exception exception2)
            {
                responseData = exception2.Message;
                LogMessage("Post Error: " + responseData);
                flag = false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                LogMessage("Finally statement. Closed successful.");
            }
            return flag;
        }
		public string CheckHttpModule()
		{
			try
			{
				Wait();
				string responseText;
				Uri currentUri = HttpContext.Current.Request.Url;
				WebRequest request = WebRequest.Create(string.Format("{0}://{1}:{2}?{3}=1", currentUri.Scheme, currentUri.Host, currentUri.Port, UrlTrackerSettings.HttpModuleCheck));
				using (WebResponse response = request.GetResponse())
				using (Stream responseStream = response.GetResponseStream())
				{
					responseText = new StreamReader(responseStream).ReadToEnd();
					if (responseText.Trim().ToUpper() == UrlTrackerSettings.HttpModuleCheck.Trim().ToUpper())
						return string.Empty;
				}
				throw new Exception(string.Format("The Http Module isn't responding, response was: '{0}'", responseText));
			}
			catch (Exception ex)
			{
				return HandleException(ex);
			}
		}
        public static CookieContainer WischiAuth(string sid, string user,out string Hinweis)
        {
            CookieContainer cc = new CookieContainer();

            //GET-Hash from Wischis-Server
            System.Net.HttpWebRequest webreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://dev.wischenbart.org/minecraft/requesthash.php?user="******"http://session.minecraft.net/game/joinserver.jsp?user="******"&sessionId=" + HttpUtility.UrlPathEncode(sid) + "&serverId=" + HttpUtility.UrlPathEncode(hash));
            string antw = new StreamReader(webreq2.GetResponse().GetResponseStream()).ReadToEnd();
            Hinweis = hash + ":" + antw + ":" + cc.Count;
            if (antw.Trim() != "OK") return null;
            return cc;
        }
Exemple #15
0
    /// <summary>
    /// 实时航班查询接口
    /// </summary>
    public FeiYingFlight GlobalFlight2(string fromCode, string toCode, string airLineCode, string cls, int num, string goTime)
    {
        //string url = aifeServerUrl + globalFlightUrl + _account + cls + "/" + fromCode + "/" + toCode + "/" + airLineCode + "/" + num + "/" + goTime;
        string url = "http://data.faredata.cn/ticketWebService.do?method=globalFlight&account=fyjp&cls=Y&fromCode=" + fromCode + "&toCode=" + toCode + "&airLineCode=" + airLineCode + "&mnum=1&goTime=" + goTime;

        //string url = "http://*****:*****@');            //舱位分隔符 @
            //只用一个舱位数据
            foreach (string flightText in flightArray)
            {
                ArrayList flight = new ArrayList();
                //转机分割符 *
                string[] relayArray = flightText.Split('*');

                int flightNum = 1;
                foreach (string relayText in relayArray)
                {
                    string[] flightOptions = relayText.Split('^');
                    if (flightOptions.Length == 9)
                    {
                        AiFeiFlightEntity affe = new AiFeiFlightEntity();

                        affe.airlineCode = flightOptions[0];
                        affe.flightNum   = flightOptions[1];
                        affe.fromAirport = flightOptions[2];
                        affe.toAirport   = flightOptions[3];
                        affe.toTime      = flightOptions[4];
                        affe.arriveTime  = flightOptions[5];
                        affe.airplan     = flightOptions[6];
                        affe.seats       = Convert.ToInt32(flightOptions[7]);
                        affe.isRelay     = Convert.ToInt32(flightOptions[8]);

                        flight.Add(affe);
                    }
                }

                if (flight.Count > 0)
                {
                    AiFeiFlightEntity affe1 = (AiFeiFlightEntity)flight[0];
                    AiFeiFlightEntity affe2 = (AiFeiFlightEntity)flight[flight.Count - 1];

                    FeiYingFlight fyf = new FeiYingFlight();

                    fyf.airlineCode = affe1.airlineCode;
                    fyf.flightNum   = affe1.flightNum;
                    fyf.fromAirport = affe1.fromAirport;
                    fyf.toAirport   = affe2.toAirport;
                    fyf.toTime      = goTime;
                    fyf.startTime   = affe1.toTime;
                    fyf.arriveTime  = affe2.arriveTime;

                    if (flight.Count > 1)
                    {
                        fyf.isRelay = 1;
                        AiFeiFlightEntity affeRelay = (AiFeiFlightEntity)flight[1];
                        fyf.relayPort = affeRelay.fromAirport;
                    }
                    else
                    {
                        fyf.isRelay = 0;
                    }

                    string  sql      = "insert into FY_Aifei_Ticket2 (fromCity,toCity,airlineCode,toTime,arriveTime,startTime,fromAirport,toAirport,isrelay,flightNum,relayPort,airplan) values ('" + fromCode + "','" + toCode + "','" + airLineCode + "','" + goTime + "','" + affe2.arriveTime + "','" + affe1.toTime + "','" + affe1.fromAirport + "','" + affe2.toAirport + "','" + fyf.isRelay + "','" + affe1.flightNum + "','" + fyf.relayPort + "','" + affe1.airplan + "')";
                    DataSet dsTicket = SqlHelper.ExecuteDataset(SqlHelper.ConnString_select, CommandType.Text, sql);

                    return(fyf);
                }
                return(null);
            }
        }catch (Exception e) {
            throw;
            //return null;
        }

        return(null);
    }
 public static XDocument GetXmlDocument(this Stream source, bool removeDocType = false)
 {
     long position = source.Position;
     string input = new StreamReader(source).ReadLine();
     source.Position = position;
     Encoding encoding = Encoding.UTF8;
     if (!string.IsNullOrEmpty(input))
     {
         Match match = new Regex("<\\?xml[^>]*encoding=\"(?<encoding>[^\"]+)\"[^>]*\\?>").Match(input);
         if (match.Success)
         {
             string name = match.Groups["encoding"].Value.ToLower();
             if (name == "windows-1251" || name == "cp-1251" || name == "win-1251")
                 source = source.Win1251ToUTF8();
             else
                 encoding = Encoding.GetEncoding(name);
         }
     }
     string str = new StreamReader(source, encoding).ReadToEnd();
     if (removeDocType)
         str = Regex.Replace(str, "<!DOCTYPE[^>]*>", string.Empty);
     try
     {
         return XDocument.Parse(str.Trim());
     }
     catch (Exception ex)
     {
         throw new Exception("Can't parse XML", ex);
     }
 }
Exemple #17
0
        public void ShouldParseScripts() {
            var assembly = Assembly.GetExecutingAssembly();
            foreach (var resx in assembly.GetManifestResourceNames()) {
                // Ignore scripts not in /Scripts
                if (!resx.Contains(".Parse")) {
                    continue;
                }

                var program = new StreamReader(assembly.GetManifestResourceStream(resx)).ReadToEnd();
                if (program.Trim() == String.Empty) {
                    continue;
                }
                Trace.WriteLine(Path.GetFileNameWithoutExtension(resx));
                JintEngine.Compile(program, true);
            }
        }
        /// <summary>
        /// Loads a string from an embedded resource file
        /// </summary>
        /// <param name="assembly">
        /// The assembly containing the resource
        /// </param>
        /// <param name="resourceNamespace">
        /// Namespace where the resource file resides. Usually the application name
        /// </param>
        /// <param name="resourceFileName">
        /// The filename of the embedded resource
        /// </param>
        /// <returns>
        /// string from embedded resource file
        /// </returns>
        /// <remarks>
        /// This code is based on an answer on stack overflow
        /// http://stackoverflow.com/questions/576571/where-do-you-put-sql-statements-in-your-c-sharp-projects
        /// answer by: http://stackoverflow.com/users/13302/marc-s
        /// </remarks>
        public static string LoadStringFromResource(
            Assembly assembly, string resourceNamespace, string resourceFileName)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            if (string.IsNullOrWhiteSpace(resourceNamespace))
            {
                throw new ArgumentNullException("resourceNamespace");
            }

            if (string.IsNullOrWhiteSpace(resourceFileName))
            {
                throw new ArgumentNullException("resourceFileName");
            }

            string result;
            string resourceName = resourceNamespace + "." + resourceFileName;
            using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
            {
                if (resourceStream == null)
                {
                    throw new FailedToGetResourceStreamException(resourceName);
                }

                result = new StreamReader(resourceStream).ReadToEnd();

                result = result.Trim();
            }

            return result;
        }