System.IO.StreamReader.Close()

Here are the examples of the csharp api System.IO.StreamReader.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1383 Examples 7

19 View Source File : Adx.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : Cmo.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    Period = Convert.ToInt32(reader.ReadLine());
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.ReadLine();

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : SourceFormat.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public string FormatCode(Stream source)
		{
			StreamReader reader = new StreamReader(source);
			string s = reader.ReadToEnd();
			reader.Close();
			return FormatCode(s, _lineNumbers, _alternate, _embedStyleSheet, false);
		}

19 View Source File : Ac.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorUp = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDown = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    LenghtLong = Convert.ToInt32(reader.ReadLine());
                    LenghtShort = Convert.ToInt32(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    Enum.TryParse(reader.ReadLine(), true, out TypeCalculationAverage);
                    reader.ReadLine();

                    reader.Close();
                }
            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : MKMInteract.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

public static XmlDoreplacedent MakeRequest(string url, string method, string body = null)
      {
        // throw the exception ourselves to prevent sending requests to MKM that would end with this error 
        // because MKM tends to revoke the user's app token if it gets too many requests above the limit
        // the 429 code is the same MKM uses for this error
        if (denyAdditionalRequests)
        {
          // MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day
          // the denial was triggered, that means the 0:00 CET has preplaceded and we can reset the deny
          if (DateTime.UtcNow.Date == denyTime.Date && DateTime.UtcNow.Hour < 22)
            throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset.");
          else
            denyAdditionalRequests = false;
        }
        // enforce the maxRequestsPerMinute limit - technically it's just an approximation as the requests
        // can arrive to MKM with some delay, but it should be close enough
        var now = DateTime.Now;
        while (requestTimes.Count > 0 && (now - requestTimes.Peek()).TotalSeconds > 60)
        {
          requestTimes.Dequeue();// keep only times of requests in the past 60 seconds
        }
        if (requestTimes.Count >= maxRequestsPerMinute)
        {
          // wait until 60.01 seconds preplaceded since the oldest request
          // we know (now - peek) is <= 60, otherwise it would get dequeued above,
          // so we are preplaceding a positive number to sleep
          System.Threading.Thread.Sleep(
              60010 - (int)(now - requestTimes.Peek()).TotalMilliseconds);
          requestTimes.Dequeue();
        }

        requestTimes.Enqueue(DateTime.Now);
        XmlDoreplacedent doc = new XmlDoreplacedent();
        for (int numAttempts = 0; numAttempts < MainView.Instance.Config.MaxTimeoutRepeat; numAttempts++)
        {
          try
          {
            var request = WebRequest.CreateHttp(url);
            request.Method = method;

            request.Headers.Add(HttpRequestHeader.Authorization, header.GetAuthorizationHeader(method, url));
            request.Method = method;

            if (body != null)
            {
              request.ServicePoint.Expect100Continue = false;
              request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(body);
              request.ContentType = "text/xml";

              var writer = new StreamWriter(request.GetRequestStream());

              writer.Write(body);
              writer.Close();
            }

            var response = request.GetResponse() as HttpWebResponse;

            // just for checking EoF, it is not accessible directly from the Stream object
            // Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets). 
            // Preplaceding empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser 
            // even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty
            StreamReader s = new StreamReader(response.GetResponseStream());
            if (!s.EndOfStream)
              doc.Load(s);
            s.Close();
            int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count"));
            int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max"));
            if (requestCount >= requestLimit)
            {
              denyAdditionalRequests = true;
              denyTime = DateTime.UtcNow;
            }
            MainView.Instance.Invoke(new MainView.UpdateRequestCountCallback(MainView.Instance.UpdateRequestCount), requestCount, requestLimit);
            break;
          }
          catch (WebException webEx)
          {
            // timeout can be either on our side (Timeout) or on server
            bool isTimeout = webEx.Status == WebExceptionStatus.Timeout;
            if (webEx.Status == WebExceptionStatus.ProtocolError)
            {
              if (webEx.Response is HttpWebResponse response)
              {
                isTimeout = response.StatusCode == HttpStatusCode.GatewayTimeout
                    || response.StatusCode == HttpStatusCode.ServiceUnavailable;
              }
            }
            // handle only timeouts, client handles other exceptions
            if (isTimeout && numAttempts + 1 < MainView.Instance.Config.MaxTimeoutRepeat)
              System.Threading.Thread.Sleep(1500); // wait and try again
            else
              throw webEx;
          }
        }
        return doc;
      }

19 View Source File : HttpApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static string ReadResponse(WebResponse response)
        {
            string result = null;
            using (response)
            {
                if (response.ContentLength != 0)
                {
                    var receivedStream = response.GetResponseStream();
                    if (receivedStream != null)
                    {
                        using (receivedStream)
                        {
                            using (var streamReader = new StreamReader(receivedStream))
                            {
                                result = streamReader.ReadToEnd();
                                streamReader.Close();
                            }
                        }
                        receivedStream.Close();
                    }
                }
                response.Close();
            }
            return result;
        }

19 View Source File : AwesomeOscillator.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorUp = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDown = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    LenghtShort = Convert.ToInt32(reader.ReadLine());
                    LenghtLong = Convert.ToInt32(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    MovingAverageTypeCalculation typeCalculation;
                    Enum.TryParse(reader.ReadLine(), true, out typeCalculation);
                    TypeCalculationAverage = typeCalculation;

                    reader.Close();
                }
            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : UploadController.cs
License : MIT License
Project Creator : ADefWebserver

private Version ReadManifest(Version objVersion, string UpgradePath)
        {
            string strManifest;
            string strFilePath = Path.Combine(UpgradePath, "Manifest.json");

            if (!System.IO.File.Exists(strFilePath))
            {
                // Manifest not found
                objVersion.ManifestLowestVersion = "";
                return objVersion;
            }

            using (StreamReader reader = new StreamReader(strFilePath))
            {
                strManifest = reader.ReadToEnd();
                reader.Close();
            }

            dynamic objManifest = JsonConvert.DeserializeObject(strManifest);

            objVersion.ManifestHighestVersion = objManifest.ManifestHighestVersion;
            objVersion.ManifestLowestVersion = objManifest.ManifestLowestVersion;
            objVersion.ManifestSuccess = objManifest.ManifestSuccess;
            objVersion.ManifestFailure = objManifest.ManifestFailure;

            return objVersion;
        }

19 View Source File : Fractail.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    ColorUp = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDown = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : ObjLoader.cs
License : The Unlicense
Project Creator : aeroson

