public void ProcessRequest(HttpContext context) { var req = context.Request; if (req.HttpMethod == "POST" && req.IsAuthenticated) { ExportAction action = ExportAction.CreateAction(req.Form["context"]); SCObjectSet result = action.Execute(context.Request); var cateName = action.CategoryName; string fileName = cateName + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"); if (TimePointContext.Current.UseCurrentTime == false) { fileName += "_" + TimePointContext.Current.SimulatedTime.ToString("yyyyMMdd_HHmmss"); } fileName += ".xml"; context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + MCS.Web.Library.ResponseExtensions.EncodeFileNameInContentDisposition(context.Response, fileName) + "\""); using (var output = context.Response.Output) { result.TimeContext = TimePointContext.Current.UseCurrentTime ? DateTime.Now : TimePointContext.Current.SimulatedTime; result.Write(output); } } else { throw new HttpException("请求的方式错误"); } }
public void SetPluginCommands( ImportAction import, ExportAction export) { ExportCommand = new AsyncCommand(token => ExportAsync(export, token)); ImportCommand = new AsyncCommand(token => ImportAsync(import, token)); OnPropertyChanged(nameof(ExportCommand)); OnPropertyChanged(nameof(ImportCommand)); }
IAction ReadExportAction(XElement actionElement, ISyncConfiguration configuration, IPathResolver pathResolver) { var enabled = ReadActionEnabled(actionElement); var inputFilterName = ReadActionInputFilterName(actionElement); var syncFolder = ReadActionSyncFolder(actionElement); var action = new ExportAction(enabled, configuration, inputFilterName, syncFolder); ApplyCommonImportExportActionProperties(actionElement, action, configuration, pathResolver); return(action); }
public void TestExport1() { var exporter = new Mock <ILogFileToFileExporter>(); exporter.Setup(x => x.Export(It.IsAny <IProgress <Percentage> >())) .Throws <DirectoryNotFoundException>(); var action = new ExportAction(exporter.Object, "", "some shitty folder"); action.Property(x => x.Progress).ShouldEventually().Be(Percentage.HundredPercent); action.Exception.Should().BeOfType <ExportException>(); action.Exception.Message.Should().Be("Unable to find or create directory 'some shitty folder'. Maybe its drive isn't connected or the medium is read only..."); }
static void Main(string[] args) { var output = new ConsoleOutput(); if (args == null || args.Length == 0) { output.WriteLine("Cannot find any arguments"); return; } var actionName = args[0].ToLowerInvariant(); IAction action; switch (actionName) { case ActionList.Export: action = new ExportAction(); break; case ActionList.Import: action = new ImportAction(output); break; case ActionList.FullReset: action = new FullResetAction(); break; case ActionList.ForceClean: action = new ForceCleanAction(); break; default: output.WriteLine($"Action {actionName} is not supported"); return; } output.WriteLine("Start action..."); try { action.Execute(args).GetAwaiter().GetResult(); } catch (OptionException ex) { output.WriteLine(ex.Message); return; } output.WriteLine("Complete"); }
private void ExportToFile() { var dataSource = DataSource; var logFile = dataSource?.FilteredLogSource; if (logFile == null) { Log.Warn("DataSource is null, cancelling export..."); return; } var exportDirectory = _applicationSettings.Export.ExportFolder; var exporter = new LogFileToFileExporter(logFile, exportDirectory, dataSource.FullFileName ); var action = new ExportAction(exporter, DisplayName, exportDirectory); _actionCenter.Add(action); }
public ExportEvent(object source, ExportAction action) : base(source, action.ToString()) { this._action = action; }
public ResultProduct UpdateProduct() { //stt: nhập kho: NK // Xuất kho : XK var log = new MongoHistoryAPI() { APIUrl = "/api/product/updateproduct", CreateTime = DateTime.Now, Sucess = 1 }; var result = new ResultProduct() { id = "1", msg = "success" }; var requestContent = Request.Content.ReadAsStringAsync().Result; log.Content = requestContent; try { var jsonserializer = new JavaScriptSerializer(); var paser = jsonserializer.Deserialize <RequestProduct>(requestContent); // log.Content = new JavaScriptSerializer().Serialize(paser); if (!mongoHelper.checkLoginSession(paser.user, paser.token)) { throw new Exception("Tài khoản của bạn đã bị đăng nhập trên một thiết bị khác!"); } WavehouseInfo wareActionInfo = new WavehouseInfo(); var staff = db.HaiStaffs.Where(p => p.UserLogin == paser.user).FirstOrDefault(); if (staff != null) { wareActionInfo.wCode = staff.HaiBranch.Code; wareActionInfo.wName = staff.HaiBranch.Name; var userStaff = db.AspNetUsers.Where(p => p.UserName == paser.user).FirstOrDefault(); var role = userStaff.AspNetRoles.FirstOrDefault(); if (role.Name == "Warehouse") { wareActionInfo.wType = "W"; } else { wareActionInfo.wType = "B"; } } else { var agency = db.CInfoCommons.Where(p => p.UserLogin == paser.user).FirstOrDefault(); if (agency != null) { wareActionInfo.wCode = agency.CCode; wareActionInfo.wName = agency.CName; wareActionInfo.wType = agency.CType; } } // check user receiver WavehouseInfo wareReceiInfo = null; // lay thong tin noi nhan if (!String.IsNullOrEmpty(paser.receiver.Trim()) && paser.status == "XK") { wareReceiInfo = new WavehouseInfo(); var branchReceiver = db.HaiBranches.Where(p => p.Code == paser.receiver).FirstOrDefault(); if (branchReceiver != null) { wareReceiInfo.wType = "B"; wareReceiInfo.wCode = branchReceiver.Code; wareReceiInfo.wName = branchReceiver.Name; } else { var agencyReceiver = db.CInfoCommons.Where(p => p.CCode == paser.receiver).FirstOrDefault(); if (agencyReceiver != null) { wareReceiInfo.wType = agencyReceiver.CType; wareReceiInfo.wCode = agencyReceiver.CCode; wareReceiInfo.wName = agencyReceiver.CName; } } if (String.IsNullOrEmpty(wareReceiInfo.wCode) || wareActionInfo.wCode == wareReceiInfo.wCode) { throw new Exception("Sai thông tin nơi nhập hàng"); } } ProductScanAction wareAction = null; if (paser.status == "NK") { wareAction = new ImportAction(db, wareActionInfo, paser.user, null); } else if (paser.status == "XK") { wareAction = new ExportAction(db, wareActionInfo, paser.user, wareReceiInfo); } if (wareAction == null) { throw new Exception("Sai thông tin quét"); } string msg = wareAction.checkRole(); if (msg != null) { throw new Exception(msg); } // kiem tra nhap kho List <GeneralInfo> productsReturn = new List <GeneralInfo>(); foreach (string barcode in paser.products) { BarcodeHistory resultSave = wareAction.Handle(barcode); db.BarcodeHistories.Add(resultSave); db.SaveChanges(); productsReturn.Add(new GeneralInfo() { code = resultSave.Barcode, name = resultSave.ProductName, status = resultSave.Messenge, success = Convert.ToInt32(resultSave.IsSuccess) }); } result.products = productsReturn; } catch (Exception e) { result.id = "0"; result.msg = e.Message; log.Sucess = 0; } log.ReturnInfo = new JavaScriptSerializer().Serialize(result); mongoHelper.createHistoryAPI(log); return(result); }
public static int Main(string[] args) { IConfiguration config = new ConfigurationBuilder() .SetBasePath(Path.Combine(AppContext.BaseDirectory)) .AddJsonFile("zonesettings.json", true, true) .AddJsonFile("zonesettings.Development.json", true, true) .Build(); var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>() .UseNpgsql( config.GetConnectionString("DefaultConnection")); zoneOptions = new ZoneWriterOptions(); config.GetSection("ZoneWriter").Bind(zoneOptions); using (ApplicationDbContext context = new ApplicationDbContext(optionsBuilder.Options)) { var lastExport = context.ExportActions.Find(RegistryProvider.ExportAction); var lastUpdate = context.ExportActions.Find(RegistryProvider.UpdateAction); var lastExportTime = lastExport?.LastModified ?? DateTimeOffset.MinValue; var lastUpdateTime = lastUpdate?.LastModified ?? DateTimeOffset.MinValue; bool forceUpdate = false; if (args.Length != 0 && args[0] == "-f") { forceUpdate = true; } if (lastExportTime > lastUpdateTime && !forceUpdate) { return(100); } // calculate next soa long nextSoa = DateTimeOffset.UtcNow.Year * 1000000; nextSoa += DateTimeOffset.UtcNow.Month * 10000; nextSoa += DateTimeOffset.UtcNow.Day * 100; long lastSoa = 0; if (lastExport != null && lastExport.LastSoa.HasValue) { lastSoa = lastExport.LastSoa.Value; } while (lastSoa > nextSoa) { nextSoa++; } StringBuilder sb = GenerateZoneFile(nextSoa, context); string contents = sb.ToString(); string tempfile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Console.WriteLine($"writing temp zone file to {tempfile}"); File.WriteAllText(tempfile, contents, Encoding.ASCII); string filename = string.Format("{0}.zone", zoneOptions.BaseZone); Console.WriteLine($"setting filename to {filename}"); string destFileName = Path.Combine(zoneOptions.ZoneFileLocation, filename); Console.WriteLine($"setting destFileName to {destFileName}"); string backupFile = Path.Combine( zoneOptions.ZoneFileLocation, string.Format("{0}.last", zoneOptions.BaseZone)); Console.WriteLine($"setting backupFile to {backupFile}"); if (File.Exists(destFileName)) { Console.WriteLine($"Backing up prior zone file"); string root1 = Path.GetPathRoot(tempfile); string root2 = Path.GetPathRoot(destFileName); if (string.Compare(root1, root2, true) == 0) { // can only replace on the same drive Console.WriteLine($"Replacing zone file with {tempfile} and writing backup at {backupFile}"); File.Replace(tempfile, destFileName, backupFile); Console.WriteLine($"Deleting tempfile {tempfile}"); File.Delete(tempfile); } else { Console.WriteLine($"Deleting zone file"); File.Delete(destFileName); File.Move(tempfile, destFileName); Console.WriteLine($"Deleting tempfile {tempfile}"); File.Delete(tempfile); } } else { Console.WriteLine($"Moving {tempfile} zone file to {destFileName}"); File.Move(tempfile, destFileName); Console.WriteLine($"Deleting tempfile {tempfile}"); File.Delete(tempfile); } if (lastExport == null) { lastExport = new ExportAction() { Id = RegistryProvider.ExportAction }; context.Add(lastExport); } lastExport.LastModified = DateTimeOffset.UtcNow; lastExport.LastSoa = nextSoa; context.SaveChanges(); } return(0); }
/// <summary> /// Effective implementation of the Export. /// </summary> private void Export(ISimpleTaskHost host, ExportAction initialAction, List <DataRelation> relationsToAdd) { // Create action queue and seed with initialAction: var actionQueue = new ExportActionsQueue(); actionQueue.Enqueue(initialAction); // Run over all actions in queue: while (actionQueue.Count > 0) { // Get next action: var action = actionQueue.Dequeue(); // Host handling: if (host.IsAbortRequested) { host.Aborting(); return; } host.Out.WriteLine(" FROM {0} WHERE {1} [{2}]", action.Table, action.Where, (action.Parameters == null) ? "" : String.Join(", ", action.Parameters)); // Retrieve or Create table definition on dataset: var dsTableName = action.Table.SchemaDotName; var dsTable = (DataTable)null; if (TargetDataSet.Tables.Contains(dsTableName)) { // Retrieve table: dsTable = TargetDataSet.Tables[dsTableName]; } else { // Create table: Connection.FillDataSet(TargetDataSet, dsTableName, "SELECT * FROM " + action.Table.ToString() + " WHERE (1=0)", MissingSchemaAction.AddWithKey); dsTable = TargetDataSet.Tables[dsTableName]; // Create relational constraints to tables already existing, in one direction: foreach (var relation in action.Table.GetFromRelations()) { if (TargetDataSet.Tables.Contains(relation.ForeignTable.SchemaDotName)) { var parentCols = new List <DataColumn>(); foreach (var col in relation.PrimaryColumns) { parentCols.Add(dsTable.Columns[col.Name]); } var childTable = TargetDataSet.Tables[relation.ForeignTable.SchemaDotName]; var childCols = new List <DataColumn>(); foreach (var col in relation.ForeignColumns) { childCols.Add(childTable.Columns[col.Name]); } relationsToAdd.Add(new DataRelation(relation.SchemaDotName, parentCols.ToArray(), childCols.ToArray())); } } // and in the other direction: foreach (var relation in action.Table.GetToRelations()) { if (TargetDataSet.Tables.Contains(relation.PrimaryTable.SchemaDotName)) { var parentTable = TargetDataSet.Tables[relation.PrimaryTable.SchemaDotName]; if (dsTable == parentTable) { continue; } var parentCols = new List <DataColumn>(); foreach (var col in relation.PrimaryColumns) { parentCols.Add(parentTable.Columns[col.Name]); } var childCols = new List <DataColumn>(); foreach (var col in relation.ForeignColumns) { childCols.Add(dsTable.Columns[col.Name]); } relationsToAdd.Add(new DataRelation(relation.SchemaDotName, parentCols.ToArray(), childCols.ToArray())); } } } // Construct SQL query for export: var sql = "SELECT * FROM " + action.Table.ToString() + " WHERE (" + action.Where + ")"; // Append filters (if any): foreach (var filter in this.TableFilters.Where(f => f.Key == action.Table)) { sql += " AND (" + filter.Value + ")"; } using (var cmd = Connection.CreateCommand(sql)) { // Add system query parameters (if any): if (action.Parameters != null && action.Parameters.Length > 0) { for (int i = 0; i < action.Parameters.Length; i++) { cmd.AddParameter("@p" + i, action.Parameters[i]); } } // Add user query parameters (if any) (only on root queries, where action.Parameters = null): if (action.Parameters == null) { foreach (var item in this.QueryArguments) { if (!sql.Contains(item.Key)) { continue; // Skip arguments that do not appear in sql. } cmd.AddParameter(item.Key, item.Value); } } // Execute the query: using (var reader = cmd.ExecuteReader()) { // Construct a map of columns: var map = (DataReaderMap)null; map = new DataReaderMap(reader); // Iterate over all returned rows: while (reader.Read()) { // Retrieve row values: var values = new object[reader.FieldCount]; reader.GetValues(values); try { // Add row to dataset: var dataRow = TargetDataSet.Tables[dsTableName].Rows.Add(values); // Enqueue related child rows for export (except if excluded): foreach (var rel in action.Table.GetFromRelations()) { if ((this.ExportMode == DbExportMode.None) && (!this.RelationsToInclude.Contains(rel))) { continue; } if (this.RelationsToExclude.Contains(rel)) { continue; } var vs = new object[rel.ForeignColumns.Count]; var wh = "(" + String.Join(") AND (", Enumerate.FromTo(0, rel.ForeignColumns.Count - 1).Select(i => "[" + rel.ForeignColumns[i].Name + "] = @p" + i).ToArray()) + ")"; for (int i = 0; i < rel.ForeignColumns.Count; i++) { vs[i] = values[map.ColumnIndexes[rel.PrimaryColumns[i].Name]]; } actionQueue.Enqueue(new ExportAction() { Table = rel.ForeignTable, Where = wh, Parameters = vs }); } // Enqueue related parent rows for export (if in Full mode or relation explicitely included): foreach (var rel in action.Table.GetToRelations()) { if ((this.ExportMode != DbExportMode.Full) && (!this.RelationsToInclude.Contains(rel))) { continue; } if (this.RelationsToExclude.Contains(rel)) { continue; } var vs = new object[rel.PrimaryColumns.Count]; var wh = "(" + String.Join(") AND (", Enumerate.FromTo(0, rel.PrimaryColumns.Count - 1).Select(i => "[" + rel.PrimaryColumns[i].Name + "] = @p" + i).ToArray()) + ")"; for (int i = 0; i < rel.PrimaryColumns.Count; i++) { vs[i] = values[map.ColumnIndexes[rel.ForeignColumns[i].Name]]; } actionQueue.Enqueue(new ExportAction() { Table = rel.PrimaryTable, Where = wh, Parameters = vs }); } } catch (System.Data.ConstraintException) { // Ignore primary key violation: record was already present... } } } } } }
private void ExportReportBtn_Click(object sender, RoutedEventArgs e) { ExportAction.Invoke(); }