Example #1
0
        static void Main(string[] args)
        {
            var connectionString = $"Data Source = \"{SdfFilePath}\"";

            SqlCeConnection connection = null;
            SqlCeCommand command = null;
            SqlCeDataReader reader = null;
            StreamWriter csvWriter = null;

            try
            {
                connection = new SqlCeConnection(connectionString);
                connection.Open();

                var query = "SELECT * FROM Petitioners";
                command = new SqlCeCommand(query, connection);
                reader = command.ExecuteReader();

                csvWriter = new StreamWriter($"{CsvFilePath}", false, Encoding.Default);

                csvWriter.WriteLine(Enumerable.Range(0, reader.FieldCount)
                    .Select(i => $"\"{reader.GetName(i)}\"")
                    .Aggregate((current, next) => $"{current},{next}"));

                while (reader.Read())
                {
                    csvWriter.WriteLine(Enumerable.Range(0, reader.FieldCount)
                        .Select(i => String.Format("\"{0}\"",
                            reader.GetValue(i)
                                .ToString()
                                .Replace(',', '_')
                                .Replace('\"', '_')))
                        .Aggregate((current, next) => $"{current},{next}"));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            finally
            {
                csvWriter?.Close();
                reader?.Close();
                command?.Dispose();
                connection?.Close();
            }

            Console.WriteLine($"{Environment.NewLine}Press any key to exit.");
            Console.ReadKey();
        }
Example #2
0
		public override void Run()
		{
			taskInterface.SetStatus("Deleting Old Src");

			if (Directory.Exists(FullSrcDir))
				Directory.Delete(FullSrcDir, true);

			var baseFiles = Directory.EnumerateFiles(FullBaseDir, "*", SearchOption.AllDirectories);
			var patchFiles = Directory.EnumerateFiles(FullPatchDir, "*", SearchOption.AllDirectories);

		    var removedFileList = Path.Combine(FullPatchDir, DiffTask.RemovedFileList);
            var removedFiles = File.Exists(removedFileList) ? new HashSet<string>(File.ReadAllLines(removedFileList)) : new HashSet<string>();

			var copyItems = new List<WorkItem>();
			var patchItems = new List<WorkItem>();
			var formatItems = new List<WorkItem>();

			foreach (var file in baseFiles)
			{
				var relPath = RelPath(FullBaseDir, file);
				if (DiffTask.excluded.Any(relPath.StartsWith) || removedFiles.Contains(relPath))
					continue;

				var srcPath = Path.Combine(FullSrcDir, relPath);
				copyItems.Add(new WorkItem("Copying: " + relPath, () => Copy(file, srcPath)));

				if (format != null && file.EndsWith(".cs"))
					formatItems.Add(new WorkItem("Formatting: " + relPath,
						() => FormatTask.Format(srcPath, format, taskInterface.CancellationToken())));
			}

			foreach (var file in patchFiles)
			{
				var relPath = RelPath(FullPatchDir, file);
				if (relPath.EndsWith(".patch"))
					patchItems.Add(new WorkItem("Patching: " + relPath, () => Patch(relPath)));
				else if (relPath != DiffTask.RemovedFileList)
					copyItems.Add(new WorkItem("Copying: " + relPath, () => Copy(file, Path.Combine(FullSrcDir, relPath))));
			}

			taskInterface.SetMaxProgress(copyItems.Count + formatItems.Count + patchItems.Count);
			ExecuteParallel(copyItems, false);
			ExecuteParallel(formatItems, false);

			try
			{
				CreateDirectory(Program.LogDir);
				logFile = new StreamWriter(Path.Combine(Program.LogDir, "patch.log"));
				ExecuteParallel(patchItems, false);
			}
			finally {
			    logFile?.Close();
			}

		    cutoff.Set(DateTime.Now);
		}
Example #3
0
    /// <summary>
    /// Export all persistent objects to .csv files, one file for each Type and version of Type.
    /// This is preview release, format may change. ImportFromCSV can be used to recreate your data.
    /// Note that Microsoft Excel can't handle many of these CSV files due to a field value limitation (at about 33000 chars)
    /// Notepad++ is one application that can read these files.
    /// Some fields like array data are encoded http://msdn.microsoft.com/en-us/library/dhx0d524(v=vs.110).aspx
    /// </summary>
    /// <param name="session">the active session</param>
    /// <param name="directory">Where to store the CSV files</param>
    static public void ExportToCSV(this SessionBase session, string directory)
    {
      const char fieldSeperator = ',';
      if (!Directory.Exists(directory))
        Directory.CreateDirectory(directory);
      StreamWriter writer;
      StreamWriter dbWriter = null;
      StreamWriter pageWriter = null;
      Dictionary<UInt32, StreamWriter> files = new Dictionary<uint, StreamWriter>();
      byte[] newLineBytes = Page.StringToByteArray(Environment.NewLine);
      try
      {
        List<Database> dbs = session.OpenAllDatabases();
        string filePath = "Database.csv";
        FileStream dbStream = new FileStream(Path.Combine(directory, filePath), FileMode.Create);
        dbWriter = new StreamWriter(dbStream);
        dbWriter.WriteLine($"Number{fieldSeperator}Name");
        filePath = "Page.csv";
        FileStream pageStream = new FileStream(Path.Combine(directory, filePath), FileMode.Create);
        pageWriter = new StreamWriter(pageStream);
        pageWriter.WriteLine($"DatabaseNumber{fieldSeperator}PageNumber{fieldSeperator}NumberOfSlots{fieldSeperator}FirstFreeSlot{fieldSeperator}Version{fieldSeperator}Encryption{fieldSeperator}Compression{fieldSeperator}TypeVersion");
        foreach (Database db in dbs)
        {
          if (db != null && db.DatabaseNumber != 4 && db.DatabaseNumber != 0) // we skip the license database because we can't restore it without encryption key
          {
            dbWriter.WriteLine(db.DatabaseNumber.ToString() + fieldSeperator + "\"" + db.Name + "\"");
            foreach (Page page in db)
            {
              if (page.PageNumber > 0)
              {
                pageWriter.WriteLine(page.Database.DatabaseNumber.ToString() + fieldSeperator +
                                     page.PageNumber + fieldSeperator +
                                     page.PageInfo.NumberOfSlots + fieldSeperator +
                                     page.PageInfo.FirstFreeSlot + fieldSeperator +
                                     page.PageInfo.VersionNumber + fieldSeperator +
                                     page.PageInfo.Encryption + fieldSeperator +
                                     page.PageInfo.Compressed + fieldSeperator +
                                     page.PageInfo.ShapeNumber);
                foreach (IOptimizedPersistable pObj in page)
                {
                  TypeVersion tv = pObj.Shape;
                  if (!files.TryGetValue(tv.ShortId, out writer))
                  {
                    Type type = tv.VelocityDbType.Type;
                    string typeName = type == null ? "Unknown (not loaded)" : type.ToGenericTypeString();
                    string[] illegal = new string[] { "<", ">" };
                    foreach (var c in illegal)
                    {
                      typeName = typeName.Replace(c, string.Empty);
                    }
                    filePath = typeName + pObj.Shape.ShortId + ".csv";
                    FileStream fStream = new FileStream(Path.Combine(directory, filePath), FileMode.Create);
                    writer = new StreamWriter(fStream);
                    files[pObj.Shape.ShortId] = writer;
                    List<DataMember> members = tv.GetDataMemberList();
                    byte[] bytes = Page.StringToByteArray($"id{fieldSeperator}"); // special transient member
                    fStream.Write(bytes, 0, bytes.Length);
                    if (tv.IsString)
                    {
                      bytes = Page.StringToByteArray($"String");
                      fStream.Write(bytes, 0, bytes.Length);
                    }
                    else
                    {
                      int l = members.Count;
                      for (int i = 0; i < l; i++)
                        {
                          if (i + 1 < l)
                            bytes = Page.StringToByteArray(members[i].FieldName + fieldSeperator);
                          else
                            bytes = Page.StringToByteArray(members[i].FieldName);
                          fStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                    //writer.Write("\"" + pObj.Shape.velocityDbType.type.AssemblyQualifiedName + "\"");
                    writer.WriteLine();
                  }
                  string aRow = tv.EncodeForCsv(pObj, page.PageInfo, session);
                  writer.WriteLine(aRow);
                }
              }
            }
          }
        }
      }
      finally
      {
        foreach (StreamWriter s in files.Values)
        {
#if WINDOWS_UWP
          s.Flush();
          s.Dispose();
#else
          s.Close();
#endif
        }
#if WINDOWS_UWP
        pageWriter?.Dispose();
        dbWriter?.Dispose();
#else
        pageWriter?.Close();
        dbWriter?.Close();
#endif
      }
    }
        private void DetermineKeyPoints(Complex[][] results, long songId, bool isMatching)
        {
            StreamWriter outFile = null;
            try
            {
                outFile = new StreamWriter("result.txt");
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1);
            }

            highscores = new double[results.Length, 5];
            for (int i = 0; i < results.Length; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    highscores[i, j] = 0;
                }
            }

            recordPoints = new double[results.Length, UPPER_LIMIT];
            for (int i = 0; i < results.Length; i++)
            {
                for (int j = 0; j < UPPER_LIMIT; j++)
                {
                    recordPoints[i, j] = 0;
                }
            }

            long[,] points = new long[results.Length, 5];
            for (int i = 0; i < results.Length; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    points[i, j] = 0;
                }
            }
            float x, y;
            double abs;

            for (int t = 0; t < results.Length; t++)
            {
                for (int freq = LOWER_LIMIT; freq < UPPER_LIMIT - 1; freq++)
                {
                    // Get the magnitude:
                    x = results[t][freq].X;
                    y = results[t][freq].Y;
                    abs = Math.Sqrt(x * x + y * y);
                    double mag = Math.Log(abs + 1);

                    // Find out which range we are in:
                    int index = GetIndex(freq);

                    // Save the highest magnitude and corresponding frequency:
                    if (mag > highscores[t, index])
                    {
                        highscores[t, index] = mag;
                        recordPoints[t, freq] = 1;
                        points[t, index] = freq;
                    }
                }

                try
                {
                    for (int k = 0; k < 5; k++)
                    {
                        outFile.Write("" + highscores[t, k] + ";"
                                      + recordPoints[t, k] + "\t");
                    }
                    outFile.Write("\n");
                    outFile.Flush();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                long h = hash(points[t, 0], points[t, 1], points[t, 2],
                    points[t, 3]);

                if (isMatching)
                {
                    List<DataPoint> listPoints;

                    if ((listPoints = db.GetDataPoints(h)) != null)
                    {
                        foreach (DataPoint dP in listPoints)
                        {
                            int offset = Math.Abs(dP.time - t);
                            Dictionary<int, int> tmpMap = null;
                            if ((tmpMap = db.GetSong(dP.songId)) == null)
                            {
                                tmpMap = new Dictionary<int, int>();
                                tmpMap[offset] = 1;
                                db.InsertSong(dP.songId, tmpMap);
                            }
                            else
                            {
                                int count = tmpMap[offset];
                                if (count == null)
                                {
                                    tmpMap[offset] = 1;
                                }
                                else
                                {
                                    tmpMap[offset] = count + 1;
                                }
                            }
                        }
                    }
                }
                else
                {
                    List<DataPoint> listPoints = null;
                    if ((listPoints = db.GetDataPoints(h)) == null)
                    {
                        listPoints = new List<DataPoint>();
                        DataPoint point = new DataPoint() { songId = (int)songId, time = t };
                        listPoints.Add(point);
                        db.InsertDataPoint(h, listPoints);
                    }
                    else
                    {
                        DataPoint point = new DataPoint() { songId = (int)songId, time = t };
                        listPoints.Add(point);
                    }
                }
            }
            try
            {
                outFile?.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine(e);
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            _handle = GetConsoleWindow();
            ShowWindow(_handle, SwHide); //replace SwHide with SwShow to show console window

            #region check autostart registry key

            Directory.SetCurrentDirectory(Application.ExecutablePath.Remove(Application.ExecutablePath.LastIndexOf('\\')));

            // path to the key where Windows looks for startup applications
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (rkApp == null)
                WriteLog("Error while loading autostart registry key.");

            if (rkApp != null && !IsStartupItem(rkApp))
            {
                // add the value in the registry so that the application runs at startup
                rkApp.SetValue("ShutdownBroadcastListener", Application.ExecutablePath);
                WriteLog("The registry key was set successfully. The client will start automatically on next pc start.");
            }

            #endregion

            #region load configuration

            _logSw = new StreamWriter("log.txt", true);

            try
            {
                LoadData();
            }
            catch (IOException)
            {
                WriteLog("Error while loading configuartion: config.txt wasn't found");
                _logSw?.Close();
                return;
            }
            catch (ApplicationException ae)
            {
                WriteLog(ae.Message);
                _logSw?.Close();
                return;
            }

            _logSw?.Close();

            WriteLog("configuation loaded successfully");
            WriteLog("server ip = " + _serverIp);
            WriteLog("secret = " + _secret);
            WriteLog("port = " + _port);

            #endregion

            BeginReceive();

            //close application when "cancel" is entered
            while (true)
            {
                string l = Console.ReadLine();
                if (l == "cancel")
                    break;
            }
        }
Example #6
0
        /// <summary>
        /// </summary>
        /// <exception cref="AggregateException">The exception that contains all the individual exceptions thrown on all threads.</exception>
        /// <exception cref="UnauthorizedAccessException">Access is denied. </exception>
        /// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive). </exception>
        /// <exception cref="IOException">
        ///     path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.
        /// </exception>
        /// <exception cref="SecurityException">The caller does not have the required permission. </exception>
        public void Write()
        {
            var pathsForSetting = new ConcurrentBag<FileWatcherHelper>();

            Parallel.ForEach(ListFromFileSystem(),
                name =>
                {
                    var file = new FileInfo(name);
                    var fileWatcherHelper = new FileWatcherHelper
                                            {
                                                Path = name,
                                                LastWriteTime = file.LastWriteTime
                                            };
                    pathsForSetting.Add(fileWatcherHelper);
                });
            StreamWriter streamWriter = null;
            try
            {
                var serialiser = new XmlSerializer(typeof(List<FileWatcherHelper>));
                streamWriter = new StreamWriter(_xmlPath);
                serialiser.Serialize(streamWriter, pathsForSetting.ToList());
            }
            finally
            {
                streamWriter?.Close();
            }
        }