public void Setup()
 {
     _controllerContext = new ControllerContext {
         HttpContext = MvcMockHelpers.DynamicHttpContextBase()
     };
     _service = new EmailTemplateService();
 }
Esempio n. 2
0
        public static string GetNewsletterText(Mailout mailout)
        {
            string body = EmailTemplateService.HtmlMessageBody("~/EmailTemplates/Newsletter/EmailTextWrapper.txt", new { FullCompanyName = Globals.Settings.CompanyName, FullPhysicalMailAddress = Settings.CustomPhysicalMailAddress });

            body = InsertDynamicContent(mailout, body, mailout.BodyText).Replace("&", "&").Replace("[[ROOT]]", Helpers.RootPath);             //Plain text does not convert the ampersand
            return(body);
        }
Esempio n. 3
0
 public ForgotPasswordModel(UserManager <ApplicationUser> userManager,
                            IEmailSender emailSender,
                            EmailTemplateService emailTemplateService)
 {
     _userManager          = userManager;
     _emailSender          = emailSender;
     _emailTemplateService = emailTemplateService;
 }
		public void ShouldThrowIfHeaderNotDetected()
		{
			var viewStream = new MemoryStream(Encoding.UTF8.GetBytes("nothing"));
			var viewReader = MockRepository.GenerateMock<IViewStreamReader>();
			viewReader.Expect(x => x.GetViewStream(null, null, null)).IgnoreArguments().Return(viewStream);

			_service = new EmailTemplateService(viewReader);
			var message = _service.RenderMessage("foo", _controllerContext, null);
		}
Esempio n. 5
0
        public ActionResult PreviewTemplate(string id)
        {
            dynamic emailView = EmailTemplateService.CreateEmailView(id, null);

            emailView.MessageId = Guid.NewGuid().ToString();
            var template = EmailTemplateService.CreateEmailMessage(emailView);

            return(Content(template.Body as string, "text/html"));
        }
        public void RestorePasswordEmailCanBeCreated()
        {
            var uploadFileService     = new FakeUploadFileService();
            var textService           = new TextService(new FakeLanguageService());
            var emailTemplateService  = new EmailTemplateService(uploadFileService, textService);
            var confirmationLink      = "https://uniwiki.com/some/confi9438729874";
            var registerEmailTemplate = emailTemplateService.GetRestorePasswordText(confirmationLink);

            Console.WriteLine(registerEmailTemplate);
        }
		public void Init()
		{
			viewEngineManagerMock = mockRepository.DynamicMock<IViewEngineManager>();

			service = new EmailTemplateService(viewEngineManagerMock);

			engineContext = new StubEngineContext(null, null, null, null);
			controller = new DummyController();
			controllerContext = new ControllerContext();
		}
Esempio n. 8
0
        public void Init()
        {
            viewEngineManagerMock = mockRepository.DynamicMock <IViewEngineManager>();

            service = new EmailTemplateService(viewEngineManagerMock);

            engineContext     = new StubEngineContext(null, null, null, null);
            controller        = new DummyController();
            controllerContext = new ControllerContext();
        }
Esempio n. 9
0
 public IndexModel(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     IEmailSender emailSender,
     EmailTemplateService templateService)
 {
     _userManager          = userManager;
     _signInManager        = signInManager;
     _emailSender          = emailSender;
     _emailTemplateService = templateService;
 }
Esempio n. 10
0
    private void purchiSubmit()
    {
        dynamic purchiObj = new ExpandoObject();

        purchiObj.name    = Request.Params["parchiName"];
        purchiObj.address = Request.Params["parchiAddress"];
        purchiObj.text    = Request.Params["parchiText"];
        purchiObj.phone   = Request.Params["purchiPhone"];
        Dictionary <String, String> responseDic = EmailTemplateService.sendPurchiOrderPlacedEmail(purchiObj);

        sendResponse(responseDic);
    }
Esempio n. 11
0
        public void JobFindInactivateExpired()
        {
            TraceCallEnterEvent.Raise();
              try
              {
            // Save data
            //m_DataContext.ndihdJobFindSetStatus(entity.ID, entity.Status);

            //ki kell keresni azokat az aktív hirdetéseket, amiknek a lejárati dátuma már eljött, de még aktívak
            JobFind filter = new JobFind(Guid.Empty);
            filter.Status = JobStatusEnum.ACT;
            filter.Expiredate = DateTime.Now;

            JobFindContainer finds = JobFindSelectFiltered(filter);

            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.JobExpired);

            UserService srvUser = new UserService();

            foreach (JobFind find in finds.All)
            {
              string bodynew;
              User sender = srvUser.UserSelect(find.Sender);
              find.LastModified = DateTime.Now;
              find.Status = JobStatusEnum.EXP;
              JobFindSetStatus(find); //inaktiváljuk
              //küldünk egy levelet a barátunknak
              bodynew = body.Replace("<FULL_USER_NAME>", sender == null ? find.Sender : sender.Name);
              bodynew = bodynew.Replace("<JOB_REFID>", find.RefId.ToString());
              bodynew = bodynew.Replace("<JOB_DESCRIPTION>", find.Description);
              bodynew = bodynew.Replace("<JOB_TYPE>", "álláskeresés");
              if (sender == null)
            break;
              SendMailToSender(EmailCategory.JobExpired, bodynew, subject, sender.Email, false, find.ID);
            }

            BusinessAuditEvent.Success();
            TraceCallReturnEvent.Raise("JobFindInactivateExpired");
            return;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail("JobFindInactivateExpired",
              new EventParameter("Exception", ex.ToString()));
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
Esempio n. 12
0
        public object GetPreviewKey(EmailConfig emailConfig)
        {
            var emailMessage = EmailTemplateService.GetEmailMessage(emailConfig);

            if (emailMessage != null)
            {
                CacheService.Add(emailConfig.MessageId, emailMessage.Body, DateTime.Now.AddHours(1));
            }
            return(new
            {
                MessageId = emailConfig.MessageId
            });
        }
Esempio n. 13
0
 public RegisterModel(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     ILogger <RegisterModel> logger,
     IEmailSender emailSender,
     EmailTemplateService templateService)
 {
     _userManager         = userManager;
     _signInManager       = signInManager;
     _logger              = logger;
     _emailSender         = emailSender;
     emailTemplateService = templateService;
 }
Esempio n. 14
0
        /// <summary>
        /// Handles the Delete event of the gEmailTemplates control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gEmailTemplates_Delete(object sender, RowEventArgs e)
        {
            EmailTemplateService emailTemplateService = new EmailTemplateService();
            EmailTemplate        emailTemplate        = emailTemplateService.Get((int)gEmailTemplates.DataKeys[e.RowIndex]["id"]);

            if (emailTemplate != null)
            {
                emailTemplateService.Delete(emailTemplate, CurrentPersonId);
                emailTemplateService.Save(emailTemplate, CurrentPersonId);
            }

            BindGrid();
        }
Esempio n. 15
0
    private void forgetPassword()
    {
        Dictionary <String, String> responseDic = new Dictionary <String, String>();

        try {
            responseDic = EmailTemplateService.sendForgetPasswordEmail(Request.Params["email"]);
        }
        catch (Exception e)
        {
            responseDic.Add("error", "Oops Internal Server Error </br> Please Try After Sometimes." + e);
        }
        sendResponse(responseDic);
    }
Esempio n. 16
0
        /// <summary>
        /// Creates the control(s) neccessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            var editControl = new RockDropDownList {
                ID = id
            };

            var service = new EmailTemplateService();

            foreach (var emailTemplate in service.Queryable().OrderBy(e => e.Title))
            {
                editControl.Items.Add(new ListItem(emailTemplate.Title, emailTemplate.Guid.ToString()));
            }

            return(editControl);
        }
		public void CanRenderMessage()
		{
			string subject = "this line is subject";
			string body = "Here is message body...";
			var viewStream = new MemoryStream(Encoding.UTF8.GetBytes(subject + Environment.NewLine + body));
			var viewReader = MockRepository.GenerateMock<IViewStreamReader>();
			viewReader.Expect(x => x.GetViewStream(null, null, null)).IgnoreArguments().Return(viewStream);

			_service = new EmailTemplateService(viewReader);
			var message = _service.RenderMessage("foo", new EmailMetadata("*****@*****.**", "*****@*****.**"), _controllerContext);

			Assert.That(message, Is.Not.Null);
			Assert.That(message.Subject, Is.EqualTo(subject));
			Assert.That(message.Body, Is.EqualTo(body));
			Assert.That(message.IsBodyHtml, Is.True, "Emails are HTML by default - plain text should be explicitly set in metadata.");
		}
Esempio n. 18
0
        public void CreateSurveyTicket(Client client)
        {
            string tokenString = Guid.NewGuid().ToString();
            var    sql         = @"insert into SurveyTickets (Client_SID, Token, ExpirationDate, TokenUsed, TokenUsedDate)
                            values (@Client_SID, @Token, @ExpirationDate , @TokenUsed, null)";

            _dbConnection.Execute(sql, new { Client_SID = client.Client_SID, Token = tokenString, ExpirationDate = DateTime.Now.AddDays(21), TokenUsed = false });
            String link = "https://newbegininingcenter.azurewebsites.net/#!/survey/" + client.Client_SID.ToString() + "/" + tokenString;

            var emailTemplateService = new EmailTemplateService();
            var body = emailTemplateService.getMailBody(link);

            var emailService = new EmailService();

            emailService.sendMail("New Beginnings Follow Up Survey", body, client.Email);
        }
		public void CanRenderMessageWithEmbededHeader()
		{
			string to = "*****@*****.**";
			string body = "<body>whatever ...</body>";
			var viewStream = new MemoryStream(Encoding.UTF8.GetBytes("to:" + to + Environment.NewLine + body));
			var viewReader = MockRepository.GenerateMock<IViewStreamReader>();
			viewReader.Expect(x => x.GetViewStream(null, null, null)).IgnoreArguments().Return(viewStream);

			_service = new EmailTemplateService(viewReader);
			var message = _service.RenderMessage("foo", _controllerContext, null);

			Assert.IsNotNull(message.To);
			Assert.IsNotNull(message.Body);

			Assert.IsTrue(message.To.ToString().Contains(to));
		}
