public async Task <IActionResult> PostWorkorder([FromBody] Workorder workorder)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // TODO: Update this to ensure it pulls the first state of the active workflow
            // TODO: Update workflows/states to determine first (and last?) state of workflow
            workorder.State = await _context.States.FirstOrDefaultAsync(x => x.Id == 1);

            workorder.Faculty = await _context.Faculties.FirstOrDefaultAsync(f => f.Id == workorder.FacultyId);

            workorder.Purpose = await _context.Purposes.FirstOrDefaultAsync(p => p.Id == workorder.PurposeId);

            workorder.DateCreated = DateTime.Now;
            workorder.Semester    = await _context.Semesters
                                    .FirstOrDefaultAsync(s =>
                                                         s.StartMonth <= workorder.DateCreated.Month &&
                                                         s.EndMonth <= workorder.DateCreated.Month);

            workorder.ReadableId = CreateReadableId(workorder.DateCreated);

            // TODO: Potentially add a default state "Created" that always has a single transition to
            //  the first state in a workflow, adding that transition to the TransitionHistory on workorder creation
            _context.Workorders.Add(workorder);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetWorkorder", new { id = workorder.Id }, workorder));
        }
Beispiel #2
0
        public WorkorderLabel GetOrCreate(Workorder wo, string serialNumber)
        {
            WorkorderLabel workorderLabel = null;

            try
            {
                workorderLabel = db.WorkorderLabels.FirstOrDefault(x => x.SerialNumber == serialNumber);

                if (workorderLabel == null)
                {
                    workorderLabel = new WorkorderLabel()
                    {
                        Id           = 0,
                        SerialNumber = serialNumber,
                        Workorder    = wo,
                        WorkorderId  = wo.Id,
                        TimeStamp    = DateTime.Now
                    };
                    Add(workorderLabel);
                }
            }
            catch (Exception ex)
            {
                Logger2FileSingleton.Instance.SaveLog("WorkorderLabelRepo.Create problem. Model: "
                                                      + workorderLabel.Id + ", "
                                                      + workorderLabel.SerialNumber + ", "
                                                      + wo?.WorkorderNumber ?? "1600000000" + ", "
                                                      + workorderLabel.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")
                                                      );
                //Logger2FileSingleton.Instance.SaveLog("ItemData: " + itemData.ExpectedName + ", " + itemData.ExpectedProductCode);
            }

            return(workorderLabel);
        }
        private void InspectLabel(string fileName)
        {
            try
            {
                Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabel(" + fileName + ") START");
                InspectLabel_AnalizeImage(fileName, out ItemData itemData, out string serialNumber, out EnumLabelType labelType);

                if (itemData != null)
                {
                    Workorder      wo             = uow.WorkorderRepo.Get(serialNumber, itemData.ItemCode);
                    WorkorderLabel workorderLabel = uow.WorkorderLabelRepo.GetOrCreate(wo, serialNumber);
                    bool           allTestsPassed = uow.WorkorderLabelInspectionRepo.SaveInspectionResults(workorderLabel, itemData, labelType);
                    uow.WorkorderRepo.UpdateStats(wo, allTestsPassed);
                    ArchiveOrDeleteRawLabel(fileName, allTestsPassed);
                    CopyWorkorderLabelIfNotExists(wo.WorkorderNumber, $"{serialNumber}_{labelType.ToString()}");
                    Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabel(" + fileName + ") END");
                }
                else
                {
                    ArchiveOrDeleteRawLabel(fileName, true);
                    Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabel(" + fileName + ") END - ItemData is NULL");
                }
            }
            catch (Exception ex)
            {
                Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabel(" + fileName + ") Exception: " + ex.Message +
                                                      Environment.NewLine + " d:" + ex.InnerException?.Message +
                                                      Environment.NewLine + " s:" + ex.ToString());
            }
        }
        public JsonResult DeleteConfirmed(int id = 0)
        {
            try
            {
                Workorder workorder = _db.Workorders.FirstOrDefault(x => x.Id == id);
                if (workorder == null)
                {
                    TempData["ErrorMessage"] = "Something went wrong. Please try again later.";
                    return(Json(new { success = false }));
                }

                _db.Workorders.Remove(workorder);
                _db.SaveChanges();

                TempData["SuccessMessage"] = "Workorder has been deleted successfully.";

                return(Json(new { success = true }));
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = "Something went wrong. Please try again later.";

                return(Json(new { success = false }));
            }
        }
        public static string MergeWorkorder(Workorder workorder)
        {
            using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) {
                tx.Create();

                // load the work order template
                tx.Load(HttpContext.Current.Server.MapPath(
                            "~/App_Data/workorder.tx"),
                        TXTextControl.StreamType.InternalUnicodeFormat);

                MailMerge mm = new MailMerge()
                {
                    TextComponent = tx
                };

                // merge the data into the template
                mm.MergeObject(workorder);

                // generate a unique filename and save the work order
                var sFileName = Helpers.GenerateUID(5);
                tx.Save(HttpContext.Current.Server.MapPath("~/App_Data/" + sFileName + ".tx"), TXTextControl.StreamType.InternalUnicodeFormat);

                return(sFileName);
            }
        }
Beispiel #6
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Description,QuoteRequested,TotalMaterialCost,TotalLabourCost,TotalCost,DateCreated,DateRequiredBy,DateCompleted,DatePickedUp,ClientPhoneNumber,ClientEmail,ClientName,EstMaterialCost,EstLabourCost,EstOtherCost,EstTotalCost,EstDeliveryDate,AuthorizedBy")] Workorder workorder)
        {
            if (id != workorder.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(workorder);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WorkorderExists(workorder.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(workorder));
        }
        public async Task <IActionResult> PutWorkorder([FromRoute] int id, [FromBody] Workorder workorder)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != workorder.Id)
            {
                return(BadRequest());
            }

            _context.Entry(workorder).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WorkorderExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Beispiel #8
