예제 #1
0
        public ActionResult LockAndCreate(string RoadmapGroupID)
        {
            try
            {
                AgentBase       ABase = new AgentBase();
                DatabaseContext dbx   = ABase.GetContext();

                RoadmapGroup group = dbx.RMManager.GetRoadmapGroup(Convert.ToInt32(RoadmapGroupID), false);
                dbx.RMManager.LockAndCreate(group.RoadmapGroupId);
                group.ConvertToVehicleInput_Status = Reco3_Enums.ConvertToVehicleInputStatus.Processing;
                dbx.SaveChanges();
                return(Json(new { success = true, message = "RoadmapGroup successfully locked." }, JsonRequestBehavior.AllowGet));

                /*
                 * if (true == dbx.RMManager.SaveRoadmap(Convert.ToInt32(StartYear), Convert.ToInt32(EndYear), Alias, Convert.ToInt32(RoadmapGroupID)))
                 *  return Json(new { success = true, message = "RoadmapGroup successfully updated." }, JsonRequestBehavior.AllowGet);
                 * return Json(new { success = false, message = "Failed to save roadmapGroup. Internal error while finding the targetmap." }, JsonRequestBehavior.AllowGet);
                 */
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(Json(new { success = false, message = e.Message }, JsonRequestBehavior.AllowGet));
            }


            //return RedirectToAction("Index");
        }
예제 #2
0
 public bool SaveRoadmap(int nStartYear, int nEndYear, string Alias, int nRoadmapGroupId)
 {
     try
     {
         // Get the roadmap, create if missing
         RoadmapGroup map = GetRoadmapGroup(nRoadmapGroupId, true);
         if (map != null)
         {
             map.StartYear   = nStartYear;
             map.EndYear     = nEndYear;
             map.RoadmapName = Alias;
             // If the roadmapgroup is newly created, add it to the database
             if (map.RoadmapGroupId == -1)
             {
                 DbCtx.RoadmapGroups.Add(map);
             }
             DbCtx.SaveChanges();
             return(true);
         }
     }
     catch
     {
     }
     return(false);
 }
예제 #3
0
 public bool GenerateRoadmapsForGroup(RoadmapGroup group)
 {
     try
     {
         List <Roadmap> maps = GetRoadmaps(group.RoadmapGroupId);
     }
     catch
     {
     }
     return(false);
 }
예제 #4
0
        public void Insert(RoadmapGroupDto data)
        {
            using (var ctx = DbContextManager <Reco4Context> .GetManager(_dbName)) {
                var item = new RoadmapGroup {
                    OwnerSss                     = data.OwnerSss,
                    RoadmapName                  = data.RoadmapName,
                    Protected                    = data.Protected,
                    CreationTime                 = data.CreationTime,
                    StartYear                    = data.StartYear,
                    EndYear                      = data.EndYear,
                    Xml                          = data.Xml,
                    Validation_Status            = data.ValidationStatusValue,
                    ConvertToVehicleInput_Status = data.ConvertToVehicleInputStatusValue
                };

                ctx.DbContext.RoadmapGroups.Add(item);
                ctx.DbContext.SaveChanges();
                data.RoadmapGroupId = item.RoadmapGroupId;
            }
        }
예제 #5
0
 public RoadmapGroup GetRoadmapGroup(int nGroupId, bool bCreateIfMissing)
 {
     try
     {
         RoadmapGroup map = DbCtx
                            .RoadmapGroups
                            .Include("Roadmaps")
                            .Where(x => x.RoadmapGroupId == nGroupId)
                            .FirstOrDefault();
         if ((map == null) &&
             (bCreateIfMissing == true))
         {
             map = new RoadmapGroup();
         }
         return(map);
     }
     catch
     {
     }
     return(null);
 }
예제 #6
0
        public bool LockAndCreate(int nRoadmapGroupId)
        {
            try
            {
                // Get the roadmap, do not create if missing
                RoadmapGroup mapGroup = GetRoadmapGroup(nRoadmapGroupId, false);
                if (mapGroup != null)
                {
                    // Get the submaps (one per year in the roadmapgroup)
                    List <Roadmap> maps = GetRoadmaps(mapGroup.RoadmapGroupId);
                    if (maps != null)
                    {
                        // This should not be the case!
                    }

                    int nCurrentYear = mapGroup.StartYear;
                    do
                    {
                        Roadmap tempMap = maps.Find(x => x.CurrentYear == nCurrentYear);
                        if (tempMap == null)
                        {
                            // This creates a new roadmap, with all properties from the RoadmapGroup
                            //  except for the xml, and that the start/end-year is set to nCurrentYear
                            DbCtx.Roadmaps.Add(new Roadmap(mapGroup, nCurrentYear));
                        }
                    } while (++nCurrentYear <= mapGroup.EndYear);

                    DbCtx.SaveChanges();
                    return(true);
                }
                return(false);
            }
            catch
            {
            }
            return(false);
        }
