예제 #1
0
        public ActionResult GetEmpTomorrowBday()
        {
            var model = GetSession.Get <Setting>((long)1);

            try
            {
                var items = GetBdayEmployeesNextDayFromToday();
                if (items.Count() == 0)
                {
                    return(Content("No workers"));
                }
                else
                {
                    //SendMailsToManagers(items);


                    var    sum  = 0;
                    string body = "<p>מחר יום הולדת לעובדים הבאים<br/></p>";

                    foreach (Employee item in items)
                    {
                        body += @"<p>שם: " + item.FirstName + ",<br/> שם משפחה: " + item.LastName + ",<br/> מחלקה: " + item.DepartmentName + ",<br/>מייל: " + item.Email + "</p>";
                        sum++;
                    }



                    var message = new MailMessage();
                    message.To.Add(new MailAddress(MvcApplication.Config("email.BDayNotificationsAdmin")));

                    //if (model.BDayEmails != "")
                    //{
                    //    string[] emails = model.BDayEmails.Split(',');
                    //    foreach (var item in emails)
                    //     {
                    //              message.CC.Add(new MailAddress(item));
                    //     }

                    //}
                    message.Subject    = "BDay notification system";
                    message.IsBodyHtml = true;
                    //message.Body = model.BDayContent;
                    message.Body = body;

                    using (var smtp = new SmtpClient())
                    {
                        smtp.Send(message);
                        return(Content("Sent about " + sum + "workers "));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Content("Error: " + ex.Message));
            }
        }
예제 #2
0
        public ActionResult ChangeInfo(string feedback)
        {
            SendEmail(MvcApplication.Config("email.ChangeInfo", "*****@*****.**"), "בקשה לשינוי Details",
                      Employee.Current.FullName +
                      Environment.NewLine +
                      Environment.NewLine +
                      feedback);

            return(RedirectToAction("ChangeInfo", new { isSent = true }));
        }
예제 #3
0
        public ActionResult GetRss()
        {
            try
            {
                var factory = new HttpFeedFactory();

                var url  = new Uri(MvcApplication.Config("home.Rss"));
                var item = factory.CreateFeed(url);

                return(View(item));
            }
            catch
            {
                return(Content(""));
            }
        }
예제 #4
0
        public void UpdateJobs()
        {
            var excel = new ExcelQueryFactory();

            string[] ex_names = MvcApplication.Config("excel_name").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            for (int ex_name = 0; ex_name < ex_names.Length; ex_name++)
            {
                excel.FileName = ex_names[ex_name];



                var result_employees = from c
                                       in excel.WorksheetNoHeader(0)
                                       select c;


                List <JobTitle> existing_jobs      = (List <JobTitle>)GetSession.QueryOver <JobTitle>().List();
                List <string>   existing_jobs_list = new List <string>();

                foreach (var job in existing_jobs)
                {
                    if (!existing_jobs_list.Contains(job.Name))
                    {
                        existing_jobs_list.Add(job.Name);
                    }
                }


                foreach (var new_job in result_employees)
                {
                    if (!string.IsNullOrEmpty(new_job[8].ToString().Trim()) && !existing_jobs_list.Contains(new_job[8].ToString().Trim()))
                    {
                        JobTitleFormModel model = new JobTitleFormModel()
                        {
                            Name = new_job[8].ToString().Trim()
                        };

                        var item = Mapper.Map <JobTitleFormModel, JobTitle>(model);
                        GetSession.Save(item);
                        existing_jobs_list.Add(new_job[8].ToString().Trim());
                    }
                }
            }
        }
예제 #5
0
        public ActionResult Show(List <int> optionResult)
        {
            var Departments = GetSession.QueryOver <Department>().Take(optionResult.Count).List();

            for (int i = 0; i < optionResult.Count; i++)
            {
                GetSession.CreateSQLQuery(
                    string.Format("Update {0}Department set Option{1}Count=Option{1}Count+1 where Id={2}",
                                  MvcApplication.Config("table.Prefix"),
                                  optionResult[i],
                                  Departments[i].Id
                                  )
                    ).ExecuteUpdate();
                Session["optionResult" + DateTime.Now.Date.ToShortDateString()] = "done";
            }

            return(RedirectToAction("DepartmentResult"));
        }
예제 #6
0
        public ActionResult GetLead(string about, string msg)
        {
            var m = new MailMessage();

            m.IsBodyHtml      = false;
            m.BodyEncoding    = Encoding.GetEncoding(1255);
            m.SubjectEncoding = Encoding.GetEncoding(1255);
            m.To.Add(MvcApplication.Config("lead.Email"));

            m.Subject  = Request.ServerVariables["HTTP_HOST"];
            m.Priority = MailPriority.High;
            m.Body     = "אין להשיב למייל זה" + "\n" +
                         "נושא: " + about + "\n" +
                         "הודעה: " + msg + "\n" +
                         "תאריך: " + DateTime.Now;

            new SmtpClient().Send(m);
            return(Content("Sent"));
        }
예제 #7
0
        public ActionResult SendMailUpdateAdmin(string warnings)
        {
            var m = new MailMessage();

            m.IsBodyHtml      = false;
            m.BodyEncoding    = Encoding.GetEncoding(1255);
            m.SubjectEncoding = Encoding.GetEncoding(1255);
            m.To.Add(MvcApplication.Config("lead.AdminUpdate"));

            m.Subject  = Request.ServerVariables["HTTP_HOST"];
            m.Priority = MailPriority.High;
            m.Body     = "אין להשיב למייל זה" + "\n" +
                         "נושא: תוצעות ריצה\n " +
                         "ישנן שורות בקובץ  - שדות -> ת.לידה,מנהל ישיר חסרים " +
                         "שורות: " + warnings + "\n" +

                         "תאריך: " + DateTime.Now;

            new SmtpClient().Send(m);
            return(Content("Sent"));
        }
예제 #8
0
        public EmployeeMap()
        {
            Id(x => x.Id).GeneratedBy.Assigned();

            Map(x => x.FirstName);
            Map(x => x.LastName);
            Map(x => x.EnglishFirstName);
            Map(x => x.EnglishLastName);
            Map(x => x.Alias);
            Map(x => x.Username);
            Map(x => x.Phone);
            Map(x => x.Mobile);
            Map(x => x.Range);
            Map(x => x.Email);
            Map(x => x.BDay);
            Map(x => x.IsActive);
            Map(x => x.Ip);
            Map(x => x.PostContent);
            Map(x => x.IsAdmin);
            Map(x => x.EmployeeMessagesCount).Formula("(select count(*) from " + MvcApplication.Config("table.Prefix") + "EmployeeMessage where " + MvcApplication.Config("table.Prefix") + "EmployeeMessage.To_Id=Id and " + MvcApplication.Config("table.Prefix") + "EmployeeMessage.IsRead='false')");;
            Map(x => x.StartYear);
            Map(x => x.Picture);
            Map(x => x.Local_id);


            References(x => x.Department);
            References(x => x.JbTitle);

            HasMany(x => x.EmployeePhotos);
            HasMany(x => x.EmployeeMessages).KeyColumn("To_id");
            HasMany(x => x.SentEmployeeMessages).KeyColumn("CreatedBy_id");
            HasMany(x => x.Likes);
            References(x => x.Manager).ForeignKey("Manager_id");

            Map(x => x.Password);
        }
예제 #9
0
        public ActionResult Index()
        {
            string[] exts  = MvcApplication.Config("gellery.Extensions", ".jpg,.gif,.swf").Split(',');
            var      item  = GetSession.Get <Setting>((long)1);
            var      items = Directory.GetFiles(Server.MapPath("~/Public/UserFiles/gallery"))
                             .Where(x => exts.Contains(Path.GetExtension(x).ToLower()))
                             .Select(x => Path.GetFileName(x))
                             .ToList();

            ViewBag.GalleryImages = items;
            string links = "<table class='table table-hover table-bordered'><tr><td>שם הנוהל</td><td>הורד לקריאה</td><td>אישור קריאה</td></tr>";

            IList <Doc> docs_list = GetSession.QueryOver <Doc>().Where(x => x.Active).List();


            List <Doc> availableToUserDocs = new List <Doc>();

            //var docum = null;

            if (docs_list.Count() > 0)
            {
                availableToUserDocs = (from r in docs_list
                                       where r.isAvailable2All == true || r.UsersAllowed.Contains(Employee.Current.Id.ToString())
                                       select r).ToList();
            }

            //long currentEmpDepId = GetSession.Get<Employee>(GetEmployeeId).Department.Id;
            //IList<Doc> docs_list = GetSession.QueryOver<Doc>().Where(x => x.Active).WhereRestrictionOn(x => x.Units).IsLike("%" + currentEmpDepId + "%").List();

            if (availableToUserDocs != null)
            {
                string sLink = "";
                foreach (Doc doc in availableToUserDocs)
                {
                    sLink = GetSubmitedDocs(Employee.Current.Id, doc);
                    if (sLink != "")
                    {
                        links += "<tr>";
                        links += sLink;
                        links += "</tr>";
                        sLink  = "";
                    }
                }

                links += "</table>";
                ViewBag.DocCounter = docCounter;
                //ViewBag.DocCounter = docs_list.Count;
                ViewBag.Links = links;
                docCounter    = 0;
            }
            else
            {
                ViewBag.DocCounter = 0;
            }

            // Departments
            item.Departments = GetSession.QueryOver <Department>().List();


            return(View(item));
        }
예제 #10
0
        public ActionResult FeedbackToManager(string feedback)
        {
            SendEmail(MvcApplication.Config("email.FeedbackToManager", "*****@*****.**"), "כתוב למנכ\"ל", feedback);

            return(RedirectToAction("FeedbackToManager", new { isSent = true }));
        }
예제 #11
0
        public ActionResult Login()
        {
            string[] allowed = MvcApplication.Config("allowed").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            //if (!allowed.Contains(HttpContext.Request.UserHostAddress.ToString()))
            //{
            //    Response.Redirect("http://www.shekelgroup.co.il/");
            //}

            //string[] temp = Convert.ToString(WindowsIdentity.GetCurrent().Name).Split('\\');
            //ViewBag.login_name = temp[1];

            var model = new LoginFormModel();

            //SSO
            string ssoConfig = MvcApplication.Config("sso.enabled");

            if (!String.IsNullOrEmpty(ssoConfig))
            {
                bool ssoEnabled = bool.Parse(ssoConfig);
                if (ssoEnabled)
                {
                    using (HostingEnvironment.Impersonate())
                    {
                        SSOClient ssoClient = new SSOClient();

                        //string ssoLoginName = ssoClient.GetCurrentLoginName();
                        string ssoLoginName = User.Identity.Name;

                        if (ssoLoginName.Contains("\\"))
                        {
                            ssoLoginName = ssoLoginName.Split('\\')[1];
                        }

                        if (!String.IsNullOrEmpty(ssoLoginName))
                        {
                            string ssoPropertyName = MvcApplication.Config("sso.id_property");

                            if (!String.IsNullOrEmpty(ssoPropertyName))
                            {
                                string ssoPropertyValue = ssoClient.GetProperty(ssoLoginName, ssoPropertyName);

                                if (!String.IsNullOrEmpty(ssoPropertyValue))
                                {
                                    //Int64 localId = 2065;
                                    Int64 localId = Int64.Parse(ssoPropertyValue);

                                    if (localId > 0)
                                    {
                                        var emp = GetSession.QueryOver <Employee>().Where(x => x.Id == localId).SingleOrDefault();
                                        if (emp != null)
                                        {
                                            if (String.IsNullOrWhiteSpace(emp.Email) ||
                                                emp.Email.Equals("*****@*****.**", StringComparison.InvariantCultureIgnoreCase) ||
                                                String.IsNullOrWhiteSpace(emp.Username))
                                            {
                                                return(View(new LoginFormModel()));
                                            }
                                            else
                                            {
                                                return(Login(new LoginFormModel()
                                                {
                                                    Username = emp.Email,
                                                    Password = emp.Password
                                                }));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(View(new LoginFormModel()));
        }
예제 #12
0
        public ActionResult UpdateEmployees()
        {
            ////-----------------
            //string filePaths = @"E:\Users\max\Desktop\Development\ON AIR SITES\New Sites Online_Alex\Zoglobek PORTAL\Source\Portal.Web.UI.Application\Public\userfiles\SOGPORTAL.xlsx";


            //string strFile = @"E:\Users\max\Desktop\Development\ON AIR SITES\New Sites Online_Alex\Zoglobek PORTAL\Source\Portal.Web.UI.Application\Public\userfiles\SOGPORTAL.xlsx";

            //string strTemp = Path.GetExtension(strFile).ToLower();

            //if (strTemp == ".xls")
            //{
            //    strFile = Path.ChangeExtension(strFile, "xlsx");
            //}



            //foreach (string myfile in filePaths)
            //{
            //    filename = Path.ChangeExtension(myfile, ".txt");
            //    System.IO.File.Move(myfile, filename);
            //}


            ////------------------



            Log newLog = new Log();

            newLog.id = Guid.NewGuid();


            int    added    = 0;
            int    deleted  = 0;
            int    updated  = 0;
            int    errors   = 0;
            int    warnings = 0;
            string result   = "";


            int    logg = 0;
            string name = "";

            try
            {
                var excel = new ExcelQueryFactory();

                string[] ex_names = MvcApplication.Config("excel_name").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);



                //insert all employees from excel to temp list<>
                List <string> excel_emp_id = new List <string>();



                for (int ex_name = 0; ex_name < ex_names.Length; ex_name++)
                {
                    excel.FileName = ex_names[ex_name];

                    //employees from excel
                    var result_employees = from c
                                           in excel.WorksheetNoHeader(0)
                                           select c;



                    List <Employee> employees = new List <Employee>();



                    UpdateJobs();
                    UpdateDepartments();

                    //Dictionary
                    Dictionary <string, long> dep_dict = new Dictionary <string, long>();


                    //existing Department from db
                    List <Department> existing_deps = (List <Department>)GetSession.QueryOver <Department>().List();


                    foreach (Department dep in existing_deps)
                    {
                        dep_dict.Add(dep.Name, dep.Id);
                    }


                    //get all employees to dictinary
                    Dictionary <string, long> emps_dict = new Dictionary <string, long>();



                    Dictionary <string, long> job_dict = new Dictionary <string, long>();

                    //existing Jobs from db
                    List <JobTitle> existing_jobs = (List <JobTitle>)GetSession.QueryOver <JobTitle>().List();

                    foreach (JobTitle job in existing_jobs)
                    {
                        job_dict.Add(job.Name, job.Id);
                    }


                    Dictionary <string, string> users_managers = new Dictionary <string, string>();

                    //result_employees -> employees from excel
                    int i = 0;
                    foreach (var employee in result_employees)
                    {
                        //check for must feilds
                        if (!string.IsNullOrEmpty(employee[1].ToString().Trim()) &&
                            !string.IsNullOrEmpty(employee[2].ToString().Trim()) &&
                            !string.IsNullOrEmpty(employee[13].ToString().Trim()) &&
                            !string.IsNullOrEmpty(employee[0].ToString().Trim()))
                        {
                            logg++;
                            name = employee[0];


                            if (i > 0 && !string.IsNullOrEmpty(employee[0].ToString().Trim()))
                            {
                                //check for wanted feilds
                                if (string.IsNullOrEmpty(employee[5].ToString().Trim()) || string.IsNullOrEmpty(employee[7].ToString().Trim()))
                                {
                                    newLog.WarningLines = newLog.WarningLines + (i + 1) + ",";
                                    warnings++;
                                }

                                excel_emp_id.Add(employee[0].ToString().Trim());

                                if (employee[5] != "")
                                {
                                    users_managers.Add(employee[0], employee[5]);
                                }



                                //if employee exists in DB
                                if (GetSession.Get <Employee>(Convert.ToInt64(employee[0].ToString().Trim())) == null)
                                {
                                    //add new employee
                                    string sBirthDate = employee[7].ToString().Trim() ?? "";
                                    //string username = employee[9].ToString().Trim() == "" ?
                                    //  "New User" : employee[9].ToString().Trim().Substring(0, employee[9].ToString().Trim().ToString().IndexOf('@'));
                                    string userName = employee[0].ToString().Trim();


                                    EmployeeFormModel model = new EmployeeFormModel()
                                    {
                                        Id        = Convert.ToInt64(employee[0].ToString().Trim()),
                                        Password  = employee[0].ToString().Trim(),
                                        LastName  = employee[2].ToString().Trim(),
                                        FirstName = employee[1].ToString().Trim(),
                                        Email     = string.IsNullOrEmpty(employee[9].ToString().Trim()) ? "*****@*****.**" : employee[9].ToString().Trim(),
                                        Phone     = employee[10].ToString().Trim(),
                                        Picture   = employee[0].ToString().Trim() + ".jpg",
                                        Mobile    = employee[11].ToString().Trim(),
                                        //Manager = GetSession.Get<Employee>(Convert.ToInt64(employee[5].ToString().Trim())),
                                        Range      = employee[12].ToString().Trim(),
                                        BDay       = (employee[7].ToString().Trim() != "") ? Convert.ToDateTime(sBirthDate) : DateTime.Now,
                                        IsActive   = Convert.ToBoolean(Convert.ToInt32(employee[13].ToString().Trim())),
                                        JbTitle    = GetSession.Get <JobTitle>(job_dict.FirstOrDefault(x => x.Key == employee[8].ToString().Trim()).Value),
                                        Department = GetSession.Get <Department>(dep_dict.FirstOrDefault(x => x.Key == employee[4].ToString().Trim()).Value),
                                        Username   = userName
                                    };

                                    var item = Mapper.Map <EmployeeFormModel, Employee>(model);

                                    GetSession.Save(item);
                                    added++;

                                    // string s = job_dict.FirstOrDefault(employee[3].ToString().Trim()).Key;
                                }
                                else
                                {
                                    //update employee

                                    var    item       = GetSession.Get <Employee>(Convert.ToInt64(employee[0].ToString().Trim()));
                                    var    model      = Mapper.Map <Employee, EmployeeFormModel>(item);
                                    string sBirthDate = employee[7].ToString().Trim().ToString();

                                    string userName = employee[0].ToString().Trim();


                                    model.Password  = employee[0].ToString().Trim();
                                    model.LastName  = employee[2].ToString().Trim();
                                    model.FirstName = employee[1].ToString().Trim();
                                    model.Email     = string.IsNullOrEmpty(employee[9].ToString().Trim()) ? "*****@*****.**" : employee[9].ToString().Trim();
                                    model.Phone     = employee[10].ToString().Trim();
                                    model.Mobile    = employee[11].ToString().Trim();
                                    model.Picture   = employee[0].ToString().Trim() + ".jpg";
                                    model.Range     = employee[12].ToString().Trim();
                                    //model.Manager = GetSession.Get<Employee>(Convert.ToInt64(employee[5].ToString().Trim()));
                                    model.IsActive   = Convert.ToBoolean(Convert.ToInt32(employee[13].ToString().Trim()));
                                    model.BDay       = (employee[7].ToString().Trim() != "") ? Convert.ToDateTime(sBirthDate) : DateTime.Now;
                                    model.JbTitle    = GetSession.Get <JobTitle>(job_dict.FirstOrDefault(x => x.Key == employee[8].ToString().Trim()).Value);
                                    model.Department = GetSession.Get <Department>(dep_dict.FirstOrDefault(x => x.Key == employee[4].ToString().Trim()).Value);
                                    //model.Username = employee[9].ToString().Trim() == "" ? "" : employee[9].ToString().Trim().ToString().Substring(0, employee[9].ToString().Trim().ToString().IndexOf('@'));
                                    model.Username = userName;
                                    Mapper.Map <EmployeeFormModel, Employee>(model, item);
                                    GetSession.Update(item);
                                    updated++;
                                }
                            }
                            i++;
                        }
                        else
                        {
                            newLog.ErrorLines = newLog.ErrorLines + (i + 1) + ",";
                            errors++;
                            i++;
                        }
                    }



                    //TODO
                    //update managers
                    //UpdateManagers(users_managers);
                }



                // bring all existing employees
                List <Employee> current_employees = (List <Employee>)GetSession.QueryOver <Employee>().List();
                foreach (Employee curr_emp in current_employees)
                {
                    // if employee nof found in excel > disactivate this employee
                    if (!excel_emp_id.Contains(curr_emp.Id.ToString()))
                    {
                        if (curr_emp.Username != MvcApplication.Config("admin.Username"))
                        {
                            var item  = GetSession.Get <Employee>(curr_emp.Id);
                            var model = Mapper.Map <Employee, EmployeeFormModel>(item);
                            model.IsActive = false;
                            Mapper.Map <EmployeeFormModel, Employee>(model, item);
                            GetSession.Update(item);

                            deleted++;
                        }
                    }

                    #region 1

                    //if (curr_emp.Username == MvcApplication.Config("admin.Username"))
                    //{
                    //    var item = GetSession.Get<Employee>(curr_emp.Id);
                    //    var model = Mapper.Map<Employee, EmployeeFormModel>(item);


                    //    model.Username = "******";
                    //    model.IsAdmin = true;
                    //    model.IsActive = true;

                    //    Mapper.Map<EmployeeFormModel, Employee>(model, item);
                    //    GetSession.Update(item);
                    //}
                    #endregion
                }
            }
            catch (Exception ex)
            {
                return(Content(ex.Data + ">>>>>" + ex.InnerException + ">>>>>" + ex.Message + " >>>>>>>> line" + logg + "name =" + name));
            }
            result = string.Format("<h3>Update Results</h3><p>New : {0} </p><p>Processed : {1} </p><p>Deleted {2}</p><p>Errors {3}</p><p>Warnings {4}</p>", added, updated, deleted, errors, warnings);


            newLog.Logdate      = DateTime.Now;
            newLog.UpdatedCount = updated;
            newLog.NewEmps      = added.ToString();
            GetSession.Save(newLog);

            TempData["warnings"] = newLog.WarningLines;


            return(RedirectToAction("ProssesResult", new { added = added, updated = updated, deleted = deleted, errors = errors, warningsL = newLog.WarningLines, warnings = warnings }));
            //return Content(result, "text/html");
        }
예제 #13
0
        public ActionResult Login(LoginFormModel model)
        {
            if (ModelState.IsValid)
            {
                var emp = GetSession.QueryOver <Employee>().Where(x => x.Email == model.Username && x.Password == model.Password && x.IsActive == true).SingleOrDefault();

                /*
                 * if (emp != null)
                 * {
                 *  if (emp.IsAdmin)
                 *  {
                 *
                 *  }
                 *  else
                 *  {
                 *
                 *
                 *  }
                 * }
                 */

                //return Content("Password:"******"Username: "******"/login" && emp.IsAdmin == false)
                    //{
                    //    return Redirect("/");
                    //}
                    FormsAuthentication.SetAuthCookie(emp.Username, false);
                    //add cookie for auto login next time
                    Response.Cookies["user"].Value        = model.Username;
                    Response.Cookies["user"].Expires      = DateTime.MaxValue;
                    Response.Cookies["password"].Value    = model.Password;
                    Response.Cookies["password"].Expires  = DateTime.MaxValue;
                    Response.Cookies["user_name"].Value   = emp.Username;
                    Response.Cookies["user_name"].Expires = DateTime.MaxValue;
                    return(Redirect(FormsAuthentication.GetRedirectUrl(emp.Username, false)));
                }
                else if (adm != null)
                {
                    if (model.Username == MvcApplication.Config("admin.Username") && model.Password == MvcApplication.Config("admin.Password"))
                    {
                        Response.Cookies["user"].Value        = model.Username;
                        Response.Cookies["user"].Expires      = DateTime.MaxValue;
                        Response.Cookies["password"].Value    = model.Password;
                        Response.Cookies["password"].Expires  = DateTime.MaxValue;
                        Response.Cookies["user_name"].Value   = model.Username;
                        Response.Cookies["user_name"].Expires = DateTime.MaxValue;
                        FormsAuthentication.SetAuthCookie(model.Username, false);
                        return(Redirect(FormsAuthentication.GetRedirectUrl(model.Username, false)));
                    }
                }
            }


            HttpCookie currentUserCookie = Request.Cookies["user"];

            if (currentUserCookie != null)
            {
                Response.Cookies.Remove("user");
                Response.Cookies.Remove("password");
                currentUserCookie.Expires = DateTime.Now.AddDays(-10);
                currentUserCookie.Value   = null;
                Response.SetCookie(currentUserCookie);
            }

            return(View(model));
        }
예제 #14
0
        public ActionResult Create(ForumFormModel model, int categoryId = 1)
        {
            if (ModelState.IsValid)
            {
                #region Replace url text with link
                string body = model.Body;

                var outputString = model.Body;

                Regex regx = new Regex(@"https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", RegexOptions.IgnoreCase);

                MatchCollection mactches = regx.Matches(model.Body);
                foreach (Match match in mactches)
                {
                    outputString = outputString.Replace(match.Value, String.Format("<a href=\"{0}\" target=\"_blank\">לחץ כאן</a>", match.Value));
                }

                body = outputString;


                model.Body = body;
                #endregion


                var item = Mapper.Map <ForumFormModel, Forum>(model);
                item.CreatedBy = new Employee
                {
                    Id = GetEmployeeId
                };

                if (model.ParentId.HasValue)
                {
                    var forum = GetSession.Load <Forum>(model.ParentId);
                    item.Parent  = forum;
                    item.Subject = item.Parent.Subject; // Must be Uniqe!!!!
                }
                ViewData["catId"] = categoryId;
                item.CategoryId   = categoryId;
                ViewBag.list      = GetSession.QueryOver <ForumItem>().List();

                GetSession.Save(item);

                var    current_domain = MvcApplication.Config("current_domain").ToString();
                string host           = HttpContext.ApplicationInstance.Request.Url.Host;


                var forumItem = GetSession.QueryOver <ForumItem>().Where(x => x.Id == categoryId).SingleOrDefault().Admin;



                #region Send mail to forum users


                if (GetSession.Get <ForumItem>(Convert.ToInt64(categoryId)).isAvailableTooAll == false)
                {
                    Employee emp;
                    var      forum_users = GetSession.Get <ForumItem>(Convert.ToInt64(categoryId)).ForumUsers;
                    string[] ids         = forum_users.Split(',');

                    var list = new List <string>(ids);
                    list.Remove(GetEmployeeId.ToString());
                    ids = list.ToArray();

                    for (int i = 0; i < ids.Length; i++)
                    {
                        long id = Convert.ToInt64(ids[i]);
                        emp = GetSession.Get <Employee>(id);
                        sendMailTo(emp, categoryId);
                    }
                }



                #endregion



                MailMessage mail = new MailMessage();
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add(forumItem.Email.ToString());
                mail.Subject    = "הודעה חדשה בפורום";
                mail.IsBodyHtml = true;
                mail.Body       = "<html><body>"
                                  + "<h1>שלום, " + forumItem.FirstName.ToString() + " !</h1>"
                                  + "<h2>הודעה חדשה בפורום</h2>"
                                  + " <a href='" + host + "/Forums/" + item.CategoryId.ToString() + "'>לחץ כאן על הקישור לכניסה לפורום</a>"
                                  + "</body></html>";

                SmtpClient smtp = new SmtpClient();
                //smtp.Send(mail);



                //SmtpClient client = new SmtpClient();
                //client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "tagmedia1234");
                //client.Port = 587;
                //client.Host = "smtp.gmail.com";
                //client.EnableSsl = true;
                //MailAddress
                //    maFrom = new MailAddress("*****@*****.**", "Sender's Name"),
                //    maTo = new MailAddress(forumItem.Email.ToString(), "Recipient's Name");
                //MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
                //mmsg.Body =
                //    "<html><body>"
                //    + "<h1>שלום, " + forumItem.FirstName.ToString() + " !</h1>"
                //    + "<h2>הודעה חדשה בפורום</h2>"
                //    + " <a href='" + host + "/Forums/" + item.CategoryId.ToString() + "'>לחץ כאן על הקישור לכניסה לפורום</a>"
                //    + "</body></html>";
                //mmsg.IsBodyHtml = true;
                //mmsg.Subject = "הודעה חדשה בפורום";



                long ebatnya = 0;
                if (item.Parent != null)
                {
                    ebatnya = GetSession.QueryOver <ForumItem>().Where(x => x.Id == item.Parent.CategoryId).SingleOrDefault().Admin.Id;
                }
                else
                {
                    ebatnya = GetSession.QueryOver <ForumItem>().Where(x => x.Id == item.CategoryId).SingleOrDefault().Admin.Id;
                }



                if (item.CreatedBy.Id != ebatnya)
                {
                    smtp.Send(mail);
                }

                if (item.Parent != null)
                {
                    var theIdOfFather = GetSession.QueryOver <Forum>().Where(x => x.Parent == null).And(x => x.Subject == item.Subject).SingleOrDefault();



                    var theParentIsAdmin = GetSession.QueryOver <ForumItem>().Where(x => x.Id == item.Parent.CategoryId).SingleOrDefault();

                    if (item.CreatedBy.Id == theParentIsAdmin.Admin.Id)
                    {
                        var msgBody =

                            "<html><body>"
                            + "<h1>שלום, " + theIdOfFather.CreatedBy.FirstName.ToString() + " !</h1>"
                            + "<h2>הודעה חדשה בפורום</h2>"
                            + "<a href='" + host + "/Forums/" + item.CategoryId.ToString() + "'>לחץ כאן על הקישור לכניסה לפורום</a>"
                            + "</body></html>";



                        var msgSubject = "הודעה חדשה בפורום";

                        SendForumEmail(theIdOfFather.CreatedBy.Email.ToString(), msgSubject, msgBody);
                    }
                }


                return(RedirectToAction("Index"));
            }
            ViewData["catId"] = categoryId;



            return(View(model));
        }