Mesh Parse(Resource resource, GameObject appendToGameObject)
        {
            using (StreamReader textReader = new StreamReader(resource))
            {

                int i1, i2, i3, i4;

                string line;
                while ((line = textReader.ReadLine()) != null)
                {
                    line = line.Trim(trimCharacters);
                    line = line.Replace("  ", " ");

                    string[] parameters = line.Split(splitCharacters);

                    switch (parameters[0])
                    {
                        case "p": // Point
                            break;

                        case "v": // Vertex
                            var v = Vector3.Zero;
                            Parse(ref parameters[1], ref v.X);
                            Parse(ref parameters[2], ref v.Y);
                            Parse(ref parameters[3], ref v.Z);
                            verticesObj.Add(v);
                            break;

                        case "vt": // TexCoord
                            gotUvs = true;
                            var vt = Vector2.Zero;
                            Parse(ref parameters[1], ref vt.X);
                            Parse(ref parameters[2], ref vt.Y);
                            uvsObj.Add(vt);
                            break;

                        case "vn": // Normal
                            gotNormal = true;
                            var vn = Vector3.Zero;
                            Parse(ref parameters[1], ref vn.X);
                            Parse(ref parameters[2], ref vn.Y);
                            Parse(ref parameters[3], ref vn.Z);
                            normalsObj.Add(vn);
                            break;

                        case "f":
                            switch (parameters.Length)
                            {
                                case 4:
                                    i1 = ParseFaceParameter(parameters[1]);
                                    i2 = ParseFaceParameter(parameters[2]);
                                    i3 = ParseFaceParameter(parameters[3]);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i2);
                                    triangleIndiciesMesh.Add(i3);
                                    break;

                                case 5:
                                    i1 = ParseFaceParameter(parameters[1]);
                                    i2 = ParseFaceParameter(parameters[2]);
                                    i3 = ParseFaceParameter(parameters[3]);
                                    i4 = ParseFaceParameter(parameters[4]);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i2);
                                    triangleIndiciesMesh.Add(i3);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i3);
                                    triangleIndiciesMesh.Add(i4);
                                    break;
                            }
                            break;
                        case "mtllib":
                            if (Resource.ResourceInFolderExists(resource, parameters[1]))
                            {
                                materialLibrary = new MaterialLibrary(Resource.GetResourceInFolder(resource, parameters[1]));
                            }
                            break;
                        case "usemtl":
                            if (materialLibrary!=null) lastMaterial = materialLibrary.GetMat(parameters[1]);
                            break;
                    }
                }

                textReader.Close();
            }


            if(appendToGameObject!=null) return EndObjPart(appendToGameObject);

            Debug.Info("Loaded " + resource.originalPath + " vertices:" + verticesMesh.Count + " faces:" + triangleIndiciesMesh.Count / 3);

            return EndMesh();
    
        }

19 View Source File : Aindicator.cs
License : Apache License 2.0
Project Creator : AlexWan

private void GetValueParameterSaveByUser(IndicatorParameter parameter)
        {
            if (Name == "")
            {
                return;
            }

            if (!File.Exists(@"Engine\" + Name + @"Parametrs.txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @"Parametrs.txt"))
                {
                    while (!reader.EndOfStream)
                    {
                        string[] save = reader.ReadLine().Split('#');

                        if (save[0] == parameter.Name)
                        {
                            parameter.LoadParamFromString(save);
                        }
                    }
                    reader.Close();
                }
            }
            catch (Exception)
            {
                // ignore
            }
        }

19 View Source File : ReportForm.cs
License : MIT License
Project Creator : AlexGyver

