Exemple #1
0
 public Filter(ADUtils adUtils)
 {
     ADUtils = adUtils;
 }
Exemple #2
0
        public string IsVisible()
        {
            if (HttpContext.Current.User.IsInRole("Domain Admins"))
            {
                return("Admin");
            }
            if (HttpContext.Current.User.Identity.Name.ToLower().Equals(Teacher.ToLower()))
            {
                return("Teacher");
            }
            UserNodes.Reverse();
            foreach (UserNode n in UserNodes)
            {
                if (n.Method == "Add")
                {
                    switch (n.Type)
                    {
                    case "User":
                        if (HttpContext.Current.User.Identity.Name.ToLower().Equals(n.Value.ToLower()))
                        {
                            return(n.Mode);
                        }
                        break;

                    case "Role":
                        if (HttpContext.Current.User.IsInRole(n.Value))
                        {
                            return(n.Mode);
                        }
                        break;

                    case "OU":
                        if (ADUtils.FindUsersIn(n.Value).Count(ui => ui.UserName.ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower())) == 1)
                        {
                            return(n.Mode);
                        }
                        break;
                    }
                }
                else
                {
                    switch (n.Type)
                    {
                    case "User":
                        if (HttpContext.Current.User.Identity.Name.ToLower().Equals(n.Value.ToLower()))
                        {
                            return("None");
                        }
                        break;

                    case "Role":
                        if (HttpContext.Current.User.IsInRole(n.Value))
                        {
                            return("None");
                        }
                        break;

                    case "OU":
                        if (ADUtils.FindUsersIn(n.Value).Count(ui => ui.UserName.ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower())) == 1)
                        {
                            return("None");
                        }
                        break;
                    }
                }
            }
            UserNodes.Reverse();
            return("None");
        }
Exemple #3
0
        protected void importSIMS_Click(object sender, EventArgs args)
        {
            if (!File.Exists(Server.MapPath("~/app_data/sims-bookings.xml")))
            {
                return;
            }
            XmlDocument doc = new XmlDocument();

            doc.Load(Server.MapPath("~/app_data/sims-bookings.xml"));
            XmlDocument sb = new XmlDocument();

            sb.Load(Server.MapPath("~/app_data/StaticBookings.xml"));
            UserInfo[] users = ADUtils.FindUsers(OUVisibility.BookingSystem);
            foreach (XmlNode n in doc.SelectNodes("/SuperStarReport/Record"))
            {
                string res = "";
                try {
                    res = n.SelectSingleNode("Name").InnerText;
                }
                catch { continue; }
                string user = "";
                if (n.SelectSingleNode("MainTeacher") == null)
                {
                    continue;
                }
                if (users.Count(u => u.Notes.ToLower() == n.SelectSingleNode("MainTeacher").InnerText.ToLower()) > 0)
                {
                    user = users.Single(u => u.Notes.ToLower() == n.SelectSingleNode("MainTeacher").InnerText.ToLower()).UserName;
                }
                else if (users.Count(u => u.DisplayName.ToLower().EndsWith(n.SelectSingleNode("MainTeacher").InnerText.ToLower().Split(new char[] { ' ' })[n.SelectSingleNode("MainTeacher").InnerText.ToLower().Split(new char[] { ' ' }).Length - 1])) == 1)
                {
                    user = users.Single(u => u.DisplayName.ToLower().EndsWith(n.SelectSingleNode("MainTeacher").InnerText.ToLower().Split(new char[] { ' ' })[n.SelectSingleNode("MainTeacher").InnerText.ToLower().Split(new char[] { ' ' }).Length - 1])).UserName;
                }
                if (string.IsNullOrWhiteSpace(user))
                {
                    throw new ArgumentOutOfRangeException("MainTeacher", "User cannot be found from " + n.SelectSingleNode("MainTeacher").InnerText);
                }
                string name = n.SelectSingleNode("Description").InnerText;
                if (n.SelectSingleNode("YearGroup") != null)
                {
                    name = n.SelectSingleNode("YearGroup").InnerText.Replace("  ", " ") + " " + name;
                }
                string d = n.SelectSingleNode("Name1").InnerText.Split(new char[] { ':' })[0];
                int    day;
                if (int.TryParse(d.Substring(d.Length - 2, 1), out day))
                {
                    day = int.Parse(d.Substring(d.Length - 2, 2));
                }
                else if (!int.TryParse(d.Substring(d.Length - 1, 1), out day))
                {
                    day = ConvertDayToInt(d);
                }
                string lesson = n.SelectSingleNode("Name1").InnerText.Split(new char[] { ':' })[1];
                lesson = config.BookingSystem.Lessons.Single(l => l.Name.EndsWith(" " + lesson)).Name;
                if (sb.SelectSingleNode("/Bookings").ChildNodes.Count == 0 || sb.SelectSingleNode("/Bookings/Booking[@day='" + day + "' and @lesson='" + lesson + "' and @room='" + res + "']") == null)
                {
                    XmlElement e = sb.CreateElement("Booking");
                    e.SetAttribute("day", day.ToString());
                    e.SetAttribute("lesson", lesson);
                    e.SetAttribute("room", res);
                    e.SetAttribute("name", name);
                    e.SetAttribute("username", user);
                    sb.SelectSingleNode("/Bookings").AppendChild(e);
                }
                else
                {
                    XmlNode e = sb.SelectSingleNode("/Bookings/Booking[@day='" + day + "' and @lesson='" + lesson + "' and @room='" + res + "']");
                    e.Attributes["name"].Value     = name;
                    e.Attributes["username"].Value = user;
                }
            }
            sb.Save(HttpContext.Current.Server.MapPath("~/App_Data/StaticBookings.xml"));
            Response.Redirect("./");
        }
Exemple #4
0
        public static void GenerateCancel(Booking booking, DateTime date, bool emailadmins)
        {
            try
            {
                if (string.IsNullOrEmpty(booking.User.Email))
                {
                    return;
                }
            }
            catch
            {
                return;
            }
            hapConfig     config = hapConfig.Current;
            StringBuilder sb     = new StringBuilder();
            StringWriter  sw     = new StringWriter(sb);

            string[] lessons = booking.Lesson.Split(new char[] { ',' });

            DateTime startDate = new DateTime(date.Year, date.Month, date.Day, config.BookingSystem.Lessons.Get(lessons[0].Trim()).StartTime.Hour, config.BookingSystem.Lessons.Get(lessons[0].Trim()).StartTime.Minute, 0);
            DateTime endDate   = new DateTime(date.Year, date.Month, date.Day, config.BookingSystem.Lessons.Get(lessons[lessons.Length - 1].Trim()).EndTime.Hour, config.BookingSystem.Lessons.Get(lessons[lessons.Length - 1].Trim()).EndTime.Minute, 0);
            string   location  = "";
            Resource resource  = config.BookingSystem.Resources[booking.Room];

            if (resource.Type == ResourceType.Room)
            {
                location = booking.Room;
            }
            else if (resource.Type == ResourceType.Laptops)
            {
                location = booking.LTRoom;
            }
            else if (resource.Type == ResourceType.Equipment || resource.Type == ResourceType.Loan)
            {
                location = booking.EquipRoom;
            }
            string summary     = "Cancellation of " + booking.Name + " in " + location;
            string description = "Cancellation of " + booking.Name + " in " + location + " during " + booking.Lesson + " on " + booking.Date.ToShortDateString() + " (" + DateTime.Now.ToString() + ")";

            if (resource.Type == ResourceType.Laptops)
            {
                summary     += " with the " + booking.Room + " [" + booking.Count + "]";
                description += " with the " + booking.Room + " [" + booking.Count + "]";
            }

            sb.AppendLine("BEGIN:VCALENDAR");
            sb.AppendLine("VERSION:2.0");
            sb.AppendLine("PRODID:-//hap/CalendarAppointment");
            sb.AppendLine("CALSCALE:GREGORIAN");
            sb.AppendLine("METHOD:CANCEL");
            sb.AppendLine("BEGIN:VEVENT");
            sb.AppendLine("DTSTART:" + startDate.ToUniversalTime().ToString(DateFormat));
            sb.AppendLine("DTEND:" + endDate.ToUniversalTime().ToString(DateFormat));
            sb.AppendLine("ORGANIZER:MAILTO:" + booking.User.Email);
            sb.AppendLine("LOCATION:" + location);
            sb.AppendLine("UID:" + booking.uid);
            sb.AppendLine("DTSTAMP:" + DateTime.Now.ToString(DateFormat));
            sb.AppendLine("SUMMARY:" + summary);
            sb.AppendLine("STATUS:CANCELLED");
            sb.AppendLine("DESCRIPTION:" + description);
            sb.AppendLine("END:VEVENT");
            sb.AppendLine("END:VCALENDAR");

            FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath("~/App_Data/ITBooking.ics"));

            if (file.Exists)
            {
                file.Delete();
            }
            StreamWriter sr = file.CreateText();

            sr.Write(sb.ToString());
            sr.Flush();
            sr.Close();
            sr.Dispose();

            MailMessage     mes     = new MailMessage();
            IFormatProvider culture = new CultureInfo("en-gb");

            mes.Subject = summary;
            mes.From    = mes.Sender = new MailAddress(config.SMTP.FromEmail, config.SMTP.FromUser);
            mes.ReplyToList.Add(mes.From);

            foreach (string s in hapConfig.Current.BookingSystem.Resources[booking.Room].Admins.Split(new char[] { ',' }))
            {
                if (s != "Inherit")
                {
                    UserInfo ui = ADUtils.FindUserInfos(s.Trim())[0];
                    try
                    {
                        if (string.IsNullOrEmpty(ui.Email))
                        {
                            continue;
                        }
                    }
                    catch
                    {
                        continue;
                    }
                    if (!string.IsNullOrEmpty(ui.Email))
                    {
                        mes.To.Add(new MailAddress(ui.Email, ui.DisplayName));
                    }
                }
            }

            mes.Body = description;

            AlternateView av = AlternateView.CreateAlternateViewFromString(sb.ToString(), new ContentType("text/calendar; method=CANCEL; name=ITBooking.ics"));

            av.TransferEncoding = TransferEncoding.SevenBit;
            mes.AlternateViews.Add(av);
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };
            //mes.Attachments.Add(new Attachment(file.FullName, "text/calendar; method=REQUEST; name=ITBooking.ics"));
            SmtpClient client = new SmtpClient(config.SMTP.Server);

            if (!string.IsNullOrEmpty(config.SMTP.User))
            {
                client.Credentials           = new NetworkCredential(config.SMTP.User, config.SMTP.Password);
                client.UseDefaultCredentials = false;
            }
            client.EnableSsl = config.SMTP.SSL;
            if (config.SMTP.TLS)
            {
                client.TargetName     = "STARTTLS/" + config.SMTP.Server;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
            }
            client.Port = config.SMTP.Port;
            client.Send(mes);
        }
Exemple #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            List <string> users = new List <string>();

            foreach (string s in config.HelpDesk.Admins.Split(new char[] { ',' }))
            {
                if (s.StartsWith("!"))
                {
                    continue;
                }
                else if (!System.Web.Security.Roles.RoleExists(s.Trim()))
                {
                    users.Add(s.Trim().ToLower());
                }
                else
                {
                    foreach (string s2 in System.Web.Security.Roles.GetUsersInRole(s.Trim()))
                    {
                        if (!users.Contains(s2.ToLower()))
                        {
                            users.Add(s2.ToLower());
                        }
                    }
                }
            }
            foreach (string s in config.HelpDesk.Admins.Split(new char[] { ',' }))
            {
                if (s.StartsWith("!") && users.Contains(s.Trim().Substring(1).ToLower()))
                {
                    users.Remove(s.Trim().Substring(1).ToLower());
                }
            }
            if (config.HelpDesk.Provider == "xml")
            {
                foreach (FileInfo f in new DirectoryInfo(Server.MapPath("~/app_data/")).GetFiles("Tickets_*.xml", SearchOption.TopDirectoryOnly))
                {
                    archiveddates.Items.Add(new ListItem(f.Name.Remove(f.Name.LastIndexOf('.')).Remove(0, 8).Replace("_", " to "), f.Name.Remove(f.Name.LastIndexOf('.')).Remove(0, 7)));
                }
            }
            else
            {
                Data.SQL.sql2linqDataContext sql = new Data.SQL.sql2linqDataContext(WebConfigurationManager.ConnectionStrings[config.HelpDesk.Provider].ConnectionString);
                foreach (var tick in sql.Tickets.Where(t => t.Archive != "").GroupBy(t => t.Archive))
                {
                    archiveddates.Items.Add(new ListItem(tick.Key.Replace("_", " to "), tick.Key));
                }
            }
            hasArch = archiveddates.Items.Count > 0;
            if (hasArch)
            {
                archiveddates.Items.Insert(0, new ListItem("--- Select ---", ""));
            }
            adminbookingpanel.Visible = archiveadmin.Visible = isHDAdmin;
            if (isHDAdmin)
            {
                userlist.Items.Clear();
                userlist2.Items.Clear();
                foreach (UserInfo user in ADUtils.FindUsers(OUVisibility.HelpDesk))
                {
                    if (user.DisplayName == user.UserName)
                    {
                        userlist.Items.Add(new ListItem(user.UserName, user.UserName.ToLower()));
                    }
                    else
                    {
                        userlist.Items.Add(new ListItem(string.Format("{0} - ({1})", user.UserName, user.DisplayName), user.UserName.ToLower()));
                    }
                    if (users.Contains(user.UserName.ToLower()))
                    {
                        if (user.DisplayName == user.UserName)
                        {
                            userlist2.Items.Add(new ListItem(user.UserName, user.UserName.ToLower()));
                        }
                        else
                        {
                            userlist2.Items.Add(new ListItem(string.Format("{0} - ({1})", user.UserName, user.DisplayName), user.UserName.ToLower()));
                        }
                    }
                }
                userlist.SelectedValue = userlist2.SelectedValue = ADUser.UserName.ToLower();
            }
            if (!Request.Browser.Browser.Contains("Chrome"))
            {
                try
                {
                    foreach (string ip in config.AD.InternalIP)
                    {
                        if (new IPSubnet(ip).Contains(Request.UserHostAddress) && Dns.GetHostEntry(Request.UserHostAddress).HostName.ToLower().EndsWith(config.AD.UPN.ToLower()))
                        {
                            newticket_pc.Value = Dns.GetHostEntry(Request.UserHostAddress).HostName.ToLower().Remove(Dns.GetHostEntry(Request.UserHostAddress).HostName.IndexOf('.'));
                        }
                    }
                }
                catch { }
            }
            migrate.Visible = isUpgrade;
        }
Exemple #6
0
 protected void Page_Load(object sender, EventArgs e)
 {
     rez = new List <Resource>();
     if (RouteData.Values.Count == 0)
     {
         foreach (Resource r in config.BookingSystem.Resources.Values)
         {
             if (isVisible(r.ShowTo, r.HideFrom))
             {
                 rez.Add(r);
             }
         }
     }
     else if (RouteData.Values.ContainsKey("resource"))
     {
         foreach (string s in RouteData.GetRequiredString("resource").Split(new char[] { ',' }))
         {
             foreach (Resource r in config.BookingSystem.Resources.Values)
             {
                 if (isVisible(r.ShowTo, r.HideFrom) && r.Name.ToLower() == s.Trim().ToLower())
                 {
                     rez.Add(r);
                 }
             }
         }
     }
     else if (RouteData.Values.ContainsKey("type"))
     {
         foreach (string s in RouteData.GetRequiredString("type").Split(new char[] { ',' }))
         {
             foreach (Resource r in config.BookingSystem.Resources.Values)
             {
                 if (isVisible(r.ShowTo, r.HideFrom) && r.Type == (ResourceType)Enum.Parse(typeof(ResourceType), s.Trim()))
                 {
                     rez.Add(r);
                 }
             }
         }
     }
     if (rez.Count == 0 && !isBSAdmin)
     {
         Response.Redirect("~/unauthorised.aspx");
     }
     resources1.DataSource = resources2.DataSource = rez.ToArray();
     resources1.DataBind(); resources2.DataBind();
     lessons.DataSource = config.BookingSystem.Lessons;
     lessons.DataBind();
     subjects.DataSource = config.BookingSystem.Subjects.ToArray();
     subjects.DataBind();
     adminlink.Visible = isBSAdmin || User.IsInRole("Domain Admins");
     userlist.Items.Clear();
     foreach (UserInfo user in ADUtils.FindUsers(OUVisibility.BookingSystem))
     {
         if (user.DisplayName == user.UserName)
         {
             userlist.Items.Add(new ListItem(user.UserName, user.UserName.ToLower()));
         }
         else
         {
             userlist.Items.Add(new ListItem(string.Format("{0} - ({1})", user.UserName, user.Notes), user.UserName.ToLower()));
         }
     }
     userlist.SelectedValue = ADUser.UserName.ToLower();
     try
     {
         DateTime d = CurrentDate;
         BodyCode = new string[] { "", "" };
     }
     catch (ArgumentOutOfRangeException) { BodyCode = new string[] { " style=\"display: none;\"", "You are current outside of the set terms, please get an Admin to set the new year terms" }; }
 }
Exemple #7
0
        /// <summary>
        /// 反安装
        /// </summary>
        /// <param name="moduleName"></param>
        public static void UninstallModule(string moduleName)
        {
            CreateNecessaryDirectories(moduleName);

            string dir = System.IO.Directory.GetCurrentDirectory() + "\\" + moduleName;

            IList <ModuleInfo> moduleInfos = ADInfoBll.Instance.GetInfos <ModuleInfo>("from Feng.ModuleInfo where Id = '" + moduleName + "'");

            if (moduleInfos.Count == 0)
            {
                throw new ArgumentException("There is no module named " + moduleName);
            }
            CompressionHelper.DecompressToFolder(moduleInfos[0].ModuleData, System.IO.Directory.GetCurrentDirectory());

            // ReferenceData
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\referencedata\\standard\\"))
            {
                ADUtils.DeleteFromXmlFile(file);
            }
            // ApplicationDictionaryData
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\sourcedata\\"))
            {
                string s = System.IO.Path.GetFileNameWithoutExtension(file);
                if (s.StartsWith("AD_Module"))
                {
                    continue;
                }

                ADUtils.DeleteFromXmlFile(file);
            }

            //// DbTable
            //foreach (string file in System.IO.Directory.GetFiles(dir + "src-db\\database\\model\\tables\\"))
            //{
            //}

            // DbView
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\views\\"))
            {
                string script = "DROP VIEW " + System.IO.Path.GetFileNameWithoutExtension(file);
                DbHelper.Instance.ExecuteNonQuery(script);
            }
            // DbFunction
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\functions\\"))
            {
                string script = "DROP FUNCTION " + System.IO.Path.GetFileNameWithoutExtension(file);
                DbHelper.Instance.ExecuteNonQuery(script);
            }
            // DbTrigger
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\triggers\\"))
            {
                string script = "DROP TRIGGER " + System.IO.Path.GetFileNameWithoutExtension(file);
                DbHelper.Instance.ExecuteNonQuery(script);
            }
            // DbProcedure
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\procedures\\"))
            {
                string script = "DROP PROCEDURE " + System.IO.Path.GetFileNameWithoutExtension(file);
                DbHelper.Instance.ExecuteNonQuery(script);
            }
        }
Exemple #8
0
        /// <summary>
        /// 安装Module
        /// </summary>
        /// <param name="moduleName"></param>
        public static void InstallModule(string moduleName)
        {
            CreateNecessaryDirectories(moduleName);

            string dir = System.IO.Directory.GetCurrentDirectory() + "\\" + moduleName;

            //// CheckModuleDependency
            //IList<ModuleDependencyInfo> moduleDependencyInfos = ADInfoBll.Instance.GetInfos<ModuleDependencyInfo>(
            //    "from ModuleDependencyInfo where Module.Name = :moduleName", new Dictionary<string, object> { { "moduleName", moduleName } });
            //foreach (ModuleDependencyInfo dependency in moduleDependencyInfos)
            //{
            //    if (dependency.DependentModule
            //}
            //// No use now
            ////ModuleByClientInfo moduleByClientInfo = null;
            ////ModuleByOrgInfo moduleByOrgInfo = null;

            IList <ModuleInfo> moduleInfos = ADInfoBll.Instance.GetInfos <ModuleInfo>("from Feng.ModuleInfo where Id = '" + moduleName + "'");

            if (moduleInfos.Count == 0)
            {
                throw new ArgumentException("There is no module named " + moduleName);
            }
            CompressionHelper.DecompressToFolder(moduleInfos[0].ModuleData, System.IO.Directory.GetCurrentDirectory());

            // ReferenceData
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\referencedata\\standard\\"))
            {
                ADUtils.ImportFromXmlFile(file);
            }
            // ApplicationDictionaryData
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\sourcedata\\"))
            {
                string s = System.IO.Path.GetFileNameWithoutExtension(file);
                if (s.StartsWith("AD_Module"))
                {
                    continue;
                }
                ADUtils.ImportFromXmlFile(file);
            }

            //// DbTable
            //foreach (string file in System.IO.Directory.GetFiles(dir + "src-db\\database\\model\\tables\\"))
            //{
            //}

            // DbView
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\views\\"))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
                {
                    string script = sr.ReadToEnd();
                    DbHelper.Instance.ExecuteNonQuery(script);
                }
            }
            // DbFunction
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\functions\\"))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
                {
                    string script = sr.ReadToEnd();
                    DbHelper.Instance.ExecuteNonQuery(script);
                }
            }
            // DbTrigger
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\triggers\\"))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
                {
                    string script = sr.ReadToEnd();
                    DbHelper.Instance.ExecuteNonQuery(script);
                }
            }
            // DbProcedure
            foreach (string file in System.IO.Directory.GetFiles(dir + "\\src-db\\database\\model\\procedures\\"))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
                {
                    string script = sr.ReadToEnd();
                    DbHelper.Instance.ExecuteNonQuery(script);
                }
            }

            //// SourceModel
            //foreach (string file in System.IO.Directory.GetFiles(dir + "\\src\\model\\"))
            //{
            //}

            //// SourceScript
            //foreach (string file in System.IO.Directory.GetFiles(dir + "\\src\\script\\"))
            //{
            //}

            //// SourceReport
            //foreach (string file in System.IO.Directory.GetFiles(dir + "\\src\\report\\"))
            //{
            //}
        }
        protected override GetDlpPolicyTipsResponse InternalExecute()
        {
            PolicyTipRequestLogger policyTipRequestLogger = PolicyTipRequestLogger.CreateInstance(this.CorrelationId);

            policyTipRequestLogger.StartStage(LogStage.ReceiveRequest);
            Item item = null;
            GetDlpPolicyTipsResponse result;

            try
            {
                GetDlpPolicyTipsCommand.SetReceiveRequestLogData(policyTipRequestLogger, this.ItemId, this.NeedToReclassify, this.BodyOrSubjectChanged, this.Recipients, this.EventTrigger, this.CustomizedStringsNeeded, this.ClientSupportsScanResultData, this.ScanResultData);
                if (base.CallContext != null && base.CallContext.AccessingADUser != null && base.CallContext.AccessingADUser.OrganizationId != null)
                {
                    this.OrganizationId = base.CallContext.AccessingADUser.OrganizationId;
                    if (this.ItemId == null || string.IsNullOrEmpty(this.ItemId.GetId()))
                    {
                        GetDlpPolicyTipsResponse invalidStoreItemIdResponse = GetDlpPolicyTipsResponse.InvalidStoreItemIdResponse;
                        this.TransitionToSendResponse(false, true, invalidStoreItemIdResponse, policyTipRequestLogger, true);
                        result = invalidStoreItemIdResponse;
                    }
                    else if (this.ItemId.GetId().Equals(GetDlpPolicyTipsCommand.pingRequestItemId, StringComparison.OrdinalIgnoreCase))
                    {
                        policyTipRequestLogger.AppendData("Ping", "1");
                        GetDlpPolicyTipsResponse responseToPingRequest = GetDlpPolicyTipsResponse.GetResponseToPingRequest();
                        this.TransitionToSendResponse(true, false, responseToPingRequest, policyTipRequestLogger, false);
                        result = responseToPingRequest;
                    }
                    else if (!GetDlpPolicyTipsCommand.AddItemToCurrentPending(this.ItemId.GetId()))
                    {
                        policyTipRequestLogger.AppendData("ItemAlreadyBeingProcessed", "1");
                        GetDlpPolicyTipsResponse itemAlreadyBeingProcessedResponse = GetDlpPolicyTipsResponse.ItemAlreadyBeingProcessedResponse;
                        this.TransitionToSendResponse(true, true, itemAlreadyBeingProcessedResponse, policyTipRequestLogger, false);
                        result = itemAlreadyBeingProcessedResponse;
                    }
                    else
                    {
                        ShortList <string> recipients   = GetDlpPolicyTipsCommand.ValidateAndGetEmailAddressStrings(this.Recipients, policyTipRequestLogger);
                        IdAndSession       idAndSession = null;
                        try
                        {
                            idAndSession = base.IdConverter.ConvertItemIdToIdAndSessionReadOnly(this.ItemId);
                        }
                        catch (InvalidStoreIdException exception)
                        {
                            policyTipRequestLogger.SetException(exception);
                            GetDlpPolicyTipsResponse invalidStoreItemIdResponse2 = GetDlpPolicyTipsResponse.InvalidStoreItemIdResponse;
                            this.TransitionToSendResponse(false, true, invalidStoreItemIdResponse2, policyTipRequestLogger, true);
                            return(invalidStoreItemIdResponse2);
                        }
                        catch (ObjectNotFoundException exception2)
                        {
                            policyTipRequestLogger.SetException(exception2);
                            GetDlpPolicyTipsResponse invalidStoreItemIdResponse3 = GetDlpPolicyTipsResponse.InvalidStoreItemIdResponse;
                            this.TransitionToSendResponse(false, true, invalidStoreItemIdResponse3, policyTipRequestLogger, true);
                            return(invalidStoreItemIdResponse3);
                        }
                        catch (AccessDeniedException exception3)
                        {
                            policyTipRequestLogger.SetException(exception3);
                            GetDlpPolicyTipsResponse accessDeniedStoreItemIdResponse = GetDlpPolicyTipsResponse.AccessDeniedStoreItemIdResponse;
                            this.TransitionToSendResponse(false, true, accessDeniedStoreItemIdResponse, policyTipRequestLogger, true);
                            return(accessDeniedStoreItemIdResponse);
                        }
                        policyTipRequestLogger.EndStageAndTransitionToStage(LogStage.LoadItem);
                        List <DlpPolicyMatchDetail> list = null;
                        bool   flag   = false;
                        string empty  = string.Empty;
                        string empty2 = string.Empty;
                        item = Item.Bind(idAndSession.Session, idAndSession.Id);
                        ScanResultStorageProvider scanResultStorageProvider = null;
                        if (this.ClientSupportsScanResultData)
                        {
                            try
                            {
                                scanResultStorageProvider = new ClientScanResultStorageProvider(this.ScanResultData, item);
                                goto IL_274;
                            }
                            catch (ClientScanResultParseException exception4)
                            {
                                policyTipRequestLogger.SetException(exception4);
                                GetDlpPolicyTipsResponse invalidClientScanResultResponse = GetDlpPolicyTipsResponse.InvalidClientScanResultResponse;
                                this.TransitionToSendResponse(false, true, invalidClientScanResultResponse, policyTipRequestLogger, true);
                                return(invalidClientScanResultResponse);
                            }
                        }
                        item.OpenAsReadWrite();
                        scanResultStorageProvider = new StoreItemScanResultStorageProvider(item);
IL_274:
                        string empty3 = string.Empty;
                        if (!GetDlpPolicyTipsCommand.IsSupportedStoreItemType(item, policyTipRequestLogger, out empty3))
                        {
                            GetDlpPolicyTipsResponse getDlpPolicyTipsResponse = new GetDlpPolicyTipsResponse(EvaluationResult.PermanentError);
                            getDlpPolicyTipsResponse.DiagnosticData = string.Format("{0}:{1}", "UnSupportedStoreItemType", empty3);
                            this.TransitionToSendResponse(false, true, getDlpPolicyTipsResponse, policyTipRequestLogger, true);
                            result = getDlpPolicyTipsResponse;
                        }
                        else
                        {
                            if (item != null)
                            {
                                policyTipRequestLogger.AppendData("Subject", PolicyTipRequestLogger.MarkAsPII(item.GetValueOrDefault <string>(InternalSchema.Subject, string.Empty)));
                            }
                            string fromAddress = GetDlpPolicyTipsCommand.GetFromAddress(idAndSession, item, policyTipRequestLogger);
                            if (string.IsNullOrEmpty(fromAddress))
                            {
                                policyTipRequestLogger.AppendData("NullFrom", "1");
                                GetDlpPolicyTipsResponse getDlpPolicyTipsResponse2 = new GetDlpPolicyTipsResponse(EvaluationResult.PermanentError);
                                getDlpPolicyTipsResponse2.DiagnosticData = "NullFrom";
                                this.TransitionToSendResponse(false, true, getDlpPolicyTipsResponse2, policyTipRequestLogger, true);
                                result = getDlpPolicyTipsResponse2;
                            }
                            else if (!GetDlpPolicyTipsCommand.HasContent(item, scanResultStorageProvider, policyTipRequestLogger))
                            {
                                policyTipRequestLogger.AppendData("NoContent", "1");
                                GetDlpPolicyTipsResponse noContentResponse = GetDlpPolicyTipsResponse.NoContentResponse;
                                this.TransitionToSendResponse(true, true, noContentResponse, policyTipRequestLogger, true);
                                result = noContentResponse;
                            }
                            else
                            {
                                policyTipRequestLogger.EndStageAndTransitionToStage(LogStage.RefreshClassifications);
                                policyTipRequestLogger.AppendData("BeforeRefreshClassifications", DiscoveredDataClassification.ToString(scanResultStorageProvider.GetDlpDetectedClassificationObjects()));
                                if (this.NeedToReclassify)
                                {
                                    scanResultStorageProvider.ResetAllClassifications();
                                }
                                else
                                {
                                    if (this.BodyOrSubjectChanged)
                                    {
                                        scanResultStorageProvider.RefreshBodyClassifications();
                                    }
                                    scanResultStorageProvider.RefreshAttachmentClassifications();
                                }
                                policyTipRequestLogger.AppendData("AfterRefreshClassifications", DiscoveredDataClassification.ToString(scanResultStorageProvider.GetDlpDetectedClassificationObjects()));
                                policyTipRequestLogger.EndStageAndTransitionToStage(LogStage.LoadRules);
                                policyTipRequestLogger.AppendData("OrganizationId", this.OrganizationId.ToString());
                                RuleCollection ruleCollection = GetDlpPolicyTipsCommand.LoadRules(this.OrganizationId);
                                if (ruleCollection == null || ruleCollection.Count == 0)
                                {
                                    policyTipRequestLogger.AppendData("RuleCount", "0");
                                    GetDlpPolicyTipsResponse noRulesResponse = GetDlpPolicyTipsResponse.NoRulesResponse;
                                    this.TransitionToSendResponse(true, true, noRulesResponse, policyTipRequestLogger, true);
                                    result = noRulesResponse;
                                }
                                else
                                {
                                    policyTipRequestLogger.AppendData("RuleCount", ruleCollection.Count.ToString());
                                    policyTipRequestLogger.AppendData("RuleNames", GetDlpPolicyTipsCommand.GetRuleNamesForTracking(ruleCollection));
                                    policyTipRequestLogger.EndStageAndTransitionToStage(LogStage.EvaluateRules);
                                    ExecutionStatus executionStatus = GetDlpPolicyTipsCommand.RunRules(ruleCollection, scanResultStorageProvider, item, fromAddress, recipients, out list, out flag, out empty, out empty2, policyTipRequestLogger);
                                    policyTipRequestLogger.AppendData("ExecutionStatus", executionStatus.ToString());
                                    policyTipRequestLogger.AppendData("MatchResults", (list == null) ? string.Empty : DlpPolicyMatchDetail.ToString(list));
                                    policyTipRequestLogger.AppendData("RuleEvalLatency", empty);
                                    policyTipRequestLogger.AppendData("RuleEvalResult", empty2);
                                    PolicyTipCustomizedStrings policyTipCustomizedStrings = null;
                                    if (this.CustomizedStringsNeeded)
                                    {
                                        policyTipRequestLogger.EndStageAndTransitionToStage(LogStage.LoadCustomStrings);
                                        UserContext userContext = UserContextManager.GetUserContext(base.CallContext.HttpContext, base.CallContext.EffectiveCaller, true);
                                        CultureInfo userCulture = userContext.UserCulture;
                                        policyTipRequestLogger.AppendData("CallersCulture", userCulture.Name);
                                        policyTipCustomizedStrings = ADUtils.GetPolicyTipStrings(this.OrganizationId, userCulture.Name);
                                        policyTipRequestLogger.AppendData("PolicyTipStrings", (policyTipCustomizedStrings == null) ? string.Empty : string.Format("Url:{0}/Notify:{1}/Override:{2}/Block:{3}", new object[]
                                        {
                                            policyTipCustomizedStrings.ComplianceURL ?? string.Empty,
                                            policyTipCustomizedStrings.PolicyTipMessageNotifyString ?? string.Empty,
                                            policyTipCustomizedStrings.PolicyTipMessageOverrideString ?? string.Empty,
                                            policyTipCustomizedStrings.PolicyTipMessageBlockString ?? string.Empty
                                        }));
                                    }
                                    GetDlpPolicyTipsResponse getDlpPolicyTipsResponse3 = new GetDlpPolicyTipsResponse(EvaluationResult.Success);
                                    if (this.ClientSupportsScanResultData)
                                    {
                                        getDlpPolicyTipsResponse3.ScanResultData            = ((ClientScanResultStorageProvider)scanResultStorageProvider).GetScanResultData();
                                        getDlpPolicyTipsResponse3.DetectedClassificationIds = ((ClientScanResultStorageProvider)scanResultStorageProvider).GetDetectedClassificationIds();
                                    }
                                    else
                                    {
                                        item.Save(SaveMode.ResolveConflicts);
                                    }
                                    if (list != null)
                                    {
                                        getDlpPolicyTipsResponse3.Matches = list.ToArray();
                                    }
                                    if (flag)
                                    {
                                        getDlpPolicyTipsResponse3.OptimizationResult = OptimizationResult.NoContentMatch;
                                    }
                                    if (this.CustomizedStringsNeeded)
                                    {
                                        getDlpPolicyTipsResponse3.CustomizedStrings = policyTipCustomizedStrings;
                                    }
                                    this.TransitionToSendResponse(true, false, getDlpPolicyTipsResponse3, policyTipRequestLogger, true);
                                    result = getDlpPolicyTipsResponse3;
                                }
                            }
                        }
                    }
                }
                else
                {
                    GetDlpPolicyTipsResponse nullOrganizationResponse = GetDlpPolicyTipsResponse.NullOrganizationResponse;
                    this.TransitionToSendResponse(false, true, nullOrganizationResponse, policyTipRequestLogger, true);
                    result = nullOrganizationResponse;
                }
            }
            catch (Exception ex)
            {
                policyTipRequestLogger.SetException(ex);
                GetDlpPolicyTipsResponse getDlpPolicyTipsResponse4;
                if (!GetDlpPolicyTipsCommand.CheckIfKnownExceptionAndUpdatePerfCounters(ex))
                {
                    getDlpPolicyTipsResponse4 = new GetDlpPolicyTipsResponse(EvaluationResult.UnexpectedPermanentError);
                    this.TransitionToSendResponse(false, false, getDlpPolicyTipsResponse4, policyTipRequestLogger, true);
                    throw;
                }
                getDlpPolicyTipsResponse4 = new GetDlpPolicyTipsResponse(EvaluationResult.PermanentError);
                this.TransitionToSendResponse(false, false, getDlpPolicyTipsResponse4, policyTipRequestLogger, true);
                List <string> list2 = null;
                List <string> list3 = null;
                string        text  = null;
                PolicyTipProtocolLog.GetExceptionTypeAndDetails(ex, out list2, out list3, out text, false);
                getDlpPolicyTipsResponse4.DiagnosticData = string.Format("OuterExceptionType:{0}/OuterExceptionMessage:{1}/InnerExceptionType:{2}/InnerExceptionMessage:{3}/ExceptionChain:{4}.", new object[]
                {
                    list2[0],
                    list3[0],
                    (list2.Count > 1) ? list2[list2.Count - 1] : string.Empty,
                    (list2.Count > 1) ? list3[list3.Count - 1] : string.Empty,
                    text
                });
                result = getDlpPolicyTipsResponse4;
            }
            finally
            {
                if (item != null)
                {
                    item.Dispose();
                    item = null;
                }
            }
            return(result);
        }
 internal static RuleCollection LoadRules(OrganizationId organizationId)
 {
     return(ADUtils.GetPolicyTipRulesPerTenantSettings(organizationId).RuleCollection);
 }
