internal static Activity FromPath(string filePath, Folder folder, Route route) { Activity result; try { ActivityFile activityFile = new ActivityFile(filePath); ServiceFile srvFile = new ServiceFile(route.RouteFolder.ServiceFile(activityFile.Activity.PlayerServices.Name)); Consist consist = Consist.GetConsist(folder, srvFile.TrainConfig, false); Path path = new Path(route.RouteFolder.PathFile(srvFile.PathId)); if (!path.IsPlayerPath) { return(null); // Not nice to throw an error now. Error was originally thrown by new Path(...); throw new InvalidDataException("Not a player path"); } else if (!activityFile.Activity.Header.RouteID.Equals(route.RouteID, StringComparison.OrdinalIgnoreCase)) { //Activity and route have different RouteID. result = new Activity($"<{catalog.GetString("Not same route:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null); } else { result = new Activity(string.Empty, filePath, activityFile, consist, path); } } #pragma warning disable CA1031 // Do not catch general exception types catch #pragma warning restore CA1031 // Do not catch general exception types { result = new Activity($"<{catalog.GetString("load error:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null); } return(result); }
public string GetClassServiceFileFromInterface( ServiceFile interfaceServiceFile, string serviceClassName, string serviceNamespace, List <string> appendUsingDirectives, ClassInterfaceBody appendClassBody) { var usingSet = interfaceServiceFile.UsingDirectives.ToHashSet(); usingSet.UnionWith(appendUsingDirectives); usingSet.Remove(serviceNamespace); var classDeclaration = _serviceCommandParserService.GetClassFromInterface( interfaceServiceFile.ServiceDeclaration, serviceClassName); var fieldDeclarations = appendClassBody?.FieldDeclarations; classDeclaration.Body.ConstructorDeclaration = appendClassBody?.ConstructorDeclaration; if (fieldDeclarations != null) { classDeclaration.Body.FieldDeclarations = fieldDeclarations; } return(_serviceCommandStgService.RenderServiceFile( usingDirectives: usingSet.ToList(), serviceNamespace: serviceNamespace, service: classDeclaration)); }
public static void Main(string[] args) { string strArg1, strArg2; try { if (args.Length >= 2) { strArg1 = args[0]; strArg2 = args[1]; ServiceFile objServiceFile = new ServiceFile(strArg1, strArg2); string strResult = objServiceFile.BringFileInformation(); Console.WriteLine(strResult); Console.Read(); } } catch (Exception e) { Console.WriteLine("Some exception happened : " + e.ToString()); Console.Read(); } }
public ActionResult Get() { ServiceFile service = new ServiceFile(); var countries = service.GetFileData(); return(Ok(countries)); }
public void BringFileInformationTest() { ServiceFile objTest = new ServiceFile("--size", "c:/test.txt"); string strActualResult = objTest.BringFileInformation(); Assert.IsTrue(strActualResult.Contains("File Size")); }
protected Activity(string filePath, Folder folder, Route route) { if (filePath == null) { Name = catalog.GetString("- Explore Route -"); } else if (File.Exists(filePath)) { var showInList = true; try { var actFile = new ActivityFile(filePath); var srvFile = new ServiceFile(System.IO.Path.Combine(System.IO.Path.Combine(route.Path, "SERVICES"), actFile.Tr_Activity.Tr_Activity_File.Player_Service_Definition.Name + ".srv")); // ITR activities are excluded. showInList = actFile.Tr_Activity.Tr_Activity_Header.Mode != ActivityMode.IntroductoryTrainRide; Name = actFile.Tr_Activity.Tr_Activity_Header.Name.Trim(); Description = actFile.Tr_Activity.Tr_Activity_Header.Description; Briefing = actFile.Tr_Activity.Tr_Activity_Header.Briefing; StartTime = actFile.Tr_Activity.Tr_Activity_Header.StartTime; Season = actFile.Tr_Activity.Tr_Activity_Header.Season; Weather = actFile.Tr_Activity.Tr_Activity_Header.Weather; Difficulty = actFile.Tr_Activity.Tr_Activity_Header.Difficulty; Duration = actFile.Tr_Activity.Tr_Activity_Header.Duration; Consist = new Consist(System.IO.Path.Combine(System.IO.Path.Combine(System.IO.Path.Combine(folder.Path, "TRAINS"), "CONSISTS"), srvFile.Train_Config + ".con"), folder); Path = new Path(System.IO.Path.Combine(System.IO.Path.Combine(route.Path, "PATHS"), srvFile.PathID + ".pat")); if (!Path.IsPlayerPath) { // Not nice to throw an error now. Error was originally thrown by new Path(...); throw new InvalidDataException("Not a player path"); } } catch { Name = "<" + catalog.GetString("load error:") + " " + System.IO.Path.GetFileNameWithoutExtension(filePath) + ">"; } if (!showInList) { throw new InvalidDataException(catalog.GetStringFmt("Activity '{0}' is excluded.", filePath)); } if (string.IsNullOrEmpty(Name)) { Name = "<" + catalog.GetString("unnamed:") + " " + System.IO.Path.GetFileNameWithoutExtension(filePath) + ">"; } if (string.IsNullOrEmpty(Description)) { Description = null; } if (string.IsNullOrEmpty(Briefing)) { Briefing = null; } } else { Name = "<" + catalog.GetString("missing:") + " " + System.IO.Path.GetFileNameWithoutExtension(filePath) + ">"; } FilePath = filePath; }
public ServiceClassInjector( IStringUtilService stringUtilService, ICSharpParserService cSharpParserService, IServiceCommandParserService serviceCommandParserService, BufferedTokenStream tokenStream, string serviceClassInterfaceName, ServiceFile serviceFile, string tabString = null) { _stringUtilService = stringUtilService; _cSharpParserService = cSharpParserService; _serviceCommandParserService = serviceCommandParserService; Tokens = tokenStream; Rewriter = new TokenStreamRewriter(tokenStream); _serviceClassInterfaceName = serviceClassInterfaceName; _serviceFile = serviceFile; _tabString = tabString; _currentNamespace = new Stack <string>(); _currentClass = new Stack <string>(); _isCorrectClass = new Stack <bool>(); _isCorrectClass.Push(false); _hasServiceNamespace = false; _hasServiceClass = false; _hasServiceConstructor = false; IsModified = false; _usingSet = _serviceFile.UsingDirectives.ToHashSet(); _ctorParamDict = new Dictionary <string, FixedParameter>(); foreach (var fixedParam in _serviceFile.ServiceDeclaration.Body.ConstructorDeclaration.FormalParameterList.FixedParameters) { _ctorParamDict.Add($"{fixedParam.Type} {fixedParam.Identifier}", fixedParam); } _fieldDict = new Dictionary <string, FieldDeclaration>(); foreach (var fieldDec in _serviceFile.ServiceDeclaration.Body.FieldDeclarations) { _fieldDict.Add($"{fieldDec.Type} {fieldDec?.VariableDeclarator?.Identifier}", fieldDec); } _ctorAssignmentDict = new Dictionary <string, SimpleAssignment>(); var statements = _serviceFile.ServiceDeclaration?.Body?.ConstructorDeclaration?.Body?.Statements; if (statements != null) { foreach (var statement in statements) { if (statement.SimpleAssignment != null) { var sa = statement.SimpleAssignment; _ctorAssignmentDict.Add($"{sa.LeftHandSide}={sa.RightHandSide};", sa); } } } }
public static DalFile ToDalFile(this ServiceFile file) { return(new DalFile { ID = file.ID, BookID = file.BookID, Path = file.Path, Format = file.Format, }); }
public IActionResult GetCountry(string name) { ServiceFile service = new ServiceFile(); var result = service.GetFileData(); var cities = result.countries.FirstOrDefault(c => c.Country == name); if (cities == null) { return(NotFound()); } return(Ok(cities)); }
public string GetInterfaceServiceFileFromClass( ServiceFile classServiceFile, string serviceInterfaceName, string serviceNamespace) { var interfaceDeclaration = _serviceCommandParserService.GetInterfaceFromClass( classServiceFile.ServiceDeclaration, serviceInterfaceName); return(_serviceCommandStgService.RenderServiceFile( usingDirectives: classServiceFile.UsingDirectives, serviceNamespace: serviceNamespace, service: interfaceDeclaration)); }
public ServiceInterfaceInjector Create( BufferedTokenStream tokenStream, string serviceClassInterfaceName, ServiceFile serviceFile, string tabString) { return(new ServiceInterfaceInjector( _stringUtilService, _cSharpParserService, _serviceCommandParserService, tokenStream, serviceClassInterfaceName, serviceFile, tabString)); }
public ServiceClassScraper( ICSharpParserService cSharpParserService, BufferedTokenStream tokenStream, string serviceClassName, string serviceNamespace, List <TypeParameter> typeParameters) { _cSharpParserService = cSharpParserService; Tokens = tokenStream; ServiceClassName = serviceClassName; TypeParameters = typeParameters; _serviceNamespace = serviceNamespace; Rewriter = new TokenStreamRewriter(tokenStream); Results = new ServiceFile(); _currentNamespace = new Stack <string>(); HasServiceClass = false; }
//private void btnDownload_Click(object sender, EventArgs e) //{ // ServiceFile ClientAsked = new ServiceFile(); // serviceFileList = service.GetFileList("D:\\Folder1"); // Set folder that make client READ // ServiceFileListForm serviceFileListForm = new ServiceFileListForm(); // serviceFileListForm.ShowDialog(); // string serviceFileName = serviceFileListForm.selectedFile; // if (serviceFileName != "") // { // ClientAsked.FilePath = "D:\\Folder1\\" + serviceFileName; // FolderBrowserDialog browsePath = new FolderBrowserDialog(); // Open a dialog make client select where to save file // browsePath.ShowDialog(); // if (browsePath.SelectedPath != "") // { // string saveFilePath = browsePath.SelectedPath + "\\" + serviceFileName; // saveFilePath = CheckFilePath(saveFilePath); // double currentProgress = 0; // int tillCurrentBytesRead = 0; // Current sum of bytes been read // ClientAsked.BufferSize = 3000000; // ClientAsked.isFirstTime = true; // Make file open until read file over // fileStream = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); // Accoring to saveFilePath create a file // do // { // service.SendFile(ref ClientAsked); // Call Service1.cs function make ClientAsked.Buffer get part of file information // fileStream.Write(ClientAsked.Buffer, 0, ClientAsked.Buffer.Length); // Write part of file information into File // tillCurrentBytesRead += ClientAsked.BytesRead; // currentProgress = (((double)tillCurrentBytesRead) / ClientAsked.FileSize) * 100; // pgbReadFile.Value = Convert.ToInt32(currentProgress); // } while (currentProgress != 100); // fileStream.Close(); // Close File makes it rest in peace // rtbHistory.AppendText("- Download \"" + serviceFileName + "\" success -"); // rtbHistory.AppendText("\n---------------------------------------------------------\n"); // } // } // #region Test Time // //Stopwatch sw_total = new Stopwatch(); // //ServiceFile ClientAsked = new ServiceFile(); // //serviceFileList = service.GetFileList("D:\\Folder1"); // Set folder that make client READ // //ServiceFileListForm serviceFileListForm = new ServiceFileListForm(); // //serviceFileListForm.ShowDialog(); // //string serviceFileName = serviceFileListForm.selectedFile; // //if (serviceFileName != "") // //{ // // for (int i = 0; i < 3; i++) // // { // // sw_total.Reset(); // // sw_total.Start(); // // ClientAsked.FilePath = "D:\\Folder1\\" + serviceFileName; // // string saveFilePath = "D:\\FolderDownload" + "\\" + serviceFileName; // // if (saveFilePath != "\\" + serviceFileName) // // { // // saveFilePath = CheckFilePath(saveFilePath); // // double currentProgress = 0; // // int tillCurrentBytesRead = 0; // Current sum of bytes been read // // ClientAsked.BufferSize = 3000000; // // ClientAsked.isFirstTime = true; // Make file open until read file over // // fileStream = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); // Accoring to saveFilePath create a file // // do // // { // // service.SendFile(ref ClientAsked); // Call Service1.cs function make ClientAsked.Buffer get part of file information // // fileStream.Write(ClientAsked.Buffer, 0, ClientAsked.Buffer.Length); // Write part of file information into File // // tillCurrentBytesRead += ClientAsked.BytesRead; // // currentProgress = (((double)tillCurrentBytesRead) / ClientAsked.FileSize) * 100; // // pgbReadFile.Value = Convert.ToInt32(currentProgress); // // } while (currentProgress != 100); // // fileStream.Close(); // Close File makes it rest in peace // // } // // sw_total.Stop(); // // rtbHistory.AppendText("-No. " + (i + 1).ToString() + " transport " + sw_total.Elapsed.TotalMilliseconds.ToString() + " ms-\n"); // // } // // rtbHistory.AppendText("---------------------------------------------------------\n\n"); // //} // #endregion //} private void btnDownload_Click(object sender, EventArgs e) { ServiceFile ClientAsked = new ServiceFile(); serviceFileList = service.GetFileList("D:\\Folder1"); // Set folder that make client READ ServiceFileListForm serviceFileListForm = new ServiceFileListForm(); serviceFileListForm.ShowDialog(); string serviceFileName = serviceFileListForm.selectedFile; if (serviceFileName != "") { ClientAsked.FilePath = "D:\\Folder1\\" + serviceFileName; FolderBrowserDialog browsePath = new FolderBrowserDialog(); // Open a dialog make client select where to save file browsePath.ShowDialog(); if (browsePath.SelectedPath != "") { string saveFilePath = browsePath.SelectedPath + "\\" + serviceFileName; saveFilePath = CheckFilePath(saveFilePath); double currentProgress = 0; int tillCurrentBytesRead = 0; // Current sum of bytes been read ClientAsked.BufferSize = 300000; ClientAsked.isFirstTime = true; // Make file open until read file over fileStream = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); // Accoring to saveFilePath create a file do { ClientAsked = service.Test(ClientAsked); // Call Service1.cs function make ClientAsked.Buffer get part of file information fileStream.Write(ClientAsked.Buffer, 0, ClientAsked.Buffer.Length); // Write part of file information into File tillCurrentBytesRead += ClientAsked.BytesRead; currentProgress = (((double)tillCurrentBytesRead) / ClientAsked.FileSize) * 100; pgbReadFile.Value = Convert.ToInt32(currentProgress); } while (currentProgress != 100); fileStream.Close(); // Close File makes it rest in peace rtbHistory.AppendText("- Download \"" + serviceFileName + "\" success -"); rtbHistory.AppendText("\n---------------------------------------------------------\n"); } } }
public string InjectDataIntoServiceClass( ServiceFile classServiceFile, CSharpParserWrapper serviceClassParser, string serviceClassName, string tabString = null) { var tree = serviceClassParser.GetParseTree(); var visitor = _serviceClassInjectorFactory.Create( tokenStream: serviceClassParser.Tokens, serviceClassInterfaceName: serviceClassName, serviceFile: classServiceFile, tabString: tabString ); visitor.Visit(tree); return(visitor.IsModified ? visitor.Rewriter.GetText() : null); }
CompareScraperResults(ServiceFile classResults, ServiceFile interfaceResults) { var classMissingResults = new ServiceFile() { ServiceNamespace = classResults.ServiceNamespace, UsingDirectives = GetMissingStrings( classResults.UsingDirectives, interfaceResults.UsingDirectives).ToList() }; var interfaceMissingResults = new ServiceFile() { ServiceNamespace = interfaceResults.ServiceNamespace, UsingDirectives = GetMissingStrings(interfaceResults.UsingDirectives, classResults.UsingDirectives).ToList() }; if (classResults.ServiceDeclaration != null && interfaceResults.ServiceDeclaration != null) { var interfaceBody = interfaceResults?.ServiceDeclaration?.Body ?? new ClassInterfaceBody(); var classBody = classResults?.ServiceDeclaration?.Body ?? new ClassInterfaceBody(); classMissingResults.ServiceDeclaration = classResults.ServiceDeclaration.CopyHeader(); classMissingResults.ServiceDeclaration.Body.MethodDeclarations = GetMissingMethodDeclarations(classBody.MethodDeclarations, interfaceBody.MethodDeclarations); classMissingResults.ServiceDeclaration.Body.PropertyDeclarations = GetMissingPropertyDeclarations(classBody.PropertyDeclarations, interfaceBody.PropertyDeclarations); interfaceMissingResults.ServiceDeclaration = interfaceResults.ServiceDeclaration.CopyHeader(); interfaceMissingResults.ServiceDeclaration.Body.MethodDeclarations = GetMissingMethodDeclarations(interfaceBody.MethodDeclarations, classBody.MethodDeclarations); interfaceMissingResults.ServiceDeclaration.Body.PropertyDeclarations = GetMissingPropertyDeclarations(interfaceBody.PropertyDeclarations, classBody.PropertyDeclarations); } return(classMissingResults, interfaceMissingResults); }
internal static async Task <Activity> FromPathAsync(string filePath, Folder folder, Route route, CancellationToken token) { return(await Task.Run(async() => { Activity result; try { ActivityFile activityFile = new ActivityFile(filePath); ServiceFile srvFile = new ServiceFile(route.RouteFolder.ServiceFile(activityFile.Activity.PlayerServices.Name)); var constistTask = Consist.GetConsist(folder, srvFile.TrainConfig, false, token); var pathTask = Path.FromFileAsync(route.RouteFolder.PathFile(srvFile.PathId), token); await Task.WhenAll(constistTask, pathTask).ConfigureAwait(false); Consist consist = await constistTask; Path path = await pathTask; if (!path.IsPlayerPath) { return null; // Not nice to throw an error now. Error was originally thrown by new Path(...); throw new InvalidDataException("Not a player path"); } else if (!activityFile.Activity.Header.RouteID.Equals(route.RouteID, StringComparison.OrdinalIgnoreCase)) { //Activity and route have different RouteID. result = new Activity($"<{catalog.GetString("Not same route:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null); } else { result = new Activity(string.Empty, filePath, activityFile, consist, path); } } catch { result = new Activity($"<{catalog.GetString("load error:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null); } return result; }, token).ConfigureAwait(false)); }
public ServiceInterfaceInjector( IStringUtilService stringUtilService, ICSharpParserService cSharpParserService, IServiceCommandParserService serviceCommandParserService, BufferedTokenStream tokenStream, string serviceClassInterfaceName, ServiceFile serviceFile, string tabString = null) { _stringUtilService = stringUtilService; _cSharpParserService = cSharpParserService; _serviceCommandParserService = serviceCommandParserService; Tokens = tokenStream; Rewriter = new TokenStreamRewriter(tokenStream); _serviceClassInterfaceName = serviceClassInterfaceName; _serviceFile = serviceFile; _tabString = tabString; _currentNamespace = new Stack <string>(); _hasServiceNamespace = false; _hasServiceInterface = false; IsModified = false; _usingSet = _serviceFile.UsingDirectives.ToHashSet(); }
public void UpdateDownloadFile(ServiceFile serviceFile, double currentProgress) { pgbReadFile.Value = Convert.ToInt32(currentProgress); }
public void AddFile(ServiceBook book, ServiceFile file) { unit.Books.AddFile(book.ToDalBook(), file.ToDalFile()); unit.Save(); }
public void RemoveFile(ServiceFile file) { unit.Books.DeleteFile(file.ToDalFile()); unit.Save(); }
/// <summary> /// Try to load the file. /// Possibly this might raise an exception. That exception is not caught here /// </summary> /// <param name="file">The file that needs to be loaded</param> public override void TryLoading(string file) { var srvFile = new ServiceFile(file); }
public string RenderServiceFile( ServiceFile serviceFile = null) { return(RenderServiceFile( serviceFile.UsingDirectives, serviceFile.ServiceNamespace, serviceFile.ServiceDeclaration)); }
private void ValidateServiceClass( string serviceClassName, List <TypeParameter> typeParameters, List <InjectedService> injectedServices, string serviceClassFilePath, string serviceNamespace, string outServiceClassFilePath) { var usingDirectives = new HashSet <string>(); var fieldDeclarations = new List <FieldDeclaration>(); var ctorParameters = new FormalParameterList(); var fixedParams = ctorParameters.FixedParameters; var ctorBody = new ConstructorBody(); var statements = ctorBody.Statements; var appendBody = new ClassInterfaceBody() { FieldDeclarations = fieldDeclarations, ConstructorDeclaration = new ConstructorDeclaration() { FormalParameterList = ctorParameters, Body = ctorBody } }; if (injectedServices != null && injectedServices.Count > 0) { foreach (var injectedService in injectedServices) { var injectedServiceIdentifier = injectedService.ServiceIdentifier ?? Regex.Replace( Regex.Replace( injectedService.Type, @"^I?([A-Z])", "$1"), @"^[A-Z]", m => m.ToString().ToLower()); if (!Regex.Match(serviceNamespace, "^" + Regex.Escape(injectedService.Namespace)).Success) { usingDirectives.Add(injectedService.Namespace); } fieldDeclarations.Add( new FieldDeclaration() { Modifiers = new List <string>() { Keywords.Private, Keywords.Readonly }, Type = injectedService.Type, VariableDeclarator = new VariableDeclarator() { Identifier = "_" + injectedServiceIdentifier } }); fixedParams.Add( new FixedParameter() { Type = injectedService.Type, Identifier = injectedServiceIdentifier }); statements.Add( new Statement() { SimpleAssignment = new SimpleAssignment() { LeftHandSide = "_" + injectedServiceIdentifier, RightHandSide = injectedServiceIdentifier } }); } } var serviceClassFile = new ServiceFile() { UsingDirectives = usingDirectives.ToList(), ServiceNamespace = serviceNamespace, ServiceDeclaration = new ClassInterfaceDeclaration() { IsInterface = false, Modifiers = new List <string>() { Keywords.Public }, Identifier = serviceClassName, TypeParameters = typeParameters.Copy(), Body = new ClassInterfaceBody() { FieldDeclarations = fieldDeclarations, ConstructorDeclaration = new ConstructorDeclaration() { Modifiers = new List <string>() { Keywords.Public }, Identifier = serviceClassName, FormalParameterList = ctorParameters, Body = ctorBody } } } }; if (!File.Exists(serviceClassFilePath)) { // Create <service> class file // Create serviceClass StringTemplate with empty class body _logger.LogDebug("Creating new service class and writing it to file."); UpdateWrittenTo(serviceClassFilePath, outServiceClassFilePath); _ioUtilService.WriteStringToFile( _serviceCommandStgService.RenderServiceFile( usingDirectives: usingDirectives.ToList(), serviceNamespace: serviceNamespace, service: serviceClassFile.ServiceDeclaration), outServiceClassFilePath); } else { var serviceClassParser = new CSharpParserWrapper(GetPathFromWrittenTo(serviceClassFilePath)); var serviceClassRewrite = _serviceCommandService.InjectDataIntoServiceClass( serviceClassFile, serviceClassParser, serviceClassName, _userSettings.Value.TabString); if (serviceClassRewrite != null) { _logger.LogDebug("Overwriting service class file."); UpdateWrittenTo(serviceClassFilePath, outServiceClassFilePath); _ioUtilService.WriteStringToFile( serviceClassRewrite, outServiceClassFilePath); } else { _logger.LogDebug("Service class file was already up to date."); } } }
private void ConsolidateServiceClassAndInterface( SourceOfTruth sourceOfTruth, string serviceClassName, string serviceInterfaceName, List <TypeParameter> typeParameters, List <InjectedService> injectedServices, string serviceClassFilePath, string serviceInterfaceFilePath, string serviceNamespace, string outServiceClassFilePath, string outServiceInterfaceFilePath) { var usingDirectives = new HashSet <string>(); var fieldDeclarations = new List <FieldDeclaration>(); var ctorParameters = new FormalParameterList(); var fixedParams = ctorParameters.FixedParameters; var ctorBody = new ConstructorBody(); var statements = ctorBody.Statements; var appendBody = new ClassInterfaceBody() { FieldDeclarations = fieldDeclarations, ConstructorDeclaration = new ConstructorDeclaration() { FormalParameterList = ctorParameters, Body = ctorBody } }; if (injectedServices != null && injectedServices.Count > 0) { foreach (var injectedService in injectedServices) { var injectedServiceIdentifier = injectedService.ServiceIdentifier ?? Regex.Replace( Regex.Replace( injectedService.Type, @"^I?([A-Z])", "$1"), @"^[A-Z]", m => m.ToString().ToLower()); if (!Regex.Match(serviceNamespace, "^" + Regex.Escape(injectedService.Namespace)).Success) { usingDirectives.Add(injectedService.Namespace); } fieldDeclarations.Add( new FieldDeclaration() { Modifiers = new List <string>() { Keywords.Private, Keywords.Readonly }, Type = injectedService.Type, VariableDeclarator = new VariableDeclarator() { Identifier = "_" + injectedServiceIdentifier } }); fixedParams.Add( new FixedParameter() { Type = injectedService.Type, Identifier = injectedServiceIdentifier }); statements.Add( new Statement() { SimpleAssignment = new SimpleAssignment() { LeftHandSide = "_" + injectedServiceIdentifier, RightHandSide = injectedServiceIdentifier } }); } } CSharpParserWrapper serviceClassParser = null; CSharpParserWrapper serviceInterfaceParser = null; ServiceFile classScraperResults = null; ServiceFile interfaceScraperResults = null; //Check if <service> class file exists: if (File.Exists(serviceClassFilePath)) { _logger.LogDebug("Service class file found. Pulling data from service class."); // Else: // Parse <service> class file // Extract list of existing public method signatures serviceClassParser = new CSharpParserWrapper(GetPathFromWrittenTo(serviceClassFilePath)); classScraperResults = _serviceCommandService.ScrapeServiceClass( serviceClassParser, serviceClassName, serviceNamespace, typeParameters); } else { _logger.LogDebug($"No service class file found at {serviceClassFilePath}."); } //Check if <service> interface file exists: if (File.Exists(serviceInterfaceFilePath)) { _logger.LogDebug("Service interface file found. Pulling data from service interface."); // Else: // Parse <service> interface file // Extract list of existing method signatures serviceInterfaceParser = new CSharpParserWrapper(GetPathFromWrittenTo(serviceInterfaceFilePath)); interfaceScraperResults = _serviceCommandService.ScrapeServiceInterface( serviceInterfaceParser, serviceInterfaceName, serviceNamespace, typeParameters); } else { _logger.LogDebug($"No service interface file found at {serviceInterfaceFilePath}."); } if (classScraperResults is null && interfaceScraperResults is null) { _logger.LogDebug("Creating new service class and interface and writing them to file."); // Create <service> class file // Create serviceClass StringTemplate with empty class body var classDeclaration = new ClassInterfaceDeclaration() { IsInterface = false, Modifiers = new List <string>() { Keywords.Public }, Identifier = serviceClassName, TypeParameters = typeParameters.Copy(), Base = new ClassInterfaceBase() { InterfaceTypeList = new List <string>() { serviceInterfaceName + _cSharpCommonStgService.RenderTypeParamList(typeParameters.Copy()) } }, Body = new ClassInterfaceBody() { FieldDeclarations = fieldDeclarations, ConstructorDeclaration = new ConstructorDeclaration() { Modifiers = new List <string>() { Keywords.Public }, Identifier = serviceClassName, FormalParameterList = ctorParameters, Body = ctorBody } } }; UpdateWrittenTo(serviceClassFilePath, outServiceClassFilePath); _ioUtilService.WriteStringToFile( _serviceCommandStgService.RenderServiceFile( usingDirectives: usingDirectives.ToList(), serviceNamespace: serviceNamespace, service: classDeclaration), outServiceClassFilePath); // Create <service> interface file // Create serviceInterface StringTemplate with empty interface body var interfaceDeclaration = new ClassInterfaceDeclaration() { IsInterface = true, Modifiers = new List <string>() { Keywords.Public }, Identifier = serviceInterfaceName, TypeParameters = typeParameters.Copy() }; UpdateWrittenTo(serviceInterfaceFilePath, outServiceInterfaceFilePath); _ioUtilService.WriteStringToFile( _serviceCommandStgService.RenderServiceFile( serviceNamespace: serviceNamespace, service: interfaceDeclaration), outServiceInterfaceFilePath); }
public void UpdateDownloadFile(ServiceFile serviceFile, double currentProgress) { _wcfForm.UpdateDownloadFile(serviceFile, currentProgress); }
public Service(Content content) { Debug.Assert(content.Type == ContentType.Service); if (System.IO.Path.GetExtension(content.PathName).Equals(".srv", StringComparison.OrdinalIgnoreCase)) { var file = new ServiceFile(content.PathName); Name = file.Name; Consist = file.Train_Config; Path = file.PathID; Debug.Assert(content is ContentMSTSService); var msts = content as ContentMSTSService; var actFile = new ActivityFile(content.Parent.PathName); if (msts.IsPlayer) { var activityTraffic = actFile.Tr_Activity.Tr_Activity_File.Player_Service_Definition.Player_Traffic_Definition; ID = "0"; StartTime = MSTSTimeToDateTime(activityTraffic.Time); Stops = from stop in activityTraffic.Player_Traffic_List select new Stop(stop.PlatformStartID, stop.DistanceDownPath, MSTSTimeToDateTime(stop.ArrivalTime), MSTSTimeToDateTime(stop.DepartTime)); } else { var trfFile = new TrafficFile(msts.TrafficPathName); var activityService = actFile.Tr_Activity.Tr_Activity_File.Traffic_Definition.ServiceDefinitionList[msts.TrafficIndex]; var trafficService = trfFile.TrafficDefinition.TrafficItems[msts.TrafficIndex]; ID = activityService.UiD.ToString(); StartTime = MSTSTimeToDateTime(activityService.Time); Stops = trafficService.TrafficDetails.Zip(activityService.ServiceList, (tt, stop) => new Stop(stop.PlatformStartID, stop.DistanceDownPath, MSTSTimeToDateTime(tt.ArrivalTime), MSTSTimeToDateTime(tt.DepartTime))); } } else if (System.IO.Path.GetExtension(content.PathName).Equals(".timetable_or", StringComparison.OrdinalIgnoreCase)) { // TODO: Make common timetable parser. var file = new TimetableReader(content.PathName); Name = content.Name; var serviceColumn = -1; var consistRow = -1; var pathRow = -1; var startRow = -1; for (var row = 0; row < file.Strings.Count; row++) { if (file.Strings[row][0] == "#consist" && consistRow == -1) { consistRow = row; } else if (file.Strings[row][0] == "#path" && pathRow == -1) { pathRow = row; } else if (file.Strings[row][0] == "#start" && startRow == -1) { startRow = row; } } for (var column = 0; column < file.Strings[0].Length; column++) { if (file.Strings[0][column] == content.Name && serviceColumn == -1) { serviceColumn = column; } } ID = serviceColumn.ToString(); var timeRE = new Regex(@"^(\d\d):(\d\d)(?:-(\d\d):(\d\d))?"); var startTimeMatch = timeRE.Match(file.Strings[startRow][serviceColumn]); if (startTimeMatch.Success) { StartTime = new DateTime(2000, 1, 1, int.Parse(startTimeMatch.Groups[1].Value), int.Parse(startTimeMatch.Groups[2].Value), 0); } var stops = new List <Stop>(); for (var row = 0; row < file.Strings.Count; row++) { if (row != startRow) { var timeMatch = timeRE.Match(file.Strings[row][serviceColumn]); if (timeMatch.Success) { var arrivalTime = new DateTime(2000, 1, 1, int.Parse(timeMatch.Groups[1].Value), int.Parse(timeMatch.Groups[2].Value), 0); var departureTime = timeMatch.Groups[3].Success ? new DateTime(2000, 1, 1, int.Parse(timeMatch.Groups[3].Value), int.Parse(timeMatch.Groups[4].Value), 0) : arrivalTime; // If the time is prior to this train's start time, assume it is rolling over in to "tomorrow". if (arrivalTime < StartTime) { arrivalTime = arrivalTime.AddDays(1); departureTime = departureTime.AddDays(1); } stops.Add(new Stop(file.Strings[row][0].Replace(" $hold", "").Replace(" $forcehold", ""), arrivalTime, departureTime)); } } } Stops = stops.OrderBy(s => s.ArrivalTime); Consist = file.Strings[consistRow][serviceColumn].Replace(" $reverse", ""); Reversed = file.Strings[consistRow][serviceColumn].Contains(" $reverse"); Path = file.Strings[pathRow][serviceColumn]; } }
public IActionResult AddService(AddServiceViewModel model) { if (ModelState.IsValid) { Car car = _carsrepository.GetCar(model.CarId); Service service = new Service { CarId = model.CarId, ClientId = model.ServiceFacilityId, Milage = model.Milage, Date = model.Date, ServiceType = model.ServiceType, Cost = model.Cost, Id = new Guid() }; MilageRecord record = new MilageRecord { CarId = service.CarId, Date = service.Date, Milage = service.Milage, Id = Guid.NewGuid() }; _milageRecordsRepository.Add(record); Guid fileid = Guid.Empty; if (model.IsInvoiceAdded) { FileHandler fileHandler = new FileHandler(); FileDescription fileDescription = fileHandler.UploadSingleFile(model.File, FileType.Serwis, car.RegistrationNumber, model.Date); _fileDescriptionsRepository.Create(fileDescription); Invoice invoice = new Invoice { Id = Guid.NewGuid(), Number = model.Number, Date = model.Date, Amount = model.Cost, ClientId = model.ServiceFacilityId, InvoiceType = InvoiceType.Koszt, FileDescriptionId = fileDescription.Id }; _invoicesRepository.Add(invoice); service.InvoiceId = invoice.Id; fileid = fileDescription.Id; } car.Milage = model.Milage; car.NextServiceMilage = model.Milage + car.ServiceInterval; _carsrepository.Update(car); _sevicesRepository.Add(service); if (model.IsInvoiceAdded) { ServiceFile serviceFile = new ServiceFile { ServiceId = service.Id, FileDescriptionId = fileid }; _serviceFilesRepository.Add(serviceFile); } return(RedirectToAction("details", "cars", new { id = model.CarId })); } return(RedirectToAction("addservice", "services", new { id = model.CarId })); }