private void sendButton_Click(object sender, EventArgs e) {
      Version version = typeof(CrashForm).replacedembly.GetName().Version;
      WebRequest request = WebRequest.Create(
        "http://openhardwaremonitor.org/report.php");
      request.Method = "POST";
      request.Timeout = 5000;
      request.ContentType = "application/x-www-form-urlencoded";

      string report =
        "type=hardware&" +
        "version=" + Uri.EscapeDataString(version.ToString()) + "&" +
        "report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
        "comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
        "email=" + Uri.EscapeDataString(emailTextBox.Text);
      byte[] byteArray = Encoding.UTF8.GetBytes(report);
      request.ContentLength = byteArray.Length;

      try {
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = request.GetResponse();
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        dataStream.Close();
        response.Close();

        Close();
      } catch (WebException) {
        MessageBox.Show("Sending the hardware report failed.", "Error",
          MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

19 View Source File : HttpApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static string ReadResponse(WebResponse response)
        {
            string result;
            using (response)
            {
                if (response.ContentLength == 0)
                {
                    result = ApiResult.RemoteEmptyErrorJson;
                }
                else
                {
                    var receivedStream = response.GetResponseStream();
                    if (receivedStream == null)
                        result = ApiResult.RemoteEmptyErrorJson;
                    else
                        using (receivedStream)
                        {
                            using (var streamReader = new StreamReader(receivedStream))
                            {
                                result = streamReader.ReadToEnd();
                                streamReader.Close();
                            }
                            receivedStream.Close();
                        }
                }
                response.Close();
            }

            return result;
        }

19 View Source File : IndicatorsFactory.cs
License : Apache License 2.0
Project Creator : AlexWan

private static string ReadFile(string path)
        {
            String result = "";

            using (StreamReader reader = new StreamReader(path))
            {
                result = reader.ReadToEnd();
                reader.Close();
            }

            return result;
        }

19 View Source File : Program_Setup.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void DoOutOfBoxSetup(string configFile)
        {
            var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
            var configJsExample = Path.Combine(exeLocation, "Config.js.example");
            var exampleFile = new FileInfo(configJsExample);
            if (!exampleFile.Exists)
            {
                log.Error("config.js.example Configuration file is missing.  Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
                throw new Exception("missing config.js configuration file");
            }
            else
            {
                if (!IsRunningInContainer)
                {
                    Console.WriteLine("config.js Configuration file is missing,  cloning from example file.");
                    File.Copy(configJsExample, configFile, true);
                }
                else
                {
                    Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                    var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
                    File.Copy(configJsDocker, configFile, true);
                }
            }

            var fileText = File.ReadAllText(configFile);
            var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));

            Console.WriteLine("Performing setup for ACEmulator...");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
            var variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.WorldName = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Host = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
            if (!string.IsNullOrWhiteSpace(variable))
            {
                var path = Path.GetFullPath(variable.Trim());
                if (!Path.EndsInDirectorySeparator(path))
                    path += Path.DirectorySeparatorChar;
                //path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");

                config.Server.DatFilesDirectory = path;
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
            Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
            Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
            Console.WriteLine("As before, pressing enter will use default value.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Authentication.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Shard.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.World.Database = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Host = variable.Trim();
                    config.MySql.Shard.Host = variable.Trim();
                    config.MySql.World.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();
            }
            else
            {
                Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "y";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Username = variable.Trim();
                    config.MySql.Shard.Username = variable.Trim();
                    config.MySql.World.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                    config.MySql.Shard.Preplacedword = variable.Trim();
                    config.MySql.World.Preplacedword = variable.Trim();
                }
            }
            else
            {
                Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Preplacedword = variable.Trim();
            }

            Console.WriteLine("commiting configuration to memory...");
            using (StreamWriter file = File.CreateText(configFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
                serializer.Serialize(file, config);
            }


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                for (; ; )
                {
                    try
                    {
                        using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
                        {
                            Console.Write(".");
                            sqlTestConnection.Open();
                        }

                        break;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                        Console.Write(".");
                        Thread.Sleep(5000);
                    }
                }
                Console.WriteLine(" connected!");

                if (IsRunningInContainer)
                {
                    Console.Write("Clearing out temporary ace% database .... ");
                    var sqlDBFile = "DROP DATABASE `ace%`;";
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" done!");
                }

                Console.WriteLine("Searching for base SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile = File.ReadAllText(file.FullName);
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    switch (file.Name)
                    {
                        case "AuthenticationBase":
                            sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
                            break;
                        case "ShardBase":
                            sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
                            break;
                    }
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Base SQL scripts import complete!");

                Console.WriteLine("Searching for Update SQL scripts .... ");

                PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);

                PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);

                PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                if (IsRunningInContainer)
                {
                    Console.WriteLine(" ");
                    Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
                    Console.WriteLine(" ");
                }

                Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");

                // webrequest code provided by OptimShi
                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;
                // webrequest code provided by OptimShi

                Console.WriteLine($"Found {tag} !");

                Console.Write($"Downloading {dbFileName} .... ");
                using (var client = new WebClient())
                {
                    client.DownloadFile(dbURL, dbFileName);
                }
                Console.WriteLine("download complete!");

                Console.Write($"Extracting {dbFileName} .... ");
                ZipFile.ExtractToDirectory(dbFileName, ".", true);
                Console.WriteLine("extraction complete!");
                Console.Write($"Deleting {dbFileName} .... ");
                File.Delete(dbFileName);
                Console.WriteLine("Deleted!");

                var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
                Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
                using (var sr = File.OpenText(sqlFile))
                {
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");

                    var line = string.Empty;
                    var completeSQLline = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        //do minimal amount of work here
                        if (line.EndsWith(";"))
                        {
                            completeSQLline += line + Environment.NewLine;

                            var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
                            try
                            {
                                script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                                var count = script.Execute();
                            }
                            catch (MySql.Data.MySqlClient.MySqlException)
                            {

                            }
                            completeSQLline = string.Empty;
                        }
                        else
                            completeSQLline += line + Environment.NewLine;
                    }
                }
                Console.WriteLine(" complete!");

                Console.Write($"Deleting {sqlFile} .... ");
                File.Delete(sqlFile);
                Console.WriteLine("Deleted!");
            }

            Console.WriteLine("exiting setup for ACEmulator.");
        }

19 View Source File : Atr.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    IsWatr = Convert.ToBoolean(reader.ReadLine());

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private void ReadData()
        {
            currentlyReading = true;
            StreamReader sr = null;
            string checkVer = c_toolVer;
            bool[] read = { false, false, false, false, false, false,
                            false, false, false };

            try
            {
                sr = new StreamReader(settingsFile);

                while (sr.Peek() > -1)
                {
                    StringRead(sr.ReadLine(), ref read, ref checkVer);
                }
            }
            catch
            {
                //if (!read[0]) toolVer = c_toolVer;

                /*if (!read[1]) pFoV = c_pFoV;
                if (!read[2]) fFoV = c_FoV;
                if (!read[3]) doBeep = c_doBeep;
                if (!read[4]) updateChk = c_updateChk;
                if (!read[5]) hotKeys = c_hotKeys;

                if (!read[6]) catchKeys[0] = c_catchKeys[0];
                if (!read[7]) catchKeys[1] = c_catchKeys[1];
                if (!read[8]) catchKeys[2] = c_catchKeys[2];*/
            }
            finally
            {
                if (sr != null) sr.Close();
            }

            if (checkVer != c_toolVer)
                pFoV = c_pFoV;

            if (!requestSent)
            {
                try
                {
                    request = (HttpWebRequest)WebRequest.Create(c_checkURL);
                    request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
                    requestSent = true;
                }
                catch { }
            }

            currentlyReading = false;
        }

19 View Source File : Bollinger.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorUp = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDown = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    Deviation = Convert.ToDecimal(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.Close();
                }
            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635

private void SetPostData(HttpItem item)
        {
            //验证在得到结果时是否有传入数据
            if (!request.Method.Trim().ToLower().Contains("get"))
            {
                if (item.PostEncoding != null)
                {
                    postencoding = item.PostEncoding;
                }
                byte[] buffer = null;
                //写入Byte类型
                if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
                {
                    //验证在得到结果时是否有传入数据
                    buffer = item.PostdataByte;
                }//写入文件
                else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrWhiteSpace(item.Postdata))
                {
                    StreamReader r = new StreamReader(item.Postdata, postencoding);
                    buffer = postencoding.GetBytes(r.ReadToEnd());
                    r.Close();
                } //写入字符串
                else if (!string.IsNullOrWhiteSpace(item.Postdata))
                {
                    buffer = postencoding.GetBytes(item.Postdata);
                }
                if (buffer != null)
                {
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
                else
                {
                    request.ContentLength = 0;
                }
            }
        }

