Esempio n. 1
0
        /// <summary>
        /// Tracks the property changes.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">The entity.</param>
        /// <param name="propName">Name of the property.</param>
        /// <param name="oldValue">The old value.</param>
        /// <param name="newValue">The new value.</param>
        public void TrackProperty <T>(T entity, string propName, string oldValue, string newValue) where T : DomainObject
        {
            var name = typeof(T).Name;

            switch (typeof(T).Name)
            {
            case "ProductModel":
                name = (entity as ProductModel).Name;
                break;

            case "ProductComponent":
                name = (entity as ProductComponent).ComponentName;
                break;

            case "WorkInstruction":
                name = (entity as GTSWorkInstruction).Title;
                break;
            }

            var change = new EntityChange
            {
                Id = Guid.NewGuid(),
                ChangedEntityId   = entity.Id,
                ChangedEntityType = typeof(T),
                ChangeDate        = DateTime.Now,
                ChangeDescription = string.Format("{3} '{4}'s property '{0}' was changed from '{1}' to '{2}'.", propName, oldValue, newValue, typeof(T).Name, name),
                ChangeMadeBy      = entity.EditedBy,
                OldValue          = oldValue,
                NewValue          = newValue
            };

            // save change to system
            GTSDataRepository.Create <EntityChange>(change);
        }
Esempio n. 2
0
        /// <summary>
        /// Attempts to tracks changes to an entity.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oldEntity">The old entity.</param>
        /// <param name="newEntity">The new entity.</param>
        public void TrackChanges <T>(T oldEntity, T newEntity) where T : DomainObject
        {
            // get a list of properties of the entity
            var props = typeof(T).GetProperties().ToList();

            var name = string.Empty;

            switch (typeof(T).Name)
            {
            case "ProductModel":
                name = (newEntity as ProductModel).Name;
                break;

            case "ProductComponent":
                name = (newEntity as ProductComponent).ComponentName;
                break;

            case "GTSWorkInstruction":
                name = (newEntity as GTSWorkInstruction).Title;
                break;
            }

            // iterate over all properties and track changes
            props.ForEach(prop =>
            {
                // get values
                var oldValue = prop.GetValue(oldEntity);
                var newValue = prop.GetValue(newEntity);

                // check for differences
                if ((oldValue != null && newValue != null) &&
                    !oldValue.Equals(newValue) &&
                    !(oldValue is IList) && !oldValue.GetType().IsGenericType &&
                    prop.Name != "ModificationDate")
                {
                    // create and save new EntityChange object
                    var change = new EntityChange
                    {
                        Id = Guid.NewGuid(),
                        ChangedEntityId   = oldEntity.Id,
                        ChangedEntityType = typeof(T),
                        ChangeDate        = DateTime.Now,
                        ChangeDescription = string.Format("{3} '{4}'s property '{0}' is changed from '{1}' to '{2}'", prop.Name, oldValue, newValue, typeof(T).Name, name),
                        ChangeMadeBy      = User.Identity.Name, //oldEntity.EditedBy,
                        OldValue          = oldValue.ToString(),
                        NewValue          = newValue.ToString()
                    };

                    // save change to system
                    GTSDataRepository.Create <EntityChange>(change);
                }
            });
        }
