Esempio n. 1
0
        public ActionResult Create([Bind(Include = "RowID,Title,Description")] GalleryVM mod)
        {
            if (ModelState.IsValid)
            {
                var file = Request.Files[0];
                if (file != null && file.ContentLength > 0)
                {
                    var        fileName = Path.GetExtension(file.FileName);
                    tblGallery tbl      = new tblGallery
                    {
                        Description = mod.Description,
                        Title       = mod.Title,
                        Status      = true,
                        Transdate   = DateTime.Now.AddHours(12),
                        UserID      = bl.GetUserID(System.Web.HttpContext.Current),
                        ImagePath   = fileName
                    };
                    db.tblGalleries.Add(tbl);
                    db.SaveChanges();
                    var path = Path.Combine(Server.MapPath("~/Images/"), "gal" + tbl.RowID + fileName);
                    file.SaveAs(path);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError("", "No Image Found");
                }
            }

            return(View(mod));
        }
Esempio n. 2
0
        private void btnNewProp_Click(object sender, RoutedEventArgs e)
        {
            string  make       = cbMarket.Text;
            string  type       = cbTypes.Text;
            int     area       = Convert.ToInt32(tbarea.Text);
            int     rooms      = Convert.ToInt32(tbrooms.Text);
            string  district   = cbDistricts.Text;
            string  adress     = tbAdress.Text;
            string  settlement = cbSettlemets.Text;
            decimal price      = Convert.ToDecimal(tbPrice.Text);
            string  owner      = cbOwners.Text;
            byte    status     = 0;

            if (statusbox.IsChecked == true)
            {
                status = 1;
            }

            if (cbMarket.Text == string.Empty || cbTypes.Text == string.Empty || tbarea.Text == string.Empty || tbrooms.Text == string.Empty || cbDistricts.Text == string.Empty || tbAdress.Text == string.Empty || cbSettlemets.Text == string.Empty || tbPrice.Text == string.Empty || cbOwners.Text == string.Empty)
            {
                MessageBox.Show("Fill all Fields");
                return;
            }

            Model.Properties add = new Model.Properties
            {
                MarketId   = db.Market.FirstOrDefault(o => o.Name == make).id,
                TypeId     = db.Types.FirstOrDefault(o => o.Name == type).id,
                Area       = area,
                Rooms      = rooms,
                DistrictId = db.District.FirstOrDefault(o => o.Name == district).id,
                Address    = adress,
                Settlement = db.Settlement.FirstOrDefault(o => o.Name == settlement).id,
                Price      = price,
                Owner      = db.Owners.FirstOrDefault(o => o.Name == owner).id,
                Status     = status
            };

            db.Properties.Add(add);
            db.SaveChanges();
            FillProperties();

            cbMarket.Text             = "";
            cbTypes.Text              = "";
            tbarea.Text               = "";
            tbrooms.Text              = "";
            cbDistricts.Text          = "";
            tbAdress.Text             = "";
            cbSettlemets.Text         = "";
            tbPrice.Text              = "";
            cbOwners.Text             = "";
            statusbox.IsChecked       = false;
            lblPhoneNumber.Visibility = Visibility.Hidden;
        }
Esempio n. 3
0
        public ActionResult Create([Bind(Include = "ID_City,City_Name,CreateBy,UpdateBy,CreateDate,UpdateDate,Status")] tbl_City tbl_City)
        {
            if (ModelState.IsValid)
            {
                tbl_City.CreateDate = DateTime.Now;
                db.tbl_City.Add(tbl_City);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(tbl_City));
        }