0
        public ActionResult Edit(AV_Site Site, Workorder wo, List <Workorder> Sectors)
        {
            //Workorder Site, List<AV_Sector> Sectors
            Response res = new Response();

            try
            {
                DataTable Sectorsdt = new DataTable();
                //  Sectorsdt = Sectors.ToDataTable();
                Sectorsdt.Columns.Remove("TestStatus");
                Sectorsdt.Columns.Remove("Latitude");
                Sectorsdt.Columns.Remove("Longitude");
                Sectorsdt.Columns.Remove("isActive");
                Sectorsdt.Columns.Remove("sectorColor");
                WorkOrderDL dl = new WorkOrderDL();
                //  dl.Edit(Site, Sectorsdt);
                res.Status  = "success";
                res.Message = "save successfully";
            }
            catch (Exception ex)
            {
                res.Status  = "danger";
                res.Message = ex.Message;
            }
            return(Json(res, JsonRequestBehavior.AllowGet));
        }
        public static List <Workorder> FetchWorkorder(string contractType, string status)
        {
            var workorderlist = new List <Workorder>();

            var conn = DBConnection.GetDBConnection();

            string query = @"select c.businessname, c.lastname, w.WorkorderID, w.Description, CONVERT(date, w.WorkorderDate) as WorkorderDate, convert(date, w.ExpectedDate) as ExpectedDate , w.CustomerID,  w.EmployeeID, w.WorkOrderStatus, w.ContractType, w.contractamount, w.partsmarkup, w.hourlyrate, w.bidid ";

            query += @"  from workorder w inner join customer c on w.customerid = c.customerID";
            //query += @" where ContractType = " + contractType.ToString();
            //query += @" and status= " + status;
            //query += @" order by BidDate desc";

            var cmd = new SqlCommand(query, conn);

            try
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Workorder currentWorkorder = new Workorder()
                        {
                            BusinessName   = reader.IsDBNull(0) ? null : reader.GetString(0),
                            LastName       = reader.GetString(1),
                            WorkorderID    = reader.GetInt32(2),
                            Description    = reader.GetString(3),
                            WorkorderDate  = reader.GetDateTime(4),
                            ExpectedDate   = reader.GetDateTime(5),
                            CustomerID     = reader.GetInt32(6),
                            EmployeeID     = reader.GetInt32(7),
                            Status         = reader.GetString(8),
                            ContractType   = reader.IsDBNull(9) ? null : reader.GetString(9),
                            ContractAmount = reader.IsDBNull(10) ? 0 : reader.GetDecimal(10),
                            PartsMarkup    = reader.IsDBNull(11) ? 0 : reader.GetInt32(11),
                            HourlyRate     = reader.IsDBNull(12) ? 0 : reader.GetDecimal(12),
                            BidID          = reader.GetInt32(13)
                        };

                        workorderlist.Add(currentWorkorder);
                    }
                }
            }
            catch (Exception)
            {
                //rethrow, let logic layer sort out
                throw;
            }
            finally
            {
                conn.Close();
            }
            conn.Close();
            //list may be empty, if so logic layer will have to deal with it
            return(workorderlist);
        }
Beispiel #10
0
        public void CreateWorkorder(Workorder.PoType type, DayTime due, int initialOp = 0)
        {
            Workorder wo = new Workorder(GetNextWoId(), type, initialOp);

            AddWorkorder("none", wo);
            DueDates[wo.Id] = due;
            NewToSend.Add(wo);
        }
Beispiel #11
0
        /// <summary>
        /// Submit the form!
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false; // prevent double submission

            // from the information provided, create us a due date to store
            DateTime? duedate;
            if (ddAdType.SelectedValue.Equals("1"))
            {
                String strDate =  DateTime.Now.Year + "/" + ddAiringMonth.SelectedValue + "/01";
                duedate = strDate.ConvertToDate();
                if (duedate.HasValue && duedate < DateTime.Now)
                    duedate = duedate.Value.AddYears(1);
            }
            else
                duedate = (DateTime)txtStartAiringDate.Text.ConvertToDate();

            // submit!
            using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
            {
                // skip the approval process for designers and coordinators
                bool IsUserDesigner = Users.IsUserDesigner();
                bool NeedsApproval = !IsUserDesigner && !Users.IsUserCoordinator();
                Workorder w = new Workorder();
                w.submitted_date = DateTime.Now;
                w.submitted_by = Function.GetUserName();
                w.wotype = 3;
                w.duedate = duedate;
                w.ProgramManager = int.Parse(ddCoordinators.SelectedValue);
                w.title = "Radio Ad";
                w.status = NeedsApproval ? 1 : 2;
                db.Workorders.InsertOnSubmit(w);

                WorkOrdersRadio r = new WorkOrdersRadio();
                r.Workorder = w;
                r.AdType = int.Parse(ddAdType.SelectedValue);
                r.AiringMonth = ddAiringMonth.SelectedIndex > 0 ? int.Parse(ddAiringMonth.SelectedValue) : (int?)null;
                r.RadioStation = ddRadioStation.SelectedIndex > 0 ? int.Parse(ddRadioStation.SelectedValue) : (int?)null;
                r.RadioStationOther = txtRadioStationOther.Text;
                r.LengthOfAd = ddLengthOfAd.SelectedIndex > 0 ? int.Parse(ddLengthOfAd.SelectedValue) : (int?)null;
                r.StartAiringDate = txtStartAiringDate.Text.ConvertToDate();
                r.EndAiringDate = txtEndAiringDate.Text.ConvertToDate();
                r.Budget = txtBudget.Text;
                r.RecordingOptions = ddRecordingOptions.SelectedIndex > 0 ? int.Parse(ddRecordingOptions.SelectedValue) : (int?)null;
                r.Notes = txtNotes.Text;
                db.WorkOrdersRadios.InsertOnSubmit(r);
                db.SubmitChanges();
                int ID = w.ID;
                // upload attached files
                WO.UploadFiles(w.ID, AttachedFiles.UploadedFiles);
                // log the activity
                WO.LogAction(ID, "Work order created");
                // send notificaiton if needed
                WO.SendNewWONotification(ID, NeedsApproval, IsUserDesigner);
                // complete!
                Response.Redirect("~/MyWorkOrders.aspx?success=true&ID=" + ID + "&type=" + w.wotype);
            }
        }