Esempio n. 20
0
        private void BindFilter()
        {
            ddlCategoryFilter.Items.Clear();
            ddlCategoryFilter.Items.Add("[All]");

            EmailTemplateService emailTemplateService = new EmailTemplateService();
            var items = emailTemplateService.Queryable().
                        Where(a => a.Category.Trim() != "" && a.Category != null).
                        OrderBy(a => a.Category).
                        Select(a => a.Category.Trim()).
                        Distinct().ToList();

            foreach (var item in items)
            {
                ddlCategoryFilter.Items.Add(item);
            }
        }
        public void CanRenderMessage()
        {
            string subject    = "this line is subject";
            string body       = "Here is message body...";
            var    viewStream = new MemoryStream(Encoding.UTF8.GetBytes(subject + Environment.NewLine + body));
            var    viewReader = MockRepository.GenerateMock <IViewStreamReader>();

            viewReader.Expect(x => x.GetViewStream(null, null, null)).IgnoreArguments().Return(viewStream);

            _service = new EmailTemplateService(viewReader);
            var message = _service.RenderMessage("foo", new EmailMetadata("*****@*****.**", "*****@*****.**"), _controllerContext);

            Assert.That(message, Is.Not.Null);
            Assert.That(message.Subject, Is.EqualTo(subject));
            Assert.That(message.Body, Is.EqualTo(body));
            Assert.That(message.IsBodyHtml, Is.True, "Emails are HTML by default - plain text should be explicitly set in metadata.");
        }
Esempio n. 22
0
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            ddlCategoryFilter.Items.Clear();
            ddlCategoryFilter.Items.Add(new ListItem(All.Text, All.Id.ToString()));

            EmailTemplateService emailTemplateService = new EmailTemplateService();
            var items = emailTemplateService.Queryable().
                        Where(a => a.Category.Trim() != "" && a.Category != null).
                        OrderBy(a => a.Category).
                        Select(a => a.Category.Trim()).
                        Distinct().ToList();

            foreach (var item in items)
            {
                ListItem li = new ListItem(item);
                li.Selected = (!Page.IsPostBack && rFilter.GetUserPreference("Category") == item);
                ddlCategoryFilter.Items.Add(li);
            }
        }
Esempio n. 23
0
        public void Setup()
        {
            MvcViewEngines.Engines.Clear();
            MvcViewEngines.Engines.Add(MockRepository.GenerateMock <IViewEngine>());

            _controllerContext = new ControllerContext
            {
                HttpContext = MvcMockHelpers.DynamicHttpContextBase(),
                Controller  = MockRepository.GenerateStub <ControllerBase>()
            };

            _controllerContext.Controller.ViewData = new ViewDataDictionary();
            _controllerContext.Controller.TempData = new TempDataDictionary();

            _service = new EmailTemplateService();

            Response.Stub(x => x.Filter).PropertyBehavior();
            Response.Expect(x => x.ContentEncoding).Return(Encoding.UTF8);
        }
Esempio n. 24
0
        public static void Main()
        {
            var serviceScopeFactory = InitializeServices();
            {
                var emailContent = RenderViewAsync(serviceScopeFactory, "Templates/EmailTemplate.cshtml").Result;

                Console.WriteLine(emailContent);
            }


            {
                var emailContent = RenderViewAsync(serviceScopeFactory, "Templates/WelcomeMail.cshtml").Result;

                Console.WriteLine(emailContent);
            }

            {
                var a = new EmailTemplateService();
                Console.WriteLine(a.RenderViewAsync("Templates/Layouts/SaltedResponsiveEmailTemplate.cshtml").Result);
            }


            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .ConfigureServices((builder, services) =>
            {
            }).ConfigureAppConfiguration(builder =>
            {
            }).Configure(builder =>
            {
                builder.Use(async(ctx, next) =>
                {
                    var a = new EmailTemplateService();

                    await ctx.Response.WriteAsync(await a.RenderViewAsync($"Templates/{ctx.Request.Path}.cshtml"));
                });
            })
                       .Build();

            host.Run();
        }
Esempio n. 25
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="emailTemplateId">The email template id.</param>
        protected void ShowEdit(int emailTemplateId)
        {
            var    globalAttributes = GlobalAttributesCache.Read();
            string globalFrom       = globalAttributes.GetValue("OrganizationEmail");

            tbFrom.Help = string.Format("If a From value is not entered the 'Organization Email' Global Attribute value of '{0}' will be used when this template is sent.", globalFrom);

            pnlList.Visible    = false;
            pnlDetails.Visible = true;

            EmailTemplateService emailTemplateService = new EmailTemplateService();
            EmailTemplate        emailTemplate        = emailTemplateService.Get(emailTemplateId);

            if (emailTemplate != null)
            {
                lActionTitle.Text       = ActionTitle.Edit(EmailTemplate.FriendlyTypeName).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = emailTemplate.Id.ToString();

                tbCategory.Text = emailTemplate.Category;
                tbTitle.Text    = emailTemplate.Title;
                tbFrom.Text     = emailTemplate.From;
                tbTo.Text       = emailTemplate.To;
                tbCc.Text       = emailTemplate.Cc;
                tbBcc.Text      = emailTemplate.Bcc;
                tbSubject.Text  = emailTemplate.Subject;
                tbBody.Text     = emailTemplate.Body;
            }
            else
            {
                lActionTitle.Text       = ActionTitle.Add(EmailTemplate.FriendlyTypeName).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = 0.ToString();

                tbCategory.Text = string.Empty;
                tbTitle.Text    = string.Empty;
                tbFrom.Text     = string.Empty;
                tbTo.Text       = string.Empty;
                tbCc.Text       = string.Empty;
                tbBcc.Text      = string.Empty;
                tbSubject.Text  = string.Empty;
                tbBody.Text     = string.Empty;
            }
        }
