protected LoginViewModel()
 {
     USERS = USERCollectionViewModel.Create();
     USERS.Entities.ToList();
     UserName = XMLHelpers.GetSettings_Username();
     Application.Current.Dispatcher.BeginInvoke(new Action(() => EVERNPCLogin()));
 }
        public override object Deserialize(XMLReader input)
        {
            var backingArr = new List <object>();

            int depth = input.Depth;

            input.GoToNextTag();
            XMLTypeHandler handler = XMLHelpers.GetDerivedTypeHandlerFromXMLTag(input, out string tag) ?? _elementTypeHandler;

            while (input.Depth >= depth && !input.Finished)
            {
                object newObj = tag.Contains("/") ? null : handler.Deserialize(input);
                backingArr.Add(newObj);
                input.GoToNextTag();
                handler = XMLHelpers.GetDerivedTypeHandlerFromXMLTag(input, out tag) ?? _elementTypeHandler;
            }

            Type listGenericType = XMLHelpers.ListType.MakeGenericType(_elementType);
            var  list            = (IList)Activator.CreateInstance(listGenericType, backingArr.Count);

            for (var i = 0; i < backingArr.Count; i++)
            {
                list.Add(backingArr[i]);
            }

            return(list);
        }
Ejemplo n.º 3
0
        public ProjectInfo GetProjectInfo(string ProjectPath)
        {
            try {
                ProjectInfo pro          = new ProjectInfo();
                string      ProductName  = XMLHelpers.ReadProNodeValue(ProjectPath, "Project", "ProductName");
                string      Guidstr      = XMLHelpers.ReadProNodeValue(ProjectPath, "Project", "GUID");
                string      ProductGN    = XMLHelpers.ReadProNodeValue(ProjectPath, "Project", "ProductGN");
                string      ProjectName  = XMLHelpers.ReadProNodeValue(ProjectPath, "Project", "ProjectName");
                string      ProductUse   = XMLHelpers.ReadProNodeValue(ProjectPath, "Project", "ProductUse");
                string      ExperAddress = XMLHelpers.ReadProNodeValue(ProjectPath, "Project", "ExperAddress");
                string      ExperTime    = XMLHelpers.ReadProNodeValue(ProjectPath, "Project", "ExperTime");

                pro.ProductName  = ProductName;
                pro.ProductGN    = ProductGN;
                pro.GUID         = Guid.Parse(Guidstr);
                pro.ProductUse   = ProductUse;
                pro.ProjectName  = ProjectName;
                pro.ProjectPath  = ProjectPath;
                pro.ExperAddress = ExperAddress;
                pro.ExperTime    = ExperTime;

                return(pro);
            }
            catch {
                return(null);
            }
        }
Ejemplo n.º 4
0
        private void BtnOk_Click(object sender, RoutedEventArgs e)
        {
            string firstName   = tbFirstName.Text;
            string lastName    = tbLastName.Text;
            string phoneNumber = tbPhoneNumber.Text;
            string email       = tbEmail.Text;
            string address     = tbAddress.Text;

            //Validate values
            if (string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(lastName) || string.IsNullOrWhiteSpace(phoneNumber))
            {
                MessageHelper.ShowWarningMessage("First Name, Last Name and Phone Number are mandatory!", "Information Error");
                return;
            }
            //If ok

            // Create new employee object
            Employee employee = new Employee(firstName, lastName, phoneNumber, email, address);
            string   newID    = UtilsHelper.GenerateID(employee);

            employee.ID = newID;

            // Store employee into DAO
            XMLHelpers.Instance().Employees.Add(employee);
            DialogResult = true;
            this.Close();
        }
Ejemplo n.º 5
0
 public void CreateProjectInfoFile(ProjectInfo pro)
 {
     try {
         XMLHelpers.CreateProjectInfo(pro);
     }
     catch { }
 }
Ejemplo n.º 6
0
        public void ReadXml(XmlReader reader)
        {
            bool wasEmpty = reader.IsEmptyElement;

            reader.Read();

            if (wasEmpty)
            {
                return;
            }
            m_Name = reader.ReadElementString("Name");
            string propTypeStr = reader.ReadElementString("PropertyType");

            Type propType = null;

            try
            {
                propType = Type.GetType(propTypeStr);
            }
            catch { }

            if (propType != null)
            {
                Property = XMLHelpers.Deserialise(reader, propType);
            }
        }
        public ActionResult Delete(FormCollection form)
        {
            //Start by reading the XMLDocument
            Users users = XMLHelpers.ReadUsersFromXml();

            if (users != null)
            {
                string userIdCsv = form["relatedUsers"];

                if (userIdCsv != null)
                {
                    string[] userIdList = userIdCsv.Split(',');
                    foreach (var id in userIdList)
                    {
                        int convertedId = Convert.ToInt32(id);
                        XMLHelpers.RemoveXmlUser(convertedId);
                    }
                }
            }

            //Redirecting to same page to avoid weird URL's - normally i would post using ajax, but im too lazy right now.
            string url = this.Request.UrlReferrer.AbsolutePath;

            return(Redirect(url));

            //DevelopXmlModel model = new DevelopXmlModel()
            //{
            //    Users = XMLHelpers.ReadUsersFromXml(),
            //    CreateUserForm = new UserData()
            //};
            //return View("Index", model);
        }
        // GET: DevelopXml
        public ActionResult Create(DevelopXmlModel data, FormCollection form)
        {
            UserData formData = data.CreateUserForm;

            formData.RelatedUsers = new List <int>();
            string userIdCsv = form["relatedUsers"];

            if (userIdCsv != null)
            {
                string[] userIdList = userIdCsv.Split(',');
                foreach (var id in userIdList)
                {
                    int convertedId = Convert.ToInt32(id);
                    formData.RelatedUsers.Add(convertedId);
                }
            }

            bool result = XMLHelpers.NewUserAsXml(formData);

            //Redirecting to same page to avoid weird URL's - normally i would post using ajax, but im too lazy right now.
            string url = this.Request.UrlReferrer.AbsolutePath;

            return(Redirect(url));

            //DevelopXmlModel model = new DevelopXmlModel()
            //{
            //    Users = XMLHelpers.ReadUsersFromXml(),
            //    CreateUserForm = new UserData()
            //};
            //return View("Index", model,);
        }
