前言
近期.net项目中,客户要求在定制化页面中展示指定用户的exchange日历会议数据以及邮箱内容数据,下面将详细来说一下实现过程
实现过程
1、所需dll
Microsoft.Exchange.WebServices 15.0.0.0
2、配置文件描述
<add key="BindIP" value="ocs-dev-ax.ocs.com" />
<add key="BindPassword" value="123456!" />
<add key="BindUserName" value="administrator" />
<add key="BindDomain" value="OCS" />
3、获取exchange service代码(初始化)
/// <summary>
/// 获取ExchangeService
/// </summary>
/// <returns></returns>
public ExchangeService getservice()
{
string Host = System.Configuration.ConfigurationManager.AppSettings["BindIP"];
string BindPassword = System.Configuration.ConfigurationManager.AppSettings["BindPassword"];
string BindUserName = System.Configuration.ConfigurationManager.AppSettings["BindUserName"];
string BindDomain = System.Configuration.ConfigurationManager.AppSettings["BindDomain"];
ExchangeService service = new ExchangeService();
try
{
service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new NetworkCredential(BindUserName, BindPassword, BindDomain);
Uri uri = new Uri("https://" + Host + "/ews/exchange.asmx");
service.Url = uri;
service.TraceEnabled = true;
service.UseDefaultCredentials = false;
service.PreAuthenticate = false;
}
catch (Exception ex)
{
}
return service;
}
4、操作exchange用户日历数据(获取、新增、修改、删除用户日历会议数据)
重点:如果在获取时候报错误信息:The specified folder could not be found in the store需要调用方法runPowerShell ,请参考【.Net】在.net项目中执行power shell命令
string runPSResult = runPowerShell(userName + "@" + BindDomain + ".com");
- 查询操作
public List<AppointmentModel> SearchCalendar(string userName, DateTime StartDate, DateTime EndDate)
{
string BindDomain = System.Configuration.ConfigurationManager.AppSettings["BindDomain"];
ExchangeService service = getservice();
List<AppointmentModel> appList = new List<AppointmentModel>();
//如果在获取时候报错误信息:The specified folder could not be found in the store需要调用方法runPowerShell
string runPSResult = runPowerShell(userName + "@" + BindDomain + ".com");
if (runPSResult == "")
{
//验证服务器证书回调自动验证
service.TraceEnabled = true;
ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
const int NUM_APPTS = 5;
// Initialize the calendar folder object with only the folder ID.
Mailbox mb = new Mailbox(userName + "@OCS.com");
FolderId folderIdFromCalendar = new FolderId(WellKnownFolderName.Calendar, mb);
CalendarFolder calendar = CalendarFolder.Bind(service, folderIdFromCalendar);
// Set the start and end time and number of appointments to retrieve.
CalendarView cView = new CalendarView(StartDate, EndDate, NUM_APPTS);
// Limit the properties returned to the appointment's subject, start time, and end time.
cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
// Retrieve a collection of appointments by using the calendar view.
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
foreach (Appointment app in appointments)
{
AppointmentModel appointmentModel = new AppointmentModel();
Appointment a = Appointment.Bind(service, new ItemId(app.Id.UniqueId));
appointmentModel.Id = a.Id.UniqueId;
appointmentModel.Body = a.Body;
appointmentModel.Subject = a.Subject;
appointmentModel.StartDate = a.Start;
appointmentModel.EndDate = a.End;
appointmentModel.IsAllDayEvent = a.IsAllDayEvent;
appointmentModel.IsPrivate = (((Item)a).Sensitivity == Sensitivity.Private) ? true : false;
appointmentModel.RequiredAttendees = new List<string>();
foreach (Attendee required in a.RequiredAttendees)
{
appointmentModel.RequiredAttendees.Add(required.Address);
}
appointmentModel.OptionalAttendees = new List<string>();
foreach (Attendee optional in a.OptionalAttendees)
{
appointmentModel.OptionalAttendees.Add(optional.Address);
}
appointmentModel.IsMeeting = a.IsMeeting;
appointmentModel.Id = app.Id.UniqueId;
appointmentModel.Subject = app.Subject;
appointmentModel.StartDate = app.Start;
appointmentModel.EndDate = app.End;
appList.Add(appointmentModel);
}
}
return appList;
}
- 添加日历会议
private bool AddNewInviteCalendar(string userName, AppointmentModel appointmentModel, ref string id)
{
ExchangeService service = getservice();
//如果在获取时候报错误信息:The specified folder could not be found in the store需要调用方法runPowerShell
string runPSResult = runPowerShell(userName + "@" + BindDomain + ".com");
//验证服务器证书回调自动验证
ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
Appointment appointment = new Appointment(service);
appointment.Subject = appointmentModel.Subject;
appointment.Body = appointmentModel.Body;
appointment.Start = appointmentModel.StartDate;
appointment.End = appointmentModel.EndDate;
appointment.IsAllDayEvent = appointmentModel.IsAllDayEvent;//全天事件
appointment.Sensitivity = (appointmentModel.IsPrivate) ? Sensitivity.Private : Sensitivity.Normal;//是否私人,去掉是Sensitivity.Normal
appointment.Location = appointmentModel.Location; //会议地点//20201225
if (appointmentModel.RequiredAttendees != null && appointmentModel.RequiredAttendees.Count > 0)
{
foreach (String rAttendee in appointmentModel.RequiredAttendees)
{
appointment.RequiredAttendees.Add(rAttendee);
}
}
if (appointmentModel.OptionalAttendees != null && appointmentModel.OptionalAttendees.Count > 0)
{
foreach (String oAttendee in appointmentModel.OptionalAttendees)
{
appointment.OptionalAttendees.Add(oAttendee);
}
}
appointment.Save(new FolderId(WellKnownFolderName.Calendar, userName + "@OMS.com"), SendInvitationsMode.SendToAllAndSaveCopy);
appointmentModel.Id = appointment.Id.UniqueId;
id = appointmentModel.Id;
return true;
}
catch (Exception ex)
{
//WriteLog("add error,subject:[" + appointmentModel.Subject + "] body:[" + appointmentModel.Body + "]msg:" + ex.ToString(), true);
return false;
}
}
- 修改日历会议
private bool ModifyInviteCalendar(AppointmentModel appointmentModel)
{
ExchangeService service = getservice();
ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
Appointment appointment = Appointment.Bind(service, new ItemId(appointmentModel.Id));
if (appointment != null)
{
appointment.Subject = appointmentModel.Subject;
appointment.Body = appointmentModel.Body;
appointment.StartTimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
//appointment.EndTimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
appointment.Start = appointmentModel.StartDate;
appointment.End = appointmentModel.EndDate;
appointment.IsAllDayEvent = appointmentModel.IsAllDayEvent;
appointment.Sensitivity = (appointmentModel.IsPrivate) ? Sensitivity.Private : Sensitivity.Normal;//是否私人,去掉是Sensitivity.Normal
appointment.Location = appointmentModel.Location; //修改地点//20201225
if (appointmentModel.RequiredAttendees != null && appointmentModel.RequiredAttendees.Count > 0)
{
appointment.RequiredAttendees.Clear();
foreach (String rAttendee in appointmentModel.RequiredAttendees)
{
appointment.RequiredAttendees.Add(rAttendee);
}
}
else
appointment.RequiredAttendees.Clear();
if (appointmentModel.OptionalAttendees != null && appointmentModel.OptionalAttendees.Count > 0)
{
appointment.OptionalAttendees.Clear();
foreach (String oAttendee in appointmentModel.OptionalAttendees)
{
appointment.OptionalAttendees.Add(oAttendee);
}
}
else
appointment.OptionalAttendees.Clear();
//appointment.Sensitivity = (appointmentModel.IsPrivate) ? Sensitivity.Private : Sensitivity.Normal;//是否私人,去掉是Sensitivity.Normal
appointment.Update(ConflictResolutionMode.AlwaysOverwrite);
DateTime dt = appointment.LastModifiedTime;
return true;
}
else
{
//errmsgid = "not find calendar schedule";
return false;
}
}
catch (Exception ex)
{
// WriteLog("edit error,id:[" + appointmentModel.Id + "] msg:" + ex.ToString(), true);
//errmsgid = "edit error";
return false;
}
}
- 删除日历会议
private bool DeleteCalendar(String id, ref string errmsgid)
{
ExchangeService service = getservice();
//验证服务器证书回调自动验证
ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
Appointment appointment = Appointment.Bind(service, new ItemId(id));
if (appointment != null)
{
appointment.Subject = appointment.Subject + "(已删除)";
//appointment.Body = appointment.Body.Text.Replace(appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")), "(已删除)" + appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")));
if (!String.IsNullOrEmpty(appointment.Body) && !String.IsNullOrEmpty(appointment.Body.Text))
{
appointment.Body = appointment.Body.Text.Replace(appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")), "(已删除)" + appointment.Body.Text.Substring(appointment.Body.Text.IndexOf("</body>")));
}
appointment.Update(ConflictResolutionMode.AlwaysOverwrite);
appointment.Delete(DeleteMode.MoveToDeletedItems);
return true;
}
else
{
errmsgid = "not find calendar schedule";
return false;
}
}
catch (Exception ex)
{
//WriteLog("delete error,id:[" + id + "] msg:" + ex.ToString(), true);
errmsgid = "del error";
return false;
}
}