Esempio n. 26
0
        public void ResendSurveyTicket(Client client)
        {
            string    link   = "";
            var       sql    = @"select Ticket_SID, Client_SID, Token, ExpirationDate, TokenUsed
                        from SurveyTickets where Client_SID = @client_SID";
            var       reader = _dbConnection.ExecuteReader(sql, new { Client_SID = client.Client_SID });
            DataTable dt     = new DataTable();

            dt.Load(reader);
            if (dt.Rows.Count > 0)
            {
                link = "https://newbeginningscenter.azurewebsites.net/survey/" + client.Client_SID.ToString() + "/" + dt.Rows[0]["Token"].ToString();

                var emailTemplateService = new EmailTemplateService();
                var body = emailTemplateService.getMailBody(link);

                EmailService emailService = new EmailService();
                emailService.sendMail("New Beginnings Follow Up Survey", body, client.Email);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// This method wraps the body of the newsletter in the desired design and replaces placeholder tags with dynamic content
        /// </summary>
        /// <param name="mailout">The Mailout containing the newsletter data to be sent</param>
        /// <param name="email">Whether this newsletter should be formatted for sending out via email (vs. web-only display)</param>
        /// <returns></returns>
        public static string GetNewsletterHtml(Mailout mailout, bool email)
        {
            string       body          = string.Empty;
            const string trackingImage = @"<img src=""[[ROOT]]newsletter-opened.aspx?entityId=[[EntityID]]&amp;mailoutId=[[MailoutID]]"" height=""1"" width=""1"" border=""0"" />";

            NewsletterDesign newsletterDesign = NewsletterDesign.GetByID(Convert.ToInt32(mailout.DesignID));

            if (newsletterDesign != null)
            {
                if (newsletterDesign.Path != null)
                {
                    body = EmailTemplateService.HtmlMessageBody("~/" + newsletterDesign.Path, new { FullCompanyName = Globals.Settings.CompanyName, FullPhysicalMailAddress = Settings.CustomPhysicalMailAddress });
                    //The final remove is necessary to get rid of the "Trouble viewing this email" stuff from the Newsletter frontend pages
                    if (!email)
                    {
                        body = body.Remove(body.IndexOf("[[Email Only]]"), body.IndexOf("[[End Email Only]]") - body.IndexOf("[[Email Only]]") + "[[End Email Only]]".Length);
                    }
                    else
                    {
                        body = body.Replace("[[Email Only]]", "")
                               .Replace("[[End Email Only]]", "") + trackingImage;
                    }
                }
                else if (newsletterDesign.Template != null)
                {
                    body = newsletterDesign.Template;
                }
                else
                {
                    throw new Exception("No design path or html for selected design");
                }
                body = InsertDynamicContent(mailout, body, mailout.Body);

                // For front-end display, remove per-subscriber replacement tags
                if (!email)
                {
                    body = body.Replace("[[EntityID]]", "");
                }
            }
            return(body.Replace("[[ROOT]]", Helpers.RootPath));
        }
Esempio n. 28
0
    private void doPaymint()
    {
        Dictionary <string, string> inventDic = AjaxService.checkInventory(null, Session.SessionID);

        if (inventDic.Count == 0)
        {
            String payMode = "COD";// this is hard code need to be change when paymint gatway will intigrate
            string orderId = AjaxService.createOrder(Session.SessionID, Session[Constant.Session.SHIPING_EMAIL] + "", payMode, Session[Constant.Session.LOGED_IN_USER_ID] + "");
            Session[Constant.Session.CURRENT_ORDER] = orderId;
            AjaxService.updateInventroy(Session.SessionID);
            AjaxService.clearCart(Session.SessionID);
            Session.Remove(Constant.Session.CART_ITEMS);
            Session.Remove(Constant.Session.TOTAL);
            EmailTemplateService.sendOrderPlacedEmail();
            Response.Redirect(ConfigUtil.hostURL() + "order-summary");
        }
        else
        {
            Response.Redirect(ConfigUtil.hostURL() + "check-out");
        }
    }
Esempio n. 29
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            EmailTemplateService emailTemplateService = new EmailTemplateService();
            EmailTemplate        emailTemplate;

            int emailTemplateId = int.Parse(hfEmailTemplateId.Value);

            if (emailTemplateId == 0)
            {
                emailTemplate = new EmailTemplate();
                emailTemplateService.Add(emailTemplate, CurrentPersonId);
            }
            else
            {
                emailTemplate = emailTemplateService.Get(emailTemplateId);
            }

            emailTemplate.Category = tbCategory.Text;
            emailTemplate.Title    = tbTitle.Text;
            emailTemplate.From     = tbFrom.Text;
            emailTemplate.To       = tbTo.Text;
            emailTemplate.Cc       = tbCc.Text;
            emailTemplate.Bcc      = tbBcc.Text;
            emailTemplate.Subject  = tbSubject.Text;
            emailTemplate.Body     = tbBody.Text;

            if (!emailTemplate.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            emailTemplateService.Save(emailTemplate, CurrentPersonId);
            BindFilter();
            BindGrid();
            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
Esempio n. 30
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            EmailTemplateService emailTemplateService = new EmailTemplateService();
            SortProperty         sortProperty         = gEmailTemplates.SortProperty;

            var emailTemplates = emailTemplateService.Queryable();

            if (ddlCategoryFilter.SelectedValue != All.Id.ToString())
            {
                emailTemplates = emailTemplates.Where(a => a.Category.Trim() == ddlCategoryFilter.SelectedValue);
            }

            if (sortProperty != null)
            {
                gEmailTemplates.DataSource = emailTemplates.Sort(sortProperty).ToList();
            }
            else
            {
                gEmailTemplates.DataSource = emailTemplates.OrderBy(a => a.Category).ThenBy(a => a.Title).ToList();
            }

            gEmailTemplates.DataBind();
        }
Esempio n. 31
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="emailTemplateId">The email template id.</param>
        protected void ShowEdit(int emailTemplateId)
        {
            pnlList.Visible    = false;
            pnlDetails.Visible = true;

            EmailTemplateService emailTemplateService = new EmailTemplateService();
            EmailTemplate        emailTemplate        = emailTemplateService.Get(emailTemplateId);

            if (emailTemplate != null)
            {
                lActionTitle.Text       = ActionTitle.Edit(EmailTemplate.FriendlyTypeName);
                hfEmailTemplateId.Value = emailTemplate.Id.ToString();

                tbCategory.Text = emailTemplate.Category;
                tbTitle.Text    = emailTemplate.Title;
                tbFrom.Text     = emailTemplate.From;
                tbTo.Text       = emailTemplate.To;
                tbCc.Text       = emailTemplate.Cc;
                tbBcc.Text      = emailTemplate.Bcc;
                tbSubject.Text  = emailTemplate.Subject;
                tbBody.Text     = emailTemplate.Body;
            }
            else
            {
                lActionTitle.Text       = ActionTitle.Add(EmailTemplate.FriendlyTypeName);
                hfEmailTemplateId.Value = 0.ToString();

                tbCategory.Text = string.Empty;
                tbTitle.Text    = string.Empty;
                tbFrom.Text     = string.Empty;
                tbTo.Text       = string.Empty;
                tbCc.Text       = string.Empty;
                tbBcc.Text      = string.Empty;
                tbSubject.Text  = string.Empty;
                tbBody.Text     = string.Empty;
            }
        }
Esempio n. 32
0
        public bool OrganisationValidateSendEmailByCategory(Organisation entity, string category, string adminMail)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            // Logical checks:
            Organisation selected = base.OrganisationSelect(entity.ID);
            if (selected == null)
              throw new ApplicationException("A megadott azonosítóval nem létezik szervezet.");

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, category);

            // Le kell kérdezni a szervezethez tartozó irási joggal rendelkező felhasználókat
            User filter = new User(DBString.Empty);

            filter.Right = "W";
            filter.OrganisationRef = entity.ID;
            filter.IsActive = true;
            filter.FilterOnIsactive = DBInt.Null;
            filter.FilterOnLockedOut = 0;

            // Retrieving data from BusinessServices
            UserService srvUser = new UserService();

            UserContainer allUser = srvUser.UserSelectFiltered(filter);
            if (allUser.AllCount == 0)
            {
              OrganisationService srvOrgUser = new OrganisationService();
              OrganisationUserContainer orgUsers = srvOrgUser.SelectChildrenByOrganisationOfOrganisationUser(selected.ID);
              foreach (OrganisationUser orguser in orgUsers.All)
              {
            User user = srvUser.UserSelect(orguser.LoginNameRef);
            if (allUser[user.HashString()] == null)
              allUser.Add(user);

              }
            }

            foreach (User user in allUser.All)
            {
              string tmpBody = body;

              //set mail:
              Email mail = new Email(Guid.NewGuid());
              mail.Category = category;
              mail.To = user.Email; //"*****@*****.**";
              mail.OrganisationRef = entity.ID;

              tmpBody = tmpBody.Replace("<FULL_USER_NAME>", user.Name);
              tmpBody = tmpBody.Replace("<LOGIN_NAME>", user.LoginName);
              tmpBody = tmpBody.Replace("<ORGANISATION>", selected.Name);

              mail.MailBody = tmpBody;
              mail.Subject = subject;

              SendMail(mail);

            }

            if (!string.IsNullOrEmpty(adminMail)) //küldünk mailt az adminna is
            {
              string tmpBody = body;

              //set mail:
              Email mail = new Email(Guid.NewGuid());
              mail.Category = EmailCategory.ValidationInactivationAdmin;
              mail.To = adminMail; //"*****@*****.**";
              mail.OrganisationRef = entity.ID;

              tmpBody = tmpBody.Replace("<ORGANISATION>", selected.Name);

              mail.MailBody = tmpBody;
              mail.Subject = subject;

              SendMail(mail);
            }
            // Log success
            BusinessAuditEvent.Success(new EventParameter("OrganisationID", entity.ID.ToString()));

            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("RegisterUserID", entity.ID.ToString())
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
        public bool OrganisationPendingUserAccept(Guid OrgPendingUseID, Guid OrganisationID, string LoginName,
                                              string RejectText)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            // Check required fields
            if (OrgPendingUseID == Guid.Empty)
              throw new ArgumentNullException("OrganisationPendingUser.OrgPendingUseID",
                                          "A jóváhagyás azonosítója nincs megadva.");
            if (OrganisationID == Guid.Empty)
              throw new ArgumentNullException("OrganisationPendingUser.OrganisationRef",
                                          "A regisztrálandó szervezet azonosítója nincs megadva.");
            if (LoginName.Length == 0)
              throw new ArgumentNullException("OrganisationPendingUser.LoginNameRef",
                                          "A regisztrálandó felhasználó nincs megadva.");

            // Logical checks
            OrganisationPendingUser selected = base.OrganisationPendingUserSelect(OrgPendingUseID);
            if (selected == null)
              throw new ApplicationException("A megadott azonosítóval nem létezik regisztráció.");
            if (! selected.Status.Equals(RegistrationStatus.New))
              throw new ApplicationException("Csak új státuszú regisztráció bírálható el.");

            // Frissitjük a regisztráció adatait
            selected.SentDate = selected.SentDate;
            selected.DecidedBy = Thread.CurrentPrincipal.Identity.Name;
            selected.DecidedDate = DBDateTime.Now;
            selected.Status = RegistrationStatus.Accepted;
            selected.RejectComment = RejectText;

            //Emailben szereplõ adatok lekkérdezése
            string userEmail = "";
            string userFullName = "";
            string organisationName = "";
            OrganisationService srvOrg = new OrganisationService();
            UserService srvUser = new UserService();
            Organisation org = srvOrg.OrganisationSelect(OrganisationID);
            User u = srvUser.UserSelect(LoginName);

            userEmail = u.Email;
            userFullName = u.Name;
            organisationName = org.Name;

            //set mail:
            Email mail = new Email(Guid.NewGuid());
            mail.Category = EmailCategory.OrganisationPendingUserAccept;
            mail.To = userEmail;

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            IEmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.OrganisationPendingUserAccept);

            mail.Subject = subject;

            body = body.Replace("<FULL_USER_NAME>", userFullName);
            body = body.Replace("<LOGIN_NAME>", LoginName);
            body = body.Replace("<ORGANISATION>", organisationName);
            mail.MailBody = body;

            // Save data to database
            EmailService emailSrv = new EmailService(m_DataContext);
            m_DataContext.BeginNestedTran();
            try
            {
              //eltároljuk a szervezet-felhasználó kapcsolatot
              OrganisationUserService orgUserSrv = new OrganisationUserService(m_DataContext);
              OrganisationUser orgUser = new OrganisationUser(OrganisationID, LoginName);
              orgUser.Right = selected.Right;
              orgUserSrv.OrganisationUserInsert(orgUser);

              base.OrganisationPendingUserUpdate(selected);
              emailSrv.EmailInsert(mail);
              m_DataContext.CommitNested();
            }
            catch
            {
              m_DataContext.RollbackNested();
              throw;
            }

            // Sending mail:
            try
            {
              emailSrv.EmailSend(mail.ID);
            }
            catch (Exception ex)
            {
              ExceptionManager.Publish(ex);
              return false;
            }

            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("OrganisationPendingUser", OrgPendingUseID.ToString()),
              new EventParameter("OrganisationID", OrganisationID.ToString()),
              new EventParameter("LoginName", LoginName)
              );
            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("OrganisationPendingUser", OrgPendingUseID.ToString()),
              new EventParameter("OrganisationID", OrganisationID.ToString()),
              new EventParameter("LoginName", LoginName)
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
        public bool OrganisationPendingUserReject(OrganisationPendingUser entity)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            // Check required fields
            if (entity.RejectComment.Length == 0)
              throw new ArgumentNullException("OrganisationPendingUser.RejectComment",
                                          "Az elutasítás indoklása nincs megadva.");

            // Logical checks
            OrganisationPendingUser selected = base.OrganisationPendingUserSelect(entity.ID);
            if (selected == null)
              throw new ApplicationException("A megadott azonosítóhoznemtartozik igénylés.");
            if (! selected.Status.Equals(RegistrationStatus.New))
              throw new ApplicationException("Csak új státuszú regisztráció bírálható el.");

            // Set properties
            selected.DecidedBy = Thread.CurrentPrincipal.Identity.Name;
            selected.DecidedDate = DBDateTime.Now;
            selected.Status = RegistrationStatus.Rejected;
            selected.RejectComment = entity.RejectComment;

            //Emailben szereplõ adatok lekkérdezése
            string userEmail = "";
            string userFullName = "";
            string organisationName = "";
            IOrganisationPendingUserService srvOpu = new OrganisationPendingUserService();
            OrganisationPendingUser opu = srvOpu.OrganisationPendingUserSelect(entity.ID);
            IOrganisationService srvOrg = new OrganisationService();
            IUserService srvUser = new UserService();
            Organisation org = srvOrg.OrganisationSelect(opu.OrganisationRef);
            User u = srvUser.UserSelect(opu.LoginNameRef);

            userEmail = u.Email;
            userFullName = u.Name;
            organisationName = org.Name;

            //set mail:
            Email mail = new Email(Guid.NewGuid());
            mail.Category = EmailCategory.OrganisationRegistrationReject;
            mail.To = userEmail;

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            IEmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.OrganisationRegistrationReject);

            mail.Subject = subject;

            body = body.Replace("<FULL_USER_NAME>", userFullName);
            body = body.Replace("<LOGIN_NAME>", u.LoginName);
            body = body.Replace("<ORGANISATION>", organisationName);
            body = body.Replace("<REJECT_COMMENT>", entity.RejectComment);
            mail.MailBody = body;

            // Save data to database
            EmailService emailSrv = new EmailService(m_DataContext);
            m_DataContext.BeginNestedTran();
            try
            {
              base.OrganisationPendingUserUpdate(selected);
              emailSrv.EmailInsert(mail);
              m_DataContext.CommitNested();
            }
            catch
            {
              m_DataContext.RollbackNested();
              throw;
            }

            // Sending mail:
            try
            {
              emailSrv.EmailSend(mail.ID);
            }
            catch (Exception ex)
            {
              ExceptionManager.Publish(ex);
              return false;
            }

            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("RegisterOrganisationID", entity.ID.ToString()),
              new EventParameter("OrganisationName", organisationName),
              new EventParameter("LoginName", u.LoginName)
              );
            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("RegisterOrganisationID", entity.ID.ToString())
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
Esempio n. 35
0
 public EmailMessage GetEmailMessage(EmailConfig emailConfig)
 {
     return(EmailTemplateService.GetEmailMessage(emailConfig));
 }
