Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ExchangeHelper
- {
- #region Varibles and Properties
- private const string EVENT_LOG_SOURCE_NAME = "Exchange Server 2010";
- private const string strLogType = "Application"; //type of the log
- static string errorMessage = "";
- static List<EmailAddressType> globalRooms;
- static List<EmailAddressType> globalLists;
- static List<MailboxData> globalRoomsMailBoxes;
- public static List<CalendarObject> CalendarList;
- static int counterRoom =0;
- #endregion
- #region Set the time Zone settings
- private struct SYSTEMTIME
- {
- public Int16 wYear;
- public Int16 wMonth;
- public Int16 wDayOfWeek;
- public Int16 wDay;
- public Int16 wHour;
- public Int16 wMinute;
- public Int16 wSecond;
- public Int16 wMilliseconds;
- public void getSysTime(byte[] Tzival, int offset)
- {
- wYear = BitConverter.ToInt16(Tzival, offset);
- wMonth = BitConverter.ToInt16(Tzival, offset + 2);
- wDayOfWeek = BitConverter.ToInt16(Tzival, offset + 4);
- wDay = BitConverter.ToInt16(Tzival, offset + 6);
- wHour = BitConverter.ToInt16(Tzival, offset + 8);
- wMinute = BitConverter.ToInt16(Tzival, offset + 10);
- wSecond = BitConverter.ToInt16(Tzival, offset + 12);
- wMilliseconds = BitConverter.ToInt16(Tzival, offset + 14);
- }
- }
- private struct REG_TZI_FORMAT
- {
- public Int32 Bias;
- public Int32 StandardBias;
- public Int32 DaylightBias;
- public SYSTEMTIME StandardDate;
- public SYSTEMTIME DaylightDate;
- public void regget(byte[] Tzival)
- {
- Bias = BitConverter.ToInt32(Tzival, 0);
- StandardBias = BitConverter.ToInt32(Tzival, 4);
- DaylightBias = BitConverter.ToInt32(Tzival, 8);
- StandardDate = new SYSTEMTIME();
- StandardDate.getSysTime(Tzival, 12);
- DaylightDate = new SYSTEMTIME();
- DaylightDate.getSysTime(Tzival, 28);
- }
- }
- #endregion
- #region Set the Exchange Server URL
- public static string GetServerName()
- {
- errorMessage = "";
- string url = null;
- try
- {
- url = @"https://" + ConfigurationManager.AppSettings["ExchangeServer_WebService_ServerName"] + "/EWS/exchange.asmx";
- }
- catch (Exception ex)
- {
- errorMessage = ex.ToString();
- }
- finally
- {
- if (String.IsNullOrEmpty(errorMessage))
- {
- LogSuccess("Find the server with URL " + url );
- }
- else
- {
- LogError(errorMessage);
- }
- }
- return url;
- }
- #endregion
- #region Validate the Certificate
- internal static void CheckCertificate()
- {
- System.Net.ServicePointManager.ServerCertificateValidationCallback =
- delegate(
- Object obj,
- X509Certificate certificate,
- X509Chain chain,
- SslPolicyErrors errors)
- {
- // Validate the certificate and return true or false as appropriate.
- // Note that it not a good practice to always return true because not
- // all certificates should be trusted.
- return true;
- };
- }
- #endregion
- #region Get all the Rooms List in the Exchange Server, then get all the Rooms within
- public static List<EmailAddressType> GetRooms(ExchangeServiceBinding esb)
- {
- try
- {
- errorMessage = "";
- globalRooms = new List<EmailAddressType>();
- globalLists = new List<EmailAddressType>();
- GetRoomListsType roomsListTypeRequest = new GetRoomListsType();
- GetRoomListsResponseMessageType roomListTypeResponse = new GetRoomListsResponseMessageType();
- roomListTypeResponse = esb.GetRoomLists(roomsListTypeRequest);
- if (roomListTypeResponse.ResponseClass == ResponseClassType.Error)
- {
- errorMessage = "Error in fetching Rooms List " + roomListTypeResponse.ResponseCode + " with Message " + roomListTypeResponse.MessageText;
- }
- else if (roomListTypeResponse.ResponseClass == ResponseClassType.Success)
- {
- // get the room list collection
- //roomsList = roomListTypeResponse.RoomLists;
- if (roomListTypeResponse.RoomLists.Length > 0)
- {
- foreach (EmailAddressType list in roomListTypeResponse.RoomLists)
- {
- globalLists.Add(list);
- //if (list.Name.Contains("VideoKonf"))
- //{
- // globalLists.Add(list);
- //}
- }
- }
- }
- //iterating all the rooms lists in the exchange server
- foreach (EmailAddressType list in globalLists)
- {
- GetRoomsType roomsTypeRequest = new GetRoomsType();
- RoomType[] roomTypeList = null;
- roomsTypeRequest.RoomList = list;
- GetRoomsResponseMessageType roomsReponseMessage = esb.GetRooms(roomsTypeRequest);
- if (roomsReponseMessage.ResponseClass == ResponseClassType.Error)
- {
- errorMessage = "Error in fetching Rooms " + roomsReponseMessage.ResponseCode + " with Message " + roomsReponseMessage.MessageText;
- }
- else if (roomsReponseMessage.ResponseClass == ResponseClassType.Success)
- {
- //fetching rooms in each of rooms list found on exchange server
- roomTypeList = roomsReponseMessage.Rooms;
- }
- foreach (RoomType room in roomTypeList)
- {
- //add all the rooms to the collection
- globalRooms.Add(room.Id);
- }
- }
- }
- catch (Exception ex)
- {
- errorMessage = ex.ToString();
- }
- finally
- {
- if (String.IsNullOrEmpty(errorMessage))
- {
- LogSuccess("Getting Rooms List and Rooms : Operation completed successfully");
- }
- else
- {
- LogError(errorMessage);
- }
- }
- return globalRooms;
- }
- #endregion
- #region Get Rooms Schedule
- public static List<CalendarObject> GetRoomsAvailability(ExchangeServiceBinding esb, DateTime startdate, DateTime enddate, List<EmailAddressType> listRooms)
- {
- errorMessage = "";
- string err = string.Empty;
- CalendarList = new List<CalendarObject>();
- globalRoomsMailBoxes = new List<MailboxData>();
- //add rooms to the global Rooms Mail Boxes
- foreach (EmailAddressType room in listRooms)
- {
- MailboxData mailbox = new MailboxData();
- EmailAddress emailaddress = new EmailAddress();
- emailaddress.Address = room.EmailAddress;
- mailbox.Email = emailaddress;
- mailbox.ExcludeConflicts = false;
- globalRoomsMailBoxes.Add(mailbox);
- }
- FreeBusyViewOptionsType fbViewOptions = new FreeBusyViewOptionsType();
- fbViewOptions.TimeWindow = new Duration();
- fbViewOptions.TimeWindow.StartTime = startdate;
- fbViewOptions.TimeWindow.EndTime = enddate;
- fbViewOptions.RequestedViewSpecified = true;
- fbViewOptions.MergedFreeBusyIntervalInMinutes = 30;
- fbViewOptions.MergedFreeBusyIntervalInMinutesSpecified = true;
- fbViewOptions.RequestedView = FreeBusyViewType.Detailed;
- // Make the request.
- GetUserAvailabilityRequestType request = new GetUserAvailabilityRequestType();
- // Set the time zone of the request.
- String tzString = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\" + TimeZone.CurrentTimeZone.StandardName;
- RegistryKey TziRegKey = Registry.LocalMachine;
- TziRegKey = TziRegKey.OpenSubKey(tzString);
- byte[] Tzival = (byte[])TziRegKey.GetValue("TZI");
- REG_TZI_FORMAT rtRegTimeZone = new REG_TZI_FORMAT();
- rtRegTimeZone.regget(Tzival);
- request.TimeZone = new SerializableTimeZone();
- request.TimeZone.DaylightTime = new SerializableTimeZoneTime();
- request.TimeZone.StandardTime = new SerializableTimeZoneTime();
- request.TimeZone.Bias = rtRegTimeZone.Bias;
- request.TimeZone.StandardTime.Bias = rtRegTimeZone.StandardBias;
- request.TimeZone.DaylightTime.Bias = rtRegTimeZone.DaylightBias;
- if (rtRegTimeZone.StandardDate.wMonth != 0)
- {
- request.TimeZone.StandardTime.DayOfWeek = ((DayOfWeek)rtRegTimeZone.StandardDate.wDayOfWeek).ToString();
- request.TimeZone.StandardTime.DayOrder = (short)rtRegTimeZone.StandardDate.wDay;
- request.TimeZone.StandardTime.Month = rtRegTimeZone.StandardDate.wMonth;
- request.TimeZone.StandardTime.Time = String.Format("{0:0#}:{1:0#}:{2:0#}", rtRegTimeZone.StandardDate.wHour, rtRegTimeZone.StandardDate.wMinute, rtRegTimeZone.StandardDate.wSecond);
- }
- else
- {
- request.TimeZone.StandardTime.DayOfWeek = "Sunday";
- request.TimeZone.StandardTime.DayOrder = 1;
- request.TimeZone.StandardTime.Month = 1;
- request.TimeZone.StandardTime.Time = "00:00:00";
- }
- if (rtRegTimeZone.DaylightDate.wMonth != 0)
- {
- request.TimeZone.DaylightTime.DayOfWeek = ((DayOfWeek)rtRegTimeZone.DaylightDate.wDayOfWeek).ToString();
- request.TimeZone.DaylightTime.DayOrder = (short)rtRegTimeZone.DaylightDate.wDay;
- request.TimeZone.DaylightTime.Month = rtRegTimeZone.DaylightDate.wMonth;
- request.TimeZone.DaylightTime.Time = "02:00:00";
- }
- else
- {
- request.TimeZone.DaylightTime.DayOfWeek = "Sunday";
- request.TimeZone.DaylightTime.DayOrder = 5;
- request.TimeZone.DaylightTime.Month = 12;
- request.TimeZone.DaylightTime.Time = "23:59:59";
- }
- // Add the mailboxes to the request.
- request.MailboxDataArray = globalRoomsMailBoxes.ToArray();
- // Add the free/busy view options to the request.
- request.FreeBusyViewOptions = fbViewOptions;
- try
- {
- // Send the request and get the response.
- GetUserAvailabilityResponseType response = esb.GetUserAvailability(request);
- // Access free/busy information.
- if (response.FreeBusyResponseArray.Length < 1)
- {
- errorMessage = "No free/busy response data available.";
- err += " No response ";
- }
- else
- {
- err += " \n found some response ";
- foreach (FreeBusyResponseType fbrt in response.FreeBusyResponseArray)
- {
- err += " \n in the room response #" + counterRoom;
- if (fbrt.ResponseMessage.ResponseClass == ResponseClassType.Error)
- {
- errorMessage = string.Format("Error: {0}", fbrt.ResponseMessage.MessageText);
- }
- else
- {
- EmailAddressType roomdetails = listRooms[counterRoom];
- err += " \n in the room name #" + roomdetails.Name;
- FreeBusyView fbv = fbrt.FreeBusyView;
- CalendarEvent[] items = fbv.CalendarEventArray;
- if (items != null)
- {
- err += " \n in the room name #" + roomdetails.Name;
- foreach (CalendarEvent myevent in items)
- {
- LegacyFreeBusyType busytype = myevent.BusyType;
- if (myevent.CalendarEventDetails != null)
- {
- CalendarEventDetails caldetails = myevent.CalendarEventDetails;
- CalendarObject calenderdetails = new CalendarObject();
- calenderdetails.ID = caldetails.ID;
- calenderdetails.StartDate = myevent.StartTime;
- calenderdetails.EndDate = myevent.EndTime;
- if (!String.IsNullOrEmpty(caldetails.Location))
- {
- string location = caldetails.Location;
- location = location.TrimEnd(';');
- string pattern = ";";
- calenderdetails.Location = Regex.Replace(location, pattern, " &");
- }
- calenderdetails.IsPrivate = caldetails.IsPrivate;
- calenderdetails.IsRecurring = caldetails.IsRecurring;
- calenderdetails.Status = myevent.BusyType.ToString();
- //Resolving the name here
- ResolveNamesType rnType = new ResolveNamesType();
- rnType.ReturnFullContactData = true;
- rnType.SearchScope = ResolveNamesSearchScopeType.ActiveDirectory;
- rnType.UnresolvedEntry = caldetails.Subject;
- ResolveNamesResponseType rnResponse = esb.ResolveNames(rnType);
- ResolutionType rt = ((ResolveNamesResponseMessageType)rnResponse.ResponseMessages.Items[0]).ResolutionSet.Resolution[0];
- if (rt.Mailbox != null)
- {
- calenderdetails.OrganizerName = rt.Mailbox.Name;
- if (rt.Contact != null)
- {
- if (rt.Contact.PhoneNumbers != null)
- {
- IEnumerator iterator = rt.Contact.PhoneNumbers.GetEnumerator();
- while (iterator.MoveNext())
- {
- if (((PhoneNumberDictionaryEntryType)iterator.Current).Key == PhoneNumberKeyType.MobilePhone)
- {
- calenderdetails.OrganizerMobil = ((PhoneNumberDictionaryEntryType)iterator.Current).Value;
- }
- if (((PhoneNumberDictionaryEntryType)iterator.Current).Key == PhoneNumberKeyType.BusinessPhone)
- {
- calenderdetails.OrganizerTelefon = ((PhoneNumberDictionaryEntryType)iterator.Current).Value;
- }
- }
- }
- }
- }
- calenderdetails.RoomName = roomdetails.Name;
- calenderdetails.RoomEmail = roomdetails.EmailAddress;
- CalendarList.Add(calenderdetails);
- }
- }
- }
- }
- counterRoom++;
- }
- }
- }
- catch (Exception e)
- {
- errorMessage = e.ToString();
- }
- finally
- {
- if (String.IsNullOrEmpty(errorMessage))
- {
- LogSuccess("Getting Rooms Schedules : Operation completed successfully");
- }
- else
- {
- LogError(errorMessage);
- }
- counterRoom = 0;
- }
- return CalendarList;
- }
- #endregion
- #region Log the Error, Information and Warning to the Windows Event Viewer
- internal static void LogWarning(string msg)
- {
- try
- {
- EventLog eventLog;
- if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
- {
- EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
- }
- if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
- {
- eventLog = new EventLog("Application");
- eventLog.Source = EVENT_LOG_SOURCE_NAME;
- eventLog.WriteEntry(msg, EventLogEntryType.Warning, 0);
- }
- }
- catch
- {
- }
- }
- internal static void LogError(string error)
- {
- try
- {
- EventLog eventLog;
- if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
- {
- EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
- }
- if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
- {
- eventLog = new EventLog("Application");
- eventLog.Source = EVENT_LOG_SOURCE_NAME;
- StringBuilder sb = new StringBuilder(100);
- sb.Append("Exchange Server: ");
- sb.Append("\r\n");
- sb.Append(error);
- eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Error, 0);
- }
- }
- catch
- {
- }
- }
- internal static void LogSuccess(string information)
- {
- try
- {
- EventLog eventLog;
- if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
- {
- EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
- }
- if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
- {
- eventLog = new EventLog("Application");
- eventLog.Source = EVENT_LOG_SOURCE_NAME;
- StringBuilder sb = new StringBuilder(100);
- sb.Append("Exchange Server: ");
- sb.Append("\r\n");
- sb.Append(information);
- eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Information, 0);
- }
- }
- catch
- {
- }
- }
- public static DataTable ToDataTable<T>(IList<T> data)
- {
- PropertyDescriptorCollection props =
- TypeDescriptor.GetProperties(typeof(T));
- DataTable table = new DataTable();
- for (int i = 0; i < props.Count; i++)
- {
- PropertyDescriptor prop = props[i];
- table.Columns.Add(prop.Name, prop.PropertyType);
- }
- object[] values = new object[props.Count];
- foreach (T item in data)
- {
- for (int i = 0; i < values.Length; i++)
- {
- values[i] = props[i].GetValue(item);
- }
- table.Rows.Add(values);
- }
- return table;
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement