private string Serialize(MitchellClaim cla)
        {
            string XmlizedString = null;

            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(MitchellClaim));
                //create an instance of the MemoryStream class since we intend to keep the XML string 
                //in memory instead of saving it to a file.
                MemoryStream memoryStream = new MemoryStream();
                //XmlTextWriter - fast, non-cached, forward-only way of generating streams or files 
                //containing XML data
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                //Serialize emp in the xmlTextWriter
                xs.Serialize(xmlTextWriter, cla);
                //Get the BaseStream of the xmlTextWriter in the Memory Stream
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                //Convert to array
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            }
            catch (Exception ex)
            {

            }

            return XmlizedString;
        }
        public void CreateClaim(MitchellClaim cla)
        {
            dal = new DAL(connString);

            dal.DBCreateClaim(cla);
        }
        public int DBCreateVehicleList(MitchellClaim newClaim)
        {
            int newVehicleListID = 0;

            try
            {
                using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
                {
                    connection.Open();

                    string query = " INSERT INTO VehicleList (VListClaimNumber) VALUES (:VListClaimNumber) RETURNING VListID; ";

                    using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
                    {
                        command.Parameters.Add(new NpgsqlParameter("VListClaimNumber", NpgsqlDbType.Varchar));

                        command.Parameters[0].Value = newClaim.ClaimNumber;

                        newVehicleListID = Int32.Parse(command.ExecuteScalar().ToString().Trim());
                    }
                }
            }
            catch (Exception ex)
            {
                // Error handling
                Console.WriteLine("Error in DBCreateVehicleList: " + ex.Message);
            }
            finally
            {

            }

            if (newClaim.Vehicles.VehicleDetails.Count > 0)
            {
                // Store each vehicle in the claim in the database
                foreach (VehicleDetails v in newClaim.Vehicles.VehicleDetails)
                {
                    DBCreateVehicles(v, newVehicleListID);
                }
            }

            //Console.WriteLine("Added vehicle list ID: " + newVehicleListID);
            return newVehicleListID;
        }
        private MitchellClaim Deserialize(byte[] xmlByteData)
        {
            MitchellClaim cla = new MitchellClaim();

            try
            {
                XmlSerializer ds = new XmlSerializer(typeof(MitchellClaim));
                MemoryStream memoryStream = new MemoryStream(xmlByteData);
                cla = (MitchellClaim)ds.Deserialize(memoryStream);
            }
            catch (Exception ex)
            {

            }

            return cla;
        }
        public void DBCreateClaim(MitchellClaim newClaim)
        {
            try
            {
                using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
                {
                    connection.Open();

                    string query =
                        " INSERT INTO MitchellClaims (ClaimNumber, ClaimantFirstName, ClaimantLastName, Status, LossDate, LossInfo, AssignedAdjusterID, Vehicles) " +
                        " VALUES (:ClaimNumber, :ClaimantFirstName, :ClaimantLastName, :Status, :LossDate, :LossInfo, :AssignedAdjusterID, :Vehicles); ";

                    using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
                    {
                        command.Parameters.Add(new NpgsqlParameter("ClaimNumber", NpgsqlDbType.Varchar));
                        command.Parameters.Add(new NpgsqlParameter("ClaimantFirstName", NpgsqlDbType.Varchar));
                        command.Parameters.Add(new NpgsqlParameter("ClaimantLastName", NpgsqlDbType.Varchar));
                        command.Parameters.Add(new NpgsqlParameter("Status", NpgsqlDbType.Integer));
                        command.Parameters.Add(new NpgsqlParameter("LossDate", NpgsqlDbType.Timestamp));
                        command.Parameters.Add(new NpgsqlParameter("LossInfo", NpgsqlDbType.Integer));
                        command.Parameters.Add(new NpgsqlParameter("AssignedAdjusterID", NpgsqlDbType.Bigint));
                        command.Parameters.Add(new NpgsqlParameter("Vehicles", NpgsqlDbType.Integer));

                        command.Parameters[0].Value = newClaim.ClaimNumber;
                        command.Parameters[1].Value = (newClaim.ClaimantFirstName == "") ? ("") : (newClaim.ClaimantFirstName);
                        command.Parameters[2].Value = (newClaim.ClaimantLastName == "") ? ("") : (newClaim.ClaimantLastName);
                        command.Parameters[3].Value = (newClaim.Status == "OPEN") ? (1) : (2);
                        command.Parameters[4].Value = newClaim.LossDate;
                        command.Parameters[5].Value = DBCreateLossInfo(newClaim.LossInfo);
                        command.Parameters[6].Value = newClaim.AssignedAdjusterID;
                        command.Parameters[7].Value = DBCreateVehicleList(newClaim);
                        
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                // Error handling
                Console.WriteLine("Error in DBCreateClaim: " + ex.Message);
            }
            finally
            {

            }
        }
        public MitchellClaim DBGetClaimByID(string claimNum)
        {
            MitchellClaim ret = new MitchellClaim();

            try
            {
                using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
                {
                    connection.Open();

                    string query =
                        " SELECT * " +
                        " FROM (( " +
                        "         MitchellClaims LEFT JOIN StatusCode ON (MitchellClaims.Status = StatusCode.StatusID) " +
                        "     ) AS withStatus LEFT JOIN LossInfo ON (withStatus.LossInfo = LossInfo.LossInfoID) " +
                        " ) AS withLossInfo LEFT JOIN CauseOfLossCode ON (withLossInfo.CauseOfLoss = CauseOfLossCode.CauseID) " +
                        " WHERE ClaimNumber = :ClaimNumber ";

                    using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
                    {
                        command.Parameters.Add(new NpgsqlParameter("ClaimNumber", NpgsqlDbType.Varchar));

                        command.Parameters[0].Value = claimNum;

                        using (NpgsqlDataReader dr = command.ExecuteReader())
                        {
                            if (dr.Read())
                            {
                                ret = new MitchellClaim()
                                {
                                    ClaimNumber = dr["ClaimNumber"].ToString().Trim(),
                                    ClaimantFirstName = dr["ClaimantFirstName"].ToString().Trim(),
                                    ClaimantLastName = dr["ClaimantLastName"].ToString().Trim(),
                                    Status = dr["StatusDesc"].ToString().Trim(),
                                    LossDate = DateTime.Parse(dr["LossDate"].ToString().Trim()),
                                    LossInfo = new LossInfoType()
                                    {
                                        CauseOfLoss = dr["CauseDesc"].ToString().Trim(),
                                        ReportedDate = DateTime.Parse(dr["ReportedDate"].ToString().Trim()),
                                        LossDescription = dr["LossDescription"].ToString().Trim()
                                    },
                                    AssignedAdjusterID = long.Parse(dr["AssignedAdjusterID"].ToString().Trim()),
                                    Vehicles = new Vehicles()
                                };
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Error handling
                Console.WriteLine("Error in DBGetClaimByID(string claimNum): " + ex.Message);
            }
            finally
            {

            }

            return ret;
        }
        private MitchellClaim CreateArbitrary(DateTime lossDate)
        {
            // Create arbitrary claim
            MitchellClaim cla = new MitchellClaim()
            {
                ClaimNumber = GenerateRandomString(10),
                ClaimantFirstName = GenerateRandomString(10),
                ClaimantLastName = GenerateRandomString(10),
                Status = "OPEN",
                LossDate = lossDate,
                LossInfo = new LossInfoType()
                {
                    CauseOfLoss = "Collision",
                    ReportedDate = new DateTime(),
                    LossDescription = GenerateRandomString(50)
                },
                AssignedAdjusterID = 12345,
                Vehicles = new Vehicles()
                {
                    VehicleDetails = new List<VehicleDetails>()
                        {
                            new VehicleDetails()
                            {
                                ModelYear = 2015,
                                MakeDescription = GenerateRandomString(10),
                                ModelDescription = GenerateRandomString(10),
                                EngineDescription = GenerateRandomString(10),
                                ExteriorColor = GenerateRandomString(10),
                                Vin = GenerateRandomString(10),
                                LicPlate = GenerateRandomString(10),
                                LicPlateState = "CA",
                                LicPlateExpDate = new DateTime(),
                                DamageDescription = GenerateRandomString(50),
                                Mileage = 1000
                            }
                        }
                }
            };

            return cla;
        }
        private static byte[] GenerateXMLClaim(MitchellClaim cla)
        {
            // Create the xml document in a memory stream - Recommended
            MemoryStream mStream = new MemoryStream();
            //XmlTextWriter xmlWriter = new XmlTextWriter(@"C:\Employee.xml", Encoding.UTF8);
            XmlTextWriter xmlWriter = new XmlTextWriter(mStream, Encoding.UTF8);
            xmlWriter.Formatting = Formatting.Indented;

            //xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("MitchellClaim");

            xmlWriter.WriteStartElement("ClaimNumber");
            xmlWriter.WriteString(cla.ClaimNumber);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("ClaimantFirstName");
            xmlWriter.WriteString(cla.ClaimantFirstName);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("ClaimantLastName");
            xmlWriter.WriteString(cla.ClaimantLastName);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("Status");
            xmlWriter.WriteString(cla.Status);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("LossDate");
            xmlWriter.WriteValue(cla.LossDate);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("LossInfo");
            xmlWriter.WriteStartElement("CauseOfLoss");
            xmlWriter.WriteString(cla.LossInfo.CauseOfLoss);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("ReportedDate");
            xmlWriter.WriteValue(cla.LossInfo.ReportedDate);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("LossDescription");
            xmlWriter.WriteString(cla.LossInfo.LossDescription);
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("AssignedAdjusterID");
            xmlWriter.WriteValue(cla.AssignedAdjusterID);
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("Vehicles");
            foreach (VehicleDetails v in cla.Vehicles.VehicleDetails)
            {
                xmlWriter.WriteStartElement("VehicleDetails");
                xmlWriter.WriteStartElement("ModelYear");
                xmlWriter.WriteValue(v.ModelYear);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("MakeDescription");
                xmlWriter.WriteString(v.MakeDescription);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("ModelDescription");
                xmlWriter.WriteString(v.ModelDescription);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("EngineDescription");
                xmlWriter.WriteString(v.EngineDescription);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("ExteriorColor");
                xmlWriter.WriteString(v.ExteriorColor);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("Vin");
                xmlWriter.WriteString(v.Vin);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("LicPlate");
                xmlWriter.WriteString(v.LicPlate);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("LicPlateState");
                xmlWriter.WriteString(v.LicPlateState);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("LicPlateExpDate");
                xmlWriter.WriteValue(v.LicPlateExpDate);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("DamageDescription");
                xmlWriter.WriteString(v.DamageDescription);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("Mileage");
                xmlWriter.WriteValue(v.Mileage);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
            }
            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndElement();
            //xmlWriter.WriteEndDocument();

            xmlWriter.Flush();
            xmlWriter.Close();
            return mStream.ToArray();
        }
        private void ReqCreateClaim(MitchellClaim cla)
        {
            try
            {
                string url = "http://localhost:35798/RestServiceImpl.svc/claims/create";

                // Build the POST request
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/json; charset=utf-8";
                req.Timeout = System.Threading.Timeout.Infinite;
                req.KeepAlive = false;
                req.Headers.Add("SOAPAction", url);

                using (var streamWriter = new StreamWriter(req.GetRequestStream()))
                {
                    string json = new JavaScriptSerializer().Serialize(cla);
                    ResTxt.Text = json;

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }

                // Get the request's response
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                ResTxt.Text = "";
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        private MitchellClaim ReqGetClaimByID(string claimNum)
        {
            MitchellClaim ret = new MitchellClaim();

            try
            {
                string url = "http://localhost:35798/RestServiceImpl.svc/claims/" + claimNum; /*22c9c23bac142856018ce14a26b6c299 for George Washington's claim*/

                // Build the GET request
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";

                using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var objText = sr.ReadToEnd();
                        ResTxt.Text = objText;
                        ret = js.Deserialize<MitchellClaim>(objText);
                    }
                }
            }
            catch (Exception ex)
            {

            }

            return ret;
        }
        protected void BtnInsert_Click(object sender, EventArgs e)
        {
            // Get all fields' values
            string newClaimNumber = ((TextBox)(XmlGridView.FooterRow.FindControl("TxtClaNum"))).Text;
            string newFirstName = ((TextBox)(XmlGridView.FooterRow.FindControl("TxtFName"))).Text;
            string newLastName = ((TextBox)(XmlGridView.FooterRow.FindControl("TxtLName"))).Text;
            string newStatus = ((DropDownList)(XmlGridView.FooterRow.FindControl("DrpStatus"))).SelectedValue;
            DateTime newLossDate = ((Calendar)(XmlGridView.FooterRow.FindControl("CalLossDate"))).SelectedDate;
            string newLossInfoCause = ((DropDownList)(XmlGridView.FooterRow.FindControl("DrpLossInfoCause"))).SelectedValue;
            DateTime newReportedDate = ((Calendar)(XmlGridView.FooterRow.FindControl("CalRepDate"))).SelectedDate;
            string newLossInfoDesc = ((TextBox)(XmlGridView.FooterRow.FindControl("TxtLossInfoDesc"))).Text;

            // Try parsing assigned adjuster ID to check if it's numeric
            string newAssignedAdjStr = ((TextBox)(XmlGridView.FooterRow.FindControl("TxtAssAdjuster"))).Text;
            long newAssignedAdjLong = 0;
            bool assignedAdjIsNum = long.TryParse(newAssignedAdjStr, out newAssignedAdjLong);

            // Validate fields
            if (newClaimNumber == "")
            {
                ResTxt.Text = "Claim number is required. Please enter a claim number.";
                return;
            }

            if (!assignedAdjIsNum ||
                newAssignedAdjStr == "")
            {
                ResTxt.Text = "Assigned adjuster ID must be numeric. Please enter a numeric ID.";
                return;
            }

            // Create Mitchell claim
            MitchellClaim cla = new MitchellClaim()
            {
                ClaimNumber = newClaimNumber,
                ClaimantFirstName = newFirstName,
                ClaimantLastName = newLastName,
                Status = newStatus,
                LossDate = newLossDate,
                LossInfo = new LossInfoType()
                {
                    CauseOfLoss = newLossInfoCause,
                    ReportedDate = newReportedDate,
                    LossDescription = newLossInfoDesc
                },
                AssignedAdjusterID = newAssignedAdjLong,
                Vehicles = new Vehicles()
                {
                    VehicleDetails = new List<VehicleDetails>()
                    {
                        new VehicleDetails()
                    }
                }
            };

            ReqCreateClaim(cla);

            UpdateGrid();
        }