/// <summary> /// Creates a new media object. /// </summary> /// <param name="media">The memory stream containing the media.</param> /// <param name="type">The media type.</param> /// <param name="rpu">A delegate of type <see cref="StatusMessageReportProgress"/> used to send messages back to the calling object.</param> /// <param name="caller">The calling object.</param> /// <returns>The id for the new media object.</returns> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public int CreateMedia(Stream media, EMedia type, StatusMessageReportProgress rpu, object caller) { using (NpgsqlConnection conn = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { NpgsqlTransaction tran = conn.BeginTransaction(); LargeObjectManager lbm = new LargeObjectManager(conn); int noid = lbm.Create(LargeObjectManager.READWRITE); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); byte[] buffer = new byte[media.Length]; media.Read(buffer, 0, (int)media.Length); BufferToLargeObject(buffer, largeObject, rpu, caller); largeObject.Close(); int newId = 0; using (NpgsqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "INSERT INTO \"MediaContent\" (data, media_type) VALUES (:data, :type) RETURNING id;"; cmd.Parameters.Add("data", noid); cmd.Parameters.Add("type", type.ToString()); newId = Convert.ToInt32(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser)); } tran.Commit(); return(newId); } }
/// <summary> /// Updates the media. /// </summary> /// <param name="id">The id.</param> /// <param name="media">The media.</param> /// <remarks>Documented by Dev02, 2008-08-06</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public void UpdateMedia(int id, Stream media) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { NpgsqlTransaction tran = con.BeginTransaction(); int noid; using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT data FROM \"MediaContent\" WHERE id=:id"; cmd.Parameters.Add("id", id); noid = Convert.ToInt32(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser)); } LargeObjectManager lbm = new LargeObjectManager(con); lbm.Delete(noid); noid = lbm.Create(LargeObjectManager.READWRITE); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); byte[] buffer = new byte[media.Length]; media.Read(buffer, 0, (int)media.Length); BufferToLargeObject(buffer, largeObject); largeObject.Close(); using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"MediaContent\" SET data=:data WHERE id=:id"; cmd.Parameters.Add("id", id); cmd.Parameters.Add("data", noid); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } tran.Commit(); } }
/// <summary> /// Gets the extension stream. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public Stream GetExtensionStream(Guid guid) { MemoryStream stream = null; using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { int noid = 0; using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT data FROM \"Extensions\" WHERE guid=:guid;"; cmd.Parameters.Add("guid", guid.ToString()); object obj = PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser); if (obj == null || obj == DBNull.Value || !(obj as long?).HasValue) { return(stream); } noid = Convert.ToInt32((obj as long?).Value); } NpgsqlTransaction tran = con.BeginTransaction(); try { LargeObjectManager lbm = new LargeObjectManager(con); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); byte[] buffer = LargeObjectToBuffer(largeObject); stream = new MemoryStream(buffer); largeObject.Close(); } catch { } finally { tran.Commit(); } } return(stream); }
/// <summary> /// Writes the media object to a stream. /// </summary> /// <param name="mediaId">The media id.</param> /// <param name="output">The output.</param> private void WriteMedia(int mediaId, Stream output) { using (NpgsqlConnection conn = FileHandlerHelpers.GetPgConnection()) { int noid = 0; using (NpgsqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT data FROM \"MediaContent\" WHERE id=:id;"; cmd.Parameters.Add("id", mediaId); noid = Convert.ToInt32(cmd.ExecuteScalar()); } NpgsqlTransaction tran = conn.BeginTransaction(); LargeObjectManager lbm = new LargeObjectManager(conn); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); largeObject.Seek(0); int size = largeObject.Size(); byte[] buffer = new byte[size]; int read = 0; int offset = 0; while (offset < size) { read = largeObject.Read(buffer, offset, Math.Min(102400, size - offset)); output.Write(buffer, offset, read); offset += 102400; } largeObject.Close(); tran.Commit(); } }
public int GetLargeObjectSize(int oid) { using (IDbTransaction transaction = BeginTransaction()) { int result; LargeObject obj = Manager.Open(oid); result = obj.Size(); obj.Close(); return(result); } }
/// <summary> /// modify a record /// </summary> public void modifyz_voluntarios(z_voluntarios myz_voluntarios, string foto) { CnxBase myBase = new CnxBase(); string reqSQL; reqSQL = "UPDATE z_voluntarios SET id_voluntario=" + myz_voluntarios.id_voluntario + ",id_compania=" + myz_voluntarios.id_compania + ",nombres='" + myz_voluntarios.nombres + "',apellidos='" + myz_voluntarios.apellidos + "',rut='" + myz_voluntarios.rut + "',direccion='" + myz_voluntarios.direccion + "',fecha_nacimiento='" + myz_voluntarios.fecha_nacimiento + "',ingreso='" + myz_voluntarios.ingreso + "',num_llamado=" + myz_voluntarios.num_llamado + ",comuna='" + myz_voluntarios.comuna + "',telefono='" + myz_voluntarios.telefono + "',celular='" + myz_voluntarios.celular + "' WHERE (id_voluntario=" + myz_voluntarios.id_voluntario + ")"; try { NpgsqlConnection myConn = myBase.OpenConnection(myBase.cnxString); if (foto != null) { NpgsqlTransaction t = myConn.BeginTransaction(); LargeObjectManager lbm = new LargeObjectManager(myConn); int noid = lbm.Create(LargeObjectManager.READWRITE); LargeObject lo = lbm.Open(noid, LargeObjectManager.READWRITE); // eliminar antiguo NpgsqlCommand comm = new NpgsqlCommand("select foto from z_voluntarios where id_voluntario=" + myz_voluntarios.id_voluntario, myConn); comm.ExecuteScalar(); //lbm.Unlink(oid); FileStream fs = File.OpenRead(foto); byte[] buf = new byte[fs.Length]; fs.Read(buf, 0, (int)fs.Length); lo.Write(buf); lo.Close(); t.Commit(); reqSQL = "UPDATE z_voluntarios SET id_voluntario=" + myz_voluntarios.id_voluntario + ",id_compania=" + myz_voluntarios.id_compania + ",nombres='" + myz_voluntarios.nombres + "',apellidos='" + myz_voluntarios.apellidos + "',rut='" + myz_voluntarios.rut + "',direccion='" + myz_voluntarios.direccion + "',fecha_nacimiento='" + myz_voluntarios.fecha_nacimiento + "',ingreso='" + myz_voluntarios.ingreso + "',num_llamado=" + myz_voluntarios.num_llamado + ",comuna='" + myz_voluntarios.comuna + "',telefono='" + myz_voluntarios.telefono + "',celular='" + myz_voluntarios.celular + "', foto=" + noid + " WHERE (id_voluntario=" + myz_voluntarios.id_voluntario + ")"; } NpgsqlCommand myCommand = new NpgsqlCommand(reqSQL, myConn); myCommand.ExecuteNonQuery(); myBase.CloseConnection(myConn); } catch (Exception myErr) { throw (new Exception(myErr.ToString() + reqSQL)); } }
/// <summary> /// Creates a large object with the given data at the database and returns the id of that object. /// </summary> /// <param name="data">The data for the large object.</param> /// <param name="connectionString">The connectionString to the database. Please refer to .Net Data Provider for Postgresql for format specifications</param> /// <returns>Returns the id of the large object at the database.</returns> /// <seealso cref="GetLargeObject"/> /// <seealso cref="DeleteLargeObject"/> /// <seealso cref="UpdateLargeObject"/> public static int CreateLargeObject(byte[] data, string connectionString) { NpgsqlConnection con = new NpgsqlConnection(connectionString); con.Open(); NpgsqlTypes.LargeObjectManager lm = new NpgsqlTypes.LargeObjectManager(con); var generatedLO = lm.Create(NpgsqlTypes.LargeObjectManager.READWRITE); var TransWrite = con.BeginTransaction(); LargeObject lo = lm.Open(generatedLO, LargeObjectManager.READWRITE); lo.Write(data); lo.Close(); TransWrite.Commit(); con.Close(); return(generatedLO); }
/// <summary> /// add a record /// </summary> /// <param name="myID"></param> public void addz_voluntarios(z_voluntarios myz_voluntarios, string foto) { CnxBase myBase = new CnxBase(); string reqSQL; reqSQL = "INSERT INTO z_voluntarios (id_compania,nombres,apellidos,rut,direccion,fecha_nacimiento,ingreso,num_llamado,comuna,telefono,celular) VALUES (" + myz_voluntarios.id_compania + ",'" + myz_voluntarios.nombres + "','" + myz_voluntarios.apellidos + "','" + myz_voluntarios.rut + "','" + myz_voluntarios.direccion + "','" + myz_voluntarios.fecha_nacimiento + "','" + myz_voluntarios.ingreso + "'," + myz_voluntarios.num_llamado + ",'" + myz_voluntarios.comuna + "','" + myz_voluntarios.telefono + "','" + myz_voluntarios.celular + "')"; try { NpgsqlConnection myConn = myBase.OpenConnection(myBase.cnxString); if (foto != null) { NpgsqlTransaction t = myConn.BeginTransaction(); LargeObjectManager lbm = new LargeObjectManager(myConn); int noid = lbm.Create(LargeObjectManager.READWRITE); LargeObject lo = lbm.Open(noid, LargeObjectManager.READWRITE); FileStream fs = File.OpenRead(foto); byte[] buf = new byte[fs.Length]; fs.Read(buf, 0, (int)fs.Length); lo.Write(buf); lo.Close(); t.Commit(); reqSQL = "INSERT INTO z_voluntarios (id_compania,nombres,apellidos,rut,direccion,fecha_nacimiento,ingreso,num_llamado,comuna,telefono,celular, foto) VALUES (" + myz_voluntarios.id_compania + ",'" + myz_voluntarios.nombres + "','" + myz_voluntarios.apellidos + "','" + myz_voluntarios.rut + "','" + myz_voluntarios.direccion + "','" + myz_voluntarios.fecha_nacimiento + "','" + myz_voluntarios.ingreso + "'," + myz_voluntarios.num_llamado + ",'" + myz_voluntarios.comuna + "','" + myz_voluntarios.telefono + "','" + myz_voluntarios.celular + "', " + noid + ")"; } NpgsqlCommand myCommand = new NpgsqlCommand(reqSQL, myConn); myCommand.ExecuteNonQuery(); myBase.CloseConnection(myConn); } catch (Exception myErr) { throw (new Exception(myErr.ToString() + reqSQL)); } }
/// <summary> /// Gets the media. /// </summary> /// <param name="id">The id.</param> /// <param name="cacheConnector">The cache connector.</param> /// <returns>A memory stream for the media object.</returns> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public Stream GetMediaStream(int id, IDbMediaConnector cacheConnector) { CachingStream stream = null; using (NpgsqlConnection conn = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { int noid = 0; using (NpgsqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT data FROM \"MediaContent\" WHERE id=:id;"; cmd.Parameters.Add("id", id); noid = Convert.ToInt32(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser)); } NpgsqlTransaction tran = conn.BeginTransaction(); LargeObjectManager lbm = new LargeObjectManager(conn); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); byte[] buffer = LargeObjectToBuffer(largeObject); stream = new CachingStream(buffer, id, cacheConnector); largeObject.Close(); tran.Commit(); } return(stream); }
/// <summary> /// Sets the extension stream. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="extensionStream">The extension stream.</param> public void SetExtensionStream(Guid guid, Stream extensionStream) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { NpgsqlTransaction tran = con.BeginTransaction(); LargeObjectManager lbm = new LargeObjectManager(con); int noid = lbm.Create(LargeObjectManager.READWRITE); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); byte[] buffer = new byte[extensionStream.Length]; extensionStream.Read(buffer, 0, (int)extensionStream.Length); BufferToLargeObject(buffer, largeObject); largeObject.Close(); using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"Extensions\" SET data=:data WHERE guid=:guid"; cmd.Parameters.Add("data", noid); cmd.Parameters.Add("guid", guid.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } tran.Commit(); } }
static void MainTemp(string[] args) { NpgsqlConnection schemaConnection = new NpgsqlConnection(connPostGreSql); schemaConnection.Open(); var databaseName = "GIS"; DataTable dataTables = schemaConnection.GetSchema("Tables", new string[] { databaseName, "public", null, null }); foreach (DataRow rowTable in dataTables.Rows) { string tableName = rowTable["table_name"].ToString(); if (tableName != "geometry_collection") { continue; } DataTable dataColumns = schemaConnection.GetSchema("Columns", new string[] { databaseName, "public", tableName }); StringBuilder sb = new StringBuilder(); sb.AppendLine("public class " + tableName); sb.AppendLine("{"); sb.AppendLine("\tpublic " + tableName + "(){}"); foreach (DataRow rowColumn in dataColumns.Rows) { string columnName = rowColumn["column_name"].ToString(); string type = rowColumn["data_type"].ToString(); sb.AppendLine("\tpublic " + type + " " + columnName + " {get;set;}"); } sb.AppendLine("}"); sb.Replace("int8", "long"); sb.Replace("int4", "int"); sb.Replace("text", "string"); sb.Replace("oid", "long"); sb.Replace("numeric", "float"); sb.Replace("timestamp", "DateTime"); var def = sb.ToString(); } schemaConnection.Close(); return; var geometryRetrieval = geometryCollection.GetSingleObjectWithId("8", true, connPostGreSql); // testing GeometryCollection Aram.OSMParser.geometryCollection col = new Aram.OSMParser.geometryCollection(); // col.gisId = col.gisType = "dummy"; col.format = "txt"; col.largeObject = null; col.lastUpdate = DateTime.Now; col.latitude = 563213212; col.longitude = 171231231; col.name = "Test2"; col.pivot = new Aram.OSMParser.Vector3GaPS() { x = 1f, y = 2f, z = 3f }; col.version = new Aram.OSMParser.GaPSlabsVersion() { versionTitle = "development", major = 0, minor = 1 }; col.AddGeometryCollectionToDatabase(connPostGreSql, false); var bytes = File.ReadAllBytes(@"C:\Users\admgaming\Documents\Visual Studio 2012\Projects\GaPSLabs\AramOSMParser\OsmParserTestApplication\bin\Debug\Npgsql.xml"); col.largeObject = bytes; col.UpdateThisGeometryOnDatabase(connPostGreSql, true); var resultBytes = geometryCollection.GetLargeObject(col.largeObjectReference, connPostGreSql); File.WriteAllBytes("c:\\dummy", resultBytes); return; // ERROR: 42704: invalid large-object descriptor: 0 ?? // largeobject only works within a transaction. Use bytea as an alternative to large objects. // http://www.postgresql.org/message-id/002701c49d7e$0f059240$d604460a@zaphod NpgsqlConnection testConnection = new NpgsqlConnection(connPostGreSql); testConnection.Open(); NpgsqlTypes.LargeObjectManager lm = new NpgsqlTypes.LargeObjectManager(testConnection); var generatedLO = lm.Create(NpgsqlTypes.LargeObjectManager.READWRITE); // It must be within a transaction var TransWrite = testConnection.BeginTransaction(); LargeObject lo = lm.Open(generatedLO, LargeObjectManager.READWRITE); lo.Write(new byte[] { 0, 10, 50, 24 }); lo.Close(); TransWrite.Commit(); var TransRead = testConnection.BeginTransaction(); var loOid = lo.GetOID(); var readlo = lm.Open(loOid, LargeObjectManager.READWRITE); var resultLo = readlo.Read(readlo.Size()); lm.Delete(generatedLO); TransRead.Commit(); testConnection.Close(); return; OSMPostgresqlSource sourceVisTest = new OSMPostgresqlSource(connPostGreSql); var bounds = sourceVisTest.Bounds; return; GaPSlabsSimulationLibrary.SUMOSimulationFCD df = new GaPSlabsSimulationLibrary.SUMOSimulationFCD(); //df.LoadFromXML(@"C:\Users\admgaming\Desktop\Dropbox\GaPSLabs\SUMO Packet Tester\Pedestrians.xml"); //df.LoadFromXML(@"C:\Users\admgaming\Desktop\Dropbox\GaPSLabs\SUMO Packet Tester\bufferoutput - 500.xml"); ServiceGapslabsClient client2 = ServicePropertiesClass.GetGapslabsService(ServicePropertiesClass.ServiceUri); int id = client2.LoadSUMOFCDSimulationList(@"C:\Users\admgaming\Desktop\Dropbox\GaPSLabs\SUMO Packet Tester\bufferoutput - 500.xml", "__POSTFIX"); //client.LoadSUMOFCDSimulation(@"C:\Users\admgaming\Desktop\Dropbox\GaPSLabs\SUMO Packet Tester\bufferoutput - 500.xml"); while (!client2.IsSimulationLoadedList(id)) { } var vvvv = client2.GetTimestepAtList(6, id); var vvvv2 = client2.GetTimestepAtList(7, id); return; int size = 16777216; int[] aa = new int[size]; int[] bbb = new int[size]; int[] cccc = new int[size]; for (int i = 0; i < size; i++) { aa[i] = i; bbb[i] = i; } var apointer = aa.ToIntPtr <int[]>(); var bpointer = bbb.ToIntPtr <int[]>(); var cpointer = cccc.ToIntPtr <int[]>(); long MinGPU = 1000000; long MinCPU = 1000000; long MinCPUParallel = 100000; Stopwatch watch = new Stopwatch(); bool SkipCpu = false; GPU_WarmUp(); int TestCounter = 0; int blockSize = 16; while (TestCounter++ < 7) { watch.Restart(); GPU_Add(apointer, bpointer, cpointer, size, blockSize); watch.Stop(); Console.WriteLine("Total GPU" + "(" + blockSize + ")" + ": " + watch.ElapsedMilliseconds); if (watch.ElapsedMilliseconds < MinGPU) { MinGPU = watch.ElapsedMilliseconds; } blockSize *= 2; } Console.WriteLine("Minimum GPU was " + MinGPU); if (!SkipCpu) { TestCounter = 0; while (TestCounter++ < 10) { watch.Restart(); CPU_AddParallel(apointer, bpointer, cpointer, size); watch.Stop(); Console.WriteLine("Total CPU Parallel: " + watch.ElapsedMilliseconds); if (watch.ElapsedMilliseconds < MinCPUParallel) { MinCPUParallel = watch.ElapsedMilliseconds; } } Console.WriteLine("Minimum CPU was " + MinCPU); TestCounter = 0; while (TestCounter++ < 10) { watch.Restart(); CPU_Add(apointer, bpointer, cpointer, size); watch.Stop(); Console.WriteLine("Total CPU: " + watch.ElapsedMilliseconds); if (watch.ElapsedMilliseconds < MinCPU) { MinCPU = watch.ElapsedMilliseconds; } } Console.WriteLine("Minimum CPU was " + MinCPU); } //apointer.Free(); //bpointer.Free(); //cpointer.Free(); Console.ReadLine(); return; //GaPSlabsSimulationLibrary.SUMOSimulationFCD simulation = new GaPSlabsSimulationLibrary.SUMOSimulationFCD(); //simulation.LoadFromXML(@"C:\Users\admgaming\Desktop\Dropbox\GaPSLabs\SUMOData\fcdoutput.xml"); //simulation.LoadFromCSV(@"C:\Users\admgaming\Desktop\Notable Software\iMobility\stkhlm-taxi.csv"); ServiceGapslabsClient client = ServicePropertiesClass.GetGapslabsService(ServicePropertiesClass.ServiceUri); //client.LoadSUMOFCDSimulation(@"C:\Users\admgaming\Desktop\Dropbox\GaPSLabs\SUMO Packet Tester\bufferoutput - 500.xml"); //while (!client.IsSimulationLoaded()) // Console.WriteLine("Loading..."); //Console.WriteLine("Load finished"); //Console.ReadLine(); //return; OSMPostgresqlSource sour = new OSMPostgresqlSource(connPostGreSql); // var TrafficNodes = sour.GetNodeIdsInBoundWithInfo(sour.Bounds, "traffic_signals"); var result = client.GetWayTags("134972364", connPostGreSql); BoundsWCF b = new BoundsWCF(); b.minlat = 59.32973; b.maxlat = 59.34481; b.minlon = 18.07556; b.maxlon = 18.1062; client.GetWayExtIdsInBound(connPostGreSql, b); client.InitializeRouter(connPostGreSql); OsmNodeWCF n1 = new OsmNodeWCF(); n1.id = "none"; n1.order = -1; n1.lat = 59.330957; n1.lon = 18.059285; //n1.lat = 59.374563; //n1.lon = 18.0135727; OsmNodeWCF n2 = new OsmNodeWCF(); n2.id = "none"; n2.order = -1; n2.lat = 59.33784; n2.lon = 18.088558; //n2.lat = 59.37225; //n2.lon = 18.00733; var RouterResult = client.RouteUsingDykstra(VehicleEnum.Car, n1, n2); OsmGeo.ShapeInterperter = new SimpleShapeInterpreter(); PostgreSQLSimpleSchemaSource source = new PostgreSQLSimpleSchemaSource(connPostGreSql); // keeps a memory-efficient version of the osm-tags. OsmTagsIndex tags_index = new OsmTagsIndex(); // creates a routing interpreter. (used to translate osm-tags into a routable network) OsmRoutingInterpreter interpreter = new OsmRoutingInterpreter(); // create routing inter OsmSourceRouterDataSource routing_data = new OsmSourceRouterDataSource( interpreter, tags_index, source); // create the router object. //IRouter<RouterPoint> router = new Router<PreProcessedEdge>(routing_data, interpreter, // new DykstraRoutingPreProcessed(routing_data.TagsIndex)); IRouter <RouterPoint> router = new Router <PreProcessedEdge>(routing_data, interpreter , new DykstraRoutingPreProcessed(routing_data.TagsIndex)); // resolve both points; find the closest routable road. //RouterPoint point1 = router.Resolve(VehicleEnum.Car, new GeoCoordinate(60.1674654,18.454302)); // RouterPoint point2 = router.Resolve(VehicleEnum.Car, new GeoCoordinate(60.1673373,18.4541732)); // Working //RouterPoint point1 = router.Resolve(VehicleEnum.Car, new GeoCoordinate(59.3863281, 18.0176665)); //RouterPoint point2 = router.Resolve(VehicleEnum.Car, new GeoCoordinate(59.3675634, 18.0140447)); // Working RouterPoint point1 = router.Resolve(VehicleEnum.Car, new GeoCoordinate(59.374563, 18.0135727)); RouterPoint point2 = router.Resolve(VehicleEnum.Car, new GeoCoordinate(59.37225, 18.00733)); //ArrayList al=new ArrayList(); //foreach (var en in Enum.GetValues(typeof(VehicleEnum))) //{ // al.Add(Enum.GetName(typeof(VehicleEnum), (VehicleEnum)en) + "=" + router.SupportsVehicle((VehicleEnum)en)); //} // calculate route. OsmSharpRoute route = router.Calculate(VehicleEnum.Car, point1, point2); route.SaveAsGpx(new FileInfo("route.gpx")); Console.ReadLine(); }
public static int CompressFiles() { byte [] buffer = new byte [1024]; int read; long saved_space = 0; using (DB db = new DB(true)) { using (DB db_save = new DB(true)) { using (IDbCommand cmd = db.CreateCommand()) { cmd.CommandText = @" SELECT File.* FROM File WHERE (File.compressed_mime = '' OR File.compressed_mime IS NULL) AND File.size <> 0 AND File.id IN (SELECT WorkFile.file_id FROM WorkFile WHERE WorkFile.file_id = File.id) LIMIT 10 "; using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { DBFile file = new DBFile(reader); long srclength; long destlength = -1; string tmpfile = Path.GetTempFileName(); string tmpfilegz; Console.Write("Downloading {0} = {1} with size {2}... ", file.id, file.filename, file.size); using (Stream stream_reader = db_save.Download(file)) { using (FileStream stream_writer = new FileStream(tmpfile, FileMode.Create, FileAccess.Write)) { while (0 < (read = stream_reader.Read(buffer, 0, buffer.Length))) { stream_writer.Write(buffer, 0, read); } } } srclength = new FileInfo(tmpfile).Length; Console.Write("Compressing file {0} with size {1}... ", tmpfile, srclength); tmpfilegz = FileUtilities.GZCompress(tmpfile); if (tmpfilegz == null) { Console.WriteLine("Compression didn't succeed."); } else { destlength = new FileInfo(tmpfilegz).Length; Console.WriteLine("Success, compressed size: {0} ({1}%)", destlength, 100 * (double)destlength / (double)srclength); using (IDbTransaction transaction = db_save.BeginTransaction()) { // Upload the compressed file. // Npgsql doesn't seem to have a way to truncate a large object, // so we just create a new large object and delete the old one. int file_id = file.file_id.Value; int gzfile_id = db_save.Manager.Create(LargeObjectManager.READWRITE); LargeObject gzfile = db_save.Manager.Open(gzfile_id, LargeObjectManager.READWRITE); using (FileStream st = new FileStream(tmpfilegz, FileMode.Open, FileAccess.Read, FileShare.Read)) { while (0 < (read = st.Read(buffer, 0, buffer.Length))) { gzfile.Write(buffer, 0, read); } } gzfile.Close(); // Save to our File record file.file_id = gzfile_id; file.compressed_mime = "application/x-gzip"; file.Save(db_save); // Delete the old large object db_save.Manager.Delete(file_id); transaction.Commit(); saved_space += (srclength - destlength); } } if (File.Exists(tmpfilegz)) { try { File.Delete(tmpfilegz); } catch { // Ignore } } if (File.Exists(tmpfile)) { try { File.Delete(tmpfile); } catch { // Ignore } } } } //} } } } Console.WriteLine("Saved {0} bytes.", saved_space); return(0); }