Exemple #11
0
        public static void Generate(Booking booking, DateTime date, bool emailadmins)
        {
            hapConfig     config = hapConfig.Current;
            StringBuilder sb     = new StringBuilder();
            StringWriter  sw     = new StringWriter(sb);

            DateTime  startDate = new DateTime(date.Year, date.Month, date.Day, config.BookingSystem.Lessons.Get(booking.Lesson).StartTime.Hour, config.BookingSystem.Lessons.Get(booking.Lesson).StartTime.Minute, 0);
            DateTime  endDate   = new DateTime(date.Year, date.Month, date.Day, config.BookingSystem.Lessons.Get(booking.Lesson).EndTime.Hour, config.BookingSystem.Lessons.Get(booking.Lesson).EndTime.Minute, 0);
            string    location  = "";
            Resource  resource  = config.BookingSystem.Resources[booking.Room];
            Templates t         = new Templates();
            Template  template  = t["generaladmin"];

            if (t.ContainsKey(resource.Name))
            {
                template = t[resource.Name + "admin"];
            }
            string ltcount = "";

            if (resource.Type == ResourceType.Room)
            {
                location = booking.Room;
            }
            else if (resource.Type == ResourceType.Laptops)
            {
                location = booking.LTRoom; ltcount = booking.Count.ToString();
            }
            else if (resource.Type == ResourceType.Equipment)
            {
                location = booking.EquipRoom;
            }

            string summary     = string.Format(template.Subject, booking.Username, booking.User.DisplayName, booking.Room, booking.Name, booking.Date.ToShortDateString(), booking.Day, booking.Lesson, location, ltcount);
            string description = string.Format(template.Content, booking.Username, booking.User.DisplayName, booking.Room, booking.Name, booking.Date.ToShortDateString(), booking.Day, booking.Lesson, location, ltcount);

            List <UserInfo> uis = new List <UserInfo>();

            sb.AppendLine("BEGIN:VCALENDAR");
            sb.AppendLine("VERSION:2.0");
            sb.AppendLine("PRODID:-//chsit/CalendarAppointment");
            sb.AppendLine("CALSCALE:GREGORIAN");
            sb.AppendLine("METHOD:REQUEST");
            sb.AppendLine("BEGIN:VEVENT");
            sb.AppendLine("DTSTART:" + startDate.ToUniversalTime().ToString(DateFormat));
            sb.AppendLine("DTEND:" + endDate.ToUniversalTime().ToString(DateFormat));
            sb.AppendLine("ORGANIZER;CN=" + booking.User.DisplayName + ":MAILTO:" + booking.User.Email);
            sb.AppendLine("ATTENDEE;ROLE=REQ-PARTICIPANT;CN=" + booking.User.DisplayName + ":MAILTO:" + booking.User.Email);
            foreach (string s in hapConfig.Current.BookingSystem.Resources[booking.Room].Admins.Split(new char[] { ',' }))
            {
                UserInfo ui = ADUtils.FindUserInfos(s)[0];
                uis.Add(ui);
                if (!string.IsNullOrEmpty(ui.Email))
                {
                    sb.AppendLine("ATTENDEE;ROLE=REQ-PARTICIPANT;CN=" + ui.DisplayName + ":MAILTO:" + ui.Email);
                }
            }
            sb.AppendLine("LOCATION:" + location);
            sb.AppendLine("UID:" + booking.uid);
            sb.AppendLine("DTSTAMP:" + DateTime.Now.ToString(DateFormat));
            sb.AppendLine("SUMMARY:" + summary);
            sb.AppendLine("DESCRIPTION:" + description);
            sb.AppendLine("BEGIN:VALARM");
            sb.AppendLine("ACTION:DISPLAY");
            sb.AppendLine("DESCRIPTION:" + summary);
            sb.AppendLine("TRIGGER:-PT5M");
            sb.AppendLine("END:VALARM");
            sb.AppendLine("END:VEVENT");
            sb.AppendLine("END:VCALENDAR");

            FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath("~/App_Data/ITBooking.ics"));

            if (file.Exists)
            {
                file.Delete();
            }
            StreamWriter sr = file.CreateText();

            sr.Write(sb.ToString());
            sr.Flush();
            sr.Close();
            sr.Dispose();

            MailMessage     mes     = new MailMessage();
            IFormatProvider culture = new CultureInfo("en-gb");

            mes.Subject = summary;
            mes.From    = mes.Sender = new MailAddress(config.SMTP.FromEmail, config.SMTP.FromUser);
            mes.ReplyToList.Add(mes.From);
            foreach (UserInfo u1 in uis.Where(u => !string.IsNullOrEmpty(u.Email)))
            {
                mes.To.Add(new MailAddress(u1.Email, u1.DisplayName));
            }

            mes.Body = description;

            AlternateView av = AlternateView.CreateAlternateViewFromString(sb.ToString(), new ContentType("text/calendar; method=REQUEST; name=ITBooking.ics"));

            av.TransferEncoding = TransferEncoding.SevenBit;
            mes.AlternateViews.Add(av);

            //mes.Attachments.Add(new Attachment(file.FullName, "text/calendar; method=REQUEST; name=ITBooking.ics"));
            SmtpClient client = new SmtpClient(config.SMTP.Server);

            if (!string.IsNullOrEmpty(config.SMTP.User))
            {
                client.Credentials = new NetworkCredential(config.SMTP.User, config.SMTP.Password);
            }
            client.EnableSsl = config.SMTP.SSL;
            client.Port      = config.SMTP.Port;
            client.Send(mes);
        }