Beispiel #12
0
        public List <Workorder> GetWO(string value1 = null, string value2 = null, string value3 = null)
        {
            AV_SitesDL       sd    = new AV_SitesDL();
            List <Workorder> wolst = new List <Workorder>();

            DataSet ds = sd.GetDataSet("SiteWithSectors", value1);

            if (ds.Tables.Count > 0)
            {
                DataTable Sit = ds.Tables[0];

                AV_Site s = new AV_Site();

                var rec = Sit.ToList <AV_Site>();
                if (rec.Count > 0)
                {
                    s = rec.FirstOrDefault();
                }

                DataTable sec = ds.Tables[1];
                Workorder wo;
                for (int i = 0; i < sec.Rows.Count; i++)
                {
                    wo               = new Workorder();
                    wo.SiteId        = s.SiteId;
                    wo.siteCode      = s.SiteCode;
                    wo.siteLatitude  = s.Latitude.ToString();
                    wo.siteLongitude = s.Longitude.ToString();
                    wo.Client        = s.ClientId.ToString();
                    wo.Scope         = s.ScopeId.ToString();
                    wo.SiteAddress   = s.SiteAddress;
                    wo.SiteName      = s.SiteName;
                    wo.SiteTypeId    = s.SiteTypeId.ToString();
                    wo.SiteClassId   = s.SiteClassId;
                    wo.Description   = s.Description;
                    wo.clusterCode   = "-";
                    wo.sectorCode    = sec.Rows[i]["SectorCode"].ToString();
                    wo.networkMode   = sec.Rows[i]["NetworkModeId"].ToString();
                    wo.Band          = sec.Rows[i]["BandId"].ToString();
                    wo.Carrier       = sec.Rows[i]["CarrierId"].ToString();
                    wo.BandWidth     = (!string.IsNullOrEmpty(sec.Rows[i]["BandWidth"].ToString())) ? sec.Rows[i]["BandWidth"].ToString() : "0";
                    wo.Antenna       = sec.Rows[i]["Antenna"].ToString();
                    wo.BeamWidth     = sec.Rows[i]["BeamWidth"].ToString();
                    wo.Azimuth       = sec.Rows[i]["Azimuth"].ToString();
                    wo.PCI           = sec.Rows[i]["PCI"].ToString();
                    wo.MRBTS         = sec.Rows[i]["MRBTS"].ToString();
                    wo.RFHeight      = DataType.ToInt32(sec.Rows[i]["RFHeight"].ToString());
                    wo.MTilt         = DataType.ToInt32(sec.Rows[i]["MTilt"].ToString());
                    wo.ETilt         = DataType.ToInt32(sec.Rows[i]["ETilt"].ToString());
                    wo.CellId        = sec.Rows[i]["CellId"].ToString();

                    wolst.Add(wo);
                }
            }

            return(wolst);
        }
Beispiel #13
0
        /// <summary>
        /// Submit the form!
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false; // prevent double submission
            using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
            {
                // if the user doesn't need approval, skip the approval process
                bool IsUserDesigner = Users.IsUserDesigner();
                bool NeedsApproval = !IsUserDesigner && !Users.IsUserCoordinator();
                Workorder w = new Workorder();
                w.submitted_date = DateTime.Now;
                w.submitted_by = Function.GetUserName();
                if (Request.QueryString["quote"] != null && Request.QueryString["quote"].Equals("1"))
                    w.wotype = 5;
                else
                    w.wotype = 1;
                w.duedate = txtDueDate.Text.ConvertToDate();
                w.ProgramManager = int.Parse(ddCoordinators.SelectedValue);
                w.title = txtPubTitle.Text;
                w.status = NeedsApproval ? 1 : 2;
                db.Workorders.InsertOnSubmit(w);

                WorkOrdersPrint p = new WorkOrdersPrint();
                p.Workorder = w;
                p.ProjectType = int.Parse(ddTypeProject.SelectedValue);
                p.ProjectTypeOther = txtProjectOther.Text;
                p.TypeOfDisplay = ddTypeOfDisplay.SelectedIndex > 0 ? int.Parse(ddTypeOfDisplay.SelectedValue) : (int?)null;
                p.TypeOfDisplayOther = txtDisplayOther.Text;
                p.PromoItem = txtPromoItem.Text;
                p.PrintingMethod = int.Parse(ddPrintingMethod.SelectedValue);
                p.Budget = txtBudget.Text;
                p.PaperSize = int.Parse(ddPaperSize.SelectedValue);
                p.CustomPaperSize = txtCustomPaperSize.Text;
                p.PaperType = int.Parse(ddPaperType.SelectedValue);
                p.ColourInfo = int.Parse(ddColourInfo.SelectedValue);
                p.NumberCopies = txtNumberCopies.Text;
                p.FullBleed = ddFullBleed.Value;
                p.Credit = int.Parse(ddCredits.SelectedValue);
                p.CreditName = txtCreditName.Text;
                p.Notes = txtNotes.Text;
                db.WorkOrdersPrints.InsertOnSubmit(p);
                db.SubmitChanges();
                int ID = p.wID;
                // upload attached files
                WO.UploadFiles(w.ID, AttachedFiles.UploadedFiles);
                // log the activity
                WO.LogAction(ID, "Work order created");
                // send notification (if necessary)
                WO.SendNewWONotification(ID, NeedsApproval, IsUserDesigner);

                // if the user added the option to add to the website, transfer user to web work order page
                if (ddAddToWebsite.Value == true)
                    Response.Redirect("~/Create/Web.aspx?AddTo=" + ID);
                else // if not, success!!
                    Response.Redirect("~/MyWorkOrders.aspx?success=true&ID=" + ID + "&type=" + w.wotype.ToString());
            }
        }