예제 #7
0
 public ActionResult Edit(int id = 0)
 {
     if (id == -1)
     {
         Co2RoadmapModel model = new Co2RoadmapModel();
         model.ReadOnly   = false;
         model.Co2Roadmap = new RoadmapGroup();
         return(View(model));
     }
     else
     {
         AgentBase       ABase = new AgentBase();
         DatabaseContext dbx   = ABase.GetContext();
         RoadmapGroup    job   = dbx.RoadmapGroups.Include("Roadmaps").Where(x => x.RoadmapGroupId == id).First();
         if (job != null)
         {
             Co2RoadmapModel model = new Co2RoadmapModel();
             model.Co2Roadmap = job;
             model.ReadOnly   = (job.ConvertToVehicleInput_Status != Reco3_Enums.ConvertToVehicleInputStatus.Pending);
             return(View(model));
         }
     }
     return(Index());
 }
예제 #8
0
        public bool ConvertToTUGVehicles(string strVehicleTemplateFile,
                                         string strSignatureFile,
                                         string strAxleTemplateFile,
                                         string strVectoXsd,
                                         bool bEnsureSignatureIsPresent,
                                         RoadmapGroup group,
                                         Roadmap map,
                                         DatabaseContext dbx,
                                         string strFailedWinsLogFile,
                                         string strPatchListFile)
        {
            int nCount = 0;

            try
            {
                Log.Debug("=>ConvertToTUGVehicles");
                XNamespace ns = Reco3Common.Reco3_Defines.DeclarationNamespace;
                XElement   signatureTemplate = XElement.Load(strSignatureFile);
                XElement   signatureNode     = signatureTemplate.Descendants(ns + "Signature").FirstOrDefault();

                XElement axleTemplate     = XElement.Load(strAxleTemplateFile);
                XElement axleTemplateNode = axleTemplate.Descendants(ns + "Axle").FirstOrDefault();


                XElement vehicleTemplate = XElement.Load(strVehicleTemplateFile);

                /*
                 * Roadmap previousmap = group.Roadmaps
                 *                          .OrderByDescending(x => x.CurrentYear)
                 *                          .Where(x => x.CurrentYear < map.CurrentYear)
                 *                          .First();
                 */

                Log.Debug("=>ConvertToTUGVehicles.Initialize");
                if (true == Converter.Initialize(ns, signatureNode, axleTemplateNode, DBContext, bEnsureSignatureIsPresent, map.CurrentYear))
                {
                    using (XmlReader schemaReader = XmlReader.Create(strVectoXsd))
                    {
                        // Prepare schemaset
                        XmlSchemaSet schemaSet = new XmlSchemaSet();
                        schemaSet.Add(XmlSchema.Read(schemaReader,
                                                     new ValidationEventHandler(
                                                         delegate(Object sender, ValidationEventArgs e) { }
                                                         )));

                        DateTime dtStart = DateTime.Now;

                        // Protect the roadmap for the time we process it, will change the status afterwards but the protection remains.
                        map.ImprovedVehicleCount         = 0;
                        map.ConvertToVehicleInput_Status = Reco3_Enums.ConvertToVehicleInputStatus.Processing;
                        map.Validation_Status            = Reco3_Enums.ValidationStatus.ValidatedWithSuccess;
                        map.Protected = true;
                        dbx.SaveChanges();


                        Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 vehicle-iteration");
                        List <Scania.Baseline.FailedPds.vehiclesVehicle> vehicleList = new List <Scania.Baseline.FailedPds.vehiclesVehicle>();
                        List <vehiclesVehicle> vehicles      = Vehicles.vehicle.ToList();
                        List <Vehicle>         readyVehicles = new List <Vehicle>();

                        // If we have a filtered VIN-list, then filter out the ones not listed
                        List <string> strlVinList = GetVINList(strPatchListFile);
                        if (strlVinList != null)
                        {
                            DateTime dtb4Filter = DateTime.Now;
                            var      hset       = new HashSet <string>(strlVinList);
                            vehicles = vehicles.Where(elem => hset.Contains(elem.VIN)).ToList();
                            DateTime dtafterFilter = DateTime.Now;

                            TimeSpan span = dtafterFilter.Subtract(dtb4Filter);
                        }


                        foreach (vehiclesVehicle vehicle in vehicles)
                        {
                            // Thread.Sleep(10);

                            nCount++;
                            Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 conversion: " + nCount + " VIN: " + vehicle.VIN);
                            // 1: Make a copy of the template
                            XElement currentVehicle = new XElement(vehicleTemplate);

                            Console.WriteLine("=>ConvertToTUGVehicles.Initialized. B4 conversion: " + nCount + " VIN: " + vehicle.VIN);

                            // 2: Construct the vehicle.xml
                            bool bContainsImprovements = false;
                            if (true == Converter.Convert2TUGVehicle(ref currentVehicle, vehicle, ref bContainsImprovements))
                            {
                                // 3: Validate against the schema from TUG
                                Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 validating against schema.");
                                bool      errors = false;
                                XDocument doc    = new XDocument(currentVehicle);
                                doc.Validate(schemaSet, (o, e) =>
                                {
                                    Log.Information("Schemafailure, vehicle: " + vehicle.VIN + ". " + e.Message);
                                    errors = true;
                                }, true);
                                if (errors == true)
                                {
                                    Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with failures...");

                                    /*
                                     * // Failures in the schema?
                                     * Scania.Baseline.FailedPds.vehiclesVehicle VIN = new Scania.Baseline.FailedPds.vehiclesVehicle();
                                     * VIN.VIN = vehicle.VIN;
                                     * VIN.SchemaFailures = new Scania.Baseline.FailedPds.vehiclesVehicleSchemaFailure[strErrorList.Count];
                                     * int n = 0;
                                     * foreach (string strError in strErrorList)
                                     * {
                                     *  vehiclesVehicleSchemaFailure failure = new vehiclesVehicleSchemaFailure();
                                     *  failure.description = strError;
                                     *  VIN.SchemaFailures[n++] = failure;
                                     * }
                                     *
                                     * vehicleList.Add(VIN);
                                     */
                                }
                                else
                                {
                                    try
                                    {
                                        Vehicle v = null;
                                        if (strlVinList != null)
                                        {
                                            v = dbx.Vehicle
                                                .Where(x => x.VIN == vehicle.VIN)
                                                .Where(x => x.GroupId == map.RoadmapId)
                                                .First();
                                        }
                                        if (v != null)
                                        {
                                            // Update the existing vehicle
                                            v.XML = doc.AsString();
                                            dbx.Entry(v).State = System.Data.Entity.EntityState.Modified;
                                            dbx.SaveChanges();

                                            // Update the report for this vehicle too
                                            var pRoadmapGroupId = new SqlParameter("@pRoadmapGroupId", group.RoadmapGroupId);
                                            var pRoadmapId      = new SqlParameter("@pRoadmapId", map.RoadmapId);
                                            var pVehicleId      = new SqlParameter("@pVehicleId", v.VehicleId);

                                            // I know!!!! This is fu##ing ugly but hey, if it offends you, stop reading, ok?
                                            dbx.Database.ExecuteSqlCommand("exec GenerateRoadmapReportForVehicleId @pRoadmapGroupId , @pRoadmapId , @pVehicleId", pRoadmapGroupId, pRoadmapId, pVehicleId);
                                        }
                                        else
                                        {
                                            dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId);
                                        }

                                        /*
                                         * Vehicle v = new Vehicle(doc.AsString(), map.RoadmapId);
                                         * v.Vehicle_Mode = Reco3_Enums.VehicleMode.VectoDeclaration;
                                         * v.GroupId = map.RoadmapId;
                                         * dbx.Vehicle.Add(v);
                                         */
                                        if (bContainsImprovements == true)
                                        {
                                            map.ImprovedVehicleCount += 1;
                                        }
                                        // dbx.SaveChanges();
                                        //TriggerEvent(v);
                                        GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                                        GC.Collect();



/*
 *                                      // 2.1: If no improvements where added,...
 *                                      if (bContainsImprovements == false)
 *                                      {
 *
 *                                          // ...and we have the previous map,...
 *                                          if (previousmap != null)
 *                                          {
 *                                              Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, no changes and we have a previous version, so making a copy.");
 *                                              // ...then fetch the previous version of the vehicle...
 *                                              Vehicle oldVehicle = dbx.Vehicle
 *                                                                      .Where(x => x.VIN == vehicle.VIN)
 *                                                                      .Where(x => x.GroupId == previousmap.RoadmapId)
 *                                                                      .First();
 *
 *                                              Vehicle clonedVehicle = oldVehicle.Clone();
 *                                              clonedVehicle.VehicleId = -1;
 *                                              clonedVehicle.GroupId = map.RoadmapId;
 *                                              dbx.Vehicle.Add(clonedVehicle);
 *                                              dbx.SaveChanges();
 *
 *                                              // ..and copy the vsum...
 *                                              List<VSumRecord> results = dbx.VSum.Where(x => x.VehicleId == oldVehicle.VehicleId).ToList();
 *                                              foreach (VSumRecord res in results)
 *                                              {
 *                                                  // ...clone the result, patch with the new vehicle-id and roadmap-id
 *                                                  VSumRecord resCopy = res.Clone();
 *                                                  resCopy.VehicleId = clonedVehicle.VehicleId;
 *                                                  resCopy.SimulationId = map.RoadmapId;
 *                                                  dbx.VSum.Add(resCopy);
 *                                              }
 *                                          }
 *                                          else
 *                                          {
 *                                              map.ImprovedVehicleCount += 1;
 *                                              Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, no changes but we dont have a previous version, so making a fresh vehicle.");
 *                                              // ...and we dont have the previous map so just add it as a new one...
 *                                              //dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId);
 *                                          }
 *
 *                                      }
 *                                      else
 *                                      {
 *                                          map.ImprovedVehicleCount += 1;
 *                                          Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, has changes so making a fresh vehicle.");
 *                                          // ...(has changes) so just add it as a new one...
 *                                          //dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId);
 *                                      }
 *                                      // ...and persist the changes...
 *                                      dbx.SaveChanges();
 *
 *                                      GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
 *                                      GC.Collect();
 */
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Fatal(ex, "ConvertToTUGVehicles.Exception while updating db:");
                                        Console.WriteLine("Exception while updating db: " + ex.Message);
                                    }
                                }
                                doc = null;
                            }
                            else
                            {
                                using (StreamWriter w = File.AppendText(strFailedWinsLogFile))
                                {
                                    w.WriteLine(vehicle.VIN);
                                }
                                Console.WriteLine("  ConvertToTUGVehicles==>Convert2TUGVehicle failed." + " (VIN: " + vehicle.VIN + ")");
                                Log.Debug("=>ConvertToTUGVehicles.Convert2TUGVehicle failed." + " (VIN: " + vehicle.VIN + ")");
                            }
                            currentVehicle = null;
                            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                            GC.Collect();
                        }

                        map.ConvertToVehicleInput_Status = Reco3_Enums.ConvertToVehicleInputStatus.ConvertedWithSuccess;
                        dbx.SaveChanges();
                        // Add the new failures,....
                        if (Converter.PDFailures.vehicle != null)
                        {
                            List <Scania.Baseline.FailedPds.vehiclesVehicle> tmpList = Converter.PDFailures.vehicle.ToList();
                            tmpList.AddRange(vehicleList);
                            Converter.PDFailures.vehicle = tmpList.ToArray();
                        }
                        else
                        {
                            Converter.PDFailures.vehicle = vehicleList.ToArray();
                        }

                        DateTime dtEnd = DateTime.Now;

                        Console.WriteLine("Conversion started: " + dtStart.ToShortDateString() + " " + dtStart.ToShortTimeString());
                        Console.WriteLine("Conversion done: " + dtEnd.ToShortDateString() + " " + dtEnd.ToShortTimeString());

                        Log.Debug("<=ConvertToTUGVehicles");
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "ConvertToTUGVehicles.OverallException");
                Console.WriteLine(ex);
            }
            Log.Debug("<=ConvertToTUGVehicles");
            return(false);
        }