19 View Source File : DynamicTrendDetector.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    CorrectionCoeff = Convert.ToDecimal(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.ReadLine();

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24

public static string ExecuteShellCommand(int PPID, bool BlockDLLs, string Command)
        {
            var saHandles = new SECURITY_ATTRIBUTES();
            saHandles.nLength = Marshal.SizeOf(saHandles);
            saHandles.bInheritHandle = true;
            saHandles.lpSecurityDescriptor = IntPtr.Zero;

            IntPtr hStdOutRead;
            IntPtr hStdOutWrite;
            IntPtr hDupStdOutWrite = IntPtr.Zero;

            CreatePipe(
                out hStdOutRead,
                out hStdOutWrite,
                ref saHandles,
                0);

            SetHandleInformation(
                hStdOutRead,
                HANDLE_FLAGS.INHERIT,
                0);

            var pInfo = new PROCESS_INFORMATION();
            var siEx = new STARTUPINFOEX();

            siEx.StartupInfo.cb = Marshal.SizeOf(siEx);
            siEx.StartupInfo.hStdErr = hStdOutWrite;
            siEx.StartupInfo.hStdOutput = hStdOutWrite;

            string result = string.Empty;

            try
            {
                var lpSize = IntPtr.Zero;
                if (BlockDLLs)
                {
                    InitializeProcThreadAttributeList(
                        IntPtr.Zero,
                        2,
                        0,
                        ref lpSize);

                    siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);

                    InitializeProcThreadAttributeList(
                        siEx.lpAttributeList,
                        2,
                        0,
                        ref lpSize);

                    var lpMitigationPolicy = Marshal.AllocHGlobal(IntPtr.Size);
                    Marshal.WriteInt64(lpMitigationPolicy, (long)BINARY_SIGNATURE_POLICY.PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON);

                    UpdateProcThreadAttribute(
                        siEx.lpAttributeList,
                        0,
                        0x20007,
                        lpMitigationPolicy,
                        (IntPtr)IntPtr.Size,
                        IntPtr.Zero,
                        IntPtr.Zero);
                }
                else
                {
                    InitializeProcThreadAttributeList(
                        IntPtr.Zero,
                        1,
                        0,
                        ref lpSize);

                    siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);

                    InitializeProcThreadAttributeList(
                        siEx.lpAttributeList,
                        1,
                        0,
                        ref lpSize);
                }

                var parentHandle = OpenProcess(
                    0x0080 | 0x0040,
                    false,
                    PPID);

                var lpParentProcess = Marshal.AllocHGlobal(IntPtr.Size);
                Marshal.WriteIntPtr(lpParentProcess, parentHandle);

                UpdateProcThreadAttribute(
                    siEx.lpAttributeList,
                    0,
                    0x00020000,
                    lpParentProcess,
                    (IntPtr)IntPtr.Size,
                    IntPtr.Zero,
                    IntPtr.Zero);

                var hCurrent = Process.GetCurrentProcess().Handle;

                DuplicateHandle(
                    hCurrent,
                    hStdOutWrite,
                    parentHandle,
                    ref hDupStdOutWrite,
                    0,
                    true,
                    0x00000001 | 0x00000002);

                siEx.StartupInfo.hStdErr = hDupStdOutWrite;
                siEx.StartupInfo.hStdOutput = hDupStdOutWrite;

                siEx.StartupInfo.dwFlags = 0x00000001 | 0x00000100;
                siEx.StartupInfo.wShowWindow = 0;

                var ps = new SECURITY_ATTRIBUTES();
                var ts = new SECURITY_ATTRIBUTES();
                ps.nLength = Marshal.SizeOf(ps);
                ts.nLength = Marshal.SizeOf(ts);

                CreateProcess(
                    null,
                    Command,
                    ref ps,
                    ref ts,
                    true,
                    CREATION_FLAGS.CREATE_NO_WINDOW | CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT,
                    IntPtr.Zero,
                    null,
                    ref siEx,
                    out pInfo);

                var safeHandle = new SafeFileHandle(hStdOutRead, false);
                var encoding = Encoding.GetEncoding(GetConsoleOutputCP());
                var reader = new StreamReader(new FileStream(safeHandle, FileAccess.Read, 4096, false), encoding, true);

                var exit = false;

                try
                {
                    do
                    {
                        if (WaitForSingleObject(pInfo.hProcess, 100) == 0)
                            exit = true;

                        char[] buf = null;
                        int bytesRead;
                        uint bytesToRead = 0;

                        var peekRet = PeekNamedPipe(
                            hStdOutRead,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            ref bytesToRead,
                            IntPtr.Zero);

                        if (peekRet == true && bytesToRead == 0)
                            if (exit == true)
                                break;
                            else
                                continue;

                        if (bytesToRead > 4096)
                            bytesToRead = 4096;

                        buf = new char[bytesToRead];
                        bytesRead = reader.Read(buf, 0, buf.Length);
                        if (bytesRead > 0)
                            result += new string(buf);

                    } while (true);
                    reader.Close();
                }
                catch { }
                finally
                {
                    safeHandle.Close();
                }

                CloseHandle(hStdOutRead);
            }
            catch { }
            finally
            {
                DeleteProcThreadAttributeList(siEx.lpAttributeList);
                Marshal.FreeHGlobal(siEx.lpAttributeList);
                CloseHandle(pInfo.hProcess);
                CloseHandle(pInfo.hThread);
            }

            return result;
        }

19 View Source File : NodeEditorUtilities.cs
License : MIT License
Project Creator : aksyr

internal static UnityEngine.Object CreateScript(string pathName, string templatePath) {
            string clreplacedName = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty);
            string templateText = string.Empty;

            UTF8Encoding encoding = new UTF8Encoding(true, false);

            if (File.Exists(templatePath)) {
                /// Read procedures.
                StreamReader reader = new StreamReader(templatePath);
                templateText = reader.ReadToEnd();
                reader.Close();

                templateText = templateText.Replace("#SCRIPTNAME#", clreplacedName);
                templateText = templateText.Replace("#NOTRIM#", string.Empty);
                /// You can replace as many tags you make on your templates, just repeat Replace function
                /// e.g.:
                /// templateText = templateText.Replace("#NEWTAG#", "MyText");

                /// Write procedures.

                StreamWriter writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding);
                writer.Write(templateText);
                writer.Close();

                replacedetDatabase.Importreplacedet(pathName);
                return replacedetDatabase.LoadreplacedetAtPath(pathName, typeof(Object));
            } else {
                Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
                return null;
            }
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : A-Tabeshfard

private void MnuFileOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (_openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    _streamReader = new StreamReader(_openFileDialog.OpenFile());
                    ((FrmContent)ActiveMdiChild).textBox.Text = _streamReader.ReadToEnd();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (_streamReader != null)
                    _streamReader.Close();
            }
        }

19 View Source File : CrashForm.cs
License : MIT License
Project Creator : AlexGyver

private void sendButton_Click(object sender, EventArgs e) {
      try {
        Version version = typeof(CrashForm).replacedembly.GetName().Version;
        WebRequest request = WebRequest.Create(
          "http://openhardwaremonitor.org/report.php");
        request.Method = "POST";
        request.Timeout = 5000;
        request.ContentType = "application/x-www-form-urlencoded";

        string report =
          "type=crash&" +
          "version=" + Uri.EscapeDataString(version.ToString()) + "&" +
          "report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
          "comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
          "email=" + Uri.EscapeDataString(emailTextBox.Text);
        byte[] byteArray = Encoding.UTF8.GetBytes(report);
        request.ContentLength = byteArray.Length;

        try {
          Stream dataStream = request.GetRequestStream();
          dataStream.Write(byteArray, 0, byteArray.Length);
          dataStream.Close();

          WebResponse response = request.GetResponse();
          dataStream = response.GetResponseStream();
          StreamReader reader = new StreamReader(dataStream);
          string responseFromServer = reader.ReadToEnd();
          reader.Close();
          dataStream.Close();
          response.Close();

          Close();
        } catch (WebException) {
          MessageBox.Show("Sending the crash report failed.", "Error", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
      } catch {
      }
    }

19 View Source File : GuiderImpl.cs
License : MIT License
Project Creator : agalasso

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                    sw = null;
                }
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                    sr = null;
                }
                if (tcpCli != null)
                {
                    Debug.WriteLine("Disconnect from phd2");
                    tcpCli.Close();
                    tcpCli = null;
                }
            }
        }

19 View Source File : AlertToPrice.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @"Alert.txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @"Alert.txt"))
                {
                    Message = reader.ReadLine();
                    IsOn = Convert.ToBoolean(reader.ReadLine());
                    MessageIsOn = Convert.ToBoolean(reader.ReadLine());
                    Enum.TryParse(reader.ReadLine(), out MusicType);

                    Enum.TryParse(reader.ReadLine(), true, out SignalType);
                    VolumeReaction = reader.ReadLine().ToDecimal();
                    Slippage = reader.ReadLine().ToDecimal();
                    NumberClosePosition = Convert.ToInt32(reader.ReadLine());
                    Enum.TryParse(reader.ReadLine(), true, out OrderPriceType);

                    Enum.TryParse(reader.ReadLine(), true, out TypeActivation);
                    PriceActivation = reader.ReadLine().ToDecimal();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                // ignore
            }
        }

19 View Source File : IOUtils.cs
License : MIT License
Project Creator : alexismorin

public static string LoadTextFileFromDisk( string pathName )
		{
			string result = string.Empty;
            if ( !string.IsNullOrEmpty( pathName ) && File.Exists( pathName ) )
            {

                StreamReader fileReader = null;
                try
                {
                    fileReader = new StreamReader( pathName );
                    result = fileReader.ReadToEnd();
                }
                catch ( Exception e )
                {
                    Debug.LogException( e );
                }
                finally
                {
                    if( fileReader != null)
                        fileReader.Close();
                }
            }
			return result;
		}

19 View Source File : HttpApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void CreateRequest(string apiName, string method, HttpRequest localRequest, RouteData data)
        {
            ApiName = apiName;
            var url = new StringBuilder();
            url.Append($"{Host?.TrimEnd('/') + "/"}{apiName?.TrimStart('/')}");
            
            if (localRequest.QueryString.HasValue)
            {
                url.Append('?');
                url.Append(data.Uri.Query);
            }
            RemoteUrl = url.ToString();



            RemoteRequest = (HttpWebRequest) WebRequest.Create(RemoteUrl);
            RemoteRequest.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {data.Token}");
            RemoteRequest.Timeout = RouteOption.Option.SystemConfig.HttpTimeOut;
            RemoteRequest.Method = method;
            RemoteRequest.KeepAlive = true;
            if (localRequest.HasFormContentType)
            {
                RemoteRequest.ContentType = "application/x-www-form-urlencoded";
                var builder = new StringBuilder();
                builder.Append($"_api_context_={HttpUtility.UrlEncode(JsonConvert.SerializeObject(GlobalContext.Current), Encoding.UTF8)}");
                foreach (var kvp in localRequest.Form)
                {
                        builder.Append('&');
                    builder.Append($"{kvp.Key}=");
                    if (!string.IsNullOrEmpty(kvp.Value))
                        builder.Append($"{HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
                }
                
                data.Form = builder.ToString();
                using (var rs = RemoteRequest.GetRequestStream())
                {
                    var formData = Encoding.UTF8.GetBytes(data.Form);
                    rs.Write(formData, 0, formData.Length);
                }
            }
            else if (localRequest.ContentLength != null)
            {
                using (var texter = new StreamReader(localRequest.Body))
                {
                    data.Context = texter.ReadToEnd();
                    texter.Close();
                }
                if (string.IsNullOrWhiteSpace(data.Context))
                    return;
                RemoteRequest.ContentType = "application/json;charset=utf-8";
                var buffer = data.Context.ToUtf8Bytes();
                using (var rs = RemoteRequest.GetRequestStream())
                {
                    rs.Write(buffer, 0, buffer.Length);
                }
            }
            else
            {
                RemoteRequest.ContentType = localRequest.ContentType;
            }
        }

19 View Source File : Aindicator.cs
License : Apache License 2.0
Project Creator : AlexWan

private void CheckSeriesParamsInSaveData(IndicatorDataSeries series)
        {
            if (Name == "")
            {
                return;
            }

            if (!File.Exists(@"Engine\" + Name + @"Values.txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @"Values.txt"))
                {
                    while (!reader.EndOfStream)
                    {
                        string[] save = reader.ReadLine().Split('&');

                        if (save[0] == series.Name)
                        {
                            series.LoadFromStr(save);
                        }
                    }
                    reader.Close();
                }
            }
            catch (Exception)
            {
                // ignore
            }
        }

19 View Source File : Program_DbUpdates.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void CheckForWorldDatabaseUpdate()
        {
            log.Info($"Automatic World Database Update started...");
            try
            {
                var worldDb = new Database.WorldDatabase();
                var currentVersion = worldDb.GetVersion();
                log.Info($"Current World Database version: Base - {currentVersion.BaseVersion} | Patch - {currentVersion.PatchVersion}");

                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;

                if (currentVersion.PatchVersion != tag)
                {
                    var patchVersionSplit = currentVersion.PatchVersion.Split(".");
                    var tagSplit = tag.Split(".");

                    int.TryParse(patchVersionSplit[0], out var patchMajor);
                    int.TryParse(patchVersionSplit[1], out var patchMinor);
                    int.TryParse(patchVersionSplit[2], out var patchBuild);

                    int.TryParse(tagSplit[0], out var tagMajor);
                    int.TryParse(tagSplit[1], out var tagMinor);
                    int.TryParse(tagSplit[2], out var tagBuild);

                    if (tagMajor > patchMajor || tagMinor > patchMinor || (tagBuild > patchBuild && patchBuild != 0))
                    {
                        log.Info($"Latest patch version is {tag} -- Update Required!");
                        UpdateToLatestWorldDatabase(dbURL, dbFileName);
                        var newVersion = worldDb.GetVersion();
                        log.Info($"Updated World Database version: Base - {newVersion.BaseVersion} | Patch - {newVersion.PatchVersion}");
                    }
                    else
                    {
                        log.Info($"Latest patch version is {tag} -- No Update Required!");
                    }
                }
                else
                {
                    log.Info($"Latest patch version is {tag} -- No Update Required!");
                }
            }
            catch (Exception ex)
            {
                log.Info($"Unable to continue with Automatic World Database Update due to the following error: {ex}");
            }
            log.Info($"Automatic World Database Update complete.");
        }

19 View Source File : AccumulationDistribution.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.ReadLine();

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : Router.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private string CallZero()
        {
            if (!(Data.RouteHost is ZeroHost host))
            {
                LogRecorder.MonitorTrace("Host Type Failed");
                return Data.ResultMessage;
            }
            try
            {
                var arguments = new Dictionary<string, string>();
                if (Request.QueryString.HasValue)
                {
                    foreach (var key in Request.Query.Keys)
                        arguments.TryAdd(key, Request.Query[key]);
                }
                if (Request.HasFormContentType)
                {
                    foreach (var key in Request.Form.Keys)
                        arguments.TryAdd(key, Request.Form[key]);
                }
                if (arguments.Count > 0)
                    Data.Form = JsonConvert.SerializeObject(arguments);
                if (Request.ContentLength != null)
                {
                    using (var texter = new StreamReader(Request.Body))
                    {
                        Data.Context = texter.ReadToEnd();
                        if (string.IsNullOrEmpty(Data.Context))
                            Data.Context = null;
                        texter.Close();
                    }
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e, "读取远程参数");
                return Data.ResultMessage = ApiResult.ArgumentErrorJson;
            }
            // 远程调用
            using (MonitorScope.CreateScope("CallZero"))
            {
                var caller = new ApiClient
                {
                    Station = host.Station,
                    Commmand = Data.ApiName,
                    Argument = Data.Context ?? Data.Form,
                    ExtendArgument = Data.Form
                };
                caller.CallCommand();
                Data.ResultMessage = caller.Result;
                Data.Status = caller.State.ToOperatorStatus(true);

                LogRecorder.MonitorTrace($"State : {caller.State}");
            }
            return Data.ResultMessage;
        }

19 View Source File : AdaptiveLookBack.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.ReadLine();

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Get(string Url, string gettDataStr)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (gettDataStr == "" ? "" : "?") + gettDataStr);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 View Source File : Alligator.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }

            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    LenghtBase = Convert.ToInt32(reader.ReadLine());
                    ShiftBase = Convert.ToInt32(reader.ReadLine());
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));

                    LenghtUp = Convert.ToInt32(reader.ReadLine());
                    ShiftUp = Convert.ToInt32(reader.ReadLine());
                    ColorUp = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));

                    LenghtDown = Convert.ToInt32(reader.ReadLine());
                    ShiftDown = Convert.ToInt32(reader.ReadLine());
                    ColorDown = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));

                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    MovingAverageTypeCalculation type;
                    Enum.TryParse(reader.ReadLine(), true, out type);

                    TypeCalculationAverage = type;

                    reader.Close();
                }
            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

