Calendar.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using Sage.O365Management.Classes.OData;
5 using System.Web.Script.Serialization;
6 using sage.ew.usuario;
7 using System.Data;
8 using sage.ew.db;
9 using sage.ew.global;
10 
11 namespace sage.ew.o365
12 {
16  public class CalendarClass : o365consumer//, ICalendarClass
17  {
18  #region Public properties
19 
23  public string _Name
24  {
25  get { return _cName; }
26  set { _cName = value; }
27  }
28  private string _cName = "";
29 
33  public CalendarColor _Color
34  {
35  get { return _oColor; }
36  set { _oColor = value; }
37  }
38  private CalendarColor _oColor = CalendarColor.Auto;
39 
43  public Dictionary<string, string> _AvailableCalendars
44  {
45  get
46  {
47  //Si me han cambiado el usuario a partir del que se montó el diccionario... lo resteo
48  if (!String.IsNullOrWhiteSpace(_Sage50User) && (_Sage50User != _CurrentUserCode)) //Si he utizado algún usuario y ahora ha cambiado...
49  {
50  _dicCalendariosUsuario = null;
51  }
52 
53 
54 
55  if (_dicCalendariosUsuario == null)
56  {
57  if (!String.IsNullOrWhiteSpace(_UserCalendars))
58  {
59  //Try to get stored user calendars
60  Dictionary<string, string> ldicCalendarios = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(_UserCalendars);
61  if (ldicCalendarios != null && ldicCalendarios.Count > 0) _dicCalendariosUsuario = ldicCalendarios;
62  else
63  {
64  UpdateCalendarList();
65  }
66  }
67  else _GetCalendars();
68  }
69 
70  return _dicCalendariosUsuario;
71 
72  }
73  set { _dicCalendariosUsuario = value; }
74  }
75  private Dictionary<string, string> _dicCalendariosUsuario = null;
76 
80  public string _RegisteredSharedEmail
81  {
82  get { return _SharedEmail; }
83  }
84 
88  public string _RegisteredSharedCalendar
89  {
90  get { return _SharedCalendarId; }
91  }
92 
96  public bool _RegisteredShareCalendar
97  {
98  get { return _SharedCalendarActive; }
99  set
100  {
101  if(_SharedCalendarActive != value)
102  _SharedCalendarActive = value;
103  }
104  }
105 
106  #endregion Public properties
107 
108  #region Private properties
109 
113  private Calendars _Calendars
114  {
115  get { return _oCalendars; }
116  set
117  {
118  _oCalendars = value;
119  _dicCalendariosUsuario = _Montar_Diccionario();
120  UpdateCalendarList(); //Save the updated calendar list
121  }
122  }
123  private Calendars _oCalendars = null;
124 
128  private Calendar _Calendar
129  {
130  get { return _oCalendar; }
131  set { _oCalendar = value; }
132  }
133  private Calendar _oCalendar = null;
134 
135  //PE-97427 Rollback shared calendar operations
136  bool _OldSharedCalendarActive = false;
137  string _OldSharedCalendarId = "";
138  string _OldSharedEmail = "";
139  string _OldSharedRefreshToken = "";
140  string _OldSharedServiceResourceIds = "";
141 
142  #endregion Private properties
143 
144  #region Constructors
145 
149  public CalendarClass()
150  {
151  _GetSharedBackupData(); //PE-97427
152  }
153 
158  public CalendarClass(bool tlRegisterMode)
159  {
160  //Set the registration mode
161  _lRegisterMode = tlRegisterMode;
162 
163  _GetSharedBackupData(); //PE-97427
164  }
165 
166  #endregion Constructors
167 
168  #region Public Methods
169 
174  public bool _New()
175  {
176  bool llOk = true;
177  Calendar loCalendar = new Calendar();
178  loCalendar.Name = _Name;
179  loCalendar.Color = _Color;
180  try
181  {
182  //check if exists
183  Calendars loCals = (Calendars)O365Management.GetCalendars();
184  bool llExists = false;
185  foreach (Calendar loCalItem in loCals.Data)
186  {
187  //Search previous existing calendar
188  if (loCalItem.Name.Contains("Calendario " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto"))))
189  {
190  llExists = true;
191  _Calendar = loCalItem;
192  break;
193  }
194  }
195 
196  if(!llExists)
197  _Calendar = (Calendar)O365Management.CreateCalendar(_Name);
198 
199  //Update calendar lists
200  llOk = (_Calendar != null);
201  if (llOk && _lRegisterMode) //Register mode
202  {
203  Sage.O365Management.Classes.OData.AccountInfo loAccount = (Sage.O365Management.Classes.OData.AccountInfo)O365Management.GetAccountInfo();
204 
205  //Register the calendar as Shared calendar
206  _SharedCalendarId = _Calendar.Id;
207  _SharedEmail = loAccount.Id;
208  _SharedRefreshToken = O365Management.RefreshToken;
209  _SharedServiceResourceIds = new JavaScriptSerializer().Serialize(O365Management.ServiceResourceIds);
210  OSharedCalendarData._Save();
211  }
212 
213  return llOk;
214  }
215  catch (Exception loException)
216  {
217  _RaiseException(loException);
218  }
219 
220  return llOk;
221  }
222 
227  internal bool _RegisterSharedCalendar()
228  {
229  if (!_lRegisterMode) return false;
230 
231  bool llOk = true;
232  Calendar loCalendar = new Calendar();
233  loCalendar.Name = _Name;
234  loCalendar.Color = _Color;
235  try
236  {
237  //To ensure use new manager
238  _ResetOManagers();
239 
240  //check if exists
241  Calendars loCals = (Calendars)O365ManagementSage50.GetCalendars();
242  bool llExists = false;
243  foreach (Calendar loCalItem in loCals.Data)
244  {
245  //Search previous existing calendar
246  if (loCalItem.Name.Contains("Calendario " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto"))))
247  {
248  llExists = true;
249  _Calendar = loCalItem;
250  break;
251  }
252  }
253 
254  if (!llExists)
255  _Calendar = (Calendar)O365ManagementSage50.CreateCalendar(_Name);
256 
257  //Update calendar lists
258  llOk = (_Calendar != null);
259  if (llOk && _lRegisterMode) //Register mode
260  {
261  Sage.O365Management.Classes.OData.AccountInfo loAccount = (Sage.O365Management.Classes.OData.AccountInfo)O365ManagementSage50.GetAccountInfo();
262 
263  //Register the calendar as Shared calendar
264  _SharedCalendarId = _Calendar.Id;
265  _SharedEmail = loAccount.Id;
266  _SharedRefreshToken = O365ManagementSage50.RefreshToken;
267  _SharedServiceResourceIds = new JavaScriptSerializer().Serialize(O365ManagementSage50.ServiceResourceIds);
268  OSharedCalendarData._Save();
269 
270  //To ensure no one have invalid Shared CalendarIds stored in BBDD
271  _ResetUserStoredCalendars();
272  //_UserCalendars = "";
273  }
274 
275  return llOk;
276  }
277  catch (Exception loException)
278  {
279  _RaiseException(loException);
280  }
281 
282  return llOk;
283  }
284 
285  #region Rollback Shared Calendar
286 
287  //PE-97427 Rollback shared calendar operations
288 
289  //PE-97427
293  private void _GetSharedBackupData()
294  {
295  _OldSharedCalendarActive = _SharedCalendarActive;
296  _OldSharedCalendarId = _SharedCalendarId;
297  _OldSharedEmail = _SharedEmail;
298  _OldSharedRefreshToken = _SharedRefreshToken;
299  _OldSharedServiceResourceIds = _SharedServiceResourceIds;
300  }
301 
302  //PE-97427
306  internal void _RestoreSharedBackupData()
307  {
308  //Restore the initial values
309  _SharedCalendarActive = _OldSharedCalendarActive;
310  _SharedCalendarId = _OldSharedCalendarId;
311  _SharedEmail = _OldSharedEmail;
312  _SharedRefreshToken = _OldSharedRefreshToken;
313  _SharedServiceResourceIds = _OldSharedServiceResourceIds;
314  OSharedCalendarData._Save();
315  }
316 
317  #endregion Rollback Shared Calendar
318 
323  internal bool _UnregisterSharedCalendar()
324  {
325  bool llOk = false;
326 
327  //Only in registration mode for defined calendar use
328  if (!_lRegisterMode || !_IsSharingCalendar) return false;
329 
330  _SharedCalendarId = "";
331  _SharedEmail = "";
332  _SharedRefreshToken = "";
333  _SharedServiceResourceIds = "";
334  llOk = OSharedCalendarData._Save();
335 
336  //Fuerzo un logout
337  _ResetOManagers();
338 
339  //To ensure no one have invalid Shared CalendarIds stored in BBDD
340  _ResetUserStoredCalendars();
341 
342  return llOk;
343  }
344 
349  public bool _Delete(string tcIdCalendar)
350  {
351  //Pending
352  return O365Management.DeleteCalendar(tcIdCalendar);
353  }
354 
361  public bool _Add(Appointment toAppointment, string tcIdCalendar = "")
362  {
363  bool llOk = true;
364 
365  try
366  {
367  return ((Appointment)toAppointment)._New(tcIdCalendar); ;
368  }
369  catch (Exception loException)
370  {
371  _RaiseException(loException);
372  llOk = false;
373  }
374 
375  return llOk;
376  }
377 
384  public bool _Add(Meeting toMeeting, string tcIdCalendar = "")
385  {
386  bool llOk = true;
387 
388  try
389  {
390  return toMeeting._New(tcIdCalendar);
391  }
392  catch (Exception loException)
393  {
394  _RaiseException(loException);
395  llOk = false;
396  }
397 
398  return llOk;
399  }
400 
405  public void _GetCalendar(string tcIdCalendar = "")
406  {
407  try
408  {
409  _oCalendar = (Calendar)O365Management.GetCalendar(tcIdCalendar);
410  }
411  catch (Exception loEx)
412  {
413  _RaiseException(loEx);
414  _ErrorMessage = loEx.Message;
415  }
416  }
417 
418 
422  public void UpdateCalendarList()
423  {
424  _UserCalendars = new JavaScriptSerializer().Serialize(_dicCalendariosUsuario);
425  Usuario._This._Save();
426  }
427 
431  public Dictionary<string, string> _GetCalendars()
432  {
433 
434  try
435  {
436  _Calendars = (Calendars)O365Management.GetCalendars(); //During the SET operation of _Calendars the dicctionary is updated
437  return _dicCalendariosUsuario;
438  }
439  catch (Exception loEx)
440  {
441  _RaiseException(loEx);
442  }
443 
444  //Void return
445  return new Dictionary<string, string>();
446  }
447 
448  #endregion Public Methods
449 
450  #region Private Methods
451 
452  //PE-99934
458  void _This__Evento_UsuarioCambiado(object sender, EventArgs e)
459  {
460  _dicCalendariosUsuario = null;
461  }
462 
468  private Events _GetEvents(string tcIdCalendar)
469  {
470  Events loEvents = new Events();
471 
472  try //PE-97495 To catch credential missing exception
473  {
474  loEvents = (Events)O365Management.GetEvents(tcIdCalendar);
475  }
476  catch (Exception loException)
477  {
478  _RaiseException(loException);
479  }
480 
481  return loEvents;
482  }
483 
491  public DataTable _GetEvents(string tcIdCalendar, string tcPattern, bool tlLiteral = false)
492  {
493  //Check if is a shared operation
494  CheckForSharedCalendarOperation(tcIdCalendar);
495 
496  DataTable ldtEventos = new DataTable();
497 
498  //Define the structure of the result DataTable
499  ldtEventos.Columns.Add("Subject", typeof(string));
500  ldtEventos.Columns.Add("Start", typeof(DateTime));
501  ldtEventos.Columns.Add("End", typeof(DateTime));
502  ldtEventos.Columns.Add("Id", typeof(string));
503 
504  Events loEvents = _GetEvents(tcIdCalendar);
505  //PE-97495 If no events or exception raised return empty table
506  if (loEvents.Data == null) return ldtEventos;
507 
508  foreach (Event loEvent in loEvents.Data)
509  {
510  TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(loEvent.Start.TimeZone);
511 
512  DataRow ldrNewRow = ldtEventos.NewRow();
513  ldrNewRow["Subject"] = loEvent.Subject;
514  //PE-97378 Local time vs UTC
515  if (loEvent.IsAllDay == true) //API limation, time is UTC dont be shown as local time
516  {
517  ldrNewRow["Start"] = Convert.ToDateTime(loEvent.Start.DateTime); //DateTime no, ha que usar hora local
518  ldrNewRow["End"] = Convert.ToDateTime(loEvent.End.DateTime).AddMinutes(-1);
519  }
520  else //Local Time
521  {
522  ldrNewRow["Start"] = TimeZoneInfo.ConvertTime(Convert.ToDateTime(loEvent.Start.DateTime), timeZone, TimeZoneInfo.Local);
523  ldrNewRow["End"] = TimeZoneInfo.ConvertTime(Convert.ToDateTime(loEvent.End.DateTime), timeZone, TimeZoneInfo.Local);
524  //ldrNewRow["Start"] = Convert.ToDateTime(loEvent.Start.DateTime); //DateTime no, ha que usar hora local
525  //ldrNewRow["End"] = Convert.ToDateTime(loEvent.End.DateTime);
526  }
527 
528  ldrNewRow["Id"] = loEvent.Id;
529 
530  //PE-97317 filtro fecha superior a la actual
531  DateTime endEvent = TimeZoneInfo.ConvertTime(Convert.ToDateTime(loEvent.End.DateTime), timeZone, TimeZoneInfo.Local);
532  if (DateTime.Compare(endEvent, DateTime.Now) > 0)
533  ldtEventos.Rows.Add(ldrNewRow);
534  }
535 
536  //PE-97317 Ordeno por fecha
537  ldtEventos.DefaultView.Sort = "Start ASC, End ASC";
538  ldtEventos = ldtEventos.DefaultView.ToTable();
539 
540  //get filter strings
541  if (!String.IsNullOrWhiteSpace(tcPattern))
542  {
543  string lcFilterString = "";
544  if (tlLiteral)
545  {
546  char[] laDelimiterChars = { '[', ']'};
547  string[] laWords = tcPattern.Split(laDelimiterChars,StringSplitOptions.RemoveEmptyEntries);
548  lcFilterString = laWords[0];
549  ldtEventos.DefaultView.RowFilter = "Subject like '[[]" + lcFilterString + "[]]%'";
550  }
551  else
552  {
553  lcFilterString = _GetFilterString(tcPattern);
554  ldtEventos.DefaultView.RowFilter = "Subject like '" + lcFilterString.Replace("[", "[[]") + "%'";
555  }
556  return ldtEventos.DefaultView.ToTable();
557  }
558 
559  return ldtEventos;
560  }
561 
566  private void CheckForSharedCalendarOperation(string tcIdCalendar)
567  {
568  //Check for Shared operation
569  _UseSharedCalendar = (_RegisteredSharedCalendar == tcIdCalendar);
570  }
571 
576  public string _GetFilterString(string tcPantalla)
577  {
578  bool llOk = false;
579  string lcSql = "";
580  DataTable ldtResult = new DataTable();
581  string lcFilterString = "";
582 
583  // Preparamos la consulta
584  lcSql = "SELECT pantalla, valor FROM " +
585  DB.SQLDatabase("comunes", "calendar") +
586  " WHERE pantalla = " + DB.SQLString(tcPantalla.Trim().ToUpper());
587 
588  llOk = DB.SQLExec(lcSql, ref ldtResult);
589  if (llOk && ldtResult != null && ldtResult.Rows.Count > 0)
590  {
591  string lcValue = Convert.ToString(ldtResult.Rows[0]["valor"]).Trim();
592  string [] laKeyParts = lcValue.Split(':');
593  if (laKeyParts.Count() > 1) //Is the correct spliter
594  {
595  lcFilterString = laKeyParts[0];
596  }
597  else //Not all items contains : => then use ]
598  {
599  laKeyParts = lcValue.Split(']');
600  if (laKeyParts.Count() > 1) //Is the correct spliter
601  {
602  lcFilterString = laKeyParts[0];
603  }
604  else lcFilterString = ""; //Unknown splitter
605  }
606  }
607 
608  return lcFilterString;
609  }
610 
611 
612 
617  private Dictionary<string, string> _Montar_Diccionario()
618  {
619  //Dictionary<string, string> loDic = new Dictionary<string, string>();
620  SortedDictionary<string, string> loDic = new SortedDictionary<string, string>();
621  foreach (Calendar loCalendar in _Calendars.Data)
622  {
623  //Skip shared calendar to avoid unsual operations
624  if (loCalendar.Id == _SharedCalendarId || loCalendar.Name.Contains("Calendario " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")))) continue;
625  //Skip special calendars
626  //PE- Se detectan casos de Días y días en los calendarios que crea Outlook y dado que la función Contains no admite cfg CaseInsensitive borramos la primera letra
627  if (loCalendar.Name.Contains("Cumpleaños") || loCalendar.Name.Contains("ías festivos de")) continue;
628  loDic.Add(loCalendar.Name, loCalendar.Id);
629  }
630 
631  //Add Shared calendar
632  if(_IsSharingCalendar)
633  loDic.Add("Calendario " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")), _SharedCalendarId);
634 
635  return new Dictionary<string, string>(loDic); //Convert to common dicctionary
636  }
637 
638  #endregion Private Methods
639  }
640 }
static sage.ew.usuario.Usuario _This
Instancia estática del objeto usuario con los datos del usuario actual (wc_usuario) ...
Definition: clsUsuario.cs:341
override bool _Save()
Override del método SAVE
Definition: clsUsuario.cs:5326
Definición de la clase Usuario
Definition: clsUsuario.cs:113