Ejemplo n.º 9
0
 bool GetXml()
 {
     try
     {
         if (!string.IsNullOrEmpty(site))
         {
             XMLHelpers xml = new XMLHelpers("BaiduPanSearch");
             webUrl      = xml.GetValue(site + "WebUrl");
             webUrl      = webUrl.Replace("SearchKey", key).Replace("PageIndex", pageNum.ToString());
             xpathNodes  = xml.GetValue(site + "Nodes");
             xpathUrl    = xml.GetValue(site + "Url");
             xpathName   = xml.GetValue(site + "Name");
             xpathSize   = xml.GetValue(site + "Size");
             xpathUpload = xml.GetValue(site + "Upload");
             if (string.IsNullOrEmpty(webUrl))
             {
                 return(false);
             }
         }
     }
     catch (Exception ex)
     {
         ex.ToShow();
         return(false);
     }
     return(true);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Metodo que Realiza a consulta
        /// O retorno é do tipo ResultadoConsulta
        /// </summary>
        /// <param name="filtro">Parametros para a consulta</param>
        /// <returns></returns>
        public ResultadoConsulta Consultar(FiltroConsulta filtro)
        {
            String URI = _Dominio + "/api/Consulta";

            String encoded = _UserEncoded;

            String requestXml = XMLHelpers.SerializeObjectToXML <FiltroConsulta>(filtro);

            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);

            request.Method = "POST";
            request.Headers.Add("Authorization", "Basic " + encoded);
            request.ContentType = "application/xml";

            request.ContentLength = bytes.Length;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            String result = String.Empty;
                            result = reader.ReadToEnd();

                            return(XMLHelpers.DeserializeXMLToObject <ResultadoConsulta>(result));
                        }
                    }
                }
            }
            catch (WebException Webex)
            {
                using (Stream dataStream = Webex.Response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        String result = String.Empty;
                        result = reader.ReadToEnd();

                        throw new Exception(result, Webex);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        // GET: DevelopXml
        public ActionResult Index()
        {
            DevelopXmlModel model = new DevelopXmlModel()
            {
                Users          = XMLHelpers.ReadUsersFromXml(),
                CreateUserForm = new UserData()
            };

            return(View(model));
        }
Ejemplo n.º 12
0
        public override object Deserialize(XMLReader input)
        {
            int    depth  = input.Depth;
            object newObj = Activator.CreateInstance(Type, true);

            input.GoToNextTag();
            while (input.Depth >= depth && !input.Finished)
            {
                XMLTypeHandler inheritedHandler = XMLHelpers.GetInheritedTypeHandlerFromXMLTag(input, out string currentTag);
                var            nullValue        = false;
                if (currentTag[^ 1] == '/')
Ejemplo n.º 13
0
        public void Login(string userName, string password)
        {
            Thread.Sleep(5000);

            IWebElement txtUserName = XMLHelpers.readObjectValues("userNameLogin");

            txtUserName.AssertElementPresent();
            txtUserName.SendKeys(userName);

            //txtUserName.SendKeys(userName);
            txtPassword.SendKeys(password);
        }
        public override object Deserialize(XMLReader input)
        {
            var backingList = new List <object>();

            int depth = input.Depth;

            input.GoToNextTag();
            XMLTypeHandler handler = XMLHelpers.GetDerivedTypeHandlerFromXMLTag(input, out string tag) ?? _elementTypeHandler;

            while (input.Depth >= depth && !input.Finished)
            {
                object newObj = tag[^ 1] == '/' ? null : handler.Deserialize(input);
Ejemplo n.º 15
0
        /// <summary>
        /// Metodo que retorna todos os produtos habilitados para o cliente
        /// /// o retorno é do tipo Produto[]
        /// </summary>
        /// <returns></returns>
        public Produto[] ListarProduto()
        {
            String URI = _Dominio + "/api/ListarProdutos";

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI);

            request.Method = "GET";
            request.Headers.Add("Authorization", "Basic " + _UserEncoded);
            request.ContentType = "application/xml";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            String result = String.Empty;
                            result = reader.ReadToEnd();

                            return(XMLHelpers.DeserializeXMLToObject <Produto[]>(result));
                        }
                    }
                }
            }
            catch (WebException Webex)
            {
                var response = (HttpWebResponse)Webex.Response;
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new Exception(Webex.Message, Webex);
                }
                using (Stream dataStream = Webex.Response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        String result = String.Empty;
                        result = reader.ReadToEnd();

                        throw new Exception(result, Webex);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// When Window is loaded
        /// The program read data from DAO Layer and
        /// push data to viewmodel for using binding in View
        /// </summary>
        private void UpdateRelatedAppointmentInfo()
        {
            NailSalonXMLDAO NailSalonDAO = XMLHelpers.Instance();

            //Load Employees
            appointmentViewModel.EmployeeList = NailSalonDAO.Employees;
            //Load Services
            appointmentViewModel.Services = NailSalonDAO.Services;
            //Update current date
            appointmentViewModel.Today = DateTime.Now;
            if (StateHelper.IsEditedAppointmentMode == false && UtilsHelper.IsEndThedate())
            {
                dpCurrentDate.SelectedDate = DateTime.Now.AddDays(1);
            }
        }
Ejemplo n.º 17
0
        protected virtual Dictionary <string, XMLFieldHandler> IndexFields()
        {
            // Gather fields and create field handlers for them.
            PropertyInfo[] properties    = Type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            FieldInfo[]    fields        = Type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            var            fieldHandlers = new Dictionary <string, XMLFieldHandler>(properties.Length + fields.Length);

            for (var i = 0; i < properties.Length; i++)
            {
                PropertyInfo property = properties[i];

                // Only serialize properties with public get; set; and who aren't marked as "DontSerialize"
                MethodInfo readMethod  = property.GetMethod;
                MethodInfo writeMethod = property.SetMethod;
                if (!property.CanRead || !property.CanWrite || readMethod == null || writeMethod == null || !readMethod.IsPublic || !writeMethod.IsPublic ||
                    property.CustomAttributes.Any(x => x.AttributeType == XMLHelpers.DontSerializeAttributeType))
                {
                    continue;
                }

                XMLFieldHandler handler = XMLHelpers.ResolveFieldHandler(property.PropertyType, new XMLReflectionHandler(property));
                if (handler == null)
                {
                    continue;
                }
                fieldHandlers.TryAdd(property.Name, handler);
            }

            for (var i = 0; i < fields.Length; i++)
            {
                FieldInfo field = fields[i];

                // Exclude fields marked as "DontSerialize"
                if (field.CustomAttributes.Any(x => x.AttributeType == XMLHelpers.DontSerializeAttributeType))
                {
                    continue;
                }

                XMLFieldHandler handler = XMLHelpers.ResolveFieldHandler(field.FieldType, new XMLReflectionHandler(field));
                if (handler == null)
                {
                    continue;
                }
                fieldHandlers.TryAdd(field.Name, handler);
            }

            return(fieldHandlers);
        }
Ejemplo n.º 18
0
        public XMLKeyValueTypeHandler(Type type) : base(type)
        {
            PropertyInfo keyProperty = Type.GetProperty("Key");

            _keyHandler = new Lazy <XMLFieldHandler>(() => XMLHelpers.ResolveFieldHandler(keyProperty.PropertyType, new XMLReflectionHandler(keyProperty)));
            PropertyInfo valueProperty = Type.GetProperty("Value");

            _valueHandler = new Lazy <XMLFieldHandler>(() => XMLHelpers.ResolveFieldHandler(valueProperty.PropertyType, new XMLReflectionHandler(valueProperty)));

            Type opaqueKeyType = XMLHelpers.GetOpaqueType(keyProperty.PropertyType, out bool opaque);

            _keyDefault = opaque && opaqueKeyType.IsValueType ? Activator.CreateInstance(opaqueKeyType) : null;
            Type opaqueValueType = XMLHelpers.GetOpaqueType(valueProperty.PropertyType, out opaque);

            _valueDefault = opaque && opaqueValueType.IsValueType ? Activator.CreateInstance(opaqueValueType) : null;
        }
        public void ReadXml(XmlReader reader)
        {
            bool wasEmpty = reader.IsEmptyElement;

            reader.Read();
            if (wasEmpty)
            {
                return;
            }

            m_BaseValue = reader.ReadElementContentAsInt("BaseValue", string.Empty);

            reader.ReadStartElement("Modifiers");
            if (!reader.IsEmptyElement)
            {
                while (reader.NodeType != XmlNodeType.EndElement)
                {
                    reader.ReadStartElement("Modifier");
                    string typeString = reader.ReadElementString("Type");

                    Type modifierType = null;
                    try
                    {
                        modifierType = Type.GetType(typeString);
                    }
                    catch { }

                    if (modifierType != null)
                    {
                        var newMod = XMLHelpers.Deserialise(reader, modifierType) as INumericalPropertyModifier <int, KDMNumericalPropertyContext, KDMNumericalPropertyModifierReader>;
                        if (newMod != null)
                        {
                            m_Modifiers.Add(newMod);
                        }
                    }
                    else
                    {
                        reader.Skip();
                    }

                    reader.ReadEndElement();
                    reader.MoveToContent();
                }
            }

            Update();
        }
Ejemplo n.º 20
0
        private bool UserAuthenticate()
        {
            USER user = USERS.Entities.FirstOrDefault(x => x.NAME == UserName);

            if (user == null)
            {
                ShowError(false, "Username not found");
                return(false);
            }
            else
            {
                if (user.GUID_ROLE == Guid.Empty)
                {
                    ShowError(false, "No role assigned on user");
                    return(false);
                }

                if (UserName != null && UserPassword != null)
                {
                    if (ActiveDirectory.Authenticate(UserName, UserPassword))
                    {
                        ShowError(false, null);
                        ShowError(true, null);
                        XMLHelpers.UpdateSettingsXML(new XMLSettings()
                        {
                            Username = UserName.Trim()
                        });
                        return(true);
                    }
                    else
                    {
                        SetUsernamePasswordError();
                        XMLHelpers.UpdateSettingsXML(new XMLSettings()
                        {
                            Username = string.Empty
                        });
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 21
0
        public static object?TransformClass(object window, Type newType)
        {
            var oldTypeHandler = (XMLComplexBaseTypeHandler?)XMLHelpers.GetTypeHandler(window.GetType());
            var newTypeHandler = (XMLComplexBaseTypeHandler?)XMLHelpers.GetTypeHandler(newType);

            if (oldTypeHandler == null || newTypeHandler == null)
            {
                return(null);
            }

            object?newTypeObject = Activator.CreateInstance(newType, true);

            Debug.Assert(newTypeObject != null);

            IEnumerator <XMLFieldHandler>?oldFields = oldTypeHandler.EnumFields();

            while (oldFields.MoveNext())
            {
                XMLFieldHandler oldField = oldFields.Current;

                XMLFieldHandler?newFieldsMatch          = null;
                IEnumerator <XMLFieldHandler>?newFields = newTypeHandler.EnumFields();
                while (newFields.MoveNext())
                {
                    XMLFieldHandler newField = newFields.Current;
                    if (newField.Name != oldField.Name || newField.TypeHandler != oldField.TypeHandler)
                    {
                        continue;
                    }
                    newFieldsMatch = newField;
                    break;
                }

                if (newFieldsMatch == null)
                {
                    continue;
                }
                object value = oldField.ReflectionInfo.GetValue(window);
                newFieldsMatch.ReflectionInfo.SetValue(newTypeObject, value);
            }

            return(newTypeObject);
        }
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("BaseValue", m_BaseValue.ToString());

            writer.WriteStartElement("Modifiers");
            int count = m_Modifiers.Count;

            for (int i = 0; i < count; ++i)
            {
                writer.WriteStartElement("Modifier");

                var mod = m_Modifiers[i];
                writer.WriteElementString("Type", mod.GetType().AssemblyQualifiedName);

                XMLHelpers.Serialize(mod, writer);

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Ejemplo n.º 23
0
 void BindSite()
 {
     try
     {
         XMLHelpers xML  = new XMLHelpers("BaiduPanSearch");
         string     temp = xML.GetValue("WebNameList");
         if (!string.IsNullOrEmpty(temp))
         {
             string[] siteList = temp.ToSplit("|");
             cb_site.Items.Clear();
             foreach (var item in siteList)
             {
                 cb_site.Items.Add(item);
             }
         }
     }
     catch (Exception ex)
     {
         ex.ToShow();
     }
 }
Ejemplo n.º 24
0
        public void WriteXml(XmlWriter writer)
        {
            int typeCount = m_AllowedTypes.Count;

            if (typeCount > 0)
            {
                writer.WriteStartElement("AllowedTypes");
                for (int i = 0; i < typeCount; i++)
                {
                    writer.WriteStartElement("PropertyType")
                    ;
                    writer.WriteElementString("Type", m_AllowedTypes[i].Type.FullName);
                    if (!string.IsNullOrEmpty(m_AllowedTypes[i].FilterData))
                    {
                        writer.WriteElementString("FilterData", m_AllowedTypes[i].FilterData);
                    }

                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }

            int itemCount = Items.Count;

            if (itemCount > 0)
            {
                writer.WriteStartElement("Items");
                for (int i = 0; i < itemCount; i++)
                {
                    writer.WriteStartElement("Item");

                    writer.WriteElementString("Type", Items[i].GetType().FullName);

                    XMLHelpers.Serialize(Items[i], writer);

                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Saves the changes
        /// </summary>
        /// <returns></returns>
        public async Task <IFailable> SaveChangesAsync()
        {
            // Create the result
            var result = new Failable();

            try
            {
                // Get the directory path
                var directoryPath = Path.GetDirectoryName(OptionsFileName);

                // If the directory doesn't exist...
                if (!Directory.Exists(directoryPath))
                {
                    // Create it
                    Directory.CreateDirectory(directoryPath);
                }

                // Get the options
                var options = ToOptions();

                // Save the options
                XMLHelpers.ToXmlFile(options, OptionsFileName, new XmlWriterSettings());

                // Get the page builder
                var pageBuilder = CeidDiplomatikiDI.GetCeidDiplomatikiMainPageBuilder;

                // Refresh the main page
                pageBuilder.Refresh();
            }
            catch (Exception ex)
            {
                // Set the error
                result.ErrorMessage = ex.Message;
            }

            // Return the result
            return(await Task.FromResult(result));
        }
Ejemplo n.º 26
0
        public void DeserializeKeyValue(XMLReader input, out object key, out object value)
        {
            key   = _keyDefault;
            value = _valueDefault;

            int depth = input.Depth;

            input.GoToNextTag();
            while (input.Depth >= depth && !input.Finished)
            {
                XMLTypeHandler handler = XMLHelpers.GetDerivedTypeHandlerFromXMLTag(input, out string currentTag);
                switch (currentTag)
                {
                case "Key":
                    if (handler == null)
                    {
                        handler = _keyHandler.Value.TypeHandler;
                    }
                    key = handler.Deserialize(input);
                    break;

                case "Value":
                    if (handler == null)
                    {
                        handler = _valueHandler.Value.TypeHandler;
                    }
                    value = handler.Deserialize(input);
                    break;

                default:
                    Engine.Log.Warning($"Unknown deserialization tag in KVP - {currentTag}.", MessageSource.XML);
                    return;
                }

                input.GoToNextTag();
            }
        }
Ejemplo n.º 27
0
        public XMLComplexTypeHandler(Type type) : base(type)
        {
            // Check if inheriting anything. If so copy its excluded members as well.
            if (Type.BaseType != null && Type.BaseType != typeof(object))
            {
                var baseClass = (XMLComplexTypeHandler)XMLHelpers.GetTypeHandler(Type.BaseType);
                HashSet <string> baseTypeExcludedMembers = baseClass?._excludedMembers;
                if (baseTypeExcludedMembers != null)
                {
                    if (_excludedMembers == null)
                    {
                        _excludedMembers = baseTypeExcludedMembers;
                    }
                    else
                    {
                        // Copy hashset as not to modify reference of attribute.
                        var newHashSet = new HashSet <string>();
                        foreach (string excludedMember in _excludedMembers)
                        {
                            newHashSet.Add(excludedMember);
                        }

                        // Add values from base type.
                        foreach (string excludedMember in baseTypeExcludedMembers)
                        {
                            newHashSet.Add(excludedMember);
                        }

                        _excludedMembers = newHashSet;
                    }
                }
            }

            // Create default value reference.
            _defaultConstruct = type.IsInterface || type.IsAbstract ? null : Activator.CreateInstance(type, true);
        }
 public XMLArrayTypeHandler(Type type, Type elementType) : base(type)
 {
     _elementTypeHandler = XMLHelpers.GetTypeHandler(elementType);
     _elementType        = elementType; // non-opaque
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Create a handler for a type.
 /// </summary>
 /// <param name="type">The type to handle.</param>
 protected XMLTypeHandler(Type type)
 {
     Type     = type;
     TypeName = XMLHelpers.GetTypeName(Type);
 }
        /// <summary>
        /// Get Data from window
        /// Create new customer and appointment
        /// Save into DAO layer
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnOk_Click(object sender, RoutedEventArgs e)
        {
            string firstName   = tbFirstName.Text;
            string lastName    = tbLastName.Text;
            string phoneNumber = tbPhoneNumber.Text;
            string email       = tbEmail.Text;
            string address     = tbAddress.Text;

            Customer customer = new Customer(firstName, lastName, phoneNumber, email, address);

            customer.ID = UtilsHelper.GenerateID(customer);
            //Add new customer into DAO
            XMLHelpers.Instance().Customers.Add(customer);

            if (string.IsNullOrWhiteSpace(firstName) ||
                string.IsNullOrWhiteSpace(lastName) ||
                string.IsNullOrWhiteSpace(phoneNumber))
            {
                MessageHelper.ShowWarningMessage("First Name, Last Name and Phone Number are mandatory!", "Error");
                return;
            }

            DateTime date = dpCurrentDate.SelectedDate.Value.Date;

            if (cbTime.SelectedItem == null || cbService.SelectedItem == null || cbNailTechnician.SelectedItem == null)
            {
                MessageHelper.ShowWarningMessage("Date , Time, Service and Employee are mandatory!", "Error");
                return;
            }

            TimeSpan selectedTime = TimeSpan.FromHours(((DateTime)cbTime.SelectedItem).Hour);

            date = date.Date + selectedTime;
            Service  service  = (Service)cbService.SelectedItem;
            Employee employee = (Employee)cbNailTechnician.SelectedItem;


            Appointment newAppointment = new  Appointment(date, customer, service, employee);

            newAppointment.ID = UtilsHelper.GenerateID(newAppointment);

            if (StateHelper.IsEditedAppointmentMode)
            {
                newAppointment.ID = StateHelper.EditedAppointment.ID;
            }

            //Check is valid appointment
            if (!UtilsHelper.IsEmployeeAvailableOn(date, employee, newAppointment))
            {
                MessageHelper.ShowWarningMessage(String.Format("Technician {0} is not available on that time\nPlease choose another time!", employee.FullName), "Appointment");
                return;
            }

            //Update Appointment into DAO when open this windom for editing
            if (StateHelper.IsEditedAppointmentMode)
            {
                //Check is valid appointment

                int index = XMLHelpers.Instance().Appointments.FindIndex(appointment => appointment.ID == StateHelper.EditedAppointment.ID);
                XMLHelpers.Instance().Appointments[index] = newAppointment;
            }
            else
            {
                // Add new appointment into DAO
                XMLHelpers.Instance().Appointments.Add(newAppointment);
            }



            DialogResult = true;

            //Reset Selected Appointment for updating
            ResetState();
            this.Close();
        }