Esempio n. 3
0
        public ActionResult ForgotPasswordJson(string emailAddress)
        {
            try
            {
                //var user = UserManager.FindByNameAsync(emailAddress);
                var user = UserManager.FindByEmail(emailAddress);
                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(new HttpStatusCodeResult(200));
                }

                //var existingHelperForEmailIds = GTSDataRepository.GetListByQuery<PasswordHelper>("FROM PasswordHelper ph WHERE ph.EmailAddress = :email", new Dictionary<string, object> { { "email", emailAddress } })

                var passwordHelper = new PasswordHelper {
                    Id = Guid.NewGuid(), EmailAddress = emailAddress, RequestDate = DateTime.Now, Token = Guid.NewGuid()
                };

                GTSDataRepository.Create(passwordHelper);

                var callBackUrl = HttpContext.Request.Url.Authority;

                var resetUrl = string.Format("http://{0}/Account/ResetPasswordFromEmail/{1}", callBackUrl, passwordHelper.Token);

                var body = string.Format(
                    "Hello," +
                    "<br />" +
                    "<br />" +
                    "This mail was sent to enable you to reset your password and will expire after 24 hours. Click <a href='{0}'>here</a> to reset your password.<br />" +
                    "If you did not request this mail you can simply ignore it." +
                    "<br />" +
                    "<br />" +
                    "Kind regards,<br />" +
                    "GTS", resetUrl);

                var subject = "GTS Password Change Request";

                var from = "*****@*****.**";

                var to = emailAddress;

                MailHandler.Send(to, from, subject, body, _logger, true, true);

                return(new HttpStatusCodeResult(200));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Tracks the addition of an object to a collection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="addedObject">The added object.</param>
        /// <param name="parentObject">The parent object.</param>
        /// <param name="propName">Name of the property.</param>
        public void TrackAddition <T, U>(T addedObject, U parentObject, string propName) where T : DomainObject where U : DomainObject
        {
            var change = new EntityChange
            {
                Id = Guid.NewGuid(),
                ChangedEntityId   = parentObject.Id,
                ChangedEntityType = typeof(U),
                ChangeDate        = DateTime.Now,
                //ChangeDescription = string.Format("Property '{0}' is changed from '{1}' to '{2}'", prop.Name, oldValue, newValue),
                ChangeMadeBy = addedObject.EditedBy,
                OldValue     = "Parent Id: " + parentObject.Id.ToString(),
                NewValue     = "Added object Id: " + addedObject.Id.ToString(),
            };

            switch (typeof(T).Name)
            {
            case "ProductComponent":
                var model     = parentObject as ProductModel;
                var component = addedObject as ProductComponent;
                change.ChangeDescription = string.Format("Model '{0}' with has added Component '{1}' to its collection of ProductComponents", model.Name, component.ComponentName);
                break;

            case "AssemblyTool":
                model = parentObject as ProductModel;
                var tool = addedObject as AssemblyTool;
                change.ChangeDescription = string.Format("Model '{0}' with has added Tool '{1}' to its collection of Tools", model.Name, tool.Name + " " + tool.ToolCode);
                break;

            case "GTSWorkInstruction":
                var parentComponent = parentObject as ProductComponent;
                var instruction     = addedObject as GTSWorkInstruction;
                change.ChangeDescription = string.Format("Product Component '{0}' with has added Work Instruction '{1}' to its collection of WorkInstructions", parentComponent.ComponentName, instruction.Title);
                break;
            }

            // save change to system
            GTSDataRepository.Create <EntityChange>(change);
        }
Esempio n. 5
0
        /// <summary>
        /// Starts the stop shipping preparation.
        /// </summary>
        /// <param name="doStart">if set to <c>true</c> [do start].</param>
        /// <param name="bomNr">The bom nr.</param>
        /// <returns></returns>
        public ActionResult PersistAndStartStopShippingPreparation(bool doStart, string bomNr)
        {
            _logger.LogDebug("User {0} attempts to set the Shipping Preparation with Bom Nr {2}'s IsActive property to {1}.", User.Identity.Name, doStart, bomNr);
            try
            {
                var newGuid             = Guid.NewGuid();
                var shippingPreparation = UnitOfWorkSession.CreateCriteria <ShippingPreparation>()
                                          .Add(Expression.Eq("BOMNr", bomNr)).UniqueResult <ShippingPreparation>()
                                          ?? new ShippingPreparation // if retrieval fails, create a new shippingPreparation
                {
                    Id            = newGuid,
                    BOMNr         = bomNr,
                    EditedBy      = User.Identity.Name,
                    StartDateTime = DateTime.Now,
                };

                shippingPreparation.IsActive = doStart;

                if (newGuid == shippingPreparation.Id)
                {
                    _logger.LogInfo("Shipping preparation did not exist yet, creating new ShippingPreparation entity with id {0}", newGuid);
                    GTSDataRepository.Create <ShippingPreparation>(shippingPreparation);
                }
                else
                {
                    GTSDataRepository.Update <ShippingPreparation>(shippingPreparation);
                }

                _logger.LogInfo("User {0} has successfully set the Shipping Preparation with Bom Nr {2}'s IsActive property to {1}.", User.Identity.Name, doStart, bomNr);

                return(new HttpStatusCodeResult(200));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Updates an assembly.
        /// </summary>
        /// <param name="objectAsString">The object as a json string.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">
        /// No product serial was found in incoming device data.
        /// or
        /// Could not find product with serial: " + postData["productSerial"]
        /// or
        /// Data is corrupted: the system found more than one product with serial " + postData["productSerial"]
        /// or
        /// Could not find component assemblies for product with serial: " + postData["productSerial"]
        /// </exception>
        private ActionResult UpdateAssemblyParsed(string objectAsString)
        {
            _logger.LogInfo("Incoming data from a remote device: {0}", objectAsString);

            try
            {
                var postData = (Dictionary <string, object>) new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(objectAsString);

                if (postData["productSerial"] == null || string.IsNullOrEmpty(postData["productSerial"].ToString()))
                {
                    throw new InvalidOperationException("No product serial was found in incoming device data.");
                }

                var keyWords = postData.Keys.ToList().Where(x => x.ToString() != "productSerial" && x.ToString() != "baseModelId" && x.ToString() != "deviceKey").ToArray <string>();

                var doCreateRemark = false;
                if (postData["createRemark"].ToString().ToLower() == "true")
                {
                    doCreateRemark = true;
                }

                // check if product exists
                var productAssemblyCriteria = UnitOfWorkSession.CreateCriteria <ProductAssembly>();
                productAssemblyCriteria = productAssemblyCriteria.Add(Expression.Eq("ProductSerial", postData["productSerial"]));
                var productAssembly = productAssemblyCriteria.List <ProductAssembly>();
                if (productAssembly.Count() == 0)
                {
                    throw new InvalidOperationException("Could not find product with serial: " + postData["productSerial"]);
                }
                if (productAssembly.Count() > 1)
                {
                    throw new InvalidOperationException("Data is corrupted: the system found more than one product with serial " + postData["productSerial"]);
                }

                var componentAssemblyCriteria = UnitOfWorkSession.CreateCriteria <ComponentAssembly>();
                componentAssemblyCriteria = componentAssemblyCriteria.CreateAlias("ProductAssembly", "pa");
                componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pa.ProductSerial", postData["productSerial"]));
                componentAssemblyCriteria = componentAssemblyCriteria.CreateAlias("ProductComponent", "pc");
                componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.In("pc.DeviceKeyword", keyWords));
                componentAssemblyCriteria = componentAssemblyCriteria.CreateAlias("pc.ProductModel", "pm");
                componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pm.IsReleased", true));
                //componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pm.IsArchived", false));
                if (postData.Keys.Contains <string>("baseModelId"))
                {
                    componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pm.BaseModelId", Guid.Parse(postData["baseModelId"].ToString())));
                }

                var filteredComponentAssemblies = componentAssemblyCriteria.List <ComponentAssembly>();

                if (filteredComponentAssemblies.Count() == 0)
                {
                    throw new InvalidOperationException("Could not find component assemblies for product with serial: " + postData["productSerial"]);
                }

                // find matching component assemblies for any device keywords in the post data
                keyWords.ToList().ForEach(x =>
                {
                    filteredComponentAssemblies.Where(y => y.ProductComponent.DeviceKeyword == x).ToList().ForEach(z =>
                    {
                        // update component assembly
                        if (postData[x] != null)
                        {
                            z.Revision = postData[x].ToString();
                            GTSDataRepository.Update <ComponentAssembly>(z);
                        }
                    });
                });

                // create remark when needed
                if (doCreateRemark)
                {
                    var remarkMessage = string.Format("Product with serial {0} failed its automated tests. Reasons given: ", postData["productSerial"].ToString());

                    if (productAssembly[0].ProductModel.Name.ToLower().Contains("wing"))
                    {
                        if (postData["deviceApproval"] != null && postData["deviceApproval"].ToString() == "no")
                        {
                            remarkMessage += "Product found to be invalid by wing checker tool, ";
                            if (postData["errorMessage"] != null)
                            {
                                remarkMessage += postData["errorMessage"].ToString();
                            }
                        }
                        if (postData["minmax"] != null && postData["minmax"].ToString() == "no")
                        {
                            remarkMessage += "User did not approve min and / or max, ";
                        }
                    }
                    else if (productAssembly[0].ProductModel.Name.ToLower().Contains("ux11 motor"))
                    {
                        if (!(bool)postData["userApproval"])
                        {
                            remarkMessage += "User disapproves (" + postData["disapprovalReason"].ToString() + "), ";
                        }
                        if (!(bool)postData["systemApprovalVoltage"])
                        {
                            remarkMessage += "Measured voltage does not conform to expectations, ";
                        }
                        if (!(bool)postData["systemApprovalCurrent"])
                        {
                            remarkMessage += "Measured current does not conform to expectations, ";
                        }
                        if (!(bool)postData["systemApprovalRPM"])
                        {
                            remarkMessage += "Measured rpm does not conform to expectations, ";
                        }
                        if (!(bool)postData["systemApprovalDirection"])
                        {
                            remarkMessage += "Measured direction of spin does not conform to expectations, ";
                        }
                    }

                    var newRemark = new RemarkSymptom
                    {
                        Id                = Guid.NewGuid(),
                        CreationDate      = DateTime.Now,
                        ResolutionDate    = DateTime.MaxValue,
                        Description       = remarkMessage,
                        ProductAssembly   = productAssembly[0],
                        EditedBy          = postData["user"].ToString(),
                        RemarkSymptomType = GTSDataRepository.GetListByQuery <RemarkSymptomType>("FROM RemarkSymptomType WHERE Name = '" + postData["remarkSymptomType"].ToString() + "'").FirstOrDefault(),
                    };

                    GTSDataRepository.Create <RemarkSymptom>(newRemark);
                }

                return(new HttpStatusCodeResult(200, "Data received"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);

                return(new HttpStatusCodeResult(500, ex.Message));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Prepares the shipping json.
        /// </summary>
        /// <returns></returns>
        public ActionResult PrepareShippingJSON()
        {
            _logger.LogDebug("User {0} chose to display the Shipping Preparation Interface.", User.Identity.Name);

            try
            {
                // create lists for picking, packaging and validations
                var packagingList      = new List <OrderLine>();
                var pickingList        = new List <Picking>();
                var bomList            = new List <dynamic>();
                var validationMessages = new List <ShippingPreparationValidationMessage>();

                // retrieve shipping GTS meta data from the database
                var activeShippingPreparations = getActiveShippingPreparations();

                // do an old-school Sql Cmd approach
                var connection = new SqlConnection(SAGE_CONN_STR);
                using (connection)
                {
                    var SqlCmd = new SqlCommand(SAGE_SQL_STR, connection);

                    connection.Open();

                    using (SqlDataReader oReader = SqlCmd.ExecuteReader())
                    {
                        while (oReader.Read())
                        {
                            Console.WriteLine(oReader.ToString());

                            // create a list of BOM nrs
                            bomList.Add(
                                new
                            {
                                BomNr    = oReader["PickingBOM"].ToString(),
                                IsActive = activeShippingPreparations.Where(x => x.BOMNr == oReader["PickingBOM"].ToString()).Count() > 0
                            });

                            // filter out data for non-activated Shippings (activation starts / stops are done in this page as well)
                            if (activeShippingPreparations.Where(x => x.BOMNr == oReader["PickingBOM"].ToString()).Count() == 0)
                            {
                                continue;
                            }

                            // Use query result row to cast to internal DTO classes
                            var packagingDTO = new OrderLine(oReader, User.Identity.Name);
                            packagingList.Add(packagingDTO);
                        }

                        connection.Close();
                    }
                }

                if (packagingList.Count > 0)
                {
                    // ensure ClientRef and SalesOrder are found on every line
                    var clientRef       = packagingList.Where(order => !string.IsNullOrEmpty(order.SalesOrder)).First().ClientRef;
                    var salesOrder      = packagingList.Where(order => !string.IsNullOrEmpty(order.SalesOrder)).First().SalesOrder;
                    var colorTagIndex   = 0;
                    var isCommercialBom = false;
                    packagingList.ForEach(order =>
                    {
                        if (order.CommercialBOM == "O")
                        {
                            isCommercialBom = true;
                        }

                        if (string.IsNullOrEmpty(order.CommercialBOM))
                        {
                            isCommercialBom = false;
                        }

                        if (!isCommercialBom)
                        {
                            colorTagIndex = (colorTagIndex + 1) % 6;
                        }
                        else if (order.CommercialBOM != "O")
                        {
                            order.DoIndent = true;
                        }

                        if (!string.IsNullOrEmpty(order.PartNr))
                        {
                            order.ColorTag = _colorTable[colorTagIndex];
                        }

                        order.ClientRef  = clientRef;
                        order.SalesOrder = salesOrder;
                    });
                }

                // when we're done creating an picking list, regroup the orderlist according to BOM nr
                var tempOrderList = new List <OrderLine>();
                packagingList.OrderBy(x => x.PickingBOM).ToList().ForEach(order =>
                {
                    var currentorderQuantity = order.Quantity;
                    if (currentorderQuantity > 1 && order.UoM == "PCE")
                    {
                        for (var c = 0; c < currentorderQuantity; c++)
                        {
                            //order.Quantity = 1;
                            tempOrderList.Add(order);
                        }
                    }
                    else
                    {
                        tempOrderList.Add(order);
                    }
                });

                var groupedOrderList = tempOrderList.GroupBy(order => order.PickingBOM);

                // create a picking list from the list of orders made in the previous step
                packagingList.ToList().ForEach(packagingDTO =>
                {
                    var existingItemInPickingList = pickingList.Where(item => item.PartNr == packagingDTO.PartNr).SingleOrDefault();

                    if (existingItemInPickingList == null)
                    {
                        existingItemInPickingList          = new Picking(packagingDTO);
                        existingItemInPickingList.Quantity = 0; // set quantity to null, we will recalculate this below

                        // create a fake stock location if needed
                        if (string.IsNullOrEmpty(packagingDTO.StockLocation) && packagingDTO.StockLevel > 0 && !string.IsNullOrEmpty(packagingDTO.UoM))
                        {
                            existingItemInPickingList.StockLocation = "";
                        }

                        pickingList.Add(existingItemInPickingList);
                    }

                    if (/*packagingDTO.UoM == "PCE" && */ packagingDTO.Quantity > 0)
                    {
                        existingItemInPickingList.Quantity += packagingDTO.Quantity;
                    }
                });

                // check stock levels to create a picking issue summary
                ShippingPreparationValidationMessage shippingPrepValidationMessage = null;
                pickingList.ForEach(shippingDTO =>
                {
                    if (ShippingPreparationValidationMessage.GetShippingPreparationValidationMessage(shippingDTO.Quantity, shippingDTO.StockLevel, shippingDTO.PartNr, out shippingPrepValidationMessage)
                        == false)
                    {
                        validationMessages.Add(shippingPrepValidationMessage);
                    }
                });

                _logger.LogInfo("User {0} successfully requested Shipping Preparation data.", User.Identity.Name);

                assignIdMasks(tempOrderList);

                // try to retrieve existing orderLines with the BOM from the database
                var searchCriteria = UnitOfWorkSession.CreateCriteria <OrderLine>()
                                     .Add(Expression.Eq("PickingBOM", packagingList.Count > 0 ? packagingList[0]?.PickingBOM : ""));

                // put the results in a list
                var existingPackagingEntities = searchCriteria.List <OrderLine>().ToList();

                // for every collection of order lines with the same BOM
                foreach (var item in packagingList)
                {
                    // iterate over all current oderlines and use the previously created list to check if the current line
                    // is already in the database and create it, if not
                    var potentiallyExistingOrderLines = existingPackagingEntities.Where(entity => entity.OrderLineNr == item.OrderLineNr);
                    if (potentiallyExistingOrderLines.Count() > 1)
                    {
                        throw new InvalidOperationException(string.Format("More then 1 row was found in the database for the current Picking BOM {0} and Order Line Nr {1}", item.PickingBOM, item.OrderLineNr));
                    }

                    if (potentiallyExistingOrderLines.Count() == 0)
                    {
                        item.Id       = Guid.NewGuid();
                        item.EditedBy = User.Identity.Name;
                        GTSDataRepository.Create <OrderLine>(item);
                    }
                    else // at this point we can assume there's only orderline found in the database, retrieve any input value if possible
                    {
                        item.FieldInput = potentiallyExistingOrderLines.First().FieldInput;
                    }
                }

                return(SerializeForWeb(new
                {
                    Picking = pickingList,
                    Packing = groupedOrderList,
                    BomList = bomList.Distinct().ToList(),
                    ValidationMessages = validationMessages,
                    TotalToPick = pickingList.Where(picking => !string.IsNullOrEmpty(picking.StockLocation)).DistinctBy(picking => picking.PartNr).Count()
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }