Advertisement
Guest User

Untitled

a guest
Feb 7th, 2011
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.85 KB | None | 0 0
  1.  class ExchangeHelper
  2.     {
  3.         #region Varibles and Properties
  4.         private const string EVENT_LOG_SOURCE_NAME = "Exchange Server 2010";
  5.         private const string strLogType = "Application"; //type of the log
  6.         static string errorMessage = "";
  7.         static List<EmailAddressType> globalRooms;
  8.         static List<EmailAddressType> globalLists;
  9.         static List<MailboxData> globalRoomsMailBoxes;
  10.         public static List<CalendarObject> CalendarList;
  11.         static int counterRoom =0;
  12.         #endregion
  13.  
  14.         #region Set the time Zone settings
  15.         private struct SYSTEMTIME
  16.         {
  17.             public Int16 wYear;
  18.             public Int16 wMonth;
  19.             public Int16 wDayOfWeek;
  20.             public Int16 wDay;
  21.             public Int16 wHour;
  22.             public Int16 wMinute;
  23.             public Int16 wSecond;
  24.             public Int16 wMilliseconds;
  25.             public void getSysTime(byte[] Tzival, int offset)
  26.             {
  27.                 wYear = BitConverter.ToInt16(Tzival, offset);
  28.                 wMonth = BitConverter.ToInt16(Tzival, offset + 2);
  29.                 wDayOfWeek = BitConverter.ToInt16(Tzival, offset + 4);
  30.                 wDay = BitConverter.ToInt16(Tzival, offset + 6);
  31.                 wHour = BitConverter.ToInt16(Tzival, offset + 8);
  32.                 wMinute = BitConverter.ToInt16(Tzival, offset + 10);
  33.                 wSecond = BitConverter.ToInt16(Tzival, offset + 12);
  34.                 wMilliseconds = BitConverter.ToInt16(Tzival, offset + 14);
  35.             }
  36.         }
  37.         private struct REG_TZI_FORMAT
  38.         {
  39.             public Int32 Bias;
  40.             public Int32 StandardBias;
  41.             public Int32 DaylightBias;
  42.             public SYSTEMTIME StandardDate;
  43.             public SYSTEMTIME DaylightDate;
  44.             public void regget(byte[] Tzival)
  45.             {
  46.                 Bias = BitConverter.ToInt32(Tzival, 0);
  47.                 StandardBias = BitConverter.ToInt32(Tzival, 4);
  48.                 DaylightBias = BitConverter.ToInt32(Tzival, 8);
  49.                 StandardDate = new SYSTEMTIME();
  50.                 StandardDate.getSysTime(Tzival, 12);
  51.                 DaylightDate = new SYSTEMTIME();
  52.                 DaylightDate.getSysTime(Tzival, 28);
  53.             }
  54.  
  55.         }
  56.         #endregion
  57.  
  58.         #region Set the Exchange Server URL
  59.         public static string GetServerName()
  60.         {
  61.             errorMessage = "";
  62.             string url = null;
  63.             try
  64.             {
  65.                 url = @"https://" + ConfigurationManager.AppSettings["ExchangeServer_WebService_ServerName"] + "/EWS/exchange.asmx";
  66.                    
  67.                
  68.             }
  69.  
  70.             catch (Exception ex)
  71.             {
  72.  
  73.                 errorMessage = ex.ToString();
  74.  
  75.             }
  76.  
  77.             finally
  78.             {
  79.  
  80.  
  81.                 if (String.IsNullOrEmpty(errorMessage))
  82.                 {
  83.  
  84.                     LogSuccess("Find the server with URL " + url  );
  85.                 }
  86.                 else
  87.                 {
  88.  
  89.                     LogError(errorMessage);
  90.                 }
  91.  
  92.             }
  93.  
  94.             return url;
  95.         }
  96.         #endregion
  97.  
  98.         #region Validate the Certificate
  99.         internal static void CheckCertificate()
  100.         {
  101.  
  102.             System.Net.ServicePointManager.ServerCertificateValidationCallback =
  103.                delegate(
  104.                    Object obj,
  105.                    X509Certificate certificate,
  106.                    X509Chain chain,
  107.                    SslPolicyErrors errors)
  108.                {
  109.                    // Validate the certificate and return true or false as appropriate.
  110.                    // Note that it not a good practice to always return true because not
  111.                    // all certificates should be trusted.
  112.                    return true;
  113.  
  114.                };
  115.         }
  116.         #endregion
  117.  
  118.         #region Get all the Rooms List in the Exchange Server, then get all the Rooms within
  119.         public static List<EmailAddressType> GetRooms(ExchangeServiceBinding esb)
  120.         {
  121.             try
  122.             {
  123.  
  124.                 errorMessage = "";
  125.                 globalRooms = new List<EmailAddressType>();
  126.                 globalLists = new List<EmailAddressType>();
  127.                 GetRoomListsType roomsListTypeRequest = new GetRoomListsType();
  128.                 GetRoomListsResponseMessageType roomListTypeResponse = new GetRoomListsResponseMessageType();
  129.                 roomListTypeResponse = esb.GetRoomLists(roomsListTypeRequest);
  130.                 if (roomListTypeResponse.ResponseClass == ResponseClassType.Error)
  131.                 {
  132.                     errorMessage = "Error in fetching Rooms List " + roomListTypeResponse.ResponseCode + " with Message " + roomListTypeResponse.MessageText;
  133.                 }
  134.                 else if (roomListTypeResponse.ResponseClass == ResponseClassType.Success)
  135.                 {
  136.                     // get the room list collection
  137.                     //roomsList = roomListTypeResponse.RoomLists;
  138.                     if (roomListTypeResponse.RoomLists.Length > 0)
  139.                     {
  140.                         foreach (EmailAddressType list in roomListTypeResponse.RoomLists)
  141.                         {
  142.                             globalLists.Add(list);
  143.                             //if (list.Name.Contains("VideoKonf"))
  144.                             //{
  145.  
  146.                             //    globalLists.Add(list);
  147.                                                            
  148.                             //}
  149.                         }
  150.                     }
  151.  
  152.                 }
  153.  
  154.                 //iterating all the rooms lists in the exchange server
  155.                 foreach (EmailAddressType list in globalLists)
  156.                 {
  157.                     GetRoomsType roomsTypeRequest = new GetRoomsType();
  158.                     RoomType[] roomTypeList = null;
  159.                     roomsTypeRequest.RoomList = list;
  160.                     GetRoomsResponseMessageType roomsReponseMessage = esb.GetRooms(roomsTypeRequest);
  161.                     if (roomsReponseMessage.ResponseClass == ResponseClassType.Error)
  162.                     {
  163.                         errorMessage = "Error in fetching Rooms " + roomsReponseMessage.ResponseCode + " with Message " + roomsReponseMessage.MessageText;
  164.  
  165.                     }
  166.                     else if (roomsReponseMessage.ResponseClass == ResponseClassType.Success)
  167.                     {
  168.                         //fetching rooms in each of rooms list found on exchange server
  169.                         roomTypeList = roomsReponseMessage.Rooms;
  170.                     }
  171.                     foreach (RoomType room in roomTypeList)
  172.                     {
  173.                         //add all the rooms to the collection
  174.                         globalRooms.Add(room.Id);
  175.  
  176.                     }
  177.                 }
  178.  
  179.             }
  180.             catch (Exception ex)
  181.             {
  182.                
  183.                 errorMessage = ex.ToString();
  184.  
  185.             }
  186.  
  187.             finally
  188.             {
  189.  
  190.  
  191.                 if (String.IsNullOrEmpty(errorMessage))
  192.                 {
  193.  
  194.                     LogSuccess("Getting Rooms List and Rooms : Operation completed successfully");
  195.                 }
  196.                 else
  197.                 {
  198.  
  199.                     LogError(errorMessage);
  200.                 }
  201.  
  202.             }
  203.             return globalRooms;
  204.  
  205.         }
  206.         #endregion
  207.  
  208.         #region Get Rooms Schedule
  209.         public static List<CalendarObject> GetRoomsAvailability(ExchangeServiceBinding esb, DateTime startdate, DateTime enddate, List<EmailAddressType> listRooms)
  210.         {
  211.             errorMessage = "";
  212.             string err = string.Empty;
  213.             CalendarList = new List<CalendarObject>();
  214.             globalRoomsMailBoxes = new List<MailboxData>();
  215.             //add rooms to the global Rooms Mail Boxes
  216.             foreach (EmailAddressType room in listRooms)
  217.             {                
  218.                 MailboxData mailbox = new MailboxData();
  219.                 EmailAddress emailaddress = new EmailAddress();
  220.                 emailaddress.Address = room.EmailAddress;
  221.                 mailbox.Email = emailaddress;                
  222.                 mailbox.ExcludeConflicts = false;
  223.                 globalRoomsMailBoxes.Add(mailbox);
  224.             }
  225.  
  226.             FreeBusyViewOptionsType fbViewOptions = new FreeBusyViewOptionsType();
  227.             fbViewOptions.TimeWindow = new Duration();
  228.             fbViewOptions.TimeWindow.StartTime = startdate;
  229.             fbViewOptions.TimeWindow.EndTime = enddate;
  230.             fbViewOptions.RequestedViewSpecified = true;
  231.             fbViewOptions.MergedFreeBusyIntervalInMinutes = 30;
  232.             fbViewOptions.MergedFreeBusyIntervalInMinutesSpecified = true;
  233.             fbViewOptions.RequestedView = FreeBusyViewType.Detailed;
  234.  
  235.             // Make the request.
  236.             GetUserAvailabilityRequestType request = new GetUserAvailabilityRequestType();
  237.  
  238.             // Set the time zone of the request.
  239.             String tzString = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\" + TimeZone.CurrentTimeZone.StandardName;
  240.             RegistryKey TziRegKey = Registry.LocalMachine;
  241.             TziRegKey = TziRegKey.OpenSubKey(tzString);
  242.             byte[] Tzival = (byte[])TziRegKey.GetValue("TZI");
  243.             REG_TZI_FORMAT rtRegTimeZone = new REG_TZI_FORMAT();
  244.             rtRegTimeZone.regget(Tzival);
  245.  
  246.             request.TimeZone = new SerializableTimeZone();
  247.             request.TimeZone.DaylightTime = new SerializableTimeZoneTime();
  248.             request.TimeZone.StandardTime = new SerializableTimeZoneTime();
  249.             request.TimeZone.Bias = rtRegTimeZone.Bias;
  250.             request.TimeZone.StandardTime.Bias = rtRegTimeZone.StandardBias;
  251.             request.TimeZone.DaylightTime.Bias = rtRegTimeZone.DaylightBias;
  252.             if (rtRegTimeZone.StandardDate.wMonth != 0)
  253.             {
  254.                 request.TimeZone.StandardTime.DayOfWeek = ((DayOfWeek)rtRegTimeZone.StandardDate.wDayOfWeek).ToString();
  255.                 request.TimeZone.StandardTime.DayOrder = (short)rtRegTimeZone.StandardDate.wDay;
  256.                 request.TimeZone.StandardTime.Month = rtRegTimeZone.StandardDate.wMonth;
  257.                 request.TimeZone.StandardTime.Time = String.Format("{0:0#}:{1:0#}:{2:0#}", rtRegTimeZone.StandardDate.wHour, rtRegTimeZone.StandardDate.wMinute, rtRegTimeZone.StandardDate.wSecond);
  258.             }
  259.  
  260.             else
  261.             {
  262.                 request.TimeZone.StandardTime.DayOfWeek = "Sunday";
  263.                 request.TimeZone.StandardTime.DayOrder = 1;
  264.                 request.TimeZone.StandardTime.Month = 1;
  265.                 request.TimeZone.StandardTime.Time = "00:00:00";
  266.  
  267.             }
  268.             if (rtRegTimeZone.DaylightDate.wMonth != 0)
  269.             {
  270.                 request.TimeZone.DaylightTime.DayOfWeek = ((DayOfWeek)rtRegTimeZone.DaylightDate.wDayOfWeek).ToString();
  271.                 request.TimeZone.DaylightTime.DayOrder = (short)rtRegTimeZone.DaylightDate.wDay;
  272.                 request.TimeZone.DaylightTime.Month = rtRegTimeZone.DaylightDate.wMonth;
  273.                 request.TimeZone.DaylightTime.Time = "02:00:00";
  274.             }
  275.             else
  276.             {
  277.                 request.TimeZone.DaylightTime.DayOfWeek = "Sunday";
  278.                 request.TimeZone.DaylightTime.DayOrder = 5;
  279.                 request.TimeZone.DaylightTime.Month = 12;
  280.                 request.TimeZone.DaylightTime.Time = "23:59:59";
  281.  
  282.             }
  283.  
  284.             // Add the mailboxes to the request.
  285.             request.MailboxDataArray = globalRoomsMailBoxes.ToArray();
  286.  
  287.             // Add the free/busy view options to the request.
  288.             request.FreeBusyViewOptions = fbViewOptions;
  289.  
  290.             try
  291.             {
  292.                 // Send the request and get the response.
  293.                 GetUserAvailabilityResponseType response = esb.GetUserAvailability(request);
  294.                 // Access free/busy information.
  295.                 if (response.FreeBusyResponseArray.Length < 1)
  296.                 {
  297.                    
  298.                     errorMessage = "No free/busy response data available.";
  299.                     err += " No response ";
  300.                 }
  301.                 else
  302.                 {
  303.                     err += " \n found some response ";
  304.                     foreach (FreeBusyResponseType fbrt in response.FreeBusyResponseArray)
  305.                     {
  306.                         err += " \n in the room response #" + counterRoom;
  307.                         if (fbrt.ResponseMessage.ResponseClass == ResponseClassType.Error)
  308.                         {
  309.                            errorMessage = string.Format("Error: {0}", fbrt.ResponseMessage.MessageText);
  310.                         }
  311.                         else
  312.                         {
  313.                             EmailAddressType roomdetails = listRooms[counterRoom];
  314.                             err += " \n in the room name  #" + roomdetails.Name;
  315.                             FreeBusyView fbv = fbrt.FreeBusyView;
  316.                             CalendarEvent[] items = fbv.CalendarEventArray;
  317.                             if (items != null)
  318.                             {
  319.                                 err += " \n in the room name  #" + roomdetails.Name;
  320.                                 foreach (CalendarEvent myevent in items)
  321.                                 {
  322.                                     LegacyFreeBusyType busytype = myevent.BusyType;
  323.                                     if (myevent.CalendarEventDetails != null)
  324.                                     {
  325.                                         CalendarEventDetails caldetails = myevent.CalendarEventDetails;
  326.                                         CalendarObject calenderdetails = new CalendarObject();
  327.                                         calenderdetails.ID = caldetails.ID;
  328.                                         calenderdetails.StartDate = myevent.StartTime;
  329.                                         calenderdetails.EndDate = myevent.EndTime;
  330.                                         if (!String.IsNullOrEmpty(caldetails.Location))
  331.                                         {
  332.                                          
  333.                                             string location = caldetails.Location;
  334.                                             location = location.TrimEnd(';');
  335.                                             string pattern = ";";
  336.                                             calenderdetails.Location = Regex.Replace(location, pattern, " &");
  337.                                         }                                                                            
  338.                                         calenderdetails.IsPrivate = caldetails.IsPrivate;
  339.                                         calenderdetails.IsRecurring = caldetails.IsRecurring;
  340.                                         calenderdetails.Status = myevent.BusyType.ToString();
  341.                                        
  342.                                         //Resolving the name here
  343.                                         ResolveNamesType rnType = new ResolveNamesType();
  344.                                         rnType.ReturnFullContactData = true;
  345.                                         rnType.SearchScope = ResolveNamesSearchScopeType.ActiveDirectory;
  346.                                         rnType.UnresolvedEntry = caldetails.Subject;
  347.                                         ResolveNamesResponseType rnResponse = esb.ResolveNames(rnType);
  348.                                         ResolutionType rt = ((ResolveNamesResponseMessageType)rnResponse.ResponseMessages.Items[0]).ResolutionSet.Resolution[0];
  349.  
  350.                                         if (rt.Mailbox != null)
  351.                                         {
  352.  
  353.                                             calenderdetails.OrganizerName = rt.Mailbox.Name;
  354.                                             if (rt.Contact != null)
  355.                                             {
  356.                                                 if (rt.Contact.PhoneNumbers != null)
  357.                                                 {
  358.                                                     IEnumerator iterator = rt.Contact.PhoneNumbers.GetEnumerator();
  359.  
  360.                                                     while (iterator.MoveNext())
  361.                                                     {
  362.  
  363.                                                         if (((PhoneNumberDictionaryEntryType)iterator.Current).Key == PhoneNumberKeyType.MobilePhone)
  364.                                                         {
  365.  
  366.                                                             calenderdetails.OrganizerMobil = ((PhoneNumberDictionaryEntryType)iterator.Current).Value;
  367.                                                         }
  368.  
  369.                                                         if (((PhoneNumberDictionaryEntryType)iterator.Current).Key == PhoneNumberKeyType.BusinessPhone)
  370.                                                         {
  371.  
  372.                                                             calenderdetails.OrganizerTelefon = ((PhoneNumberDictionaryEntryType)iterator.Current).Value;
  373.                                                         }
  374.  
  375.                                                     }              
  376.                                                
  377.                                                 }
  378.                                                                                
  379.                                             }
  380.                                         }
  381.  
  382.                                         calenderdetails.RoomName = roomdetails.Name;
  383.                                         calenderdetails.RoomEmail = roomdetails.EmailAddress;
  384.                                         CalendarList.Add(calenderdetails);
  385.  
  386.                                     }
  387.                                 }
  388.                             }
  389.                      
  390.                         }
  391.                         counterRoom++;
  392.                        
  393.                     }
  394.                 }
  395.  
  396.             }
  397.             catch (Exception e)
  398.             {
  399.  
  400.                 errorMessage = e.ToString();
  401.             }
  402.             finally
  403.             {
  404.  
  405.  
  406.                 if (String.IsNullOrEmpty(errorMessage))
  407.                 {
  408.  
  409.                     LogSuccess("Getting Rooms Schedules : Operation completed successfully");
  410.                 }
  411.                 else
  412.                 {
  413.  
  414.                     LogError(errorMessage);
  415.                 }
  416.                 counterRoom = 0;
  417.             }
  418.             return CalendarList;
  419.         }
  420.         #endregion      
  421.  
  422.          #region Log the Error, Information and Warning to the Windows Event Viewer
  423.  
  424.         internal static void LogWarning(string msg)
  425.         {
  426.             try
  427.             {
  428.                 EventLog eventLog;
  429.                 if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
  430.                 {
  431.                     EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
  432.                 }
  433.                 if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
  434.                 {
  435.                     eventLog = new EventLog("Application");
  436.                     eventLog.Source = EVENT_LOG_SOURCE_NAME;
  437.                     eventLog.WriteEntry(msg, EventLogEntryType.Warning, 0);
  438.                 }
  439.             }
  440.             catch
  441.             {
  442.  
  443.             }
  444.         }
  445.  
  446.         internal static void LogError(string error)
  447.         {
  448.             try
  449.             {
  450.                 EventLog eventLog;
  451.                 if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
  452.                 {
  453.                     EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
  454.                 }
  455.                 if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
  456.                 {
  457.                     eventLog = new EventLog("Application");
  458.                     eventLog.Source = EVENT_LOG_SOURCE_NAME;
  459.                     StringBuilder sb = new StringBuilder(100);
  460.                     sb.Append("Exchange Server: ");
  461.                     sb.Append("\r\n");
  462.                     sb.Append(error);
  463.                     eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Error, 0);
  464.                 }
  465.             }
  466.             catch
  467.             {
  468.             }
  469.         }
  470.         internal static void LogSuccess(string information)
  471.         {
  472.             try
  473.             {
  474.                 EventLog eventLog;
  475.                 if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
  476.                 {
  477.                     EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
  478.                 }
  479.                 if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
  480.                 {
  481.                     eventLog = new EventLog("Application");
  482.                     eventLog.Source = EVENT_LOG_SOURCE_NAME;
  483.                     StringBuilder sb = new StringBuilder(100);
  484.                     sb.Append("Exchange Server: ");
  485.                     sb.Append("\r\n");
  486.                     sb.Append(information);
  487.                     eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Information, 0);
  488.  
  489.                 }
  490.             }
  491.             catch
  492.             {
  493.  
  494.             }
  495.         }
  496.         public static DataTable ToDataTable<T>(IList<T> data)
  497.         {
  498.             PropertyDescriptorCollection props =
  499.                 TypeDescriptor.GetProperties(typeof(T));
  500.             DataTable table = new DataTable();
  501.             for (int i = 0; i < props.Count; i++)
  502.             {
  503.                 PropertyDescriptor prop = props[i];
  504.                 table.Columns.Add(prop.Name, prop.PropertyType);
  505.             }
  506.             object[] values = new object[props.Count];
  507.             foreach (T item in data)
  508.             {
  509.                 for (int i = 0; i < values.Length; i++)
  510.                 {
  511.                     values[i] = props[i].GetValue(item);
  512.                 }
  513.                 table.Rows.Add(values);
  514.             }
  515.             return table;
  516.         }
  517.         #endregion
  518.  
  519.  
  520.  
  521.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement