Пример #1
0
        //get date in icalendater format
        public static string getStartTimeevent(CalendarBasicModel ev)
        {
            string[] mas = ev.rec_type.Split('#');
            string[] arr = mas[0].Split('_');
            int      n   = 0;
            int      day = 0;

            switch (arr[0])
            {
            case "day":
                return(DateTime.Parse(ev.start_date).ToString(d.format));

            case "week":
                string[] diff = explode(',', arr[4]);
                if (diff[0] == "0")
                {
                    n = 7;
                }
                else
                {
                    n = Convert.ToInt32(diff[0]);
                }

                day = DateTime.Parse(ev.start_date).Day + n;
                string dayString = day.ToString();
                if (day < 10)
                {
                    dayString = "0" + dayString;
                }

                return(DateTime.Parse(ev.start_date).ToString("yyyyMM") + dayString + "T" + DateTime.Parse(ev.start_date).ToString("HHmmss"));

            case "month":
            case "year":
                if (arr[2] != "" && arr[3] != "")
                {
                    int dif = Convert.ToInt32(arr[2]) - Convert.ToInt32(DateTime.Parse(ev.start_date).DayOfWeek);
                    if (dif > 0)
                    {
                        dif -= 7;
                    }

                    day = (7 * Convert.ToInt32(arr[3])) + dif + 1;

                    dayString = day.ToString();
                    if (day < 10)
                    {
                        dayString = "0" + dayString;
                    }

                    return(DateTime.Parse(ev.start_date).ToString("yyyyMM") + dayString + "T" + DateTime.Parse(ev.start_date).ToString("HHmmss"));
                }
                else
                {
                    return(DateTime.Parse(ev.start_date).ToString(d.format));
                }

            default: return("");
            }
        }
Пример #2
0
        public static string getEndTimeevent(CalendarBasicModel ev)
        {
            string s          = getStartTimeevent(ev);
            string start_date = String.Format("{0}-{1}-{2}T{3}:{4}:{5}", s.Substring(0, 4), s.Substring(4, 2), s.Substring(6, 2), s.Substring(9, 2), s.Substring(11, 2), s.Substring(13, 2));
            string end_date   = DateTime.Parse(start_date).AddSeconds(ev.event_length).ToString(d.format);

            return(end_date);
        }
Пример #3
0
        //returns a string of remote events
        public static string getExdate(long id, CalendarBasicModel c)
        {
            string a = "0";

            if (id == c.event_pid && c.rec_type == "none")
            {
                a = UnixTimeStampToDateTime(c.event_length).ToString(d.format);
            }
            return(a);
        }
Пример #4
0
        public ActionResult SubmitEvent(CalendarEvent c)
        {
            string oldId = Convert.ToString(Session["oldId"]);
            string op    = Convert.ToString(Session["oper"]);

            try
            {
                if (op.IndexOf("edit") >= 0)
                {
                    db.Entry(c).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else if (op.IndexOf("add") >= 0)
                {
                    db.CalendarEvents.Add(c);
                    db.SaveChanges();
                }

                CalendarBasicModel calendarBasicModel = new CalendarBasicModel
                {
                    id           = c.id,
                    text         = c.text.ToString(),
                    start_date   = c.start_date.ToString("yyyy-MM-dd HH:mm"),
                    end_date     = c.end_date.ToString("yyyy-MM-dd HH:mm"),
                    type         = Convert.ToInt32(c.type),
                    rec_pattern  = c.rec_pattern == null ? "" : Convert.ToString(c.rec_pattern),
                    rec_type     = c.rec_type == null ? "" : Convert.ToString(c.rec_type),
                    event_pid    = Convert.ToInt64(c.event_pid),
                    event_length = Convert.ToInt64(c.event_length),
                    attendees    = Convert.ToString(c.attendees),
                };

                var response = new
                {
                    ev      = calendarBasicModel,
                    oldId   = oldId,
                    op      = op,
                    success = true
                };
                return(Json(response, JsonRequestBehavior.AllowGet));
            }
            catch
            {
                var response = new
                {
                    oldId   = oldId,
                    op      = op,
                    success = false
                };
                return(Json(response, JsonRequestBehavior.AllowGet));
            }
        }
Пример #5
0
        public ActionResult sendEmail(CalendarBasicModel c, string ssd)
        {
            try
            {
                List <KeyValuePair <string, string> > emailAddresses = new List <KeyValuePair <string, string> >();
                string             meetingType = "";
                CalendarBasicModel ev          = new CalendarBasicModel();

                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "SELECT email,name FROM Users where id in (" + c.attendees + ")";
                        command.CommandType = CommandType.Text;
                        try
                        {
                            connection.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                emailAddresses = reader.Select(r =>
                                                               new KeyValuePair <string, string>(Convert.ToString(r["name"]), Convert.ToString(r["email"]))).ToList();
                            }
                            command.CommandText = "SELECT type FROM MeetingType where id=" + c.type;
                            command.CommandType = CommandType.Text;
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                meetingType = reader.Select(r =>
                                                            Convert.ToString(r["type"])).FirstOrDefault();
                            }
                            command.CommandText = "SELECT * FROM CalendarEvents where id=" + c.id;
                            command.CommandType = CommandType.Text;
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                //while (reader.Read())
                                //{
                                ev = reader.Select(r =>
                                                   new CalendarBasicModel
                                {
                                    id           = r["id"] is DBNull ? 0 : Convert.ToInt64(r["id"]),
                                    text         = r["text"] is DBNull ? "" : r["text"].ToString(),
                                    start_date   = r["start_date"] is DBNull ? DateTime.Now.ToString() : Convert.ToDateTime(r["start_date"]).ToString(),
                                    end_date     = r["end_date"] is DBNull ? DateTime.Now.ToString() : Convert.ToDateTime(r["end_date"]).ToString(),
                                    type         = r["type"] is DBNull ? 0 : Convert.ToInt32(r["type"]),
                                    rec_pattern  = r["rec_pattern"] is DBNull ? "" : r["rec_pattern"].ToString(),
                                    rec_type     = r["rec_type"] is DBNull ? "" : r["rec_type"].ToString(),
                                    event_pid    = r["event_pid"] is DBNull ? 0 : Convert.ToInt64(r["event_pid"]),
                                    event_length = r["event_length"] is DBNull ? 0 : Convert.ToInt64(r["event_length"]),
                                    attendees    = r["attendees"] is DBNull ? "" : Convert.ToString(r["attendees"]),
                                    description  = r["description"] is DBNull ? "" : Convert.ToString(r["description"]),
                                    saved2DB     = true
                                }).FirstOrDefault();
                                //}
                            }
                        }
                        finally
                        {
                            try
                            {
                                if (connection.State == ConnectionState.Open)
                                {
                                    connection.Close();
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                Helpers.SendMeetingRequest(ev, emailAddresses, meetingType, ssd);
                return(Json(new { success = true, i = 1 }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, i = 0 }, JsonRequestBehavior.AllowGet));
            }
        }