void ReadSettings()
        {
            currentlyReading = true;
            StreamReader sr = null;
            string checkVer = c_toolVer;

            try
            {
                using (sr = new StreamReader(settingsFile))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        try
                        {
                            int equalsign = line.IndexOf('=');
                            if (equalsign > 0)
                            {
                                string varName = line.Substring(0, equalsign);
                                string varValue = line.Substring(equalsign + 1);

                                if (varName == "ToolVersion" || varName == "GameVersion")
                                {
                                    checkVer = varValue;
                                }
                                else if (varName == "GameMode")
                                {
                                    rbSingleplayer.Checked = (varValue == "sp");
                                }
                                else if (varName == "Beep")
                                {
                                    chkBeep.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "FoV")
                                {
                                    SetFoV(float.Parse(varValue));
                                }
                                else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
                                {
                                    dword_ptr tmp = dword_ptr.Parse(varValue, NumberStyles.AllowHexSpecifier);
                                    if (tmp > (dword_ptr)gameMode.GetValue("c_baseAddr"))
                                        pFoV = (varName == "RelativeFoVOffset" ? (dword_ptr)gameMode.GetValue("c_baseAddr") : 0) + tmp;
                                }
                                else if (varName == "UpdateNotify")
                                {
                                    chkUpdate.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "DisableHotkeys")
                                {
                                    chkHotkeys.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "HotkeyIncrease")
                                {
                                    catchKeys[0] = (Keys)int.Parse(varValue);
                                    btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
                                }
                                else if (varName == "HotkeyDecrease")
                                {
                                    catchKeys[1] = (Keys)int.Parse(varValue);
                                    btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
                                }
                                else if (varName == "HotkeyReset")
                                {
                                    catchKeys[2] = (Keys)int.Parse(varValue);
                                    btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

            if (checkVer != c_toolVer)
                pFoV = (dword_ptr)gameMode.GetValue("c_pFoV");

            UpdateCheck();

            currentlyReading = false;
        }

19 View Source File : AtrChannel.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    Multiplier = Convert.ToDecimal(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.ReadLine();

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Actipro

private string LoadDoreplacedentText(string path) {
			if (File.Exists(path)) {
				StreamReader reader = new StreamReader(path);
				string text = reader.ReadToEnd();
				reader.Close();
				return text;
			}
			return null;
		}

19 View Source File : BearsPower.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    Period = Convert.ToInt32(reader.ReadLine());
                    ColorUp = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDown = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.ReadLine();

                    reader.Close();
                }


            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

void ReadSettings()
        {
            currentlyReading = true;
            StreamReader sr = null;
            string checkVer = c_toolVer;

            try
            {
                using (sr = new StreamReader(settingsFile))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        try
                        {
                            int equalsign = line.IndexOf('=');
                            if (equalsign > 0)
                            {
                                string varName = line.Substring(0, equalsign);
                                string varValue = line.Substring(equalsign + 1);

                                if (varName == "ToolVersion" || varName == "GameVersion")
                                {
                                    checkVer = varValue;
                                }
                                else if (varName == "GameMode")
                                {
                                    rbSingleplayer.Checked = (varValue == "sp");
                                }
                                else if (varName == "Beep")
                                {
                                    chkBeep.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "FoV")
                                {
                                    SetFoV(float.Parse(varValue));
                                }
                                else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
                                {
                                    int tmp = int.Parse(varValue, NumberStyles.AllowHexSpecifier);
                                    if (tmp > (int)gameMode.GetValue("c_baseAddr") && tmp < 0x40000000)
                                        pFoV = (varName == "RelativeFoVOffset" ? (int)gameMode.GetValue("c_baseAddr") : 0) + tmp;
                                }
                                else if (varName == "UpdatePopup" || varName == "UpdateCheck")
                                {
                                    chkUpdate.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "DisableHotkeys")
                                {
                                    chkHotkeys.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "HotkeyIncrease")
                                {
                                    catchKeys[0] = (Keys)int.Parse(varValue);
                                    btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
                                }
                                else if (varName == "HotkeyDecrease")
                                {
                                    catchKeys[1] = (Keys)int.Parse(varValue);
                                    btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
                                }
                                else if (varName == "HotkeyReset")
                                {
                                    catchKeys[2] = (Keys)int.Parse(varValue);
                                    btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

            if (checkVer != c_toolVer)
                pFoV = (int)gameMode.GetValue("c_pFoV");

            if (!requestSent)
            {
                try
                {
                    request = (HttpWebRequest)WebRequest.Create(c_checkURL);
                    request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
                    requestSent = true;
                }
                catch { }
            }

            currentlyReading = false;
        }

19 View Source File : CCI.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {

                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorBase = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    Enum.TryParse(reader.ReadLine(), true, out TypePointsToSearch);
                    reader.ReadLine();

                    reader.Close();
                }
            }
            catch (Exception)
            {
                // send to log
                // отправить в лог
            }
        }

19 View Source File : AlifeConfigurator.cs
License : MIT License
Project Creator : 1upD

public static List<BaseAgent> ReadConfiguration(string filepath)
        {
            List<BaseAgent> agents = null;
            try
            {
                log.Info(string.Format("Loading artificial life configuration from file: {0}", filepath));
                XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));

                StreamReader reader = new StreamReader(filepath);
                agents = (List<BaseAgent>)serializer.Deserialize(reader);
                reader.Close();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Error reading artificial life configuration in file: {0}", filepath), e);
            }

            return agents;
        }

19 View Source File : DonchianChannel.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    ColorUp = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorAvg = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDown = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    Lenght = Convert.ToInt32(reader.ReadLine());
                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.Close();
                }
            }
            catch (Exception)
            {
                // отправить в лог
            }
        }

19 View Source File : StreamReader.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public void Close()
        {
            M_StreamReader.Close();
        }

19 View Source File : PaypalHelper.cs
License : MIT License
Project Creator : Adoxio

public IPayPalPaymentDataTransferResponse GetPaymentDataTransferResponse(string idenreplacedyToken, string transactionId)
		{
			var query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionId, idenreplacedyToken);

			var request = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);

			request.Method = WebRequestMethods.Http.Post;
			request.ContentType = "application/x-www-form-urlencoded";
			request.ContentLength = query.Length;

			var streamOut = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
			streamOut.Write(query);
			streamOut.Close();
			var streamIn = new StreamReader(request.GetResponse().GetResponseStream());
			var response = streamIn.ReadToEnd();
			streamIn.Close();
			
			return new PayPalPaymentDataTransferResponse(response);
		}

19 View Source File : NailsConfig.cs
License : MIT License
Project Creator : 1upD