Esempio n. 4
0
        public ActionResult Create([Bind(Include = "ID_Ward,Ward_Name,ID_District,CreateBy,UpdateBy,CreateDate,UpdateDate,Status")] tbl_Ward tbl_Ward)
        {
            if (ModelState.IsValid)
            {
                tbl_Ward.CreateDate = DateTime.Now;
                db.tbl_Ward.Add(tbl_Ward);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ID_District = new SelectList(db.tbl_District, "ID_District", "District_Name", tbl_Ward.ID_District);
            return(View(tbl_Ward));
        }
Esempio n. 5
0
        public ActionResult Create([Bind(Include = "ID_Account,Account_Name,Sex,Birthday,Address,Email,Phone,ID_Position,Account,Pass,CreateBy,UpdateBy,CreateDate,UpdateDate,Status,Avarta")] tbl_Account tbl_Account)
        {
            if (ModelState.IsValid)
            {
                tbl_Account.CreateDate = DateTime.Now;
                db.tbl_Account.Add(tbl_Account);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ID_Position = new SelectList(db.tbl_Position, "ID_Position", "Position_Name", tbl_Account.ID_Position);
            return(View(tbl_Account));
        }
Esempio n. 6
0
        public ActionResult Create([Bind(Include = "ID_District,District_Name,ID_City,CreateBy,UpdateBy,CreateDate,UpdateDate,Status")] tbl_District tbl_District)
        {
            if (ModelState.IsValid)
            {
                tbl_District.CreateDate = DateTime.Now;
                db.tbl_District.Add(tbl_District);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ID_City = new SelectList(db.tbl_City, "ID_City", "City_Name", tbl_District.ID_City);
            return(View(tbl_District));
        }
Esempio n. 7
0
      public ActionResult CreateNewProperty(Property property)
      {
          if (property.id == 0)
          {
              db.Properties.Add(property);
          }
          else
          {
              var updateProperty = db.Properties.Find(property.id);
              if (updateProperty == null)
              {
                  return(HttpNotFound());
              }

              updateProperty.district      = property.district;
              updateProperty.adress        = property.adress;
              updateProperty.explanation   = property.explanation;
              updateProperty.floor         = property.floor;
              updateProperty.numberofrooms = property.numberofrooms;
              updateProperty.price         = property.price;
              updateProperty.stateId       = property.stateId;
              updateProperty.city          = property.city;
              updateProperty.m2            = property.m2;
          }
          db.SaveChanges();
          return(RedirectToAction("Index"));
      }
Esempio n. 8
0
        public ActionResult tblProperties_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable <PropertyVM> tblproperties)
        {
            //ModelState["TransDate"].Errors.Clear();
            //&& ModelState.IsValid
            var entities = new List <tblProperty>();

            if (tblproperties != null)
            {
                foreach (var c in tblproperties)
                {
                    var entity = db.tblProperties.Find(c.PropertyID);
                    entity.PropertyTitle = c.PropertyTitle;
                    entity.Purpose       = c.Purpose;
                    entity.TypeID        = c.TypeID;
                    entity.CityID        = c.CityID;
                    entity.SocietyID     = c.SocietyID;
                    entity.Description   = c.Description;
                    entity.Price         = c.Price;
                    entity.LandArea      = c.LandArea;
                    entity.UOMID         = c.UOMID;
                    entity.Status        = c.Status;
                    entity.IsFeatured    = c.IsFeatured;
                    entity.Block         = c.Block;
                    entity.ContactNo     = c.ContactNo;
                    entity.Estate        = c.Estate;
                    entity.IsDealer      = c.IsDealer;
                    entity.Owner         = c.Owner;
                    entity.PlotNo        = c.PlotNo;
                    entities.Add(entity);
                    db.tblProperties.Attach(entity);
                    db.Entry(entity).State = EntityState.Modified;
                }
                db.SaveChanges();
            }

            return(Json(entities.ToDataSourceResult(request, ModelState, tblProperty => new PropertyVM
            {
                PropertyTitle = tblProperty.PropertyTitle,
                Purpose = tblProperty.Purpose,
                Description = tblProperty.Description,
                Price = tblProperty.Price,
                LandArea = tblProperty.LandArea,
                TransDate = tblProperty.TransDate,
                Status = tblProperty.Status,
                IsFeatured = tblProperty.IsFeatured,
                CityID = tblProperty.CityID,
                PropertyID = tblProperty.PropertyID,
                SocietyID = tblProperty.SocietyID,
                TypeID = tblProperty.TypeID,
                UOMID = tblProperty.UOMID,
                UserID = tblProperty.UserID,
                Block = tblProperty.Block,
                ContactNo = tblProperty.ContactNo,
                Estate = tblProperty.Estate,
                IsDealer = tblProperty.IsDealer,
                Owner = tblProperty.Owner,
                PlotNo = tblProperty.PlotNo,
                User = tblProperty.tblUser.FullName
            })));
        }
Esempio n. 9
0
        public static bool PostData(MunicipalityTax municipality)
        {
            RealEstateEntities _context = new RealEstateEntities();
            var checkTaxtype            = _context.TaxTypes.Where(i => i.Id == municipality.TaxType).FirstOrDefault();

            if (checkTaxtype == null)
            {
                return(false);
            }

            var municipal = _context.Municipalities.Where(i => i.MunicipalityName == municipality.MunicipalityName).FirstOrDefault();

            if (municipal == null)
            {
                var t = new Data.Municipality();
                t.MunicipalityName = municipality.MunicipalityName;
                _context.Municipalities.Add(t);
                _context.SaveChanges();
            }

            var m            = _context.MunicipalityTaxes.Where(i => i.Municipality.MunicipalityName == municipality.MunicipalityName && i.TaxDate == municipality.TaxDate).FirstOrDefault();
            var currentValue = _context.Municipalities.Where(i => i.MunicipalityName == municipality.MunicipalityName).FirstOrDefault();

            if (m == null)
            {
                var t = new Data.MunicipalityTax()
                {
                    MunicipalityId = currentValue.Id,
                    TaxDate        = municipality.TaxDate,
                    Tax            = municipality.Tax,
                    TaxType        = municipality.TaxType
                };
                _context.MunicipalityTaxes.Add(t);
                _context.SaveChanges();
            }
            else
            {
                m.TaxType = municipality.TaxType;
                m.Tax     = municipality.Tax;
                _context.SaveChanges();
            }
            return(true);
        }
Esempio n. 10
0
        private void btnAddOwner_Click(object sender, RoutedEventArgs e)
        {
            lblOwner.Content = "";
            string name  = tbOwnersNameAddUpdate.Text;
            string phone = tbOwnersPhoneAddUpdate.Text;
            string email = tbOwnersEmailAddUpdate.Text;

            if (name == string.Empty || phone == string.Empty || email == string.Empty)
            {
                lblOwner.Content = "Error: Fill all boxes";
                return;
            }

            if (name == "Name" || phone == "Phone" || email == "E-mail")
            {
                lblOwner.Content = "Error: Fill right Data";
                return;
            }

            foreach (Owners item in db.Owners)
            {
                if (item.Phone == phone)
                {
                    lblOwner.Content = "Owner already exists.";
                    return;
                }
            }

            Owners count = new Owners
            {
                Name  = name,
                Phone = phone,
                Email = email
            };

            db.Owners.Add(count);
            db.SaveChanges();
            FillOwners();
            tbOwnersNameAddUpdate.Text  = "";
            tbOwnersPhoneAddUpdate.Text = "";
            tbOwnersEmailAddUpdate.Text = "";
        }
Esempio n. 11
0
 public bool UpdateAccount(RealEstateAccountDto model)
 {
     try
     {
         var item = _realEstateEntities.Accounts.Find(model.AccountId);
         item.Email        = model.Email;
         item.FirstName    = model.FirstName;
         item.LastName     = model.LastName;
         item.UserName     = model.UserName;
         item.DepartmentId = model.Department.DepartmentId;
         _realEstateEntities.SaveChanges();
         return(true);
     }
     catch (System.Exception)
     {
         return(false);
     }
 }
Esempio n. 12
0
 public ActionResult Contact(mail mail)
 {
     db.mails.Add(mail);
     db.SaveChanges();
     return(RedirectToAction("/"));
 }
Esempio n. 13
0
        static void RetrieveMailWithXOAUTH2Microsoft(string userEmail, string accessToken, string SenderContainsEmail, int AccountId)
        {
            try
            {
                // Hotmail/Outlook/LIVE Imap4 Server
                MailServer oServer = new MailServer("imap-mail.outlook.com",
                                                    userEmail,
                                                    accessToken, // use access token as password
                                                    ServerProtocol.Imap4);

                // Set IMAP OAUTH 2.0
                oServer.AuthType = ServerAuthType.AuthXOAUTH2;
                // Enable SSL/TLS connection, most modern email server require SSL/TLS by default
                oServer.SSLConnection = true;
                // Set IMAP4 SSL Port
                oServer.Port = 993;

                MailClient oClient = new MailClient("TryIt");
                // Get new email only, if you want to get all emails, please remove this line
                oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
                oClient.GetMailInfosParam.SenderContains      = SenderContainsEmail;

                Console.WriteLine("Connecting {0} ...", oServer.Server);
                oClient.Connect(oServer);

                MailInfo[] infos = oClient.GetMailInfos();
                Console.WriteLine("Total {0} email(s)\r\n", infos.Length);

                using (var db = new RealEstateEntities())
                {
                    var oLeadEmailMessage = db.tblLeadEmailMessages.Where(x => x.AccountId == AccountId && x.EmailMessageId == 0).ToList();
                    foreach (var item in oLeadEmailMessage)
                    {
                        for (int i = 0; i < infos.Length; i++)
                        {
                            MailInfo info = infos[i];
                            Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                              info.Index, info.Size, info.UIDL);

                            // Receive email from email server
                            Mail oMail = oClient.GetMail(info);

                            Console.WriteLine("From: {0}", oMail.From.ToString());
                            Console.WriteLine("Subject: {0}\r\n", oMail.Subject);


                            if (item.Subject.Equals(oMail.Subject.Replace("Re:", "").Replace("(Trial Version)", "").Trim()))
                            {
                                tblLeadEmailMessage obj = new tblLeadEmailMessage();
                                obj.AccountId      = AccountId;
                                obj.LeadId         = item.LeadId;
                                obj.Subject        = item.Subject;
                                obj.Body           = oMail.HtmlBody;
                                obj.IsReplay       = true;
                                obj.EmailMessageId = item.LeadEmailMessageId;
                                obj.CreatedDate    = oMail.ReceivedDate;
                                db.tblLeadEmailMessages.Add(obj);
                                db.SaveChanges();
                            }


                            // Mark email as read to prevent retrieving this email again.
                            oClient.MarkAsRead(info, true);

                            // If you want to delete current email, please use Delete method instead of MarkAsRead
                            // oClient.Delete(info);
                        }
                    }
                }
                // Quit and expunge emails marked as deleted from server.
                oClient.Quit();
                Console.WriteLine("Completed!");
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }
Esempio n. 14
0
        static async Task Main(string[] args)
        {
            try
            {
                // List<Gmail> MailLists = GetAllEmails(Convert.ToString(ConfigurationManager.AppSettings["HostAddress"]));
                //Console.WriteLine("+------------------------------------------------------------------+");
                //Console.WriteLine("  Sign in with Google                                             ");
                //Console.WriteLine("   If you got \"This app isn't verified\" information in Web Browser, ");
                //Console.WriteLine("   click \"Advanced\" -> Go to ... to continue test.");
                //Console.WriteLine("+------------------------------------------------------------------+");
                //Console.WriteLine("");
                //Console.WriteLine("Press any key to sign in...");
                //Console.ReadKey();
                utility.log("Gmail Service Started:-" + DateTime.Now);
                try
                {
                    using (var db = new RealEstateEntities())
                    {
                        Program p = new Program();

                        //string response1 = await p.DoOauthAndRetrieveRefreshtokenMicrosoft("M.R3_BAY.-CYU*OTLb*bB5E02FuQWE8eH!x2c9YnijegHItUdUwGKAkq!glywkGeatDSJDZD3bEGuLUomu1IVJG8sLZQKqgQ3hZeaz2yiWltW!cXxQnhcXSd8QxuMNK!pEAZPBN!xhBc7gHfLEQCgv!DqQHxYC1ySkkdOcOgFMZUdsbgP5p6QcZ3l99qdGrqrjvRm644tv8zxnYIIQ0Qzukua3ydx5ctqUaHUpoIO8tBMqCqMatVUZOShjyG1lUR87b96v3ketEZ2vN1!acZGc6*YncgdjvB4f3NYUP98K3CKvZ5pXybpZykRESyyFR!XUQ6Gn73vxUC1rh21cZzNc45krFvQqHUg$");

                        //p.DoOauthAndRetrieveEmail();
                        int AgentRoleId = RoleType.Agent.GetHashCode();
                        var oAgentList  = db.tblAccounts.Where(x => x.RoleId.Value == AgentRoleId && x.IsEmailConfig == true).ToList();
                        if (oAgentList.Count > 0)
                        {
                            foreach (var item in oAgentList)
                            {
                                //tblAccountIntegration oData = db.tblAccountIntegrations.Where(x => x.AccountId == item.AccountId).FirstOrDefault();
                                //var oData = item.tblAccountIntegrations.Where(x => x.AccountId == item.AccountId).FirstOrDefault();
                                if (item.tblAccountIntegrations.Count >= 1)
                                {
                                    foreach (var itemAccountIntegrations in item.tblAccountIntegrations)
                                    {
                                        if (itemAccountIntegrations.AuthAccountType == AuthAccountType.GoogleAuth.GetHashCode())
                                        {
                                            DateTime myDate1    = itemAccountIntegrations.CreatedDate.Value;
                                            DateTime myDate2    = DateTime.Now;
                                            TimeSpan difference = myDate2.Subtract(myDate1);
                                            //if (DateTime.Now.Subtract(oData.CreatedDate.Value).Hours >= 1)
                                            if (difference.TotalHours >= 1)
                                            {
                                                string response = await p.DoOauthAndRetrieveRefreshtoken(itemAccountIntegrations.RefreshToken);

                                                //OAuthResponseParser parser = new OAuthResponseParser();
                                                //parser.Load(response);

                                                Rootobject result = JsonConvert.DeserializeObject <Rootobject>(response);

                                                if (result.access_token != "" && result.access_token != null)
                                                {
                                                    utility.log("Refreshtoken Sucessfully Generated for Gmail");
                                                    itemAccountIntegrations.AccessToken = result.access_token;
                                                    itemAccountIntegrations.CreatedDate = DateTime.Now;
                                                    db.SaveChanges();

                                                    //var UserEmail = db.tblLeads.Where(x => x.AgentId == item.AccountId).FirstOrDefault();
                                                    //if (UserEmail != null)
                                                    //{
                                                    //    RetrieveMailWithXOAUTH(oData.EmailAddress, result.access_token, UserEmail.EmailAddress, (int)oData.AccountId);
                                                    //}
                                                    //var UserList = db.tblLeads.Where(x => x.AgentId == item.AccountId).ToList();
                                                    if (item.tblLeads1.Count >= 1)
                                                    {
                                                        foreach (var itemUserList in item.tblLeads1)
                                                        {
                                                            var oLeadEmailMessage = item.tblLeadEmailMessages.Where(x => x.LeadId == itemUserList.LeadId && x.AccountId == itemUserList.AgentId && x.IsType == MessageType.EmailMessage.GetHashCode()).FirstOrDefault();
                                                            if (oLeadEmailMessage != null)
                                                            {
                                                                //RetrieveMailWithXOAUTH(itemAccountIntegrations.EmailAddress, itemAccountIntegrations.AccessToken /*result.access_token*/, itemUserList.EmailAddress, (int)itemAccountIntegrations.AccountId, oLeadEmailMessage.LeadEmailMessageId);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                //string response = await p.DoOauthAndRetrieveRefreshtoken(oData.RefreshToken);
                                                //Rootobject result = JsonConvert.DeserializeObject<Rootobject>(response);

                                                if (itemAccountIntegrations.AccessToken != "" && itemAccountIntegrations.AccessToken != null)
                                                {
                                                    //RetrieveMailWithXOAUTH2(oData.EmailAddress, result.access_token);
                                                    //var UserEmail = db.tblLeads.Where(x => x.AgentId == item.AccountId).FirstOrDefault();
                                                    //if (UserEmail != null)
                                                    //{
                                                    //    RetrieveMailWithXOAUTH(oData.EmailAddress, oData.AccessToken /*result.access_token*/, UserEmail.EmailAddress, (int)oData.AccountId);
                                                    //}


                                                    //var UserList = db.tblLeads.Where(x => x.AgentId == item.AccountId).ToList();
                                                    if (item.tblLeads1.Count >= 1)
                                                    {
                                                        foreach (var itemUserList in item.tblLeads1)
                                                        {
                                                            var oLeadEmailMessage = item.tblLeadEmailMessages.Where(x => x.LeadId == itemUserList.LeadId && x.AccountId == itemUserList.AgentId && x.IsReplay == false && x.EmailMessageId == 0 && x.IsType == MessageType.EmailMessage.GetHashCode()).ToList();
                                                            //if (oLeadEmailMessage != null)
                                                            foreach (var itemLeadEmailMessage in oLeadEmailMessage)
                                                            {
                                                                RetrieveMailWithXOAUTH(itemAccountIntegrations.EmailAddress, itemAccountIntegrations.AccessToken /*result.access_token*/, itemUserList.EmailAddress, (int)itemAccountIntegrations.AccountId, /*itemLeadEmailMessage.LeadEmailMessageId*/ itemLeadEmailMessage);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if (itemAccountIntegrations.AuthAccountType == AuthAccountType.MicrosoftAuth.GetHashCode())
                                        {
                                            DateTime myDate1    = itemAccountIntegrations.CreatedDate.Value;
                                            DateTime myDate2    = DateTime.Now;
                                            TimeSpan difference = myDate2.Subtract(myDate1);
                                            //if (DateTime.Now.Subtract(oData.CreatedDate.Value).Hours >= 1)
                                            if (difference.TotalHours >= 1)
                                            {
                                                string response = await p.DoOauthAndRetrieveRefreshtokenMicrosoft(itemAccountIntegrations.RefreshToken);

                                                RootobjectMicrosoft result = JsonConvert.DeserializeObject <RootobjectMicrosoft>(response);

                                                if (result.access_token != "" && result.access_token != null)
                                                {
                                                    itemAccountIntegrations.AccessToken = result.access_token;
                                                    itemAccountIntegrations.CreatedDate = DateTime.Now;
                                                    db.SaveChanges();

                                                    var UserEmail = db.tblLeads.Where(x => x.AgentId == item.AccountId).FirstOrDefault();
                                                    if (UserEmail != null)
                                                    {
                                                        RetrieveMailWithXOAUTH2Microsoft(itemAccountIntegrations.EmailAddress, result.access_token, UserEmail.EmailAddress, (int)itemAccountIntegrations.AccountId);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                //string response = await p.DoOauthAndRetrieveRefreshtoken(oData.RefreshToken);
                                                //Rootobject result = JsonConvert.DeserializeObject<Rootobject>(response);

                                                if (itemAccountIntegrations.AccessToken != "" && itemAccountIntegrations.AccessToken != null)
                                                {
                                                    //RetrieveMailWithXOAUTH2(oData.EmailAddress, result.access_token);
                                                    var UserEmail = db.tblLeads.Where(x => x.AgentId == item.AccountId).FirstOrDefault();
                                                    if (UserEmail != null)
                                                    {
                                                        RetrieveMailWithXOAUTH2Microsoft(itemAccountIntegrations.EmailAddress, itemAccountIntegrations.AccessToken /*result.access_token*/, UserEmail.EmailAddress, (int)itemAccountIntegrations.AccountId);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    utility.log("Gmail Or Office 365 account is not linked for this agent.");
                                }
                            }
                        }
                        else
                        {
                            utility.log("No Agent have configure mail service.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    utility.log(ex.ToString());
                    //Console.WriteLine(ep.ToString());
                }
                //Console.ReadKey();
            }
            catch (Exception ex)
            {
                utility.log(ex.ToString());
                //Console.WriteLine("Error: " + ex);
            }
        }
Esempio n. 15
0
        static void RetrieveMailWithXOAUTH(string userEmail, string accessToken, string SenderContainsEmail, int AccountId, /*int LeadEmailMessageId*/ tblLeadEmailMessage itemLeadEmailMessage)
        {
            try
            {
                //// Create a folder named "inbox" under current directory
                //// to save the email retrieved.
                //string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
                //// If the folder is not existed, create it.
                //if (!Directory.Exists(localInbox))
                //{
                //    Directory.CreateDirectory(localInbox);
                //}

                MailServer oServer = new MailServer("imap.gmail.com",
                                                    userEmail,
                                                    accessToken, // use access token as password
                                                    ServerProtocol.Imap4);

                // Set IMAP OAUTH 2.0
                oServer.AuthType = ServerAuthType.AuthXOAUTH2;
                // Enable SSL/TLS connection, most modern email server require SSL/TLS by default
                oServer.SSLConnection = true;
                // Set IMAP4 SSL Port
                oServer.Port = 993;

                MailClient oClient = new MailClient("TryIt");
                // Get new email only, if you want to get all emails, please remove this line
                oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
                oClient.GetMailInfosParam.SenderContains      = SenderContainsEmail;


                Console.WriteLine("Connecting {0} ...", oServer.Server);
                utility.log("Connecting Gmail {0} ..." + oServer.Server);
                oClient.Connect(oServer);

                MailInfo[] infos = oClient.GetMailInfos();
                //MailInfo[] infos = oClient.SearchMail("ALL FROM \"Constro\"");
                Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
                utility.log("Total number of new email found from Gmail:-" + infos.Length);

                using (var db = new RealEstateEntities())
                {
                    //var oLeadEmailMessage = db.tblLeadEmailMessages.Where(x => x.AccountId == AccountId && x.EmailMessageId == 0).ToList();
                    //foreach (var item in itemLeadEmailMessage)
                    //{
                    for (int i = 0; i < infos.Length; i++)
                    {
                        MailInfo info = infos[i];
                        Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}; Flags: {3}",
                                          info.Index, info.Size, info.UIDL, info.Flags);


                        // Receive email from email server
                        Mail oMail = oClient.GetMail(info);

                        Console.WriteLine("From: {0}", oMail.From.ToString());
                        Console.WriteLine("To: {0}", oMail.To.ToString());
                        Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                        utility.log("From:-" + oMail.From.ToString());
                        utility.log("To:-" + oMail.To[0].ToString());
                        utility.log("Subject:-" + oMail.Subject);
                        utility.log("Subject1:-" + oMail.Subject.Replace("Re:", "").Replace("(Trial Version)", "").Trim());
                        //Console.WriteLine("Body: {0}\r\n", oMail.HtmlBody);
                        //Console.WriteLine("Text Body: {0}\r\n", oMail.TextBody);
                        string oRepSubj = oMail.Subject.Replace("Re:", "").Replace("(Trial Version)", "").Trim();
                        if (itemLeadEmailMessage.Subject.Equals(oRepSubj)) // && LeadEmailMessageId == item.LeadEmailMessageId
                        {
                            utility.log(itemLeadEmailMessage.Subject + "----" + oMail.Subject + "---Matched");

                            foreach (var itemAttachment in oMail.Attachments)
                            {
                                if (itemAttachment.ContentID != "")
                                {
                                    string matchString = Regex.Match(oMail.HtmlBody, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[0].Value;
                                    if (matchString != "")
                                    {
                                        if (matchString.Contains(itemAttachment.ContentID))
                                        {
                                            if (!Directory.Exists(MailReadImgPath))
                                            {
                                                Directory.CreateDirectory(MailReadImgPath);
                                            }
                                            string fileName = Guid.NewGuid().ToString("N").Substring(0, 8) + Path.GetExtension(itemAttachment.Name);
                                            File.WriteAllBytes(MailReadImgPath + "\\" + fileName, itemAttachment.Content); // Requires System.IO

                                            oMail.HtmlBody = Regex.Replace(oMail.HtmlBody, matchString, @"<img src='../../mail-read-img/" + fileName + @"'/>");
                                        }
                                    }
                                }
                            }

                            tblLeadEmailMessage obj = new tblLeadEmailMessage();
                            obj.AccountId = AccountId;
                            obj.LeadId    = itemLeadEmailMessage.LeadId;
                            foreach (var itemTo in oMail.To)
                            {
                                obj.ToName = itemTo.Name == "" ? itemTo.Address.Split('@')[0] : itemTo.Name;
                            }
                            obj.FromName       = oMail.From.Name;
                            obj.Subject        = itemLeadEmailMessage.Subject;
                            obj.Body           = oMail.HtmlBody;
                            obj.IsReplay       = true;
                            obj.IsRead         = false;
                            obj.EmailMessageId = itemLeadEmailMessage.LeadEmailMessageId;
                            obj.CreatedDate    = oMail.ReceivedDate;
                            db.tblLeadEmailMessages.Add(obj);
                            db.SaveChanges();


                            var oLeadEmailMessage = db.tblLeadEmailMessages.Where(x => x.AccountId == AccountId && x.LeadEmailMessageId == itemLeadEmailMessage.LeadEmailMessageId && x.IsType == MessageType.EmailMessage.GetHashCode()).FirstOrDefault();
                            if (oLeadEmailMessage != null)
                            {
                                oLeadEmailMessage.IsRead = false;
                                db.SaveChanges();
                            }

                            foreach (var itemAttachment in oMail.Attachments)
                            {
                                if (itemAttachment.ContentID == "")
                                {
                                    string fileName = Guid.NewGuid().ToString("N").Substring(0, 8) + Path.GetExtension(itemAttachment.Name);
                                    //FileStream filestream = new FileStream(ImagePath + "\\" + item.AccountId + "\\" + item.LeadId + "\\" + fileName, FileMode.Create);
                                    //var streamwriter = new StreamWriter(filestream);
                                    //streamwriter.AutoFlush = true;
                                    //Console.SetOut(streamwriter);
                                    //Console.SetError(streamwriter);

                                    File.WriteAllBytes(ImagePath + "\\" + itemLeadEmailMessage.AccountId + "\\" + itemLeadEmailMessage.LeadId + "\\" + fileName, itemAttachment.Content); // Requires System.IO

                                    tblLeadEmailMessageAttachment oData = new tblLeadEmailMessageAttachment();
                                    //oData.LeadEmailMessageId = item.LeadEmailMessageId;
                                    oData.LeadEmailMessageId = obj.LeadEmailMessageId;
                                    oData.Attachement        = string.IsNullOrEmpty(fileName) ? string.Empty : fileName;
                                    oData.CreatedDate        = DateTime.Now;
                                    db.tblLeadEmailMessageAttachments.Add(oData);
                                    db.SaveChanges();
                                }
                            }

                            // Mark email as read to prevent retrieving this email again.
                            oClient.MarkAsRead(info, true);
                        }

                        // If you want to delete current email, please use Delete method instead of MarkAsRead
                        // oClient.Delete(info);
                    }
                    //}
                }
                // Quit and expunge emails marked as deleted from server.
                oClient.Quit();
                utility.log("Gmail Service completed:-" + DateTime.Now);
                utility.log("===================");
                //Console.WriteLine("Completed!");
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }
Esempio n. 16
0
        public ActionResult Create(PropertyVM mod)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (mod.SocietyID <= 0)
                    {
                        tblSociety soc = new tblSociety
                        {
                            CityID  = mod.CityID,
                            Society = mod.OtherSociety,
                            Status  = true
                        };
                        db.tblSocieties.Add(soc);
                        db.SaveChanges();
                        mod.SocietyID = soc.SocietyID;
                    }
                    tblProperty tbl = new tblProperty
                    {
                        CityID        = mod.CityID,
                        Description   = mod.Description,
                        IsFeatured    = mod.IsFeatured,
                        LandArea      = mod.LandArea,
                        Price         = mod.Price,
                        PropertyTitle = mod.PropertyTitle,
                        Purpose       = mod.Purpose,
                        SocietyID     = mod.SocietyID,
                        Status        = "H",
                        TransDate     = DateTime.Now.AddHours(12),
                        TypeID        = mod.TypeID,
                        UOMID         = mod.UOMID,
                        UserID        = bl.GetUserID(System.Web.HttpContext.Current),
                        Block         = mod.Block,
                        ContactNo     = mod.ContactNo,
                        Estate        = mod.Estate,
                        IsDealer      = mod.IsDealer,
                        Owner         = mod.Owner,
                        PlotNo        = mod.PlotNo
                    };
                    db.tblProperties.Add(tbl);
                    db.SaveChanges();

                    var coun = Request.Files.Count;
                    for (int i = 0; i < coun; i++)
                    {
                        var file = Request.Files[i];
                        if (file != null && file.ContentLength > 0)
                        {
                            var      fileName = Path.GetExtension(file.FileName);
                            tblImage img      = new tblImage
                            {
                                PropertyID = tbl.PropertyID,
                                ImagePath  = fileName,
                                Status     = true
                            };
                            db.tblImages.Add(img);
                            db.SaveChanges();
                            var path = Path.Combine(Server.MapPath("~/Images/"), img.ImageID + fileName);
                            file.SaveAs(path);
                        }
                    }
                    return(RedirectToAction("Create"));
                }
                catch (Exception)
                {
                }
            }
            return(View(mod));
        }