예제 #9
0
        public ActionResult UploadBaseline(string RoadmapGroupId)
        {
            try
            {
                int nRoadmapGroupId = -1;
                if (RoadmapGroupId.Contains("-1") == true)
                {
                    logger.Debug("UploadBaseline failed, due to invalid GroupId (-1)");
                    return(Json(new { success = false, message = "Failed to upload baseline. Internal error: RoadmapId is invalid." }, JsonRequestBehavior.AllowGet));
                }
                nRoadmapGroupId = Convert.ToInt32(RoadmapGroupId);
                AgentBase       ABase = new AgentBase();
                DatabaseContext dbx   = ABase.GetContext();
                RoadmapGroup    map   = dbx.RMManager.GetRoadmapGroup(nRoadmapGroupId, false);
                if (map != null)
                {
                    if (map.Protected == true)
                    {
                        logger.Debug("UploadBaseline failed, due to locked roadmp");
                        return(Json(new { success = false, message = "Roadmap is locked for further changes. Action is aborted." }, JsonRequestBehavior.AllowGet));
                    }
                    if (Request.Files.Count > 0)
                    {
                        var    root          = "/Filedrop";
                        string strDropFolder = GetVirtualFolder(root);
                        if (strDropFolder.Length <= 0)
                        {
                            logger.Debug("UploadBaseline failed, due to filedrop-area is missing (Virtual folder");
                            return(Json(new { success = false, message = "Server-error, filedrop-area is missing (Virtual folder). Action is aborted." }, JsonRequestBehavior.AllowGet));
                        }


                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            // First save the stream to disk
                            var files    = Request.Files[i];
                            var fileName = System.IO.Path.GetFileName(files.FileName);
                            var path     = System.IO.Path.Combine(strDropFolder, fileName);
                            files.SaveAs(path);

                            var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
                            using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
                            {
                                string content = reader.ReadToEnd();


                                map.Validation_Status = Reco3_Enums.ValidationStatus.Processing;
                                map.XML = content;
                                dbx.SaveChanges();

                                // Lets validate the input
                                Reco3Config.ConfigModel Configuration = new ConfigModel(WebConfigurationManager.AppSettings["ConfigFile"]);
                                map.XMLSchemaFilename = "";
                                string strVectoSchemaFilename     = Configuration.Reco3Config.Schemas.ToList().Find(x => x.id == "Vecto.Declaration").filename;
                                string strConversionLogFile       = string.Format("{0}{1}", Configuration.Reco3Config.BackEnd.FilePaths.ToList().Find(x => x.id == "Log").path, "BaselineModel.b.Conversion.txt");
                                BaselineModel.BaselineModel fleet = new BaselineModel.BaselineModel(strConversionLogFile);
                                if (false == fleet.InitializeFromXML(map.XML, map.XMLSchemaFilename))
                                {
                                    // Tag the baseline as "not ok"
                                    map.Validation_Status = Reco3_Enums.ValidationStatus.ValidatedWithFailures;
                                    dbx.SaveChanges();
                                    logger.Debug("UploadBaseline failed, due to validation-error of the baseline");
                                    return(Json(new { success = false, message = "Failed to save roadmap. Internal error while validating the baseline using: " + map.XMLSchemaFilename + "." }, JsonRequestBehavior.AllowGet));
                                }

                                // Tag the baseline as "ok"
                                map.Validation_Status = Reco3_Enums.ValidationStatus.ValidatedWithSuccess;
                                dbx.SaveChanges();

                                /*
                                 * try
                                 * {
                                 *  // Indicating that there are no available roadmaps, so lets generated them
                                 *  int nRoadmapId = -1;
                                 *  if (nRoadmapId == -1)
                                 *  {
                                 *      for (int n = map.StartYear; n <= map.EndYear; n++)
                                 *      {
                                 *          Roadmap oldMap = map.Roadmaps.First(x => x.CurrentYear == n);
                                 *          if (oldMap == null)
                                 *          {
                                 *              Roadmap newMap = new Roadmap(map, n);
                                 *              map.Roadmaps.Add(newMap);
                                 *              dbx.SaveChanges();
                                 *              if (nRoadmapId == -1)
                                 *                  nRoadmapId = newMap.RoadmapId;
                                 *          }
                                 *
                                 *      }
                                 *  }
                                 * }
                                 * catch (Exception ex)
                                 * {
                                 *  logger.Debug("UploadBaseline failed, failed to create roadmaps. {0}", ex.Message);
                                 *  return Json(new { success = false, message = "Failed to create roadmaps for group : " + ex.Message }, JsonRequestBehavior.AllowGet);
                                 * }
                                 */


                                // Post a msmq-msg to indicate the newly uploaded file!
                                BatchQueue.BatchQueue queue = new BatchQueue.BatchQueue();
                                queue.IsLocalQueue = true;
                                queue.SetRecieverEndpoint(Configuration.Reco3Config.MSMQ.HostName, Configuration.Reco3Config.MSMQ.ConversionQueue);

                                // Must look at this again!....
                                foreach (Roadmap map2 in map.Roadmaps)
                                {
                                    if (map2.Protected == false)
                                    {
                                        queue.SendMsg(new Reco3Msg(map.RoadmapGroupId, map2.RoadmapId));
                                    }
                                }
                                return(Json(new { success = true, message = "File uploaded successfully, file is queued for validation." }, JsonRequestBehavior.AllowGet));
                            }
                        }
                        return(Json(new { success = false, message = "Failed to save roadmap. Internal error while finding the targetmap." }, JsonRequestBehavior.AllowGet));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet));
            }
            return(Json(new { success = false, message = "Fatal error!" }, JsonRequestBehavior.AllowGet));
        }