Пример #6
0
        public ActionResult AddEvent(CalendarBasicModel c, string op)
        {
            //throw new Exception("hello");
            int           i     = 0;
            List <string> query = new List <string>();

            if (op.IndexOf("add") >= 0)
            {
                query.Add(@"Insert into CalendarEvents values ('" + c.text + "','Hyderabad','" + c.start_date + "','" + c.end_date + "'," + c.type + ",'" + c.description + "','" + c.rec_type + "'," + c.event_length + "," + c.event_pid + ",'" + c.rec_pattern + "','" + c.attendees + "',-1) ; SELECT CAST(scope_identity() AS int)");
            }
            else if (op.IndexOf("edit") >= 0 && c.id > 0)
            {
                query.Add(@"Update CalendarEvents Set text='" + c.text + "',location='Hyderabad',start_date='" + c.start_date + "',end_date='" + c.end_date + "',type=" + c.type + ",description='" + c.description + "',rec_type='" + c.rec_type + "',event_length=" + c.event_length + ",event_pid=" + c.event_pid + ",rec_pattern='" + c.rec_pattern + "', attendees='" + c.attendees + "' where id=" + c.id);
                if (c.rec_type != null && Convert.ToString(c.rec_type).Trim().Length > 0)
                {
                    query.Add(@"Delete from CalendarEvents where event_pid=" + c.id);
                }
            }
            else if (op.IndexOf("del") >= 0 && c.id > 0)
            {
                if (c.event_pid > 0)
                {
                    query.Add(@"Update CalendarEvents Set rec_type='none', rec_pattern='none' where id=" + c.id);
                }
                else
                {
                    query.Add(@"Delete from CalendarEvents where id=" + c.id);
                }
                if (c.rec_type != null && Convert.ToString(c.rec_type).Trim().Length > 0)
                {
                    query.Add(@"Delete from CalendarEvents where event_pid=" + c.id);
                }
            }

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlTransaction transaction;

                connection.Open();
                transaction = connection.BeginTransaction();
                try
                {
                    foreach (string item in query)
                    {
                        if (op.IndexOf("add") >= 0)
                        {
                            //SqlParameter param = new SqlParameter("@id", SqlDbType.BigInt);
                            //param.Direction = ParameterDirection.Output;
                            //SqlCommand cmd = new SqlCommand(item, connection, transaction);
                            //cmd.Parameters.Add(param);
                            i = (int)new SqlCommand(item, connection, transaction).ExecuteScalar();
                        }
                        else
                        {
                            new SqlCommand(item, connection, transaction).ExecuteNonQuery();
                        }
                    }
                    transaction.Commit();
                    return(Json(new { success = true, i = i }, JsonRequestBehavior.AllowGet));
                }
                catch (SqlException sqlError)
                {
                    transaction.Rollback();
                }
                finally
                {
                    connection.Close();
                }
            }
            return(Json(new { success = false, i = i }, JsonRequestBehavior.AllowGet));
        }