Esempio n. 36
0
 public List <EmailTemplate> GetTemplateList()
 {
     return(EmailTemplateService.GetTemplateList());
 }
Esempio n. 37
0
        public void JobAnswerInactivateExpired()
        {
            TraceCallEnterEvent.Raise();
              try
              {
            // Save data
            //m_DataContext.ndihdJobFindSetStatus(entity.ID, entity.Status);
            // Save data
            //m_DataContext.ndihdJobFindSetStatus(entity.ID, entity.Status);

            //ki kell keresni azokat az aktív hirdetéseket, amiknek a lejárati dátuma már eljött, de még aktívak
            JobAnswer filter = new JobAnswer(Guid.Empty, "", "", "");
            filter.FilterOnIsActive = 1;
            filter.Expiredate = DateTime.Now;
            //filter.FilterOnSubscriberNotificationSend = 0;
            JobAnswerContainer answers = JobAnswerSelectFiltered(filter);

            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.JobExpired);
            UserService srvUser = new UserService();
            JobFindService srvFind = new JobFindService();
            JobOfferService srvOff = new JobOfferService();
            foreach (JobAnswer answer in answers.All)
            {
              User subscriber = srvUser.UserSelect(answer.SubscriberNameRef);

              string refId = "";
              string description = "";
              if (answer.Type == JobAnswerTypeEnum.FIN)
              {
            JobFind job = srvFind.JobFindSelect(answer.JobRef);
            if (job != null)
            {
              refId = job.RefId.ToString();
              description = job.Description;
            }
              }
              else
              {
            JobOffer job = srvOff.JobOfferSelect(answer.JobRef);
            if (job != null)
            {
              refId = job.RefId.ToString();
              description = job.Description;
            }
              }
              string bodynew = "";
              //küldünk egy levelet a barátunknak
              bodynew = body.Replace("<FULL_USER_NAME>", subscriber == null ? answer.SubscriberNameRef : subscriber.Name);
              bodynew = bodynew.Replace("<JOB_REFID>", refId);
              bodynew = bodynew.Replace("<JOB_DESCRIPTION>", description);
              bodynew = bodynew.Replace("<JOB_TYPE>", "állásajánlat");
              bodynew = bodynew.Replace("<JOB_DATE>", answer.Expiredate.ToShortDateString());
              if (subscriber == null)
            break;
              SendMailToSender(EmailCategory.JobExpired, bodynew, subject, subscriber.Email, true, answer);
            }
            BusinessAuditEvent.Success();
            TraceCallReturnEvent.Raise("JobAnswerInactivateExpired");
            return;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail("JobAnswerInactivateExpired",
              new EventParameter("Exception", ex.ToString()));
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
		public void CanRenderMessageFirstLineEmpty()
		{
			var viewStream = new MemoryStream(Encoding.UTF8.GetBytes(@"
to: [email protected]
subject: Hello !
<html>
<head>
		<title>EmbedHeader</title>
</head>
<body>
what are you doing?
</body>
</html>
"));
			var viewReader = MockRepository.GenerateMock<IViewStreamReader>();
			viewReader.Expect(x => x.GetViewStream(null, null, null)).IgnoreArguments().Return(viewStream);

			_service = new EmailTemplateService(viewReader);
			var message = _service.RenderMessage("foo", _controllerContext, null);

			Assert.IsNotNull(message.To);
		}
Esempio n. 39
0
        public bool RegisterUserAccept(RegisterUser entity)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            // Check required fields
            if (entity.LoginName.Length == 0)
              throw new ArgumentNullException("RegisterUser.LoginName",
                                          "A regisztrálandó felhasználó bejelentkezési neve nincs megadva.");
            if (entity.Name.Length == 0)
              throw new ArgumentNullException("RegisterUser.Name", "A regisztrálandó felhasználó neve nincs megadva.");
            if (entity.Sex.Length == 0)
              throw new ArgumentNullException("RegisterUser.Sex", "A regisztrálandó felhasználó neme nincs megadva.");
            if (entity.BirthYear.Length == 0)
              throw new ArgumentNullException("RegisterUser.BirthYear",
                                          "A regisztrálandó felhasználó születési éve nincs megadva.");
            if (entity.Email.Length == 0)
              throw new ArgumentNullException("RegisterUser.Email",
                                          "A regisztrálandó felhasználó e-mail címe nincs megadva.");
            if (entity.QualificationRef.Length == 0)
              throw new ArgumentNullException("RegisterUser.QualificationRef",
                                          "A regisztrálandó felhasználó legmagasabb iskolai végzettsége nincs megadva.");
            if (entity.ReasonOfRegistration.Length == 0)
              throw new ArgumentNullException("RegisterUser.ReasonOfRegistration",
                                          "Az adatbázis használatának célja nincs megadva.");
            if (entity.Right.Length == 0)
              throw new ArgumentNullException("RegisterUser.Right", "A jogosultság nincs megadva.");

            // Logical checks:
            RegisterUser selected = base.RegisterUserSelect(entity.ID);
            if (selected == null)
              throw new ApplicationException("A megadott azonosítóval nem létezik regisztrálandó felhasználó.");
            if (!selected.Status.Equals(RegistrationStatus.New))
              throw new ApplicationException("Csak új státuszú regisztráció bírálható el.");

            // Set properties
            entity.SentDate = selected.SentDate;
            entity.DecidedBy = Thread.CurrentPrincipal.Identity.Name;
            entity.DecidedDate = DBDateTime.Now;
            entity.Status = RegistrationStatus.Accepted;

            User newUser = new User(entity.LoginName);
            string generatedPassword = Password.Generate();
            newUser.Password = Password.ComputeHash(generatedPassword);

            newUser.OrganisationRef = entity.OrganisationRef;
            newUser.Name = entity.Name;
            newUser.Sex = entity.Sex;
            newUser.BirthYear = entity.BirthYear;
            newUser.Phone = entity.Phone;
            newUser.Email = entity.Email;
            newUser.PostCode = entity.PostCode;
            newUser.City = entity.City;
            newUser.Address = entity.Address;
            newUser.Country = entity.Country;
            newUser.QualificationRef = entity.QualificationRef;
            newUser.ReasonOfRegistration = entity.ReasonOfRegistration;
            newUser.Right = entity.Right;
            newUser.IsActive = true;
            newUser.NewsMail = entity.NewsMail;
            newUser.MustChangePassword = true;
            newUser.LockedOut = false;
            newUser.FailedAttemptCount = 0;

            //set mail:
            Email mail = new Email(Guid.NewGuid());
            mail.Category = EmailCategory.UserRegistrationAccept;
            mail.To = entity.Email;

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.UserRegistrationAccept);

            mail.Subject = subject;

            body = body.Replace("<FULL_USER_NAME>", entity.Name);
            body = body.Replace("<LOGIN_NAME>", entity.LoginName);
            body = body.Replace("<PASSWORD>", generatedPassword);
            mail.MailBody = body;

            // Save data to database
            EmailService emailSrv = new EmailService(m_DataContext);
            m_DataContext.BeginNestedTran();
            try
            {
              UserServiceBase userSrv = new UserServiceBase(m_DataContext);
              userSrv.UserInsert(newUser);
              base.RegisterUserUpdate(entity);
              emailSrv.EmailInsert(mail);
              m_DataContext.CommitNested();
            }
            catch
            {
              m_DataContext.RollbackNested();
              throw;
            }

            // Sending mail:
            try
            {
              emailSrv.EmailSend(mail.ID);
            }
            catch (Exception ex)
            {
              ExceptionManager.Publish(ex);
              return false;
            }

            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("RegisterUserID", entity.ID.ToString()),
              new EventParameter("LoginName", entity.LoginName)
              );
            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("RegisterUserID", entity.ID.ToString()),
              new EventParameter("LoginName", entity.LoginName)
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
Esempio n. 40
0
        public void JobOfferSendNotificationTomorrowExpire()
        {
            TraceCallEnterEvent.Raise();
              try
              {
            // Save data
            //m_DataContext.ndihdJobOfferSetStatus(entity.ID, entity.Status);
              // Save data
            //m_DataContext.ndihdJobOfferSetStatus(entity.ID, entity.Status);

            //ki kell keresni azokat az aktív hirdetéseket, amiknek a lejárati dátuma már eljött, de még aktívak
            JobOffer filter = new JobOffer(Guid.Empty);
            filter.Status = JobStatusEnum.ACT;
            filter.ExpireDatexpired =  DateTime.Now.AddDays(-1);
            filter.FilterOnNotificationsent = 0;
            JobOfferContainer offers = JobOfferSelectFiltered(filter);

            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.JobExpireTomorrow);

            foreach (JobOffer offer in offers.All)
            {
              offer.LastModified = DateTime.Now;
              //offer.Status = JobStatusEnum.EXP;
              //JobOfferSetStatus(offer); //inaktiváljuk
              //küldünk egy levelet a barátunknak
              string bodynew;
              bodynew = body.Replace("<FULL_USER_NAME>", offer.ContactName);
              bodynew = bodynew.Replace("<JOB_REFID>", offer.RefId.ToString());
              bodynew = bodynew.Replace("<JOB_DESCRIPTION>", offer.Description);
              bodynew = bodynew.Replace("<JOB_TYPE>", "állásajánlat");
              bodynew = bodynew.Replace("<JOB_DATE>", offer.Expiredate.ToShortDateString());
              SendMailToSender(EmailCategory.JobExpireTomorrow, bodynew, subject, offer, false);
            }
            BusinessAuditEvent.Success();
            TraceCallReturnEvent.Raise("JobOfferSendNotificationTomorrowExpire");
            return;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail("JobOfferSendNotificationTomorrowExpire",
              new EventParameter("Exception", ex.ToString()));
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
Esempio n. 41
0
        public new void JobOfferInsert(JobOffer entity)
        {
            // check permission: Writer or Admin
              PrincipalPermission permReg = new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Registered");
              PrincipalPermission permAdmin = new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permReg.Union(permAdmin).Demand();

              TraceCallEnterEvent.Raise();
              m_DataContext.BeginNestedTran();
              try
              {
            // check required fields:
            if (entity.Description.Length == 0)
              throw new ArgumentNullException("JobOffer.Description", "A hirdetés leírása nincs megadva.");

            entity.Sender = Thread.CurrentPrincipal.Identity.Name;
            entity.Status = JobStatusEnum.ACT;
            entity.NotificationSend = false;
            entity.LastModified = DateTime.Now;
            entity.Created = DateTime.Now;
            base.JobOfferInsert(entity);

            JobOfferAttachmentService attSrv = new JobOfferAttachmentService(m_DataContext);

            // EDocumentAttachments - insert:
            foreach (JobOfferAttachment file in entity.JobOfferAttachments.Current)
            {
              file.JobOfferRef = entity.ID;
              file.IsActive = true;
              file.CreatedDate = DateTime.Now;
              attSrv.JobOfferAttachmentInsert(file);
            }
            m_DataContext.CommitNested();

            #region Találati mail
            entity = JobOfferSelect(entity.ID); // a refid miatt kell

            //Ellenõrizni kell, hogy van-epárja megye, végzettség szerint. Ha van levelet kell küldeni
            //a pár feladójának
            JobFindService srvJobFind = new JobFindService();
            JobFind filter = new JobFind(Guid.Empty);
            filter.RegionRef = entity.RegionRef;
            filter.Qualification = entity.QualificationMinRef;
            filter.Status = JobStatusEnum.ACT;
            //filter.Expiredate = DateTime.Now;
            QualificationService srvQualification = new QualificationService();
            UserService srvUser = new UserService();

            JobFindContainer finds = srvJobFind.JobFindSelectFiltered(filter);
            //Van pár
            foreach (JobFind find in finds.All)
            {
              //Itt meg kell nézni azt is, hogy nem õ-e a másik hirdetés feladója
              if (find.Sender != entity.Sender)
              {

            //értesítjük a feladót, hogy valaki válaszolt a hirdetésére
            //set mail:
            Email mail = new Email(Guid.NewGuid());
            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.JobFindMatchCreated);
            mail.Category = EmailCategory.JobFindMatchCreated;
            mail.Subject = subject;

            User findSender = srvUser.UserSelect(find.Sender);
            if (findSender != null)
            {
              mail.To = findSender.Email;
              body = body.Replace("<FULL_USER_NAME>", findSender.Name);
              body = body.Replace("<JOB_REFID>", entity.RefId.ToString());
              body = body.Replace("<JOB_DESCRIPTION>", entity.Description);
              body = body.Replace("<SENDER_NAME>", entity.ContactName);
              body = body.Replace("<SENDER_MAIL>", entity.ContactEmail);
            }
            mail.MailBody = body;

            if (mail.MailBody != null && mail.To != null && mail.Subject != null)
            {
              // Save data to database
              EmailService emailSrv = new EmailService(m_DataContext);
              m_DataContext.BeginNestedTran();
              try
              {
                emailSrv.EmailInsert(mail);
                m_DataContext.CommitNested();
              }
              catch
              {
                m_DataContext.RollbackNested();
                throw;
              }

              // Sending mail:
              try
              {
                emailSrv.EmailSend(mail.ID);
              }
              catch (Exception ex)
              {
                ExceptionManager.Publish(ex);
                return;
              }
            }
              }
            }

            #endregion
            BusinessAuditEvent.Success(
              new EventParameter("JobOfferID", entity.ID.ToString()),
              new EventParameter("JobOfferLogin", entity.Sender)
              );
            TraceCallReturnEvent.Raise();
            return;
              }
              catch (Exception ex)
              {
            m_DataContext.RollbackNested();
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("JobOfferID", entity.ID.ToString()),
              new EventParameter("JobOfferLogin", entity.Sender)
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
Esempio n. 42
0
 public EmailTemplate CreateCustomTemplate()
 {
     return(EmailTemplateService.CreateCustomTemplate());
 }
        public bool PendingQuestionFormSendBackNew(PendingQuestionForm entity)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            //Check required fields
            if (entity.ID.IsNull)
              throw new ArgumentNullException("PendingQuestionForm.ID", "Az elbírálandó kérdõív azonosítója nincs megadva.");
            if (entity.ProgramCategoryId.Length == 0)
              throw new ArgumentNullException("PendingQuestionForm.ProgramCategoryId",
                                          "Az elbírálandó kérdõív kategóriája nincs megadva.");
            if (entity.TemplateRef.IsNull)
              throw new ArgumentNullException("PendingQuestionForm.TemplateRef", "A sablon azonosítója nincs megadva.");
            if (entity.RejectComment.Length == 0)
              throw new ArgumentNullException("PendingQuestionForm.RejectComment", "A visszaküldés indoklása nincs megadva.");

            // Logical checks:
            PendingQuestionForm selected = base.PendingQuestionFormSelect(entity.ID);
            if (selected == null)
              throw new ApplicationException("A megadott azonosítóval nem létezik elbírálandó kérdõív.");
            if (!selected.Status.Equals(QuestionFormStatus.New_WaitingForDecision))
              throw new ApplicationException("Csak jóváhagyásra váró státuszú kérdõív bírálható el.");

            // Set properties
            selected.DecidedBy = Thread.CurrentPrincipal.Identity.Name;
            selected.DecidedDate = DBDateTime.Now;
            selected.Status = QuestionFormStatus.New_SendBack;
            selected.RejectComment = entity.RejectComment;
            selected.QuestionFormRef = entity.QuestionFormRef;
            selected.IsActual = false;
            //Set mail:
            UserService userSrv = new UserService(m_DataContext);
            User sentBy = userSrv.UserSelect(selected.SentBy);
            Email mail = new Email(Guid.NewGuid());
            mail.Category = EmailCategory.QuestionFormInsertSendBack;
            mail.To = sentBy.Email;

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.QuestionFormInsertSendBack);

            mail.Subject = subject;

            body = body.Replace("<FULL_USER_NAME>", sentBy.Name);
            body = body.Replace("<SENT_DATE>", entity.SentDate.ToString());
            body = body.Replace("<TEMPLATE_NAME>", entity.TemplateName);
            body = body.Replace("<REJECT_COMMENT>", entity.RejectComment);
            mail.MailBody = body;

            // Save data to database
            EmailService emailSrv = new EmailService(m_DataContext);
            m_DataContext.BeginNestedTran();
            try
            {
              base.PendingQuestionFormUpdate(selected);
              emailSrv.EmailInsert(mail);
              m_DataContext.CommitNested();
            }
            catch
            {
              m_DataContext.RollbackNested();
              throw;
            }

            // Sending mail:
            try
            {
              emailSrv.EmailSend(mail.ID);
            }
            catch (Exception ex)
            {
              ExceptionManager.Publish(ex);
              return false;
            }

            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("PendingQuestionFormID", entity.ID.ToString()),
              new EventParameter("ProgramID", entity.ProgramID.ToString()),
              new EventParameter("OrganisationID", entity.OrganisationID.ToString())
              );
            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("PendingQuestionFormID", entity.ID.ToString()),
              new EventParameter("ProgramID", entity.ProgramID.ToString()),
              new EventParameter("OrganisationID", entity.OrganisationID.ToString())
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
        public bool RegisterOrganisationToUserAccept(RegisterOrganisation entity)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            // Check required fields
            // Organisation
            if (entity.Name.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.Name", "A regisztrálandó szervezet neve nincs megadva.");
            if (entity.RegionRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.RegionRef",
                                          "A regisztrálandó szervezet megyéje nincs megadva.");
            if (entity.WorkingAreaRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.WorkingAreaRef",
                                          "A regisztrálandó szervezet mûködési területe nincs megadva.");
            if (entity.OrganisationFormRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.OrganisationFormRef",
                                          "A regisztrálandó szervezet szervezeti formája nincs megadva.");
            if (entity.ReasonOfRegistration.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.ReasonOfRegistration",
                                          "Az adatbázis használatának célja nincs megadva.");
            if (entity.PostCode.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.PostCode",
                                          "A szervezet címének irányítószáma nincs megadva.");
            if (entity.City.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.City",
                                          "A szervezet címének település része nincs megadva.");
            if (entity.Address.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.Address",
                                          "A szervezet címének utca, házszám része nincs megadva.");

            // User
            if (entity.LoginName.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.LoginName",
                                          "A regisztrálandó felhasználó bejelentkezési neve nincs megadva.");
            if (entity.UserName.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserName",
                                          "A regisztrálandó felhasználó neve nincs megadva.");
            if (entity.UserSex.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserSex",
                                          "A regisztrálandó felhasználó neme nincs megadva.");
            if (entity.UserBirthYear.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserBirthYear",
                                          "A regisztrálandó felhasználó születési éve nincs megadva.");
            if (entity.UserEmail.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserEmail",
                                          "A regisztrálandó felhasználó e-mail címe nincs megadva.");
            if (entity.QualificationRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.QualificationRef",
                                          "A regisztrálandó felhasználó legmagasabb iskolai végzettsége nincs megadva.");

            // Logical checks
            RegisterOrganisation selected = base.RegisterOrganisationSelect(entity.ID);
            if (selected == null)
              throw new ApplicationException("A megadott azonosítóval nem létezik regisztrálandó szervezet.");
            if (! selected.Status.Equals(RegistrationStatus.New))
              throw new ApplicationException("Csak új státuszú regisztráció bírálható el.");

            // Set properties
            entity.SentDate = selected.SentDate;
            entity.DecidedBy = Thread.CurrentPrincipal.Identity.Name;
            entity.DecidedDate = DBDateTime.Now;
            entity.Status = RegistrationStatus.Accepted;

            Organisation newOrg = new Organisation(entity.ID);
            newOrg.Name = entity.Name;
            newOrg.Department = entity.Department;
            newOrg.PostCode = entity.PostCode;
            newOrg.City = entity.City;
            newOrg.Address = entity.Address;
            newOrg.Country = entity.Country;
            newOrg.Phone1 = entity.Phone1;
            newOrg.Fax = entity.Fax;
            newOrg.Email1 = entity.Email1;
            newOrg.HomePage = entity.HomePage;
            newOrg.RegionRef = entity.RegionRef;
            newOrg.WorkingAreaRef = entity.WorkingAreaRef;
            newOrg.WorkingAreaOther = entity.WorkingAreaOther;
            newOrg.OrganisationFormRef = entity.OrganisationFormRef;
            newOrg.ActivityPrevention = entity.ActivityPrevention;
            newOrg.ActivityRehabilitation = entity.ActivityRehabilitation;
            newOrg.ActivityResearch = entity.ActivityResearch;
            newOrg.ActivityOther = entity.ActivityOther;
            newOrg.SourceGovernment = 0;
            newOrg.SourceCompetition = 0;
            newOrg.SourceSponsor = 0;
            newOrg.SourceDonation = 0;
            newOrg.SourceTax = 0;
            newOrg.SourceOther = 0;
            newOrg.IsActive = true;
            // defaults
            newOrg.WorkersFix = 0;
            newOrg.WorkersExternal = 0;
            newOrg.WorkersVolunteer = 0;
            newOrg.JobPsychologist = 0;
            newOrg.JobPsychiater = 0;
            newOrg.JobDoctor = 0;
            newOrg.JobMedicalExpert = 0;
            newOrg.JobHealthExpert = 0;
            newOrg.JobSociologist = 0;
            newOrg.JobSocialPolitician = 0;
            newOrg.JobSocialWorker = 0;
            newOrg.JobSocialPedagogist = 0;
            newOrg.JobPedagogist = 0;
            newOrg.JobManualist = 0;
            newOrg.JobLawyer = 0;
            newOrg.JobPoliceman = 0;
            newOrg.JobMentalhygiene = 0;
            newOrg.JobCultureOrganizer = 0;
            newOrg.JobOther1 = 0;
            newOrg.JobOther2 = 0;
            newOrg.JobOther3 = 0;
            newOrg.IsActual = true;
            newOrg.LastModified = DateTime.Now;
            //set mail:
            Email mail = new Email(Guid.NewGuid());
            mail.Category = EmailCategory.OrganisationRegistrationAccept;
            mail.To = entity.UserEmail;

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.OrganisationRegistrationAccept);

            mail.Subject = subject;

            body = body.Replace("<FULL_USER_NAME>", entity.Name);
            body = body.Replace("<LOGIN_NAME>", entity.LoginName);
            body = body.Replace("<ORGANIZATION>", newOrg.Name);

            mail.MailBody = body;

            // Save data to database
            EmailService emailSrv = new EmailService(m_DataContext);
            m_DataContext.BeginNestedTran();
            try
            {
              //elmentjük a szervezet adatait
              OrganisationService orgSrv = new OrganisationService(m_DataContext);
              orgSrv.OrganisationInsert(newOrg);

              //eltároljuk a szervezet-felhasználó kapcsolatot
              OrganisationUserService orgUserSrv = new OrganisationUserService(m_DataContext);
              OrganisationUser orgUser = new OrganisationUser(newOrg.ID, entity.LoginName);
              orgUser.Right = UserRights.Write;
              orgUserSrv.OrganisationUserInsert(orgUser);

              base.RegisterOrganisationUpdate(entity);
              emailSrv.EmailInsert(mail);
              m_DataContext.CommitNested();
            }
            catch
            {
              m_DataContext.RollbackNested();
              throw;
            }

            // Sending mail:
            try
            {
              emailSrv.EmailSend(mail.ID);
            }
            catch (Exception ex)
            {
              ExceptionManager.Publish(ex);
              return false;
            }

            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("RegisterOrganisationID", entity.ID.ToString()),
              new EventParameter("OrganisationID", newOrg.ID.ToString()),
              new EventParameter("OrganisationName", entity.Name),
              new EventParameter("LoginName", entity.LoginName)
              );
            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("RegisterOrganisationID", entity.ID.ToString()),
              new EventParameter("OrganisationName", entity.Name),
              new EventParameter("LoginName", entity.LoginName)
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
Esempio n. 45
0
        /// <summary>
        /// This method checks the Content Manager page for form fields.
        /// If it finds form fields it will submit them to the form recipient.
        /// </summary>
        public static void ParseRequestForFormFields(string regionName)
        {
            if (String.IsNullOrEmpty(HttpContext.Current.Request.Form[DynamicSubmitName]))
            {
                return;
            }
            int?   micrositeID   = null;
            bool   globalContact = false;
            CMPage cmPage        = CMSHelpers.GetCurrentRequestCMSPage();

            // determine legit fields
            List <CMPageRegion> prs = new List <CMPageRegion>();
            int?userID = Helpers.GetCurrentUserID();

            if (userID == 0)
            {
                userID = null;
            }
            if (cmPage != null)
            {
                CMRegion cmRegion = CMRegion.CMRegionPage(0, 1, "", "", true, new CMRegion.Filters {
                    FilterCMRegionName = regionName
                }).FirstOrDefault();
                if (cmRegion != null)
                {
                    CMPageRegion currentRegion = CMPageRegion.LoadContentRegion(new CMPageRegion.Filters {
                        FilterCMPageRegionCMRegionID = cmRegion.CMRegionID.ToString(), FilterCMPageRegionUserID = userID.ToString(), FilterCMPageRegionCMPageID = cmPage.CMPageID.ToString(), FilterCMPageRegionNeedsApproval = false.ToString()
                    });
                    if (currentRegion != null)
                    {
                        prs.Add(currentRegion);
                    }
                }
            }

            //Also get Global areas that might contain forms
            List <CMPage> globalAreas = CMSHelpers.GetCachedCMPages().Where(c => !c.CMTemplateID.HasValue && c.FileName.Equals(regionName)).ToList();
            List <CMPage> temp        = new List <CMPage>();

            temp.AddRange(globalAreas);
            foreach (CMPage globalPage in temp)
            {
                CMRegion cmRegion = CMRegion.CMRegionGetByName(regionName).FirstOrDefault();
                if (cmRegion != null)
                {
                    CMPageRegion region = CMPageRegion.LoadContentRegion(new CMPageRegion.Filters {
                        FilterCMPageRegionCMRegionID = cmRegion.CMRegionID.ToString(), FilterCMPageRegionUserID = userID.ToString(), FilterCMPageRegionCMPageID = globalPage.CMPageID.ToString(), FilterCMPageRegionNeedsApproval = false.ToString()
                    });
                    if (region != null)
                    {
                        prs.Clear();
                        prs.Add(region);
                    }
                    else
                    {
                        globalAreas.Remove(globalPage);
                    }
                }
                else
                {
                    globalAreas.Remove(globalPage);
                }
            }
            if (prs.Count > 0)
            {
                bool hasFields = false;

                List <string> validFields = new List <string>();
                List <string> checkBoxes  = new List <string>();

                foreach (CMPageRegion pr in prs)
                {
                    MatchCollection ms = Regex.Matches(pr.Content, @"<(input|textarea|select) (.|\n)*?name=""?((\w|\d|\s|\-|\(|\))+)""?(.|\n)*?/?>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    if (ms.Count > 0 && globalAreas.Exists(c => c.CMPageID == pr.CMPageID))
                    {
                        cmPage        = globalAreas.Find(c => c.CMPageID == pr.CMPageID);
                        globalContact = true;
                    }
                    foreach (Match m in ms)
                    {
                        if (!m.ToString().Contains("type=\"radio\"") || !validFields.Contains(m.Groups[3].Value))
                        {
                            validFields.Add(m.Groups[3].Value);
                        }
                        if (m.ToString().Contains("type=\"checkbox\""))
                        {
                            checkBoxes.Add(m.Groups[3].Value);
                        }
                    }
                }

                validFields.Remove("dynamicsubmit");

                CMSubmittedForm newForm = new CMSubmittedForm();
                newForm.IsProcessed    = false;
                newForm.DateSubmitted  = DateTime.UtcNow;
                newForm.FormRecipient  = cmPage.FormRecipient;
                newForm.ResponsePageID = cmPage.ResponsePageID;
                newForm.CMMicrositeID  = cmPage.CMMicrositeID;

                if (HttpContext.Current.Request.Files.Count > 0)
                {
                    if (Regex.IsMatch(HttpContext.Current.Request.Files[0].FileName, "(\\.(doc)|(docx)|(pdf)|(jpg)|(jpeg)|(bmp)|(png)|(gif)|(ppt)|(pptx)|(xls)|(xlsx))$"))
                    {
                        HttpContext.Current.Request.Files[0].SaveAs(HttpContext.Current.Server.MapPath(UploadedFilesLocation + HttpContext.Current.Request.Files[0].FileName));
                        newForm.UploadedFile = HttpContext.Current.Request.Files[0].FileName;
                    }
                    else
                    {
                        Page page = (Page)HttpContext.Current.Handler;
                        page.ClientScript.RegisterStartupScript(page.GetType(), "InvalidFileExt", "alert('Invalid file extension.  Valid extensions are: doc,docx,pdf,jpg,jpeg,bmp,png,gif,ppt,pptx,xls,xlsx');", true);
                        return;
                    }
                }

                if (validFields.Count > 0)
                {
                    StringBuilder formData = new StringBuilder();
                    validFields.ForEach(s =>
                    {
                        if (HttpContext.Current.Request.Form[s] != null)
                        {
                            formData.Append(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", s, HttpContext.Current.Request.Form[s].ToString()));
                            if (!hasFields)
                            {
                                hasFields = true;
                            }
                        }                                                                         // if the item is not posted, no harm, just dont include it
                        else if (checkBoxes.Contains(s))
                        {
                            formData.Append(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", s, "off"));
                            if (!hasFields)
                            {
                                hasFields = true;
                            }
                        }
                    });
                    if (hasFields)
                    {
                        string body = EmailTemplateService.HtmlMessageBody(EmailTemplates.CMSFormPost, new { PageName = cmPage.FileName, FormFields = formData.ToString() });

                        newForm.FormHTML = body;
                        newForm.Save();
                        if (globalContact && !String.IsNullOrEmpty(Settings.GlobalContactEmailAddress))
                        {
                            MailMessage message = new MailMessage();
                            message.To.Add(Settings.GlobalContactEmailAddress);
                            message.IsBodyHtml = true;
                            message.Body       = body;
                            message.Subject    = Globals.Settings.SiteTitle + "- Form Submission From " + cmPage.FileName;
                            if (!String.IsNullOrEmpty(newForm.UploadedFile))
                            {
                                message.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath(UploadedFilesLocation + newForm.UploadedFile)));
                            }
                            SmtpClient client = new SmtpClient();
                            client.Send(message);
                        }
                        else if (!String.IsNullOrEmpty(cmPage.FormRecipient))
                        {
                            cmPage.FormRecipient.Split(',').ToList().ForEach(recipient =>
                            {
                                MailMessage message = new MailMessage();
                                message.To.Add(recipient);
                                message.IsBodyHtml = true;
                                message.Body       = body;
                                message.Subject    = Globals.Settings.SiteTitle + "- Form Submission From " + cmPage.FileName;
                                if (!String.IsNullOrEmpty(newForm.UploadedFile))
                                {
                                    message.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath(UploadedFilesLocation + newForm.UploadedFile)));
                                }
                                SmtpClient client = new SmtpClient();
                                client.Send(message);
                            });
                        }
                    }
                    if (hasFields)
                    {
                        if (globalContact)
                        {
                            Page page = (Page)HttpContext.Current.Handler;
                            page.ClientScript.RegisterStartupScript(page.GetType(), PopupScriptName, @"$(document).ready(function(){
	if ($('a#contactDummyLink').length == 0)
		$('div.contactSuccess').parent().parent().prepend('<a href=""#contactSuccess"" style=""display:none;"" id=""contactDummyLink"">success</a>');
	$('a#contactDummyLink').fancybox();
	$('a#contactDummyLink').trigger('click');
	setTimeout(function(){$.fancybox.close();}, 4000);
});", true);
                        }
                        else if (cmPage.ResponsePageID != null)
                        {
                            HttpContext.Current.Response.Redirect(CMSHelpers.GetCachedCMPages().Where(p => p.CMPageID == cmPage.ResponsePageID.Value).Single().FileName);
                        }
                        else
                        {
                            Page page = (Page)HttpContext.Current.Handler;
                            //If you change the key or type of the script below,
                            //you must also change it on the _RadEditor.cs file or your page will not load correctly
                            //in the if statement with Page.ClientScript.IsStartupScriptRegistered(Page.GetType(), "PopupScript")
                            page.ClientScript.RegisterStartupScript(page.GetType(), PopupScriptName, "alert('Thank you. Your form has been submitted successfully.');", true);
                        }
                    }
                }
            }
        }
        public bool RegisterKefOrganisation(RegisterOrganisation entity, string regSearchCode, DBInt disSearchCode,
                                        string estYear, string estMonth, string areaHomePage)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            // Check required fields
            // Organisation
            if (entity.Name.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.Name", "A regisztrálandó szervezet neve nincs megadva.");
            if (entity.RegionRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.RegionRef",
                                          "A regisztrálandó szervezet megyéje nincs megadva.");
            if (entity.WorkingAreaRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.WorkingAreaRef",
                                          "A regisztrálandó szervezet mûködési területe nincs megadva.");
            if (entity.OrganisationFormRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.OrganisationFormRef",
                                          "A regisztrálandó szervezet szervezeti formája nincs megadva.");
            if (entity.ReasonOfRegistration.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.ReasonOfRegistration",
                                          "Az adatbázis használatának célja nincs megadva.");
            if (entity.PostCode.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.PostCode",
                                          "A szervezet címének irányítószáma nincs megadva.");
            if (entity.City.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.City",
                                          "A szervezet címének település része nincs megadva.");
            if (entity.Address.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.Address",
                                          "A szervezet címének utca, házszám része nincs megadva.");

            // User
            if (entity.LoginName.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.LoginName",
                                          "A regisztrálandó felhasználó bejelentkezési neve nincs megadva.");
            if (entity.UserName.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserName",
                                          "A regisztrálandó felhasználó neve nincs megadva.");
            if (entity.UserSex.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserSex",
                                          "A regisztrálandó felhasználó neme nincs megadva.");
            if (entity.UserBirthYear.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserBirthYear",
                                          "A regisztrálandó felhasználó születési éve nincs megadva.");
            if (entity.UserEmail.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.UserEmail",
                                          "A regisztrálandó felhasználó e-mail címe nincs megadva.");
            if (entity.QualificationRef.Length == 0)
              throw new ArgumentNullException("RegisterOrganisation.QualificationRef",
                                          "A regisztrálandó felhasználó legmagasabb iskolai végzettsége nincs megadva.");

            Organisation newOrg = new Organisation(entity.ID);
            newOrg.Name = entity.Name;
            newOrg.Department = entity.Department;
            newOrg.PostCode = entity.PostCode;
            newOrg.City = entity.City;
            newOrg.Address = entity.Address;
            newOrg.Country = entity.Country;
            newOrg.Phone1 = entity.Phone1;
            newOrg.Fax = entity.Fax;
            newOrg.Email1 = entity.Email1;
            newOrg.HomePage = entity.HomePage;
            newOrg.RegionRef = entity.RegionRef;
            newOrg.WorkingAreaRef = entity.WorkingAreaRef;
            newOrg.WorkingAreaOther = entity.WorkingAreaOther;
            newOrg.OrganisationFormRef = entity.OrganisationFormRef;
            newOrg.ActivityPrevention = entity.ActivityPrevention;
            newOrg.ActivityRehabilitation = entity.ActivityRehabilitation;
            newOrg.ActivityResearch = entity.ActivityResearch;
            newOrg.ActivityOther = entity.ActivityOther;
            newOrg.SourceGovernment = 0;
            newOrg.SourceCompetition = 0;
            newOrg.SourceSponsor = 0;
            newOrg.SourceDonation = 0;
            newOrg.SourceTax = 0;
            newOrg.SourceOther = 0;
            newOrg.IsActive = true;
            // defaults
            newOrg.WorkersFix = 0;
            newOrg.WorkersExternal = 0;
            newOrg.WorkersVolunteer = 0;
            newOrg.JobPsychologist = 0;
            newOrg.JobPsychiater = 0;
            newOrg.JobDoctor = 0;
            newOrg.JobMedicalExpert = 0;
            newOrg.JobHealthExpert = 0;
            newOrg.JobSociologist = 0;
            newOrg.JobSocialPolitician = 0;
            newOrg.JobSocialWorker = 0;
            newOrg.JobSocialPedagogist = 0;
            newOrg.JobPedagogist = 0;
            newOrg.JobManualist = 0;
            newOrg.JobLawyer = 0;
            newOrg.JobPoliceman = 0;
            newOrg.JobMentalhygiene = 0;
            newOrg.JobCultureOrganizer = 0;
            newOrg.JobOther1 = 0;
            newOrg.JobOther2 = 0;
            newOrg.JobOther3 = 0;

            //It's a KEF -> set KEF specific data
            newOrg.IsKef = true;
            newOrg.RegionSearchCodeRef = regSearchCode;
            newOrg.DistrictSearchCodeRef = disSearchCode;
            newOrg.EstablishmentYear = estYear;
            newOrg.EstablishmentMonth = estMonth;
            newOrg.AreaHomePage = areaHomePage;
            newOrg.IsActual = true;
            newOrg.LastModified = DateTime.Now;

            //save the user
            User newUser = new User(entity.LoginName);
            newUser.OrganisationRef = entity.ID;

            string generatedPassword = Password.Generate();
            newUser.Password = Password.ComputeHash(generatedPassword);

            newUser.Address = entity.UserAddress;
            newUser.Name = entity.UserName;
            newUser.Sex = entity.UserSex;
            newUser.BirthYear = entity.UserBirthYear;
            newUser.Phone = entity.UserPhone;
            newUser.Email = entity.UserEmail;
            newUser.PostCode = entity.UserPostCode;
            newUser.City = entity.UserCity;
            newUser.Address = entity.UserAddress;
            newUser.Country = entity.UserCountry;
            newUser.QualificationRef = entity.QualificationRef;
            newUser.ReasonOfRegistration = entity.ReasonOfRegistration;
            newUser.Right = UserRights.Write;
            newUser.IsActive = true;
            newUser.NewsMail = false;
            newUser.MustChangePassword = true;
            newUser.FailedAttemptCount = 0;
            newUser.LockedOut = false;

            //set mail:
            Email mail = new Email(Guid.NewGuid());
            mail.Category = EmailCategory.OrganisationRegistrationAccept;
            mail.To = entity.UserEmail;

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            IEmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.OrganisationRegistrationAccept);

            mail.Subject = subject;

            body = body.Replace("<FULL_USER_NAME>", entity.Name);
            body = body.Replace("<LOGIN_NAME>", entity.LoginName);
            body = body.Replace("<ORGANIZATION>", newOrg.Name);
            body = body.Replace("<PASSWORD>", generatedPassword);
            mail.MailBody = body;

            // Save data to database
            EmailService emailSrv = new EmailService(m_DataContext);
            m_DataContext.BeginNestedTran();
            try
            {
              UserServiceBase userSrv = new UserServiceBase(m_DataContext);
              OrganisationService orgSrv = new OrganisationService(m_DataContext);
              orgSrv.OrganisationInsert(newOrg);
              userSrv.UserInsert(newUser);
              emailSrv.EmailInsert(mail);
              m_DataContext.CommitNested();
            }
            catch
            {
              m_DataContext.RollbackNested();
              throw;
            }

            // Sending mail:
            try
            {
              emailSrv.EmailSend(mail.ID);
            }
            catch (Exception ex)
            {
              ExceptionManager.Publish(ex);
              return false;
            }

            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("RegisterOrganisationID", entity.ID.ToString()),
              new EventParameter("OrganisationID", newOrg.ID.ToString()),
              new EventParameter("OrganisationName", entity.Name),
              new EventParameter("LoginName", entity.LoginName)
              );
            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("RegisterOrganisationID", entity.ID.ToString()),
              new EventParameter("OrganisationName", entity.Name),
              new EventParameter("LoginName", entity.LoginName)
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
Esempio n. 47
0
        public new void JobAnswerInsert(JobAnswer entity)
        {
            try
              {
            PrincipalPermission permReg = new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Registered");
            PrincipalPermission permAdmin = new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
            permReg.Union(permAdmin).Demand();

            JobAnswer ja = base.JobAnswerSelect(entity.JobRef, entity.Type, entity.SubscriberNameRef, entity.SenderNameRef);
            if(ja != null)
            {
              if(ja.IsActive)
              throw new ApplicationException("Erre a hirdetésre már válaszolt.");
            }

            //entity.SubscriberNameRef = Thread.CurrentPrincipal.Identity.Name;
            entity.Created = DateTime.Now;
            entity.IsActive = true;
            if (ja == null)
            {
              base.JobAnswerInsert(entity);
            }
            else
            {
              ja = entity;
              base.JobAnswerUpdate(ja);
            }
            //értesítjük a feladót, hogy valaki válaszolt a hirdetésére
            //set mail:
            Email mail = new Email(Guid.NewGuid());
            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.JobAnswerCreated);
            mail.Category = EmailCategory.JobAnswerCreated;
            mail.Subject = subject;
            UserService srvUser = new UserService();
            User subscriber = srvUser.UserSelect(entity.SubscriberNameRef);
            //Ha keresés hirdetésre jelentkezett valaki
            if (entity.Type == JobAnswerTypeEnum.FIN)
            {
              User sender = srvUser.UserSelect(entity.SenderNameRef);

              if (sender != null && sender.Email.Length > 0)
              {
            JobFindService srvJob = new JobFindService();
            JobFind find = srvJob.JobFindSelect(entity.JobRef);
            mail.To = sender.Email;
            body = body.Replace("<FULL_USER_NAME>", sender.Name);
            if (find != null)
            {
              body = body.Replace("<JOB_REFID>", find.RefId.ToString());
              body = body.Replace("<JOB_DESCRIPTION>", find.Description);
            }
              }
            }
            else
            {
              //ajánlat
              JobOfferService srvJob = new JobOfferService();
              JobOffer offer = srvJob.JobOfferSelect(entity.JobRef);
              if (offer != null && offer.ContactEmail.Length > 0)
              {
            mail.To = offer.ContactEmail;
            body = body.Replace("<FULL_USER_NAME>", offer.ContactName);
            body = body.Replace("<JOB_REFID>", offer.RefId.ToString());
            body = body.Replace("<JOB_DESCRIPTION>", offer.Description);
              }
            }
            if (subscriber != null)
            {
              body = body.Replace("<SUBSCRIBER_NAME>", subscriber.Name);
              body = body.Replace("<SUBSCRIBER_MAIL>", subscriber.Email);
              body = body.Replace("<MOTIVATION>", entity.Motivation);
            }

            mail.MailBody = body;

            if (mail.MailBody != null && mail.To != null && mail.Subject != null)
            {
              // Save data to database
              EmailService emailSrv = new EmailService(m_DataContext);
              m_DataContext.BeginNestedTran();
              try
              {
            emailSrv.EmailInsert(mail);
            m_DataContext.CommitNested();
              }
              catch
              {
            m_DataContext.RollbackNested();
            throw;
              }

              // Sending mail:
              try
              {
            emailSrv.EmailSend(mail.ID);
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            return;
              }
            }
            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("JobRef", entity.JobRef.ToString()),
              new EventParameter("OrganisationID", Thread.CurrentPrincipal.Identity.Name)
              );
            TraceCallReturnEvent.Raise();
            return;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("JobRef", entity.JobRef.ToString()),
              new EventParameter("OrganisationID", Thread.CurrentPrincipal.Identity.Name)
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
        public bool PendingQuestionFormAcceptNew(PendingQuestionForm entity)
        {
            //Check permission: Admin
              PrincipalPermission permissionAdm =
            new PrincipalPermission(Thread.CurrentPrincipal.Identity.Name, "Administrator");
              permissionAdm.Demand();

              TraceCallEnterEvent.Raise();
              try
              {
            //Check required fields
            if (entity.ID.IsNull)
              throw new ArgumentNullException("PendingQuestionForm.ID", "Az elbírálandó kérdõív azonosítója nincs megadva.");
            if (entity.ProgramCategoryId.Length == 0)
              throw new ArgumentNullException("PendingQuestionForm.ProgramCategoryId",
                                          "Az elbírálandó kérdõív kategóriája nincs megadva.");
            if (entity.TemplateRef.IsNull)
              throw new ArgumentNullException("PendingQuestionForm.TemplateRef", "A sablon azonosítója nincs megadva.");
            if (entity.Details.AllCount == 0)
              throw new ArgumentNullException("PendingQuestionForm.Details", "A válaszok nincsenek megadva.");
            if (entity.ProgramCategoryId.Equals("ORG"))
            {
              if (entity.OrganisationID.IsNull)
            throw new ArgumentNullException("PendingQuestionForm.OrganisationID",
                                            "A szervezet azonosítója nincs megadva.");
            }
            else
            {
              if (entity.ProgramID.IsNull)
            throw new ArgumentNullException("PendingQuestionForm.ProgramID", "A program azonosítója nincs megadva.");
            }

            // Logical checks:
            PendingQuestionForm selected = base.PendingQuestionFormSelect(entity.ID);
            if (selected == null)
              throw new ApplicationException("A megadott azonosítóval nem létezik elbírálandó kérdõív.");
            if (!selected.Status.Equals(QuestionFormStatus.New_WaitingForDecision))
              throw new ApplicationException("Csak jóváhagyásra váró státuszú kérdõív bírálható el.");

            // Set properties
            DBGuid questionFormID = Guid.NewGuid();
            QuestionForm questionForm = new QuestionForm(questionFormID);
            questionForm.TemplateRef = entity.TemplateRef;

            selected.DecidedBy = Thread.CurrentPrincipal.Identity.Name;
            selected.DecidedDate = DBDateTime.Now;
            selected.Status = QuestionFormStatus.New_Accepted;
            selected.QuestionFormRef = questionFormID;
            selected.IsActual = true;
            //utolsó módosítás, és elfogadás dátuma
            questionForm.LastModifiedDate = selected.SentDate;
            questionForm.DecidedDate = selected.DecidedDate;
            questionForm.LastModifiedByUser = selected.LastModifiedByUser;
            questionForm.IsActual = true;
            //Set mail:
            string modifiedAnswers = "";
            PendingQuestionFormDetailContainer origAnswers = base.SelectChildrenByDetailOfPendingQuestionForm(entity.ID);
            TemplateDetailService templateDetailService = new TemplateDetailService(m_DataContext);
            foreach (PendingQuestionFormDetail origDetail in origAnswers.All)
            {
              string hash = origDetail.HashString();
              PendingQuestionFormDetail currentDetail = (PendingQuestionFormDetail) entity.Details[hash];
              if (currentDetail != null)
              {
            if (!origDetail.Answer.Equals(currentDetail.Answer))
            {
              TemplateDetail question =
                templateDetailService.TemplateDetailSelect(origDetail.TemplateDetailRef, origDetail.TemplateRef);
              modifiedAnswers += "Kérdés:  " + question.Question + "\n";
              modifiedAnswers += "  Eredeti válasz:    " + origDetail.Answer + "\n";
              modifiedAnswers += "  Módosított válasz: " + currentDetail.Answer + "\n\n";
            }
              }
            }
            if (modifiedAnswers.Length == 0)
            {
              modifiedAnswers = "  A jóváhagyó módosítás nélkül fogadta el a kitöltött kérdõívet.\n";
            }

            UserService userSrv = new UserService(m_DataContext);
            User sentBy = userSrv.UserSelect(selected.SentBy);
            Email mail = new Email(Guid.NewGuid());
            mail.Category = EmailCategory.QuestionFormInsertAccept;
            mail.To = sentBy.Email;

            //Subject és body lekérdezése
            string body = "";
            string subject = "";
            EmailTemplateService srvTemplate = new EmailTemplateService();
            srvTemplate.GetEmailTemplateByCode(ref subject, ref body, EmailCategory.QuestionFormInsertAccept);

            mail.Subject = subject;

            body = body.Replace("<FULL_USER_NAME>", sentBy.Name);
            body = body.Replace("<SENT_DATE>", entity.SentDate.ToString());
            body = body.Replace("<TEMPLATE_NAME>", entity.TemplateName);
            body = body.Replace("<MODIFIED_ANSWERS>", modifiedAnswers);
            mail.MailBody = body;

            // Save data to database
            EmailService emailSrv = new EmailService(m_DataContext);
            QuestionFormService questionFormService = new QuestionFormService(m_DataContext);
            ProgramQuestionFormService programQuestionFormService = new ProgramQuestionFormService(m_DataContext);
            OrganisationQuestionFormService organisationQuestionFormService =
              new OrganisationQuestionFormService(m_DataContext);
            QuestionFormDetailService questionFormDetailService = new QuestionFormDetailService(m_DataContext);
            m_DataContext.BeginNestedTran();
            try
            {
              questionFormService.QuestionFormInsert(questionForm);
              base.PendingQuestionFormUpdate(selected);

              if (entity.ProgramCategoryId.Equals("ORG"))
              {
            OrganisationQuestionForm organisationQuestionForm =
              new OrganisationQuestionForm("ORG", entity.OrganisationID, questionFormID);

            //organisationQuestionForm.QuestionFormRef = questionFormID;
            organisationQuestionFormService.OrganisationQuestionFormInsert(organisationQuestionForm);
              }
              else
              {
            ProgramQuestionForm programQuestionForm =
              new ProgramQuestionForm(entity.ProgramCategoryId, entity.ProgramID, questionFormID);
            //programQuestionForm.QuestionFormRef = questionFormID;
            programQuestionFormService.ProgramQuestionFormInsert(programQuestionForm);
              }

              foreach (PendingQuestionFormDetail pendingDetail in entity.Details.All)
              {
            QuestionFormDetail detail =
              new QuestionFormDetail(questionFormID, pendingDetail.TemplateDetailRef, entity.TemplateRef);
            detail.Answer = pendingDetail.Answer;
            detail.FreetextId = Guid.NewGuid();
            questionFormDetailService.QuestionFormDetailInsert(detail);
              }

              emailSrv.EmailInsert(mail);
              m_DataContext.CommitNested();
            }
            catch
            {
              m_DataContext.RollbackNested();
              throw;
            }

            // Sending mail:
            try
            {
              emailSrv.EmailSend(mail.ID);
            }
            catch (Exception ex)
            {
              ExceptionManager.Publish(ex);
              return false;
            }

            // Log success
            BusinessAuditEvent.Success(
              new EventParameter("PendingQuestionFormID", entity.ID.ToString()),
              new EventParameter("ProgramID", entity.ProgramID.ToString()),
              new EventParameter("OrganisationID", entity.OrganisationID.ToString())
              );
            TraceCallReturnEvent.Raise();
            return true;
              }
              catch (Exception ex)
              {
            ExceptionManager.Publish(ex);
            BusinessAuditEvent.Fail(
              new EventParameter("Exception", ex.ToString()),
              new EventParameter("PendingQuestionFormID", entity.ID.ToString()),
              new EventParameter("ProgramID", entity.ProgramID.ToString()),
              new EventParameter("OrganisationID", entity.OrganisationID.ToString())
              );
            TraceCallReturnEvent.Raise(false);
            throw;
              }
        }
		public void Setup()
		{
			_controllerContext = new ControllerContext { HttpContext = MvcMockHelpers.DynamicHttpContextBase() };
			_service = new EmailTemplateService();
		}