Beispiel #14
0
        public async Task OnControlCenterEscalation([ServiceBusTrigger("efp-api-escalation-topic", "efp-api-escalation-sub-send-notification")] BrokeredMessage message,
                                                    TraceWriter trace)
        {
            message.Complete();
            try
            {
                var          deserializedObject    = DeserializeBrokeredMessage <string>(message);
                var          parsedJObject         = JObject.Parse(deserializedObject);
                string       recepient             = parsedJObject["Entity"]["To"].ToObject <string>();
                Workorder    deserializedWorkorder = parsedJObject["Entity"]["Workorder"].ToObject <Workorder>();
                Product      parsedProduct         = parsedJObject["Entity"]["Product"].ToObject <Product>();
                EventMonitor eventMonitor          = parsedJObject["Entity"]["EventMonitor"].ToObject <EventMonitor>();

                var workorder = await _apiService.WorkorderData(deserializedWorkorder.Id);

                TimeZones timezoneId = await _apiService.TimeZoneData(workorder.Site.TimeZone);

                Product product = await _apiService.ProductData(parsedProduct.Id);

                bool sublocation = product.Group.Name == "SUBLOCATION";

                if (!recepient.Contains("@"))
                {
                    using (MailService mailService = new MailService(_cultureService))
                    {
                        mailService.CreateTwilioClient();

                        var body = sublocation
                            ? mailService.SmsSublocation(workorder, product)
                            : mailService.SmsEquipment(workorder, product);

                        var result = await MessageResource.CreateAsync(new PhoneNumber(recepient),
                                                                       from : new PhoneNumber("+13094200014"),
                                                                       body : body);

                        LogData(trace, $"Sent sms to {result.To} for workorder: {workorder.Id} for escalation: {eventMonitor.Name}", false);
                    }
                }
                else
                {
                    var templateKey = sublocation ? "TemplateEscalationSublocation" : "TemplateEscalationEquipment";
                    using (MailService mailService = new MailService(_cultureService))
                    {
                        MailMessage mail = mailService.EscalationMail(workorder, product, eventMonitor, timezoneId, recepient, templateKey);
                        mailService.SmtpClient.Send(mail);
                    }
                    LogData(trace, $"Sent mail to {recepient} for workorder: {workorder.Id} for escalation: {eventMonitor.Name}", false);
                }
            }
            catch (Exception ex)
            {
                LogData(trace, $"Message:{ex.Message} InnerException:{ex.InnerException} StackTrace:{ex.StackTrace}", true);
            }

            LogData(trace, "Escalation Alert Sending Finished", false);
        }
Beispiel #15
0
        public ActionResult Index()
        {
            Workorder workorder = new Workorder()
            {
                Approved       = false,
                ContractorName = "Peter Petersen"
            };

            return(View(workorder));
        }
Beispiel #16
0
        //Prep Helpers
        public void SetupSubject(int workIterations)
        {
            Workorder wo = new Workorder(1, Workorder.PoType.p7, 4);

            _subject.AddToQueue(wo);

            for (int i = 0; i < workIterations; i++)
            {
                _subject.Work(_dayTime);
            }
        }
Beispiel #17
0
        public async Task <IActionResult> Create([Bind("ID,Description,QuoteRequested,TotalMaterialCost,TotalLabourCost,TotalCost,DateCreated,DateRequiredBy,DateCompleted,DatePickedUp,ClientPhoneNumber,ClientEmail,ClientName,EstMaterialCost,EstLabourCost,EstOtherCost,EstTotalCost,EstDeliveryDate,AuthorizedBy")] Workorder workorder)
        {
            if (ModelState.IsValid)
            {
                _context.Add(workorder);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(workorder));
        }
