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());
        }
Example #2
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[] { };
        }
Example #3
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");
            }
        }
Example #4
0
        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);
        }
Example #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();
        }
Example #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;
        }
Example #7
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);
            }
        }
 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];
     }
 }
Example #9
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;
        }
Example #10
0
        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;
        }
 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);
     }
 }
Example #12
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;
        }
Example #13
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=" + HttpUtility.UrlPathEncode(user));
            webreq.CookieContainer = cc;
            string hash = new StreamReader(webreq.GetResponse().GetResponseStream()).ReadToEnd();

            //Register-Hash on Mojangs-Server
            System.Net.HttpWebRequest webreq2 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://session.minecraft.net/game/joinserver.jsp?user=" + HttpUtility.UrlPathEncode(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;
        }
        /// <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;
        }