public static NailsConfig ReadConfiguration(string filepath)
		{
			NailsConfig config = null;
			try
			{
				log.Info(string.Format("Loading Nails configuration from file: {0}", filepath));
				XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));

				StreamReader reader = new StreamReader(filepath);
				config = (NailsConfig)serializer.Deserialize(reader);
				reader.Close();
			}
			catch (Exception e)
			{
				log.Error(string.Format("Error reading Nails configuration in file: {0}", filepath), e);
			}

			return config;
		}

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
            {
                cookieContainer = cookieContainer ?? new CookieContainer();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                request.CookieContainer = cookieContainer;
                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                myStreamWriter.Write(postDataStr);
                myStreamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 View Source File : HttpGetSearch.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

private static string ReadResponse(HttpWebRequest webRequest) {
         StreamReader Reader;
         HttpWebResponse Response;
         String ResponseContents = "";
         try {
            Response = ((HttpWebResponse)(webRequest.GetResponse()));
            Reader = new StreamReader(Response.GetResponseStream());
            ResponseContents = Reader.ReadToEnd();
            Reader.Close();
         }
         catch (ObjectDisposedException) {
            throw;
         }
         catch (IOException) {
            throw;
         }
         catch (SystemException) {
            throw;
         }
         return ResponseContents;
      }

19 View Source File : HttpApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static async Task<string> ReadResponse(WebResponse response)
        {
            string json;
            using (response)
            {
                if (response.ContentLength == 0)
                {
                    return null;
                }
                var receivedStream = response.GetResponseStream();
                if (receivedStream == null)
                    return null;

                using (receivedStream)
                {
                    using (var streamReader = new StreamReader(receivedStream))
                    {
                        json = await streamReader.ReadToEndAsync();
                        streamReader.Close();
                    }
                    receivedStream.Close();
                }
                response.Close();
            }
            return json;
        }

19 View Source File : screenwriter.cs
License : MIT License
Project Creator : alexismorin

[MenuItem ("Tools/Parse Screenplay")]
    static void ParseScreenplay () {

        Clear ();

        // load file
        var selectedFilepath = EditorUtility.OpenFilePanel ("Select Screenplay", "", "txt");
        FileInfo fileInfo = new FileInfo (selectedFilepath);
        string timeText = System.DateTime.Now.ToString ("hh.mm.ss"); // get time so we can mark where these changes were made

        // create playabledirector in scene
        currentPlayableGameObject = new GameObject ();

        currentPlayableGameObject.name = fileInfo.Name.Replace (".txt", string.Empty) + " " + timeText + " Timeline";
        currentDataSlate = currentPlayableGameObject.AddComponent<screenwriterDataSlate> ();
        currentPlayable = currentPlayableGameObject.AddComponent<PlayableDirector> ();

        // create timeline replacedet
        Timelinereplacedet currentTimeline = ScriptableObject.CreateInstance ("Timelinereplacedet") as Timelinereplacedet;
        replacedetDatabase.Createreplacedet (currentTimeline, "replacedets/Timelines/" + fileInfo.Name.Replace (".txt", string.Empty) + " " + timeText + ".playable");

        currentTimeline = (Timelinereplacedet) replacedetDatabase.LoadreplacedetAtPath ("replacedets/Timelines/" + fileInfo.Name.Replace (".txt", string.Empty) + " " + timeText + ".playable", typeof (Timelinereplacedet));

        currentPlayable.playablereplacedet = currentTimeline;

        masterTrack = currentTimeline.CreateTrack<GroupTrack> (null, "Master Group");
        currentTimeline.CreateTrack<ControlTrack> (masterTrack, "Shots");
        currentTimeline.CreateTrack<ControlTrack> (masterTrack, "Lighting");
        //      currentTimeline.CreateTrack<SignalTrack> (null, "Track");
        //      currentTimeline.CreateTrack<AnimationTrack> (null, "Track");

        string filePath = fileInfo.FullName;
        line = null;
        StreamReader reader = new StreamReader (filePath);

        using (reader) {
            do {
                thirdLastLine = lastLine;
                lastLine = line;
                line = reader.ReadLine ();
                if (System.String.IsNullOrEmpty (line) == false) {

                    // this is where we actually parse the screenplay

                    lineCount++;
                    //  print ("Parsing line #" + lineCount);

                    // capital letters checker
                    char[] possibleCharacter = line.ToCharArray ();
                    int capitalization = 0;
                    for (int i = 0; i < possibleCharacter.Length; i++) {
                        if (System.Char.IsUpper (possibleCharacter[i])) {
                            capitalization++;
                        }
                    }

                    // location, time of day
                    if (line.Contains ("EXT") || line.Contains ("INT")) {
                        char splitChar = '-';

                        string[] splitString = line.Split (splitChar);

                        currentDataSlate.TryAddLocation (splitString[0]);
                        currentLocation = splitString[0];

                        currentDataSlate.TryAddLightingScenario (splitString[1]);
                        currentLightingScenario = splitString[1];
                        continue;
                    }

                    // character check - all capitals and no :
                    if (capitalization > possibleCharacter.Length * 0.8f && line.Contains (":") == false) {
                        currentDataSlate.TryAddCharacter (line);
                        currentCharacter = line;
                        continue;
                    }

                    // extra actor instructions check - has ()
                    if (line.Contains ("(")) {
                        currentMood = line;
                        continue;
                    }

                    // transition data - contains : and is caps
                    if (line.Contains (":") && capitalization > possibleCharacter.Length * 0.5f) {
                        continue;
                    }

                    // at this point there arent many edge cases left - check if we have a actor guidelines or an actor name above us to see if this is dialogue
                    if (lastLine != null) {
                        if (lastLine.Contains ("(") || currentDataSlate.characters.Contains (lastLine)) {

                            //dialogue callback

                            // check if we already have a character group
                            bool alreadyCreatedCharacter = false;
                            IEnumerable<Trackreplacedet> duplicateCharacterCheck = currentTimeline.GetRootTracks ();
                            foreach (Trackreplacedet track in duplicateCharacterCheck) {
                                print (track.name);
                                if (track.name == currentCharacter) {
                                    alreadyCreatedCharacter = true;

                                }
                            }

                            if (alreadyCreatedCharacter == false) {

                                Trackreplacedet characterTrack = currentTimeline.CreateTrack<GroupTrack> (null, currentCharacter);
                                Trackreplacedet possibleSignalTrack = currentTimeline.CreateTrack<SignalTrack> (characterTrack, currentCharacter + " Signals");
                                Trackreplacedet animationTrack = currentTimeline.CreateTrack<AnimationTrack> (characterTrack, currentCharacter + " Animation Overrides");
                            }

                            IEnumerable<Trackreplacedet> allTracksForActors = currentTimeline.GetOutputTracks ();
                            foreach (Trackreplacedet track in allTracksForActors) {
                                if (track.name == currentCharacter + " Signals") {

                                    IMarker newMarker = track.CreateMarker<SignalEmitter> (currentTimelineScrub);

                                }
                                if (track.name == currentCharacter + " Animation Overrides") {

                                    TimelineClip newClip = track.CreateDefaultClip ();
                                    newClip.start = currentTimelineScrub;
                                    newClip.duration = Convert.ToDouble (line.Length) / 12.0;
                                    newClip.displayName = "Dialogue Animation";
                                }

                            }

                        }
                    }

                    // shot callback
                    IEnumerable<Trackreplacedet> allTracksForActions = currentTimeline.GetOutputTracks ();
                    foreach (Trackreplacedet track in allTracksForActions) {
                        if (track.name == "Shots") {

                            GameObject cameraInstance = PrefabUtility.InstantiatePrefab (currentDataSlate.cameraPrefab) as GameObject;
                            cameraInstance.name = "Shot Camera";
                            cameraInstance.transform.parent = currentPlayableGameObject.transform;

                            //   TimelineClip newClip = track.CreateDefaultClip ();
                            //   

                            TimelineClip tlClip = track.CreateClip<ControlPlayablereplacedet> ();
                            ControlPlayablereplacedet clip = tlClip.replacedet as ControlPlayablereplacedet;
                            clip.sourceGameObject.exposedName = UnityEditor.GUID.Generate ().ToString ();
                            currentPlayable.SetReferenceValue (clip.sourceGameObject.exposedName, cameraInstance);

                            tlClip.clipIn = currentTimelineScrub;
                            tlClip.duration = Convert.ToDouble (line.Length) / 12.0;
                            tlClip.displayName = line;
                        }
                        if (track.name == "Lighting") {

                            TimelineClip newClip = track.CreateDefaultClip ();
                            newClip.displayName = currentLightingScenario;
                            newClip.clipIn = currentTimelineScrub;
                            newClip.duration = Convert.ToDouble (line.Length) / 12.0;
                        }
                    }

                    currentTimelineScrub = currentTimeline.duration;

                }
            }
            while (line != null);
            reader.Close ();
        }
    }

See More Examples