Beispiel #18
0
        //todo: this handler is technically turned off
        public async Task OnWorkOrderCreate([ServiceBusTrigger("efp-api-create_workorder-topic", "efp-api-wocreate-sub-send-email")] BrokeredMessage message,
                                            TraceWriter trace)
        {
            message.Complete();
            try
            {
                JObject   deserializedObject    = DeserializeBrokeredMessage <MessageData <object> >(message).Entity as JObject;
                Workorder deserializedWorkorder = deserializedObject.ToObject <Workorder>();
                Workorder workorder             = await _apiService.WorkorderData(deserializedWorkorder.Id);

                if (deserializedWorkorder.Tasks?.FirstOrDefault()?.Notes.Count > 0)
                {
                    workorder.Tasks.FirstOrDefault().Notes = deserializedWorkorder.Tasks.FirstOrDefault().Notes;
                }

                if (workorder.SiteId == null)
                {
                    LogData(trace, $"No SiteId provided for Workorder: {workorder.Id} sending to {workorder.Contacts.FirstOrDefault().Email ?? "no address"}", false);
                }
                else
                {
                    var product = await _apiService.ProductData(workorder.Tasks.FirstOrDefault().ProductId);

                    if (product == null)
                    {
                        LogData(trace, $"Product in database does not exist problem. Product id: {workorder.Tasks.FirstOrDefault().ProductId}", false);
                    }
                    else
                    {
                        var templateKey = product.Group.Name == "SUBLOCATION" ? "TemplateWorkorderSublocation" : "TemplateWorkorderEquipment";

                        foreach (var contact in workorder.Contacts)
                        {
                            if (contact.Email != null)
                            {
                                LogData(trace, $"Sending message to {contact.Email} regarding Workorder: {workorder.Id}", false);
                                using (var mailService = new MailService(_cultureService))
                                {
                                    var mail = mailService.WorkorderMail(workorder, product, contact.Email, templateKey, workorder.Status);
                                    mailService.SmtpClient.Send(mail);
                                }
                                LogData(trace, $"Sent message to {contact.Email} regarding Workorder: {workorder.Id}", false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogData(trace, $"Message:{ex.Message} InnerException:{ex.InnerException} StackTrace:{ex.StackTrace}", false);
            }

            LogData(trace, "Workorder Create Sending Finished", false);
        }
Beispiel #19
0
 public EmailTests()
 {
     Settings.Initialize();
     TemplateConfiguration.Initialize();
     _cultureService = new CultureService();
     _mailService    = new MailService(_cultureService);
     _workorder      = CreateWorkorderMock();
     _equipment      = CreateEquipmentMock();
     _sublocation    = CreateSublocationMock();
     _eventMonitor   = CreateEventMonitorMock();
 }
Beispiel #20
0
        public void TryCreateWorkorderWithSomeBarcodes()
        {
            var order = new Workorder();

            order.Scans = new List <Scan>
            {
                new Barcode("ASD123"),
                new QRCode("CIPPA_LIPPA_123")
            };

            Assert.IsTrue(order.Scans.Count > 0);
        }
Beispiel #21
0
        public List <Workorder> initWorkOrders()
        {
            List <Workorder> workorders = new List <Workorder>();
            Workorder        workorder  = new Workorder();

            workorder.Id        = 1001;
            workorder.StartDate = new DateTime(2017, 01, 01, 08, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 01, 16, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1002;
            workorder.StartDate = new DateTime(2017, 01, 01, 16, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 02, 00, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1003;
            workorder.StartDate = new DateTime(2017, 01, 02, 00, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 02, 08, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1004;
            workorder.StartDate = new DateTime(2017, 01, 02, 08, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 02, 16, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1005;
            workorder.StartDate = new DateTime(2017, 01, 02, 16, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 03, 00, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1006;
            workorder.StartDate = new DateTime(2017, 01, 03, 00, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 03, 08, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1007;
            workorder.StartDate = new DateTime(2017, 01, 03, 08, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 03, 16, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1008;
            workorder.StartDate = new DateTime(2017, 01, 03, 16, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 04, 00, 00, 00);
            workorders.Add(workorder);
            workorder           = new Workorder();
            workorder.Id        = 1009;
            workorder.StartDate = new DateTime(2017, 01, 04, 00, 00, 00);
            workorder.EndDate   = new DateTime(2017, 01, 04, 08, 00, 00);
            workorders.Add(workorder);

            return(workorders);
        }
Beispiel #22
0
        public string SmsSublocation(Workorder workorder, Product product)
        {
            _cultureService.SetCulture(workorder.CustomerProblemDescription.ToLower(), workorder.Site.LocaleCode.ToLower());
            var message = $"{_cultureService.DetermineEscalationCompleted(workorder)}-" +
                          $"{LocalizedText.WO}{workorder.Id}@{LocalizedText.Site}{workorder.Site.Name}-" +
                          $"{LocalizedText.Subloc}{product.Id ?? LocalizedText.NA }-" +
                          $"{LocalizedText.BldgLoc}{product.BuildingLocation ?? LocalizedText.NA}-" +
                          $"{LocalizedText.EquipDescr}{product.Description ?? LocalizedText.NA}-" +
                          $"{LocalizedText.EquipCrit}{product.CriticalityId}-" +
                          $"{LocalizedText.Notes}{GroupNotes(workorder) ?? LocalizedText.NA}";

            return(TruncateMessage(message));
        }
Beispiel #23
0
        public ActionResult Register(Workorder workorder)
        {
            if (ModelState.IsValid)
            {
                string sFileName = Helpers.MergeWorkorder(workorder);

                return(View(Helpers.CreateBarcode(sFileName)));
            }
            else
            {
                return(View(ModelState));
            }
        }
Beispiel #24
0
        private Dictionary <string, Workorder> LoadUnfilledWorkordersMap()
        {
            var path         = Path.Combine(CSVBasePath, "workorders.csv");
            var workorderMap = new Dictionary <string, Workorder>();

            if (!File.Exists(path))
            {
                CreateEmptyWorkorderFile(path);
                return(workorderMap);
            }

            using (var f = File.OpenRead(path))
                using (var csv = new CsvHelper.CsvReader(new StreamReader(f)))
                {
                    foreach (var row in csv.GetRecords <UnscheduledCsvRow>())
                    {
                        Workorder work;
                        if (workorderMap.ContainsKey(row.Id))
                        {
                            work = workorderMap[row.Id];
                        }
                        else
                        {
                            work = new Workorder
                            {
                                WorkorderId = row.Id,
                                Priority    = row.Priority,
                                DueDate     = row.DueDate,
                                Parts       = new List <WorkorderDemand>()
                            };
                            workorderMap.Add(row.Id, work);
                        }
                        work.Parts.Add(new WorkorderDemand
                        {
                            WorkorderId = row.Id,
                            Part        = row.Part,
                            Quantity    = row.Quantity
                        });
                    }
                }

            foreach (var id in workorderMap.Keys.ToList())
            {
                var f = Path.Combine(CSVBasePath, Path.Combine(FilledWorkordersPath, id + ".csv"));
                if (File.Exists(f))
                {
                    workorderMap.Remove(id);
                }
            }
            return(workorderMap);
        }
Beispiel #25
0
        private string GroupNotes(Workorder workorder)
        {
            string notes = string.Empty;

            foreach (var task in workorder.Tasks.OrderByDescending(x => x.Id))
            {
                foreach (var note in task.Notes.OrderByDescending(x => x.Id))
                {
                    if (!string.IsNullOrEmpty(note.Text))
                    {
                        notes += note.Text;
                        notes += "|";
                    }
                }
            }
            return(notes);
        }
Beispiel #26
0
        /// <summary>
        /// Submit the form
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false; // prevent double entry
            using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
            {
                // skip approval process for designers and program managers (coordinators)
                bool IsUserDesigner = Users.IsUserDesigner();
                bool NeedsApproval = !IsUserDesigner && !Users.IsUserCoordinator();
                Workorder w = new Workorder();
                w.submitted_date = DateTime.Now;
                w.submitted_by = Function.GetUserName();
                w.wotype = 6;
                w.duedate = txtDueDate.Text.ConvertToDate();
                w.ProgramManager = int.Parse(ddCoordinators.SelectedValue);
                w.title = txtTitleVideo.Text;
                w.status = NeedsApproval ? 1 : 2;
                db.Workorders.InsertOnSubmit(w);

                WorkOrdersVideo v = new WorkOrdersVideo();
                v.Workorder = w;
                v.VideoSource = int.Parse(ddVideoSource.SelectedValue);
                v.VideoDestination = Function.GetChecklistItems(chkVideoDestination);
                v.DestinationURL = txtDestinationURL.Text;
                v.NumberDVDs = txtNumberDVDs.Text;
                v.VideoLength = txtVideoLength.Text;
                v.BackgroundMusic = ddBackgroundMusic.Value;
                v.SongChoices = txtSongChoices.Text;
                v.NarrationReqd = ddNarrationRequired.Value;
                v.Narrator = ddNarrator.SelectedIndex > 0 ? ddNarrator.SelectedIndex : (int?)null;
                v.VideoDescription = txtVideoDescription.Text;
                v.CreditsRequired = ddCreditsRequired.Value;
                v.Notes = txtNotes.Text;
                db.WorkOrdersVideos.InsertOnSubmit(v);
                db.SubmitChanges();
                int ID = w.ID;
                // upload the attached files
                WO.UploadFiles(w.ID, AttachedFiles.UploadedFiles);
                // log it
                WO.LogAction(ID, "Work order created");
                // send out the notifications if necessary
                WO.SendNewWONotification(ID, NeedsApproval, IsUserDesigner);
                // success!
                Response.Redirect("~/MyWorkOrders.aspx?success=true&ID=" + ID + "&type=" + w.wotype);
            }
        }
        public LabelinspViewModel InspectLabelTest(string fileName)
        {
            LabelinspViewModel packingLabelViewModel = new LabelinspViewModel();

            packingLabelViewModel.WorkorderLabel            = new WorkorderLabel();
            packingLabelViewModel.WorkorderLabelInspections = new List <WorkorderLabelInspection>();

            try
            {
                Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabelTest(" + fileName + ") START");
                InspectLabel_AnalizeImage(fileName, out ItemData itemData, out string serialNumber, out EnumLabelType labelType, true);

                if (itemData != null)
                {
                    Workorder wo = uow.WorkorderRepo.Get(serialNumber, itemData.ItemCode);
                    packingLabelViewModel.WorkorderLabel = new WorkorderLabel()
                    {
                        Id           = 0,
                        SerialNumber = serialNumber,
                        TimeStamp    = DateTime.Now,
                        Workorder    = new Workorder()
                        {
                            ItemCode        = wo?.ItemCode ?? "",
                            ItemName        = wo?.ItemName ?? "",
                            WorkorderNumber = wo?.WorkorderNumber ?? ""
                        }
                    };
                    packingLabelViewModel.WorkorderLabelInspections = WorkorderLabelInspectionRepo.PrepareInspectionResults(0, itemData, labelType);
                    Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabelTest(" + fileName + ") END");
                }
                else
                {
                    //ArchiveOrDeleteRawLabel(fileName, true);
                    Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabelTest(" + fileName + ") END - ItemData is NULL");
                }
            }
            catch (Exception ex)
            {
                Logger2FileSingleton.Instance.SaveLog("LabelInspectionManager.InspectLabelTest(" + fileName + ") Exception: " + ex.Message +
                                                      Environment.NewLine + " d:" + ex.InnerException?.Message +
                                                      Environment.NewLine + " s:" + ex.ToString());
            }

            return(packingLabelViewModel);
        }
Beispiel #28
0
        public void CreateWOTable()
        {
            //setup connection to database
            var db = new SQLite.SQLiteConnection(dbPath);

            //create table
            db.CreateTable <Workorder>();


            //create employee
            Workorder wo1 = new Workorder(2564, 'A', "Dishwasher Not draining", null);
            Workorder wo2 = new Workorder(8004, 'F', "AC unit not blowing cold air", "9326");


            ////store the object
            db.Insert(wo1);
            db.Insert(wo2);
        }
        public static int SetWorkorder(Workorder wOld, Workorder wNew)
        {
            int count = 0;
            var conn  = DBConnection.GetDBConnection();
            var cmd   = new SqlCommand("spupdateworkorder", conn);

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(@"workorderid", SqlDbType.Int).Value        = wOld.WorkorderID;
            cmd.Parameters.Add(@"workorderdate", SqlDbType.DateTime).Value = wNew.WorkorderDate;
            cmd.Parameters.Add(@"bidid", SqlDbType.Int).Value                         = wNew.BidID;
            cmd.Parameters.Add(@"expecteddate", SqlDbType.DateTime).Value             = wNew.ExpectedDate;
            cmd.Parameters.Add(@"customerid", SqlDbType.Int).Value                    = wNew.CustomerID;
            cmd.Parameters.Add(@"description", SqlDbType.VarChar, 150).Value          = wNew.Description;
            cmd.Parameters.Add(@"employeeid", SqlDbType.Int).Value                    = wNew.EmployeeID;
            cmd.Parameters.Add(@"workorderstatus", SqlDbType.Char, 1).Value           = wNew.Status;
            cmd.Parameters.Add(@"contracttype", SqlDbType.Char, 1).Value              = wNew.ContractType;
            cmd.Parameters.Add(@"contractamount", SqlDbType.Money).Value              = wNew.ContractAmount;
            cmd.Parameters.Add(@"partsmarkup", SqlDbType.Int).Value                   = wNew.PartsMarkup;
            cmd.Parameters.Add(@"hourlyrate", SqlDbType.Money).Value                  = wNew.HourlyRate;
            cmd.Parameters.Add(@"Original_workorderdate", SqlDbType.DateTime).Value   = wOld.WorkorderDate;
            cmd.Parameters.Add(@"Original_bidid", SqlDbType.Int).Value                = wOld.BidID;
            cmd.Parameters.Add(@"Original_expecteddate", SqlDbType.DateTime).Value    = wOld.ExpectedDate;
            cmd.Parameters.Add(@"Original_customerid", SqlDbType.Int).Value           = wOld.CustomerID;
            cmd.Parameters.Add(@"Original_description", SqlDbType.VarChar, 150).Value = wOld.Description;
            cmd.Parameters.Add(@"Original_employeeid", SqlDbType.Int).Value           = wOld.EmployeeID;
            cmd.Parameters.Add(@"Original_workorderstatus", SqlDbType.Char, 1).Value  = wOld.Status;
            cmd.Parameters.Add(@"Original_contracttype", SqlDbType.Char, 1).Value     = wOld.ContractType;
            cmd.Parameters.Add(@"Original_contractamount", SqlDbType.Money).Value     = wOld.ContractAmount;
            cmd.Parameters.Add(@"Original_partsmarkup", SqlDbType.Int).Value          = wOld.PartsMarkup;
            cmd.Parameters.Add(@"Original_hourlyrate", SqlDbType.Money).Value         = wOld.HourlyRate;

            try
            {
                conn.Open();
                count = cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                throw;
            }
            finally { conn.Close(); }
            return(count);
        }
Beispiel #30
0
        public MailMessage EscalationMail(Workorder workorder, Product product, EventMonitor eventMonitor, TimeZones timeZoneId, string receipient, string templateKey)
        {
            _cultureService.SetCulture(workorder.CustomerProblemDescription.ToLower(), workorder.Site.LocaleCode.ToLower());
            workorder.Status          = _cultureService.LocalizeWorkorderStatus(workorder.Status);
            product.OperatingStatusId = _cultureService.LocalizeEquipmentStatus(product.OperatingStatusId);
            var woCreated         = _cultureService.LocalTimeConversion(timeZoneId, (DateTime)workorder.Created);
            var escalatedAt       = _cultureService.LocalTimeConversion(timeZoneId, DateTime.Now.ToUniversalTime());
            var localizedTimeZone = _cultureService.LocalizedTimeZone(timeZoneId);
            var completion        = _cultureService.DetermineEscalationCompleted(workorder);

            var wrapper = new EscalationWrapper
            {
                Workorder        = workorder,
                Product          = product,
                EventMonitor     = eventMonitor,
                WorkorderCreated = $"{woCreated} {localizedTimeZone}",
                EscalatedAt      = $"{escalatedAt} {localizedTimeZone}",
                AssignedTech     = workorder.Tasks?.FirstOrDefault()?.AssignedPerson?.FullName,
                TaskTemplateId   = workorder.Tasks?.FirstOrDefault()?.TaskTemplateId,
                Subject          = $"{product.AssetId} @ {product.Site?.Name} {completion}",
                SubjectHeader    = completion,
                SubjectSub       = product.Group?.Name == "SUBLOCATION" ? LocalizedText.NoEquip : $"{product.Id} @ {workorder.Site.Name}",
                FooterButton     = Settings.EmailConfig.FooterButton,
                HeaderHeadset    = Settings.EmailConfig.HeaderHeadset,
                HeaderLogo       = Settings.EmailConfig.HeaderLogo,
                PortalLink       = Settings.EmailConfig.PortalLink
            };

            foreach (var task in workorder.Tasks)
            {
                foreach (var note in task.Notes)
                {
                    wrapper.NotesAndRemarks.Add(note.Text);
                }
            }

            if (wrapper.NotesAndRemarks.Count == 0)
            {
                wrapper.NotesAndRemarks.Add(LocalizedText.NoRepairRemarks);
            }

            return(ConstrutMail(wrapper, receipient, wrapper.Subject, templateKey));
        }
 public static int AddWorkorder(Workorder wNew)
 {
     try
     {
         int i = WorkorderAccessor.NewWorkorder(wNew);
         if (i != 0)
         {
             return(i);
         }
         else
         {
             throw new ApplicationException("Record not updated! An error occured.");
             //throw new ApplicationException(i.ToString());
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Beispiel #32
0
        public MailMessage WorkorderMail(Workorder workorder, Product product, string recipient, string templateKey, string status)
        {
            _cultureService.SetCulture(workorder.CustomerProblemDescription.ToLower(), workorder.Site.LocaleCode.ToLower());
            workorder.Status          = _cultureService.LocalizeWorkorderStatus(workorder.Status);
            product.OperatingStatusId = _cultureService.LocalizeEquipmentStatus(product.OperatingStatusId);
            var wrapper = new WorkorderNotificationWrapper
            {
                Workorder     = workorder,
                Product       = product,
                FooterButton  = Settings.EmailConfig.FooterButton,
                HeaderHeadset = Settings.EmailConfig.HeaderHeadset,
                HeaderLogo    = Settings.EmailConfig.HeaderLogo,
                PortalLink    = Settings.EmailConfig.PortalLink
            };

            foreach (var task in workorder.Tasks)
            {
                foreach (var note in task.Notes)
                {
                    wrapper.NotesAndRemarks.Add(note.Text);
                }
            }

            if (wrapper.NotesAndRemarks.Count == 0)
            {
                wrapper.NotesAndRemarks.Add(LocalizedText.NA);
            }

            if (status == "COMPLETE")
            {
                wrapper.Subject    = string.Format(LocalizedText.SubjectCompleted, workorder.Id);
                wrapper.SubjectSub = string.Format(LocalizedText.WorkOrderCompleted, workorder.Id);
            }
            else
            {
                wrapper.Subject    = string.Format(LocalizedText.SubjectCreated, workorder.Id);
                wrapper.SubjectSub = string.Format(LocalizedText.WorkOrderCreated, workorder.Id);
            }

            return(ConstrutMail(wrapper, recipient, wrapper.Subject, templateKey));
        }
        public JsonResult Approve(int id)
        {
            Workorder workorder = _db.Workorders.FirstOrDefault(x => x.Id == id);

            if (workorder == null)
            {
                TempData["ErrorMessage"] = "Something went wrong. Please try again later.";
                return(Json(new { success = false }));
            }

            workorder.Approved = DateTime.Now;
            workorder.Approver = User.Identity.Name;
            workorder.Rejected = null;
            workorder.Rejector = null;

            _db.SaveChanges();

            TempData["SuccessMessage"] = "Workorder has been Approved and moved to Open Workorders.";

            return(Json(new { success = true }));
        }
Beispiel #34
0
        /// <summary>
        /// Submit the form!
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false; // prevent double submission
            using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
            {
                // if the user is a designer or coordinator, they don't need to go through the approval process
                bool IsUserDesigner = Users.IsUserDesigner();
                bool NeedsApproval = !IsUserDesigner && !Users.IsUserCoordinator();
                Workorder w = new Workorder();
                w.submitted_date = DateTime.Now;
                w.submitted_by = Function.GetUserName();
                w.wotype = 4;
                w.duedate = txtDateToIssue.Text.ConvertToDate();
                w.ProgramManager = int.Parse(ddCoordinators.SelectedValue);
                w.title = txtTitleTopic.Text;
                w.status = NeedsApproval ? 1 : 2;
                db.Workorders.InsertOnSubmit(w);
                WorkOrdersNews n = new WorkOrdersNews();
                n.Workorder = w;
                n.DistributionOutlets = int.Parse(ddDistributionOutlets.SelectedValue);
                n.DistributionDetails = txtDistributionOutletsOther.Text;
                n.Contact = txtContact.Text;
                n.AdditionalNotes = txtNotes.Text;
                db.WorkOrdersNews.InsertOnSubmit(n);
                db.SubmitChanges();
                int ID = w.ID;

                // look after the files
                WO.UploadFiles(w.ID, AttachedFiles.UploadedFiles);
                // log the work order
                WO.LogAction(ID, "Work order created");
                // send notification as needed
                WO.SendNewWONotification(ID, NeedsApproval, IsUserDesigner);

                // move on!
                Response.Redirect("~/MyWorkOrders.aspx?success=true&ID=" + ID + "&type=" + w.wotype);
            }
        }
Beispiel #35
0
        /// <summary>
        /// Submitting the form!
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false; // prevent double submission
            using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
            {
                // skip the approval process for designers and program managers
                bool IsUserDesigner = Users.IsUserDesigner();
                bool NeedsApproval = !IsUserDesigner && !Users.IsUserCoordinator();
                Workorder w = new Workorder();
                w.submitted_date = DateTime.Now;
                w.submitted_by = Function.GetUserName();
                w.wotype = 2;

                // decide on the duedate based on which web work order selected
                switch (Int32.Parse(ddTypeWebWork.SelectedValue))
                {
                    case 1: // new content
                        w.duedate = txtAtoZPostingDate.Text.ConvertToDate(); break;
                    case 2: // update content
                        w.duedate = txtDateToBeChanged.Text.ConvertToDate(); break;
                    case 4: // cd989 web ad
                        w.duedate = txtWebAdPostDate.Text.ConvertToDate(); break;
                    case 5: // facebook status
                        w.duedate = txtFacebookPostDate.Text.ConvertToDate(); break;
                    default:
                    case 3: // new website
                        w.duedate = DateTime.Today; break;
                }
                w.ProgramManager = int.Parse(ddCoordinators.SelectedValue);
                w.title = ddTypeWebWork.SelectedIndex > 0 ? ddTypeWebWork.SelectedItem.Text : "Unspecified";
                w.status = NeedsApproval ? 1 : 2;
                db.Workorders.InsertOnSubmit(w);

                WorkOrdersWeb wow = new WorkOrdersWeb();
                wow.Workorder = w;
                wow.TypeWebWork = ddTypeWebWork.SelectedIndex > 0 ? int.Parse(ddTypeWebWork.SelectedValue) : (int?)null;
                wow.Website = ddWebsite.SelectedIndex > 0 ? int.Parse(ddWebsite.SelectedValue) : (int?)null;
                wow.Location = Function.GetChecklistItems(chkLocation);
                wow.AtoZLocation = txtAtoZLocation.Text;
                wow.AtoZPostingDate = txtAtoZPostingDate.Text.ConvertToDate();
                wow.AtoZRemovalDate = txtAtoZRemovalDate.Text.ConvertToDate();
                wow.AtoZHeading = txtAtoZHeading.Text;
                wow.AtoZContent = txtAtoZContent.Text;
                wow.CalEventName = txtCalEventName.Text;
                wow.CalEventLocation = txtCalEventLocation.Text;
                wow.CalEventStartDate = txtCalStartDate.Text.ConvertToDate();
                wow.CalEventStartTime = txtCalStartTime.Text;
                wow.CalEventEndDate = txtCalEndDate.Text.ConvertToDate();
                wow.CalEventEndTime = txtCalEndTime.Text;
                wow.ContactName = txtContactName.Text;
                wow.ContactEmail = txtContactEmail.Text;
                wow.EventDescription = txtEventDesc.Text;
                wow.DateToBePosted = txtDatePosted.Text.ConvertToDate();
                wow.TypeOfUpdate = ddTypeOfUpdate.SelectedIndex > 0 ? int.Parse(ddTypeOfUpdate.SelectedValue) : (int?)null;
                wow.DateToBeChanged = txtDateToBeChanged.Text.ConvertToDate();
                wow.UpdateLocation = txtURL.Text;
                wow.UpdateDescription = txtUpdateDesc.Text;
                wow.Budget = txtBudget.Text;
                wow.Timeframe = txtTimeFrame.Text;
                wow.Goals = txtGoals.Text;
                wow.Explanation = txtExplanation.Text;
                wow.Audience = txtAudience.Text;
                wow.NumberOfPages = txtNumberOfPages.Text;
                wow.WebAdPostDate = txtWebAdPostDate.Text.ConvertToDate();
                wow.WebAdEndDate = txtWebAdEndDate.Text.ConvertToDate();
                wow.WebAdURL = txtWebAdURL.Text;
                wow.WebAdContent = txtWebAdContent.Text;
                wow.FacebookPostDate = txtFacebookPostDate.Text.ConvertToDate();
                wow.FacebookContent = txtFacebookContent.Text;
                wow.Notes = txtNotes.Text;

                // if this was added on to a Print work order, let's link this to it!
                int pID = 0;
                if (int.TryParse(Request.QueryString["AddTo"], out pID))
                {
                    wow.pID = pID;
                }
                else
                    wow.pID = null;
                db.WorkOrdersWebs.InsertOnSubmit(wow);
                db.SubmitChanges();
                int ID = w.ID;

                // if we're linking print and web work orders, let's add the link to the print work order too so we can go back and forth easily
                if (pID != 0)
                {
                    WorkOrdersPrint p = db.WorkOrdersPrints.Single(u => u.wID == pID);
                    p.webID = ID;
                    db.SubmitChanges();
                }
                // upload attached files
                WO.UploadFiles(ID, AttachedFiles.UploadedFiles);
                // log actions
                WO.LogAction(ID, "Work order created.");
                // send notifications if necessary
                WO.SendNewWONotification(ID, NeedsApproval, IsUserDesigner);
                // redirect! hooray!
                Response.Redirect("~/MyWorkOrders.aspx?success=true&ID=" + ID + "&type=" + w.wotype);
            }
        }