Пример #7
0
        public static void SendMeetingRequest(CalendarBasicModel c, List <KeyValuePair <string, string> > emailAddresses, string meetingType, string ssd)
        {
            string sender   = "*****@*****.**";        //ConfigurationSettings.AppSettings["Sender"].ToString();
            string userName = "******"; //ConfigurationSettings.AppSettings["UserName"].ToString();
            string password = "******";                        //ConfigurationSettings.AppSettings["Password"].ToString();
            string smtpURL  = "smtp.sendgrid.net";               //ConfigurationSettings.AppSettings["SmtpURL"].ToString();
            int    smtpPort = 587;                               //ConfigurationSettings.AppSettings["Port"].ToString();

            try
            {
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(sender);
                foreach (KeyValuePair <string, string> email in emailAddresses)
                {
                    msg.To.Add(new MailAddress(email.Value, email.Key));
                }

                msg.Subject = meetingType + " Invitation";
                msg.Body    = c.text;

                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
                ct.Parameters.Add("method", "REQUEST");
                ct.Parameters.Add("name", "Meeting.ics");

                StringBuilder str = new StringBuilder();
                str.AppendLine("BEGIN:VCALENDAR");
                str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN");
                str.AppendLine("VERSION:2.0");
                str.AppendLine("METHOD:REQUEST");

                TimeZoneInfo localZone = TimeZoneInfo.Local;
                str.AppendLine("BEGIN:VTIMEZONE");
                str.AppendLine(string.Format("TZID:{0}", localZone.Id));
                //str.AppendLine("BEGIN:STANDARD");
                //str.AppendLine("DTSTART:16010101T000000");
                //str.AppendLine("TZOFFSETFROM:+0530");
                //str.AppendLine("TZOFFSETTO:+0530");
                //str.AppendLine("END:STANDARD");
                str.AppendLine("END:VTIMEZONE");
                str.AppendLine("BEGIN:VEVENT");

                if (c.event_pid != 0 && c.rec_type == "")
                {
                    str.AppendLine("DTSTART:" + DateTime.Parse(c.start_date).ToString(d.format));
                    str.AppendLine("DTEND:" + DateTime.Parse(c.end_date).ToString(d.format));
                    str.AppendLine("RECURRENCE-ID:" + UnixTimeStampToDateTime(c.event_length).ToString(d.format));
                    // str.AppendLine("RECURRENCE-ID:" + DateTime.Parse(c.end_date).ToString(d.format));//UnixTimeStampToDateTime(c.event_length).ToString(d.format));
                    str.AppendLine("UID:" + c.event_pid);
                    // DateTime.Parse(
                }
                else if (c.rec_type != "" && c.event_pid == 0)
                {
                    str.AppendLine("DTSTART:" + getStartTimeevent(c));
                    str.AppendLine("DTEND:" + getEndTimeevent(c));
                    str.AppendLine("RRULE:" + getRrule(c));
                    string exdate = getExdate(c.id, c);
                    if (exdate != "0")
                    {
                        str.AppendLine("EXDATE:" + exdate);
                    }
                    str.AppendLine("UID:" + c.id);
                }
                else if (c.rec_type == "" && c.event_pid == 0)
                {
                    str.AppendLine("DTSTART:" + DateTime.Parse(c.start_date).ToString(d.format));
                    str.AppendLine("DTEND:" + DateTime.Parse(c.end_date).ToString(d.format));
                    str.AppendLine("UID:" + c.id);
                }
                //   str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
                // str.AppendLine("When: " + string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(dtStartDate.ToString(), null, DateTimeStyles.AdjustToUniversal) + string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(dtEndDate.ToString(), null, DateTimeStyles.AdjustToUniversal))));
                str.AppendLine("LOCATION: " + "Static Content");
                str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body));
                str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body));
                str.AppendLine(string.Format("SUMMARY:{0}", msg.Subject));
                str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", msg.From.Address));

                str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));

                str.AppendLine("BEGIN:VALARM");
                str.AppendLine("TRIGGER:-PT15M");
                str.AppendLine("ACTION:DISPLAY");
                str.AppendLine("DESCRIPTION:Reminder");
                str.AppendLine("END:VALARM");
                str.AppendLine("END:VEVENT");
                str.AppendLine("END:VCALENDAR");

                // AlternateView htmlView = AlternateView.CreateAlternateViewFromString(str.ToString(), new System.Net.Mime.ContentType("text/html; method=request; charset=UTF-8;component=vevent"));
                AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), ct);
                msg.AlternateViews.Add(avCal);
                // msg.AlternateViews.Add(htmlView);
                SmtpClient clt = new SmtpClient(smtpURL);
                clt.Port         = smtpPort;
                clt.Credentials  = new System.Net.NetworkCredential(userName, password);
                clt.EnableSsl    = true;
                msg.IsBodyHtml   = true;
                msg.BodyEncoding = Encoding.UTF8;
                //   System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };

                clt.Send(msg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #8
0
        //get iCal rrule for recurrence events
        public static string getRrule(CalendarBasicModel ev)
        {
            string[] mas = ev.rec_type.Split('#');
            string[] a   = mas[0].Split('_');

            string type     = "FREQ=" + getConvertType(a[0]) + ";";
            string interval = "INTERVAL=" + a[1] + ";";
            string count    = "";
            string count2   = "";
            string day      = "";
            string days     = "";
            string byday    = "";
            string until    = "";

            if (mas[1] != "no")
            {
                count = "COUNT=" + mas[1] + ";";
            }
            else
            {
                count = "";
            }
            count2 = a[3];
            if (a[2] != "")
            {
                day = getConvertDay(a[2]);
            }
            else
            {
                day = "";
            }
            if (a[4] != "")
            {
                days = getConvertDays(a[4]);
            }
            else
            {
                days = "";
            }
            if (day != "" && count2 != "")
            {
                byday = "BYDAY=" + count2 + "" + day + ";";
            }
            else if (days != "")
            {
                byday = "BYDAY=" + days + ";";
            }
            else
            {
                byday = "";
            }
            string end_date = DateTime.Parse(ev.end_date).ToString(d.format);

            if (end_date.Substring(0, 4) != "9999")
            {
                until = "UNTIL=" + end_date + ";";
            }
            else
            {
                until = "";
            };
            return(type + "" + interval + "" + count + "" + byday + "" + until);
        }