public bool AddListing(FormCollection myCollection) { RealEstateEntities db = new RealEstateEntities(); Listing oL = new Listing(); return(true); }
public Agent GetAgentInfo() { using (var context = new RealEstateEntities()) { context.ContextOptions.LazyLoadingEnabled = false; Agent ag = context.Agents.Select(a => a).SingleOrDefault(); return(ag); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); using (RealEstateEntities db = new RealEstateEntities()) { var account = db.Accounts.Where(x => x.Email == context.UserName && x.IsDelete == false).Select(x => new LoginModel { AccountId = x.AccountId, Email = x.Email, Password = x.Password, FirstName = x.FirstName, LastName = x.LastName }).FirstOrDefault(); if (account == null) { context.SetError("Invalid grant", "Tài khoản không tồn tại !"); return; } else { string password = Common.Security.MD5Decrypt(account.Password); if (context.Password != password) { context.SetError("Invalid grant", "Mật khẩu không đúng !"); return; } else { var roles = db.AccountRoles.Where(x => x.AccountId == account.AccountId && x.IsDelete == false) .Select(x => x.Role.RoleName).ToList(); if (roles != null) { var props = new AuthenticationProperties(new Dictionary <string, string> { { "roles", string.Join(",", roles) }, { "user_id", $"{account.AccountId}" }, { "name", $"{account.FirstName}" } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else { context.SetError("Invalid grant", "Your account don't have role in system!"); return; } } } } }
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); }
bool GetUserIdByToken(string token, out string userId) { userId = null; var simplePrinciple = GetPrincipal(token); if (simplePrinciple == null) { return(false); } var identity = simplePrinciple.Identity as ClaimsIdentity; if (identity == null) { return(false); } if (!identity.IsAuthenticated) { return(false); } var usernameClaim = identity.FindFirst(ClaimTypes.NameIdentifier); userId = usernameClaim?.Value; if (string.IsNullOrEmpty(userId)) { return(false); } var accountId = Double.Parse(userId); using (RealEstateEntities db = new RealEstateEntities()) { var userAccount = db.Accounts.FirstOrDefault(x => x.AccountId == accountId && x.IsDelete == true); return(userAccount == null); } }
public BaseService(RealEstateEntities db) { Db = db; }
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); } }
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); } }
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); } }
public RealEstateService(RealEstateEntities realEstateEntities) : base(realEstateEntities) { _realEstateEntities = realEstateEntities; }