diff options
12 files changed, 386 insertions, 309 deletions
diff --git a/Software/Visual_Studio/Tango.Logging/VSOutputLogger.cs b/Software/Visual_Studio/Tango.Logging/VSOutputLogger.cs index 66a11c7df..a39f14593 100644 --- a/Software/Visual_Studio/Tango.Logging/VSOutputLogger.cs +++ b/Software/Visual_Studio/Tango.Logging/VSOutputLogger.cs @@ -18,11 +18,11 @@ namespace Tango.Logging /// <summary> /// Initializes a new instance of the <see cref="VSOutputLogger"/> class. /// </summary> - public VSOutputLogger() + public VSOutputLogger(String projectName = null) { Enabled = true; - _assembly_name = Assembly.GetEntryAssembly().GetName().Name + ": "; + _assembly_name = projectName != null ? projectName : Assembly.GetEntryAssembly().GetName().Name + ": "; } /// <summary> diff --git a/Software/Visual_Studio/Tango.UnitTesting/MachineService_TST.cs b/Software/Visual_Studio/Tango.UnitTesting/MachineService_TST.cs new file mode 100644 index 000000000..4afa31edf --- /dev/null +++ b/Software/Visual_Studio/Tango.UnitTesting/MachineService_TST.cs @@ -0,0 +1,27 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tango.PMR.Synchronization; +using Tango.Transport.Web; + +namespace Tango.UnitTesting +{ + [TestClass] + [TestCategory("Machine Service")] + public class MachineService_TST + { + [TestMethod] + public void Check_For_Updates() + { + ITransportWebClient client = new ProtoWebClient(); + var result = client.Post<CheckForUpdateRequest, CheckForUpdateResponse>("http://localhost:51581/api/Synchronization/CheckForUpdate", new CheckForUpdateRequest() + { + SerialNumber = "0000", + Version = "0.0.0.0", + }).Result; + } + } +} diff --git a/Software/Visual_Studio/Tango.UnitTesting/Tango.UnitTesting.csproj b/Software/Visual_Studio/Tango.UnitTesting/Tango.UnitTesting.csproj index 98e43d0a6..aa8b71dd1 100644 --- a/Software/Visual_Studio/Tango.UnitTesting/Tango.UnitTesting.csproj +++ b/Software/Visual_Studio/Tango.UnitTesting/Tango.UnitTesting.csproj @@ -94,6 +94,7 @@ <Compile Include="ColorCatalogs_TST.cs" /> <Compile Include="DependencyInjection_TST.cs" /> <Compile Include="Logging_TST.cs" /> + <Compile Include="MachineService_TST.cs" /> <Compile Include="MachineStudio_TST.cs" /> <Compile Include="RemoteRunner_TST.cs" /> <Compile Include="SQLExaminer_TST.cs" /> @@ -210,7 +211,7 @@ <Import Project="..\packages\System.Data.SQLite.Core.1.0.108.0\build\net46\System.Data.SQLite.Core.targets" Condition="Exists('..\packages\System.Data.SQLite.Core.1.0.108.0\build\net46\System.Data.SQLite.Core.targets')" /> <ProjectExtensions> <VisualStudio> - <UserProperties BuildVersion_AssemblyInfoFilename="Properties\AssemblyInfo.cs" BuildVersion_UpdateAssemblyVersion="True" BuildVersion_BuildVersioningStyle="None.None.Increment.TimeStamp" BuildVersion_UseGlobalSettings="False" BuildVersion_StartDate="2000/1/1" /> + <UserProperties BuildVersion_StartDate="2000/1/1" BuildVersion_UseGlobalSettings="False" BuildVersion_BuildVersioningStyle="None.None.Increment.TimeStamp" BuildVersion_UpdateAssemblyVersion="True" BuildVersion_AssemblyInfoFilename="Properties\AssemblyInfo.cs" /> </VisualStudio> </ProjectExtensions> </Project>
\ No newline at end of file diff --git a/Software/Visual_Studio/Web/Tango.MachineService/App_Start/RouteConfig.cs b/Software/Visual_Studio/Web/Tango.MachineService/App_Start/RouteConfig.cs index 33fa703a8..60453c3a1 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/App_Start/RouteConfig.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/App_Start/RouteConfig.cs @@ -13,11 +13,11 @@ namespace Tango.MachineService { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); - routes.MapRoute( - name: "Default", - url: "{controller}/{action}/{id}", - defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } - ); + //routes.MapRoute( + // name: "Default", + // url: "{controller}/{action}/{id}", + // defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } + //); } } } diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/SynchronizationController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/SynchronizationController.cs index 5c5a13c4e..304ea34f2 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/SynchronizationController.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/SynchronizationController.cs @@ -10,6 +10,7 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Http; +using System.Security.Authentication; using System.Threading.Tasks; using System.Web.Hosting; using System.Web.Http; @@ -30,113 +31,103 @@ using Tango.Synchronization.Remote; namespace Tango.MachineService.Controllers { - public class SynchronizationController : ApiController + public class SynchronizationController : ProtoController { - private LogManager logManager = LogManager.Default; + ///// <summary> + ///// Expects a DB synchronization request from a remote machine and returns the synchronized version of the machine database. + ///// </summary> + ///// <param name="request">The request.</param> + ///// <returns></returns> + //[HttpPost] + //public SynchronizeDBResponse Synchronize(SynchronizeDBRequest request) + //{ + // var tempFolder = TemporaryManager.Default.CreateFolder(); - /// <summary> - /// Expects a DB synchronization request from a remote machine and returns the synchronized version of the machine database. - /// </summary> - /// <param name="request">The request.</param> - /// <returns></returns> - [HttpPost] - public SynchronizeDBResponse Synchronize(SynchronizeDBRequest request) - { - var tempFolder = TemporaryManager.Default.CreateFolder(); + // try + // { + // //File path for the reflected remote data base SQLite. + // String masterSQLiteFile = Path.Combine(tempFolder, "Remote.db"); + // //File path for the received machine SQLite db. + // String slaveSQLiteFile = Path.Combine(tempFolder, "Local.db"); - try - { - //File path for the reflected remote data base SQLite. - String masterSQLiteFile = Path.Combine(tempFolder, "Remote.db"); - //File path for the received machine SQLite db. - String slaveSQLiteFile = Path.Combine(tempFolder, "Local.db"); + // //Save the machine db to file. + // File.WriteAllBytes(slaveSQLiteFile, request.LocalDB.ToByteArray()); - //Save the machine db to file. - File.WriteAllBytes(slaveSQLiteFile, request.LocalDB.ToByteArray()); + // //Copy an SQLite db template. + // File.Copy(HostingEnvironment.MapPath(@"~/App_Data/Tango.db"), masterSQLiteFile); - //Copy an SQLite db template. - File.Copy(HostingEnvironment.MapPath(@"~/App_Data/Tango.db"), masterSQLiteFile); + // //Synchronize the SQL Server db with the new SQLite template. (Overwrite basically) + // RemoteDBSynchronizer.Synchronize(masterSQLiteFile, request.SerialNumber, true); - //Synchronize the SQL Server db with the new SQLite template. (Overwrite basically) - RemoteDBSynchronizer.Synchronize(masterSQLiteFile, request.SerialNumber, true); + // //Synchronize the received machine db with the filled template. + // LocalDBSynchronizer.Synchronize(masterSQLiteFile, slaveSQLiteFile); - //Synchronize the received machine db with the filled template. - LocalDBSynchronizer.Synchronize(masterSQLiteFile, slaveSQLiteFile); + // //Send the synchronized machine db to the machine to the machine. + // SynchronizeDBResponse response = new SynchronizeDBResponse(); + // response.RemoteDB = ByteString.CopyFrom(File.ReadAllBytes(slaveSQLiteFile)); - //Send the synchronized machine db to the machine to the machine. - SynchronizeDBResponse response = new SynchronizeDBResponse(); - response.RemoteDB = ByteString.CopyFrom(File.ReadAllBytes(slaveSQLiteFile)); - - return response; - } - catch (Exception) - { - throw; - } - finally - { - //Remove all temporary files and folder. - tempFolder.Delete(); - } - } + // return response; + // } + // catch (Exception) + // { + // throw; + // } + // finally + // { + // //Remove all temporary files and folder. + // tempFolder.Delete(); + // } + //} [HttpPost] public MachineSetupResponse MachineSetup(MachineSetupRequest request) { MachineSetupResponse response = new MachineSetupResponse(); - logManager.Log("Setup request received: " + request.ToString()); + LogManager.Log("Setup request received: " + request.ToString()); - try + using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { - using (ObservablesContext db = ObservablesContextHelper.CreateContext()) - { - db.Configuration.LazyLoadingEnabled = false; - String serial_number = request.SerialNumber; + db.Configuration.LazyLoadingEnabled = false; + String serial_number = request.SerialNumber; - var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number); + var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number); - if (machine == null) - { - ThrowError(HttpStatusCode.NotFound, "The specified serial number could not be found."); - } + if (machine == null) + { + throw new AuthenticationException("The specified serial number could not be found."); + } - var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid); + var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid); - var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); + var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); - response.Version = latest_machine_version.Version; + response.Version = latest_machine_version.Version; - var client = StorageHelper.GetStorageBlobClient(); - var container = StorageHelper.GetTangoVersionsContainer(client); - var blob = container.GetBlockBlobReference(latest_machine_version.BlobName); + var client = StorageHelper.GetStorageBlobClient(); + var container = StorageHelper.GetTangoVersionsContainer(client); + var blob = container.GetBlockBlobReference(latest_machine_version.BlobName); - response.BlobAddress = StorageHelper.GenerateBlobReadSignature(blob, TimeSpan.FromMinutes(60)); + response.BlobAddress = StorageHelper.GenerateBlobReadSignature(blob, TimeSpan.FromMinutes(60)); - DbCredentials credentials = new DbCredentials(); + DbCredentials credentials = new DbCredentials(); - using (SmoManager manager = new SmoManager()) - { - credentials = manager.CreateRandomLoginAndUser(); + using (SmoManager manager = new SmoManager()) + { + credentials = manager.CreateRandomLoginAndUser(); - Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) => + Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) => + { + using (SmoManager m = new SmoManager()) { - using (SmoManager m = new SmoManager()) - { - m.DeleteLoginAndUser(credentials.UserName); - } - }); - } - - response.DbAddress = Config.DB_ADDRESS; - response.DbUserName = credentials.UserName; - response.DbPassword = credentials.Password; + m.DeleteLoginAndUser(credentials.UserName); + } + }); } - } - catch (Exception ex) - { - logManager.Log(ex); - throw; + + response.DbAddress = Config.DB_ADDRESS; + response.DbUserName = credentials.UserName; + response.DbPassword = credentials.Password; } return response; @@ -147,55 +138,48 @@ namespace Tango.MachineService.Controllers { DownloadUpdateResponse response = new DownloadUpdateResponse(); - try + using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { - using (ObservablesContext db = ObservablesContextHelper.CreateContext()) - { - db.Configuration.LazyLoadingEnabled = false; - String serial_number = request.SerialNumber; + db.Configuration.LazyLoadingEnabled = false; + String serial_number = request.SerialNumber; - var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number); + var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number); - if (machine == null) - { - OnError(HttpStatusCode.NotFound, "The specified serial number could not be found."); - } + if (machine == null) + { + throw new AuthenticationException("The specified serial number could not be found."); + } - var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid); + var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid); - var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); + var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); - response.Version = latest_machine_version.Version; + response.Version = latest_machine_version.Version; - var client = StorageHelper.GetStorageBlobClient(); - var container = StorageHelper.GetTangoVersionsContainer(client); - var blob = container.GetBlockBlobReference(latest_machine_version.BlobName); + var client = StorageHelper.GetStorageBlobClient(); + var container = StorageHelper.GetTangoVersionsContainer(client); + var blob = container.GetBlockBlobReference(latest_machine_version.BlobName); - response.BlobAddress = StorageHelper.GenerateBlobReadSignature(blob, TimeSpan.FromMinutes(60)); + response.BlobAddress = StorageHelper.GenerateBlobReadSignature(blob, TimeSpan.FromMinutes(60)); - DbCredentials credentials = new DbCredentials(); + DbCredentials credentials = new DbCredentials(); - using (SmoManager manager = new SmoManager()) - { - credentials = manager.CreateRandomLoginAndUser(); + using (SmoManager manager = new SmoManager()) + { + credentials = manager.CreateRandomLoginAndUser(); - Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) => + Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) => + { + using (SmoManager m = new SmoManager()) { - using (SmoManager m = new SmoManager()) - { - m.DeleteLoginAndUser(credentials.UserName); - } - }); - } - - response.DbAddress = Config.DB_ADDRESS; - response.DbUserName = credentials.UserName; - response.DbPassword = credentials.Password; + m.DeleteLoginAndUser(credentials.UserName); + } + }); } - } - catch (Exception ex) - { - OnError(HttpStatusCode.InternalServerError, ex.Message); + + response.DbAddress = Config.DB_ADDRESS; + response.DbUserName = credentials.UserName; + response.DbPassword = credentials.Password; } return response; @@ -206,34 +190,27 @@ namespace Tango.MachineService.Controllers { CheckForUpdateResponse response = new CheckForUpdateResponse(); - try + using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { - using (ObservablesContext db = ObservablesContextHelper.CreateContext()) - { - db.Configuration.LazyLoadingEnabled = false; - - var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == request.SerialNumber); + db.Configuration.LazyLoadingEnabled = false; - if (machine == null) - { - OnError(HttpStatusCode.NotFound, "The specified serial number could not be found."); - } + var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == request.SerialNumber); - var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid); + if (machine == null) + { + throw new AuthenticationException("The specified serial number could not be found."); + } - var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); + var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid); - if (Version.Parse(latest_machine_version.Version) > Version.Parse(request.Version)) - { - response.IsUpdateAvailable = true; - } + var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault(); - response.Version = latest_machine_version.Version; + if (Version.Parse(latest_machine_version.Version) > Version.Parse(request.Version)) + { + response.IsUpdateAvailable = true; } - } - catch (Exception ex) - { - OnError(HttpStatusCode.InternalServerError, ex.Message); + + response.Version = latest_machine_version.Version; } return response; @@ -244,43 +221,36 @@ namespace Tango.MachineService.Controllers { UpdateDBResponse response = new UpdateDBResponse(); - try + using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { - using (ObservablesContext db = ObservablesContextHelper.CreateContext()) - { - db.Configuration.LazyLoadingEnabled = false; - String serial_number = request.SerialNumber; + db.Configuration.LazyLoadingEnabled = false; + String serial_number = request.SerialNumber; - var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number); + var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number); - if (machine == null) - { - OnError(HttpStatusCode.NotFound, "The specified serial number could not be found."); - } + if (machine == null) + { + throw new AuthenticationException("The specified serial number could not be found."); + } - DbCredentials credentials = new DbCredentials(); + DbCredentials credentials = new DbCredentials(); - using (SmoManager manager = new SmoManager()) - { - credentials = manager.CreateRandomLoginAndUser(); + using (SmoManager manager = new SmoManager()) + { + credentials = manager.CreateRandomLoginAndUser(); - Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) => + Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) => + { + using (SmoManager m = new SmoManager()) { - using (SmoManager m = new SmoManager()) - { - m.DeleteLoginAndUser(credentials.UserName); - } - }); - } - - response.DbAddress = Config.DB_ADDRESS; - response.DbUserName = credentials.UserName; - response.DbPassword = credentials.Password; + m.DeleteLoginAndUser(credentials.UserName); + } + }); } - } - catch (Exception ex) - { - OnError(HttpStatusCode.InternalServerError, ex.Message); + + response.DbAddress = Config.DB_ADDRESS; + response.DbUserName = credentials.UserName; + response.DbPassword = credentials.Password; } return response; @@ -299,18 +269,5 @@ namespace Tango.MachineService.Controllers return machine; } } - - #region Helpers - - private void ThrowError(HttpStatusCode code, String message) - { - throw new WebApiException(code, message); - } - - private void OnError(HttpStatusCode code, String message) - { - throw new HttpResponseException(Request.CreateErrorResponse(code, message)); - } - #endregion } } diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/VersionUpdateController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/VersionUpdateController.cs index 953399530..b68da06a7 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/VersionUpdateController.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/VersionUpdateController.cs @@ -14,10 +14,8 @@ using Tango.PPC.Common.Update; namespace Tango.MachineService.Controllers { - public class VersionUpdateController : ApiController + public class VersionUpdateController : JsonController { - private LogManager LogManager = LogManager.Default; - private class PendingUpload { public String Token { get; set; } @@ -43,158 +41,118 @@ namespace Tango.MachineService.Controllers [HttpPost] public LatestVersionResponse GetLatestVersion(LatestVersionRequest request) { - try + LatestVersionResponse response = new LatestVersionResponse(); + + using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { - LatestVersionResponse response = new LatestVersionResponse(); + var versions = db.TangoVersions.Where(x => x.MachineVersionGuid == request.MachineVersionGuid).ToList(); - using (ObservablesContext db = ObservablesContextHelper.CreateContext()) + if (versions.Count > 0) { - var versions = db.TangoVersions.Where(x => x.MachineVersionGuid == request.MachineVersionGuid).ToList(); - - if (versions.Count > 0) - { - response.Version = db.TangoVersions.Where(x => x.MachineVersionGuid == request.MachineVersionGuid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault().Version; - } - else - { - return new LatestVersionResponse() - { - Version = "0.0.0.0" - }; - } + response.Version = db.TangoVersions.Where(x => x.MachineVersionGuid == request.MachineVersionGuid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault().Version; + } + else + { + throw new ArgumentException("The specified machine version was not found!"); } - - return response; - } - catch (Exception ex) - { - throw CreateError(ex, HttpStatusCode.InternalServerError); } + + return response; } [HttpPost] public UploadVersionResponse UploadVersion(UploadVersionRequest request) { - try + UploadVersionResponse response = new UploadVersionResponse(); + + using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { - UploadVersionResponse response = new UploadVersionResponse(); + //Load relations first... + db.Roles.ToList(); + db.Permissions.ToList(); + db.UsersRoles.ToList(); + db.RolesPermissions.ToList(); - using (ObservablesContext db = ObservablesContextHelper.CreateContext()) + var user = db.Users.SingleOrDefault(x => x.Email.ToLower() == request.Email.ToLower() && x.Password == request.Password); + + if (user != null && user.HasPermission(Permissions.PublishMachineStudioVersion)) { - //Load relation first... - db.Roles.ToList(); - db.Permissions.ToList(); - db.UsersRoles.ToList(); - db.RolesPermissions.ToList(); + var versions = db.TangoVersions.ToList().Where(x => x.MachineVersionGuid == request.MachineVersionGuid).OrderByDescending(x => Version.Parse(x.Version)).ToList(); - var user = db.Users.SingleOrDefault(x => x.Email.ToLower() == request.Email.ToLower() && x.Password == request.Password); + TangoVersion latestVersion = new TangoVersion(); + latestVersion.Version = "0.0.0.0"; - if (user != null && user.HasPermission(Permissions.PublishMachineStudioVersion)) + if (versions.Count > 0) { - var versions = db.TangoVersions.ToList().Where(x => x.MachineVersionGuid == request.MachineVersionGuid).OrderByDescending(x => Version.Parse(x.Version)).ToList(); - - TangoVersion latestVersion = new TangoVersion(); - latestVersion.Version = "0.0.0.0"; - - if (versions.Count > 0) - { - latestVersion = versions.FirstOrDefault(); - } + latestVersion = versions.FirstOrDefault(); + } - Version currentVersion = Version.Parse(request.Version); + Version currentVersion = Version.Parse(request.Version); - if (currentVersion > Version.Parse(latestVersion.Version)) - { - String newVersionFileName = "Tango Version" + " " + currentVersion.ToString() + ".zip"; + if (currentVersion > Version.Parse(latestVersion.Version)) + { + String newVersionFileName = "Tango Version" + " " + currentVersion.ToString() + ".zip"; - var client = StorageHelper.GetStorageBlobClient(); - var container = StorageHelper.GetTangoVersionsContainer(client); - var blob = StorageHelper.CreateEmptyBlob(container, newVersionFileName); + var client = StorageHelper.GetStorageBlobClient(); + var container = StorageHelper.GetTangoVersionsContainer(client); + var blob = StorageHelper.CreateEmptyBlob(container, newVersionFileName); - response.Token = Guid.NewGuid().ToString(); - response.BlobAddress = StorageHelper.GenerateBlobWriteSignature(blob, TimeSpan.FromMinutes(30)); + response.Token = Guid.NewGuid().ToString(); + response.BlobAddress = StorageHelper.GenerateBlobWriteSignature(blob, TimeSpan.FromMinutes(30)); - _pendingUploads.Add(new PendingUpload() - { - UserGuid = user.Guid, - Comments = request.Comments, - Token = response.Token, - Version = request.Version, - BlobName = blob.Name, - MachineVersionGuid = request.MachineVersionGuid, - }); - } - else + _pendingUploads.Add(new PendingUpload() { - throw CreateError(new ArgumentException("New version must be greater than latest version."), HttpStatusCode.BadRequest); - } + UserGuid = user.Guid, + Comments = request.Comments, + Token = response.Token, + Version = request.Version, + BlobName = blob.Name, + MachineVersionGuid = request.MachineVersionGuid, + }); } else { - throw CreateError(new AuthenticationException("Invalid user credentials."), HttpStatusCode.Unauthorized); + throw new ArgumentException("New version must be greater than latest version."); } } - - return response; - } - catch (HttpResponseException ex) - { - throw ex; - } - catch (Exception ex) - { - LogManager.Log(ex); - throw CreateError(ex, HttpStatusCode.InternalServerError); + else + { + throw new AuthenticationException("Invalid user credentials."); + } } + + return response; } [HttpPost] public UploadCompletedResponse NotifyUploadCompleted(UploadCompletedRequest request) { - try + PendingUpload upload = _pendingUploads.FirstOrDefault(x => x.Token == request.Token); + + if (upload != null) { - PendingUpload upload = _pendingUploads.FirstOrDefault(x => x.Token == request.Token); + _pendingUploads.RemoveAll(x => x.Token == upload.Token); - if (upload != null) + using (ObservablesContext db = ObservablesContextHelper.CreateContext()) { - _pendingUploads.RemoveAll(x => x.Token == upload.Token); - - using (ObservablesContext db = ObservablesContextHelper.CreateContext()) + db.TangoVersions.Add(new TangoVersion() { - db.TangoVersions.Add(new TangoVersion() - { - Comments = upload.Comments, - BlobName = upload.BlobName, - UserGuid = upload.UserGuid, - Version = upload.Version, - MachineVersionGuid = upload.MachineVersionGuid - }); - - db.SaveChanges(); - } + Comments = upload.Comments, + BlobName = upload.BlobName, + UserGuid = upload.UserGuid, + Version = upload.Version, + MachineVersionGuid = upload.MachineVersionGuid + }); - return new UploadCompletedResponse(); - } - else - { - throw CreateError(new AuthenticationException("Invalid Token."), HttpStatusCode.Unauthorized); + db.SaveChanges(); } + + return new UploadCompletedResponse(); } - catch (HttpRequestException ex) - { - throw ex; - } - catch (Exception ex) + else { - LogManager.Log(ex); - throw CreateError(ex, HttpStatusCode.InternalServerError); + throw new AuthenticationException("Invalid upload token."); } } - - private Exception CreateError(Exception ex, HttpStatusCode code) - { - LogManager.Log(ex); - return new HttpResponseException(Request.CreateErrorResponse(code, ex.Message)); - } } } diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Global.asax.cs b/Software/Visual_Studio/Web/Tango.MachineService/Global.asax.cs index ffb8042e2..d90d11d15 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Global.asax.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Global.asax.cs @@ -30,6 +30,7 @@ namespace Tango.MachineService RouteConfig.RegisterRoutes(RouteTable.Routes); LogManager.Default.RegisterLogger(new FileLogger()); + LogManager.Default.RegisterLogger(new VSOutputLogger("MachineService")); //register your filter with Web API pipeline GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute()); diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Helpers/ObservablesContextHelper.cs b/Software/Visual_Studio/Web/Tango.MachineService/Helpers/ObservablesContextHelper.cs index 8f096b0ca..fff0eebea 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Helpers/ObservablesContextHelper.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/Helpers/ObservablesContextHelper.cs @@ -12,19 +12,14 @@ namespace Tango.MachineService.Helpers { public static ObservablesContext CreateContext() { - String address = ConfigurationManager.AppSettings["DbAddress"].ToString(); - String userName = ConfigurationManager.AppSettings["DbUserName"].ToString(); - String password = ConfigurationManager.AppSettings["DbPassword"].ToString(); - String catalog = ConfigurationManager.AppSettings["DbCatalog"].ToString(); - return new ObservablesContext(new DataSource() { - Address = address, - Catalog = catalog, + Address = Config.DB_ADDRESS, + Catalog = Config.DB_CATALOG, IntegratedSecurity = false, Type = DataSourceType.SQLServer, - UserName = userName, - Password = password + UserName = Config.DB_USER_NAME, + Password = Config.DB_PASSWORD }); } } diff --git a/Software/Visual_Studio/Web/Tango.MachineService/JsonController.cs b/Software/Visual_Studio/Web/Tango.MachineService/JsonController.cs new file mode 100644 index 000000000..163a89589 --- /dev/null +++ b/Software/Visual_Studio/Web/Tango.MachineService/JsonController.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Security.Authentication; +using System.Threading; +using System.Threading.Tasks; +using System.Web; +using System.Web.Http; +using System.Web.Http.Controllers; +using Tango.Logging; + +namespace Tango.MachineService +{ + public class JsonController : ApiController + { + protected LogManager LogManager { get; private set; } + + public JsonController() + { + LogManager = LogManager.Default; + } + + public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext context, CancellationToken cancellationToken) + { + string controllerName = String.Empty; + string actionName = String.Empty; + + try + { + var routeData = HttpContext.Current.Request.RequestContext.RouteData; + actionName = routeData.Values["action"].ToString(); + controllerName = routeData.Values["controller"].ToString(); + } + catch { } + + try + { + String request = String.Empty; + + try + { + request = context.Request.Content.ReadAsStringAsync().Result; + } + catch {} + + LogManager.Log($"Request Received on {controllerName + "/" + actionName}: \n{request}"); + + var result = await base.ExecuteAsync(context, cancellationToken); + return result; + } + catch (Exception ex) + { + LogManager.Log(ex, $"An error occurred while processing the request message on {controllerName + "/" + actionName}."); + + HttpStatusCode code = HttpStatusCode.InternalServerError; + + if (ex is ArgumentException) + { + code = HttpStatusCode.BadRequest; + } + else if (ex is AuthenticationException) + { + code = HttpStatusCode.Unauthorized; + } + + throw new HttpResponseException(Request.CreateErrorResponse(code, ex.Message)); + } + } + } +}
\ No newline at end of file diff --git a/Software/Visual_Studio/Web/Tango.MachineService/ProtoBufFormatter.cs b/Software/Visual_Studio/Web/Tango.MachineService/ProtoBufFormatter.cs index ef233df7d..b82f1adef 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/ProtoBufFormatter.cs +++ b/Software/Visual_Studio/Web/Tango.MachineService/ProtoBufFormatter.cs @@ -123,7 +123,7 @@ namespace Tango.MachineService try { HttpProtoException msg = new HttpProtoException(); - msg.Message = httpError.ExceptionMessage; + msg.Message = httpError["Message"].ToString(); msg.StatusCode = (int)HttpStatusCode.InternalServerError; msg.WriteTo(stream); diff --git a/Software/Visual_Studio/Web/Tango.MachineService/ProtoController.cs b/Software/Visual_Studio/Web/Tango.MachineService/ProtoController.cs new file mode 100644 index 000000000..572604d3c --- /dev/null +++ b/Software/Visual_Studio/Web/Tango.MachineService/ProtoController.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Security.Authentication; +using System.Threading; +using System.Threading.Tasks; +using System.Web; +using System.Web.Http; +using System.Web.Http.Controllers; +using Tango.Logging; + +namespace Tango.MachineService +{ + public class ProtoController : ApiController + { + protected LogManager LogManager { get; private set; } + + public ProtoController() + { + LogManager = LogManager.Default; + } + + public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext context, CancellationToken cancellationToken) + { + string controllerName = String.Empty; + string actionName = String.Empty; + + try + { + var routeData = HttpContext.Current.Request.RequestContext.RouteData; + actionName = routeData.Values["action"].ToString(); + controllerName = routeData.Values["controller"].ToString(); + } + catch { } + + try + { + LogManager.Log($"Request Received on {controllerName + "/" + actionName}."); + + var result = await base.ExecuteAsync(context, cancellationToken); + return result; + } + catch (Exception ex) + { + LogManager.Log(ex, $"An error occurred while processing the request message on {controllerName + "/" + actionName}."); + + HttpStatusCode code = HttpStatusCode.InternalServerError; + + if (ex is ArgumentException) + { + code = HttpStatusCode.BadRequest; + } + else if (ex is AuthenticationException) + { + code = HttpStatusCode.Unauthorized; + } + + throw new HttpResponseException(Request.CreateErrorResponse(code, ex.Message)); + } + } + } +}
\ No newline at end of file diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Tango.MachineService.csproj b/Software/Visual_Studio/Web/Tango.MachineService/Tango.MachineService.csproj index 255ba88ea..9f0b2cba2 100644 --- a/Software/Visual_Studio/Web/Tango.MachineService/Tango.MachineService.csproj +++ b/Software/Visual_Studio/Web/Tango.MachineService/Tango.MachineService.csproj @@ -273,6 +273,7 @@ <Compile Include="Controllers\VersionUpdateController.cs" /> <Compile Include="Helpers\ObservablesContextHelper.cs" /> <Compile Include="Helpers\StorageHelper.cs" /> + <Compile Include="JsonController.cs" /> <Compile Include="JsonNetFormatter.cs" /> <Compile Include="ProtoBufFormatter.cs" /> <Compile Include="App_Start\RouteConfig.cs" /> @@ -285,6 +286,7 @@ </Compile> <Compile Include="Models\Person.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="ProtoController.cs" /> <Compile Include="SMO\SmoManager.cs" /> <Compile Include="WebApiException.cs" /> </ItemGroup> |
