protected void Page_Load(object sender, EventArgs e) { // http://localhost/gpstracker/UpdateLocation.aspx?longitude=-122.0214996&latitude=47.4758847&extrainfo=0&username=momo&distance=0.012262854&date=2014-09-16%2B17%253A49%253A57&direction=0&accuracy=65&phonenumber=867-5309&eventtype=android&sessionid=0a6dfd74-df4d-466e-b1b8-23234ef57512&speed=0&locationmethod=fused string latitude = Request.QueryString["latitude"]; string longitude = Request.QueryString["longitude"]; string speed = Request.QueryString["speed"]; string direction = Request.QueryString["direction"]; string distance = Request.QueryString["distance"]; string date = Server.UrlDecode(Request.QueryString["date"]); // convert to DateTime format date = convertFromMySqlDate(date); string locationMethod = Server.UrlDecode(Request.QueryString["locationmethod"]); string phoneNumber = Request.QueryString["phonenumber"]; string userName = Request.QueryString["username"]; string sessionID = Request.QueryString["sessionid"]; string accuracy = Request.QueryString["accuracy"]; string eventType = Request.QueryString["eventtype"]; string extraInfo = Request.QueryString["extrainfo"]; // our helper class to update the database DbWriter dbw = new DbWriter(); string returnValue = ""; try { // update the database with our GPS data from the phone returnValue = dbw.updateDB("prcSaveGPSLocation", new SqlParameter("@latitude", latitude), new SqlParameter("@longitude", longitude), new SqlParameter("@speed", speed), new SqlParameter("@direction", direction), new SqlParameter("@distance", distance), new SqlParameter("@date", date), new SqlParameter("@locationMethod", locationMethod), new SqlParameter("@phoneNumber", phoneNumber), new SqlParameter("@userName", userName), new SqlParameter("@sessionID", sessionID), new SqlParameter("@accuracy", accuracy), new SqlParameter("@eventType", eventType), new SqlParameter("@extraInfo", extraInfo)); } catch (Exception ex) { Response.Write(ex.Message); } Response.Write(date + ": " + returnValue); }
protected void Page_Load(object sender, EventArgs e) { string sessionID = Request.QueryString["sessionID"]; DbWriter writer = new DbWriter(); try { writer.updateDB("prcDeleteRoute", new SqlParameter("@sessionID", sessionID)); } catch (Exception ex) { Response.Write(ex.Message); } Response.Write("0"); }
protected void Page_Load(object sender, EventArgs e) { string latitude = Request.Form["latitude"]; string longitude = Request.Form["longitude"]; string speed = Request.Form["speed"]; string direction = Request.Form["direction"]; string distance = Request.Form["distance"]; string date = Server.UrlDecode(Request.Form["date"]); // convert to DateTime format date = convertFromMySqlDate(date); string locationMethod = Server.UrlDecode(Request.Form["locationmethod"]); string phoneNumber = Request.Form["phonenumber"]; string sessionID = Request.Form["sessionid"]; string accuracy = Request.Form["accuracy"]; string eventType = Request.Form["eventtype"]; string extraInfo = Request.Form["extrainfo"]; // our helper class to update the database DbWriter dbw = new DbWriter(); try { // update the database with our GPS data from the phone dbw.updateDB("prcSaveGPSLocation", new SqlParameter("@latitude", latitude), new SqlParameter("@longitude", longitude), new SqlParameter("@speed", speed), new SqlParameter("@direction", direction), new SqlParameter("@distance", distance), new SqlParameter("@date", date), new SqlParameter("@locationMethod", locationMethod), new SqlParameter("@phoneNumber", phoneNumber), new SqlParameter("@sessionID", sessionID), new SqlParameter("@accuracy", accuracy), new SqlParameter("@eventType", eventType), new SqlParameter("@extraInfo", extraInfo)); } catch (Exception ex) { Response.Write(ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { // http://localhost/gpstracker/UpdateLocation.aspx?longitude=-122.0214996&latitude=47.4758847&extrainfo=0&username=momo&distance=0.012262854&date=2014-09-16%2B17%253A49%253A57&direction=0&accuracy=65&phonenumber=867-5309&eventtype=android&sessionid=0a6dfd74-df4d-466e-b1b8-23234ef57512&speed=0&locationmethod=fused string latitude = Request.QueryString["latitude"]; latitude = latitude.Replace(",", "."); // to handle European locale decimals string longitude = Request.QueryString["longitude"]; longitude = longitude.Replace(",", "."); string sessionID = Request.QueryString["sessionid"]; string userName = Request.QueryString["username"]; // do a little validation Decimal latDecimal; bool result = Decimal.TryParse(latitude, out latDecimal); if (!result) { latDecimal = 0.0M; } Decimal lngDecimal; bool result2 = Decimal.TryParse(longitude, out lngDecimal); if (!result2) { lngDecimal = 0.0M; } if (latDecimal == 0.0M && lngDecimal == 0.0M) { Response.Write("-1"); return; } if (sessionID.Trim().Length == 0) { Response.Write("-2"); return; } if (userName.Trim().Length == 0) { Response.Write("-3"); return; } string speed = Request.QueryString["speed"]; string direction = Request.QueryString["direction"]; direction = direction.Replace(",", "."); Decimal directionDecimal; bool result4 = Decimal.TryParse(latitude, out directionDecimal); if (!result4) { directionDecimal = 0.0M; } string distance = Request.QueryString["distance"]; string date = Server.UrlDecode(Request.QueryString["date"]); DateTime tempDateTime; bool result3 = DateTime.TryParse(date, out tempDateTime); if (!result3) { tempDateTime = DateTime.Now; } string locationMethod = Server.UrlDecode(Request.QueryString["locationmethod"]); string phoneNumber = Request.QueryString["phonenumber"]; string accuracy = Request.QueryString["accuracy"]; string eventType = Request.QueryString["eventtype"]; string extraInfo = Request.QueryString["extrainfo"]; // our helper class to update the database DbWriter dbw = new DbWriter(); string returnValue = ""; try { // update the database with our GPS data from the phone returnValue = dbw.updateDB("prcSaveGPSLocation", new SqlParameter("@latitude", latDecimal), new SqlParameter("@longitude", lngDecimal), new SqlParameter("@speed", speed), new SqlParameter("@direction", directionDecimal), new SqlParameter("@distance", distance), new SqlParameter("@date", tempDateTime), new SqlParameter("@locationMethod", locationMethod), new SqlParameter("@phoneNumber", phoneNumber), new SqlParameter("@userName", userName), new SqlParameter("@sessionID", sessionID), new SqlParameter("@accuracy", accuracy), new SqlParameter("@eventType", eventType), new SqlParameter("@extraInfo", extraInfo)); } catch (Exception ex) { Response.Write(ex.Message); } Response.Write(returnValue); }
public void SomeContentMetricsWereFound(VideoDailyMetric[] metrics) { DbWriter.Write(metrics); }
public void SomeVideosWereFound(Video[] videos, string channelId) { DbWriter.Write(videos, channelId, LoggerFactory.GetTestLogger()); }
public TestResponse TestProject([FromBody] TestRequest request) { try { var solution = _db.Solutions.Find(request.SolutionId); if (solution is null) { return(new TestResponse { OK = false, Message = "no solution found", Result = ResultCode.IE, TestId = request.TestId, }); } var compilation = _db.CompilationResults.Find(request.SolutionId); if (compilation is null) { return(new TestResponse { OK = false, Message = "no compilation found", Result = ResultCode.IE, TestId = request.TestId, }); } if (compilation.ResultCode != ResultCode.OK || compilation.File is null) { return(new TestResponse { OK = false, Message = "no compilation file found", Result = ResultCode.IE, TestId = request.TestId, }); } else { TestingResult result; var resp = CheckCodeStyle(compilation.StOutput); resp.OK = true; result = new TestingResult { SolutionId = solution.Id, TestId = request.TestId, Commentary = resp.Commentary, ResultCode = resp.Result, Score = resp.Score, TestData = JsonConvert.SerializeObject(resp) }; return(DbWriter.WriteToDb(_db, result, request.ReCheck)); } } catch (Exception e) { return(new TestResponse { OK = false, Message = "Error occured: " + e.Message + (e.InnerException is null ? "" : " Inner: " + e.InnerException.Message), Result = ResultCode.IE, TestId = request.TestId, });
static void Main(string[] args) { // Считаем количество потоков из CustomConfig. int threadCount = DataManager.GetThreadCountFromConfig( Environment.CurrentDirectory.ToString() + @"\AppConfigure\customConfig.txt"); // Параллельно считываем input файл. people = DataManager.ReadInputFileAsParallel(); // Запускаем потоки для обработки списка записей и записи в бд. List <Task> tasks = new List <Task>(); // Разделяем записи по потокам. int integerPart = people.Count / threadCount; int remainderPart = people.Count % threadCount; Console.WriteLine("Директория файла с логами: " + Environment.CurrentDirectory.ToString() + @"\DataManagement\OutputData"); Console.WriteLine($"Количество людей: {people.Count}"); Console.WriteLine($"Разделение людей по группам: "); for (int i = 0; i < threadCount; i++) { TaskArgs arg = new TaskArgs() { From = integerPart * i, To = integerPart * i + integerPart - 1 }; Console.WriteLine($"from {arg.From} to {arg.To}"); // Все оставшиеся строки отдаем в последний поток. if (i == threadCount - 1) { arg.To = integerPart * i + integerPart - 1 + remainderPart; } // Записываем данные в таблицу бд. var task = new TaskFactory().StartNew(new Action(() => { Parallel.For(arg.From, arg.To + 1, count => { var db = new DbWriter(); string log = string.Empty; db.WriteToDbRow(people[count], ref log); // Логирование. DataManager.Log(DataManager.Logger.Console, log); DataManager.Log(DataManager.Logger.File, log); }); })); } // Выход из приложения по ESC оставим в главном потоке. ConsoleKeyInfo cki; do { cki = Console.ReadKey(); } while (cki.Key != ConsoleKey.Escape); // Закрытие всех потоков. Environment.Exit(Environment.ExitCode); }
protected void Page_Load(object sender, EventArgs e) { // http://localhost/gpstracker/UpdateLocation.aspx?longitude=-122.0214996&latitude=47.4758847&extrainfo=0&username=momo&distance=0.012262854&date=2014-09-16%2B17%253A49%253A57&direction=0&accuracy=65&phonenumber=867-5309&eventtype=android&sessionid=0a6dfd74-df4d-466e-b1b8-23234ef57512&speed=0&locationmethod=fused string latitude = Request.QueryString["latitude"]; latitude = latitude.Replace(",", "."); // to handle European locale decimals string longitude = Request.QueryString["longitude"]; longitude = longitude.Replace(",", "."); string sessionID = Request.QueryString["sessionid"]; string userName = Request.QueryString["username"]; // do a little validation Decimal latDecimal; bool result = Decimal.TryParse(latitude, out latDecimal); if (!result) { latDecimal = 0.0M; } Decimal lngDecimal; bool result2 = Decimal.TryParse(longitude, out lngDecimal); if (!result2) { lngDecimal = 0.0M; } if (latDecimal == 0.0M && lngDecimal == 0.0M) { Response.Write("-1"); return; } if (sessionID.Trim().Length == 0) { Response.Write("-2"); return; } if (userName.Trim().Length == 0) { Response.Write("-3"); return; } string speed = Request.QueryString["speed"]; string direction = Request.QueryString["direction"]; direction = direction.Replace(",", "."); Decimal directionDecimal; bool result4 = Decimal.TryParse(latitude, out directionDecimal); if (!result4) { directionDecimal = 0.0M; } //sometimes in eu phones you get this with a comma string distance = Request.QueryString["distance"].Replace(",", "."); string date = Server.UrlDecode(Request.QueryString["date"]); DateTime tempDateTime; bool result3 = DateTime.TryParse(date, out tempDateTime); if (!result3) { tempDateTime = DateTime.Now; } string locationMethod = Server.UrlDecode(Request.QueryString["locationmethod"]); string phoneNumber = Request.QueryString["phonenumber"]; string accuracy = Request.QueryString["accuracy"]; string eventType = Request.QueryString["eventtype"]; string extraInfo = Request.QueryString["extrainfo"]; // our helper class to update the database DbWriter dbw = new DbWriter(); string returnValue = ""; try { // update the database with our GPS data from the phone returnValue = dbw.updateDB("prcSaveGPSLocation", new SqlParameter("@latitude", latDecimal), new SqlParameter("@longitude", lngDecimal), new SqlParameter("@speed", speed), new SqlParameter("@direction", directionDecimal), new SqlParameter("@distance", distance), new SqlParameter("@date", tempDateTime), new SqlParameter("@locationMethod", locationMethod), new SqlParameter("@phoneNumber", phoneNumber), new SqlParameter("@userName", userName), new SqlParameter("@sessionID", sessionID), new SqlParameter("@accuracy", accuracy), new SqlParameter("@eventType", eventType), new SqlParameter("@extraInfo", extraInfo)); } catch (Exception ex) { Response.Write(ex.Message); } Response.Write(returnValue); }
public async Task <TestResponse> TestProject([FromBody] TestRequest request) { try { var solution = _db.Solutions.Find(request.SolutionId); if (solution is null) { return(new TestResponse { OK = false, Message = "no solution found", Result = ResultCode.IE, TestId = request.TestId, }); } var compilation = _db.CompilationResults.Find(request.SolutionId); if (compilation is null) { return(new TestResponse { OK = false, Message = "no compilation found", Result = ResultCode.IE, TestId = request.TestId, }); } if (compilation.ResultCode != ResultCode.OK || compilation.File is null) { return(new TestResponse { OK = false, Message = "no compilation file found", Result = ResultCode.IE, TestId = request.TestId, }); } else { string dirPath = "/home/solution"; if (Directory.Exists(dirPath)) { Directory.Delete(dirPath, true); } var dir = Directory.CreateDirectory(dirPath); string fullPath = dirPath + "/" + compilation.File.Name; System.IO.File.WriteAllBytes(fullPath, compilation.File.Content); ZipFile.ExtractToDirectory(fullPath, dirPath, true); var pathToDll = FindExeFile(dir); TestingResult result; if (pathToDll == null) { dir.Delete(true); result = new TestingResult { SolutionId = solution.Id, TestId = request.TestId, Commentary = "No dll file found!", ResultCode = ResultCode.RE, }; return(DbWriter.WriteToDb(_db, result, request.ReCheck)); } var resp = await TestProject(pathToDll, request.TestId); resp.OK = true; dir.Delete(true); result = new TestingResult { SolutionId = solution.Id, TestId = request.TestId, Commentary = resp.Commentary, ResultCode = resp.Result, Score = resp.Score, TestData = JsonConvert.SerializeObject(resp) }; return(DbWriter.WriteToDb(_db, result, request.ReCheck)); } } catch (Exception e) { return(new TestResponse { OK = false, Message = "Error occured: " + e.Message + (e.InnerException is null ? "" : " Inner: " + e.InnerException.Message), Result = ResultCode.IE, TestId = request.TestId, });
public void SaveChanges() { foreach (var entity in ChangedEntities.Distinct()) { var entityType = entity.GetType(); if ((entity.State & EntityState.Added) == EntityState.Added) { if (entityType == typeof(Node)) { ((Node)entity).NodeId = DbControl.AllocateId(DbControl.NodePath); } else if (entityType == typeof(Relation)) { ((Relation)entity).RelationId = DbControl.AllocateId(DbControl.RelationPath); } else if (entityType == typeof(NodeProperty)) { ((NodeProperty)entity).PropertyId = DbControl.AllocateId(DbControl.NodePropertyPath); } else if (entityType == typeof(RelationProperty)) { ((RelationProperty)entity).PropertyId = DbControl.AllocateId(DbControl.RelationPropertyPath); } } if (((entity.State & EntityState.Deleted) == EntityState.Deleted) & ((entity.State & EntityState.Added) == EntityState.Added)) continue; if ((entity.State & EntityState.Deleted) == EntityState.Deleted) { if (entityType == typeof(Node)) { var node = ((Node)entity); DbWriter.InvalidateBlock(DbControl.NodePath, node.NodeId); var nodeBlock = DbReader.ReadNodeBlock(node.NodeId); var nextNodePropertyId = nodeBlock.FirstPropertyId; while (nextNodePropertyId != 0) { var nextPropertyBlock = DbReader.ReadPropertyBlock(DbControl.NodePropertyPath, nextNodePropertyId); DbWriter.InvalidateBlock(DbControl.NodePropertyPath, nextNodePropertyId); if (nextPropertyBlock.PropertyType is PropertyType.String) { DbWriter.InvalidateBlock(DbControl.StringPath, BitConverter.ToInt32(nextPropertyBlock.Value, 0)); } nextNodePropertyId = nextPropertyBlock.NextPropertyId; } var nextOutRelationId = nodeBlock.FirstOutRelationId; while (nextOutRelationId != 0) { var nextOutRelationBLock = DbReader.ReadRelationBlock(nextOutRelationId); DbWriter.InvalidateBlock(DbControl.RelationPath, nextOutRelationId); var nextRelationPropertyId = nextOutRelationBLock.FirstPropertyId; while (nextRelationPropertyId != 0) { var nextPropertyBlock = DbReader.ReadPropertyBlock(DbControl.RelationPropertyPath, nextRelationPropertyId); DbWriter.InvalidateBlock(DbControl.RelationPropertyPath, nextRelationPropertyId); if (nextPropertyBlock.PropertyType is PropertyType.String) { DbWriter.InvalidateBlock(DbControl.StringPath, BitConverter.ToInt32(nextPropertyBlock.Value, 0)); } nextRelationPropertyId = nextPropertyBlock.NextPropertyId; } nextOutRelationId = nextOutRelationBLock.FirstNodeNextRelation; } var nextInRelationId = nodeBlock.FirstInRelationId; while (nextInRelationId != 0) { var nextInRelationBlock = DbReader.ReadRelationBlock(nextInRelationId); DbWriter.InvalidateBlock(DbControl.RelationPath, nextInRelationId); var nextRelationPropertyId = nextInRelationBlock.FirstPropertyId; while (nextRelationPropertyId != 0) { var nextPropertyBlock = DbReader.ReadPropertyBlock(DbControl.RelationPropertyPath, nextRelationPropertyId); DbWriter.InvalidateBlock(DbControl.RelationPropertyPath, nextRelationPropertyId); if (nextPropertyBlock.PropertyType is PropertyType.String) { DbWriter.InvalidateBlock(DbControl.StringPath, BitConverter.ToInt32(nextPropertyBlock.Value, 0)); } nextRelationPropertyId = nextPropertyBlock.NextPropertyId; } nextInRelationId = nextInRelationBlock.SecondNodeNextRelation; } } else if (entityType == typeof(Relation)) { var relation = ((Relation)entity); DbWriter.InvalidateBlock(DbControl.RelationPath, relation.RelationId); var relationBlock = DbReader.ReadRelationBlock(relation.RelationId); var nextPropertyId = relationBlock.FirstPropertyId; while (nextPropertyId != 0) { var nextPropertyBlock = DbReader.ReadPropertyBlock(DbControl.RelationPropertyPath, nextPropertyId); DbWriter.InvalidateBlock(DbControl.NodePropertyPath, nextPropertyId); if (nextPropertyBlock.PropertyType is PropertyType.String) { DbWriter.InvalidateBlock(DbControl.StringPath, BitConverter.ToInt32(nextPropertyBlock.Value, 0)); } nextPropertyId = nextPropertyBlock.NextPropertyId; } } else if (entityType == typeof(NodeProperty)) { var nodeProperty = ((NodeProperty)entity); if (nodeProperty.PropertyType is PropertyType.String) { var nodePropertyBlock = DbReader.ReadPropertyBlock(DbControl.NodePropertyPath, nodeProperty.PropertyId); DbWriter.InvalidateBlock(DbControl.StringPath, BitConverter.ToInt32(nodePropertyBlock.Value, 0)); } DbWriter.InvalidateBlock(DbControl.NodePropertyPath, nodeProperty.PropertyId); } else if (entityType == typeof(RelationProperty)) { var relationProperty = ((RelationProperty)entity); if (relationProperty.PropertyType is PropertyType.String) { var relationPropertyBlock = DbReader.ReadPropertyBlock(DbControl.RelationPropertyPath, relationProperty.PropertyId); DbWriter.InvalidateBlock(DbControl.StringPath, BitConverter.ToInt32(relationPropertyBlock.Value, 0)); } DbWriter.InvalidateBlock(DbControl.RelationPropertyPath, relationProperty.PropertyId); } else { throw new NotSupportedException("Not supported Entity Type"); } continue; } if ((entity.State & EntityState.Added) == EntityState.Added) { NodeBlock nodeBlock; RelationBlock relationBlock; switch (entity) { case Node node: nodeBlock = new NodeBlock(true, node.NodeId, 0, 0, 0, DbControl.FetchLabelId(node.Label)); DbWriter.WriteNodeBlock(nodeBlock); break; case Relation relation: //Cast, Create with given information relationBlock = new RelationBlock { Used = true, FirstNodeId = relation.From.NodeId, SecondNodeId = relation.To.NodeId, FirstNodePreviousRelationId = 0, SecondNodePreviousRelationId = 0, LabelId = DbControl.FetchLabelId(relation.Label), FirstPropertyId = 0, RelationId = relation.RelationId }; // Read Source, Target nodes to change the links in them and get their current links var fromNodeBlock = DbReader.ReadNodeBlock(relationBlock.FirstNodeId); var toNodeBlock = DbReader.ReadNodeBlock(relationBlock.SecondNodeId); // Point to the current relations relationBlock.FirstNodeNextRelation = fromNodeBlock.FirstOutRelationId; relationBlock.SecondNodeNextRelation = toNodeBlock.FirstInRelationId; // Read Relations to which nodes point to update them if (fromNodeBlock.FirstOutRelationId != 0) { var fromNodeFirstOutRelationBlock = DbReader.ReadRelationBlock(fromNodeBlock.FirstOutRelationId); fromNodeFirstOutRelationBlock.FirstNodePreviousRelationId = relation.RelationId; DbWriter.WriteRelationBlock(fromNodeFirstOutRelationBlock); } if (toNodeBlock.FirstInRelationId != 0) { var toNodeFirstInRelationBlock = DbReader.ReadRelationBlock(toNodeBlock.FirstInRelationId); toNodeFirstInRelationBlock.SecondNodePreviousRelationId = relation.RelationId; DbWriter.WriteRelationBlock(toNodeFirstInRelationBlock); } toNodeBlock.FirstInRelationId = relation.RelationId; fromNodeBlock.FirstOutRelationId = relation.RelationId; DbWriter.WriteNodeBlock(toNodeBlock); DbWriter.WriteNodeBlock(fromNodeBlock); DbWriter.WriteRelationBlock(relationBlock); break; case NodeProperty _: case RelationProperty _: var property = (Property)entity; byte[] byteValue = new byte[4]; switch (property.PropertyType) { case PropertyType.Int: byteValue = BitConverter.GetBytes((int)property.Value); break; case PropertyType.Bool: byteValue[3] = (byte)((bool)property.Value ? 1 : 0); break; case PropertyType.Float: byteValue = BitConverter.GetBytes((float)property.Value); break; case PropertyType.String: // Add to String Storage, get returned pointer to the string storage, write it as the byteValue var newStringId = DbControl.AllocateId(DbControl.StringPath); DbWriter.WriteStringBlock(new StringBlock(true, (string)property.Value, newStringId)); byteValue = BitConverter.GetBytes(newStringId); break; default: throw new NotSupportedException(); } int parentId; PropertyBlock propertyBlock; switch (property) { case NodeProperty _: parentId = ((Node)property.Parent).NodeId; propertyBlock = new NodePropertyBlock(property.PropertyId, true, property.PropertyType, DbControl.FetchPropertyNameId(property.Key), byteValue, 0, parentId); nodeBlock = DbReader.ReadNodeBlock(parentId); propertyBlock.NextPropertyId = nodeBlock.FirstPropertyId; nodeBlock.FirstPropertyId = propertyBlock.PropertyId; DbWriter.WritePropertyBlock(propertyBlock); DbWriter.WriteNodeBlock(nodeBlock); break; case RelationProperty _: parentId = ((Relation)property.Parent).RelationId; propertyBlock = new RelationPropertyBlock(property.PropertyId, true, property.PropertyType, DbControl.FetchPropertyNameId(property.Key), byteValue, 0, parentId); relationBlock = DbReader.ReadRelationBlock(parentId); propertyBlock.NextPropertyId = relationBlock.FirstPropertyId; relationBlock.FirstPropertyId = propertyBlock.PropertyId; DbWriter.WritePropertyBlock(propertyBlock); DbWriter.WriteRelationBlock(relationBlock); break; default: throw new NotSupportedException(); } break; } continue; } if ((entity.State & EntityState.Modified) == EntityState.Modified) { switch (entity) { case Node _: throw new NotSupportedException( "Node modification is not supported. Update it's properties instead."); case Relation _: throw new NotSupportedException( "Relation modification is not supported. Update it's properties instead."); case NodeProperty _: // case RelationProperty _: var property = (Property)entity; var propertyPath = (property is NodeProperty) ? DbControl.NodePropertyPath : DbControl.RelationPropertyPath; var oldPropertyBlock = DbReader.ReadPropertyBlock(propertyPath, property.PropertyId); byte[] byteValue = new byte[4]; switch (property.PropertyType) { case PropertyType.Int: byteValue = BitConverter.GetBytes((int)property.Value); break; case PropertyType.Bool: byteValue[3] = (byte)((bool)property.Value ? 1 : 0); break; case PropertyType.Float: byteValue = BitConverter.GetBytes((float)property.Value); break; case PropertyType.String: DbWriter.InvalidateBlock(DbControl.StringPath, BitConverter.ToInt32(oldPropertyBlock.Value, 0)); var newStringId = DbControl.AllocateId(DbControl.StringPath); DbWriter.WriteStringBlock(new StringBlock(true, (string)property.Value, newStringId)); byteValue = BitConverter.GetBytes(newStringId); break; default: throw new NotSupportedException("Such Property dtye is not supported"); } oldPropertyBlock.Value = byteValue; DbWriter.WritePropertyBlock(oldPropertyBlock); break; } } } ChangedEntities.Clear(); }
public static async Task <string> Handle(MessageResult result) { var builder = new MessageBuilder(Constants.DefaultSeparator); var userDb = new DbWriter($"{AppDomain.CurrentDomain.BaseDirectory}User.csv", "Username;Password"); var cepDb = new DbWriter($"{AppDomain.CurrentDomain.BaseDirectory}Cep.csv", "UserId;Cep;Logradouro;Bairro;Complemento;Cidade;Uf;DataBusca"); switch (result.MessageType.ToUpper()) { case "CADASTRAR": { //TODO: Cadastrar usuário no CSV var username = result.GetFieldValue("USERNAME"); var password = result.GetFieldValue("PASSWORD"); if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(username)) { builder.AddFailure("Usuário ou senha estão vazios ou nulos"); } else if (password.Length < 8) { builder.AddFailure("A senha deve possuir pelo menos 8 caracteres"); } else { var emailRegex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); if (!emailRegex.Match(username).Success) { builder.AddFailure("Email invalido"); } else if (userDb.GetLines("Username", username).Count() > 0) { builder.AddFailure("Usuario ja cadastrado"); } else { password = UserHelper.Encrypt(password); Console.WriteLine(userDb.InsertLine(new string[] { username, password })); builder.AddSucess(); } } break; } case "LOGIN": { var username = result.GetFieldValue("USERNAME"); var password = result.GetFieldValue("PASSWORD"); var connectionDurationStr = result.GetFieldValue("CONNECTION_DURATION"); Int32.TryParse(connectionDurationStr, out int connectionDuration); if (connectionDuration <= 0) { builder.AddFailure("Tempo de conexão inválido"); break; } if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { builder.AddFailure("Usuário ou senha inválidos"); break; } var userLines = userDb.GetLines("Username", username); if (userLines.Count != 1) { builder.AddFailure("Usuário ou senha inválidos"); break; } var user = userLines.FirstOrDefault(); if (user == null || !UserHelper.PasswordEquals(password, user[1])) { builder.AddFailure("Usuário ou senha inválidos"); break; } builder.AddSucess(); builder.AddField("TOKEN", UserHelper.GenerateToken(user[0], connectionDuration)); break; } case "CEP": { var token = result.GetFieldValue("TOKEN"); var userId = UserHelper.ValidateToken(token); if (string.IsNullOrWhiteSpace(userId)) { builder.AddFailure("Token inválido"); break; } var cep = result.GetFieldValue("CEP"); var client = new ViaCepClient(); var address = await client.GetAddressByCep(cep); if (address.Erro) { builder.AddFailure("Endereço não encontrado"); break; } builder.AddSucess(); builder.AddField("CEP", address.Cep); builder.AddField("LOGRADOURO", address.Logradouro); builder.AddField("BAIRRO", address.Bairro); builder.AddField("COMPLEMENTO", address.Complemento); builder.AddField("CIDADE", address.Localidade); builder.AddField("UF", address.Uf); //Salvar no Historico cepDb.InsertLine(new string[] { userId, address.Cep, address.Logradouro, address.Bairro, address.Complemento, address.Localidade, address.Uf, DateTime.Now.ToString() }); break; } case "HISTORICO": { var token = result.GetFieldValue("TOKEN"); var userId = UserHelper.ValidateToken(token); if (string.IsNullOrWhiteSpace(userId)) { builder.AddFailure("Token inválido"); break; } var results = cepDb.GetLines("UserId", userId); if (!results.Any()) { builder.AddFailure("Histórico vazio"); break; } builder.AddSucess(); int i = 0; foreach (var line in results) { builder.AddField("INDEX", i.ToString()); builder.AddField("USER_ID", line[0]); builder.AddField("CEP", line[1]); builder.AddField("LOGRADOURO", line[2]); builder.AddField("BAIRRO", line[3]); builder.AddField("COMPLEMENTO", line[4]); builder.AddField("CIDADE", line[5]); builder.AddField("UF", line[6]); builder.AddField("DATA_DA_BUSCA", line[7]); i++; } break; } default: { builder.AddFailure("Mensagem inválida"); break; } } return(builder.BuildValues()); }
private void button2_Click(object sender, EventArgs e) { DbWriter.Write(); }
public void ReadOmiArgs() { DbWriter dbwriter = new DbWriter(); RandomInputGenerator.InputGenerator random = new InputGenerator(); //---- initialize random input generator IArgument[] arg = new IArgument[1]; arg[0] = new Argument("ElementCount", "1", true, ""); random.Initialize(arg); //---- initialize dbwriter string myCustomMethod = "Simulation 1, m=10, Tmax=100000"; string myVariableName = "millimeters per second"; string mySourceContact = "Tony"; string mySourceDesc = "Test dource description"; IArgument[] arguments = new IArgument[17]; arguments[0] = new Argument("DbPath", @".\example4.sqlite", true, ""); arguments[1] = new Argument("Variable.UnitName", myVariableName, true, ""); arguments[2] = new Argument("Variable.UnitAbbr", "m^3/s", true, ""); arguments[3] = new Argument("Variable.UnitType", "Flow", true, ""); arguments[4] = new Argument("Time.UnitName", "second", true, ""); arguments[5] = new Argument("Time.UnitAbbr", "s", true, ""); arguments[6] = new Argument("Time.UnitType", "Time", true, ""); arguments[7] = new Argument("Method.Description", myCustomMethod, true, ""); arguments[8] = new Argument("Source.Organization", "University of South Carolina", true, ""); arguments[9] = new Argument("Source.Address", "300 Main St.", true, ""); arguments[10] = new Argument("Source.City", "Columbia", true, ""); arguments[11] = new Argument("Source.State", "SC", true, ""); arguments[12] = new Argument("Source.Zip", "29206", true, ""); arguments[13] = new Argument("Source.Contact", mySourceContact, true, ""); arguments[14] = new Argument("Variable.Category", " ", true, ""); //intentionally left blank arguments[15] = new Argument("Variable.SampleMedium", "Surface Water", true, ""); arguments[16] = new Argument("Source.Description", mySourceDesc, true, ""); dbwriter.Initialize(arguments); //---- link the components Link link = new Link(); link.ID = "link-1"; link.TargetElementSet = dbwriter.GetInputExchangeItem(0).ElementSet; link.TargetQuantity = dbwriter.GetInputExchangeItem(0).Quantity; link.TargetComponent = dbwriter; ElementSet eset = new ElementSet("rand element set", "r_eset", ElementType.XYPoint, new SpatialReference("1")); Element e = new Element("1"); e.AddVertex(new Vertex(1, 1, 0)); eset.AddElement(e); link.SourceElementSet = eset; link.SourceQuantity = random.GetOutputExchangeItem(0).Quantity; link.SourceComponent = random; dbwriter.AddLink(link); //---- get the series info HydroDesktop.Interfaces.ObjectModel.Series series = dbwriter.serieses["r_eset_RandomInputGenerator_loc0"]; //---- check that omi values were set properly Assert.IsTrue(series.Method.Description == myCustomMethod); Assert.IsTrue(series.Variable.VariableUnit.Name == myVariableName); Assert.IsTrue(series.Source.ContactName == mySourceContact); Assert.IsTrue(series.Variable.GeneralCategory == "Hydrology", "blank argument is not ignored!!"); Assert.IsTrue(series.Source.Description == mySourceDesc); }