I have a way here how I check multiple variables for null, and fill them with the correct data according to the nullness. However, this way is very messy and I am now wondering if there is a better way to do this.
`
try
{
user = new ADUser();
nextEntry = ldapSearch.Next();
var attName = nextEntry.getAttribute("name");
var attMail = nextEntry.getAttribute("mail");
var attTelephone = nextEntry.getAttribute("telephoneNumber");
if(attName == null || attMail == null || attTelephone == null)
{
if( attName == null)
{
user.name = "";
}
else
{
user.name = attName.StringValue;
}
if(attMail == null)
{
user.mail = "";
}
else
{
user.mail = attMail.StringValue;
}
if(attTelephone == null)
{
user.telephone = "";
}
else
{
user.telephone = attTelephone.StringValue;
}
}
else
{
user.name = attName.StringValue;
user.mail = attMail.StringValue;
user.telephone = attTelephone.StringValue;
}
model.ADUserList.Add(user);
}
catch
{
continue;
}
`
I have tried it my way, but I think it can be done cleaner.
yes, you can achive the same result without any 'if-else':
user.name = attName?.StringValue ?? "";
user.mail = attMail?.StringValue ?? "";
user.telephone = attTelephone?.StringValue ?? "";
you can also write an extension method to return the empty string:
public static class StringExtensions
{
public static string EmptyIfNull(this string str)
{
return str ?? String.Empty;
}
}
and then use it like this:
user.name = attName?.StringValue.EmptyIfNull();
user.mail = attMail?.StringValue.EmptyIfNull();
user.telephone = attTelephone?.StringValue.EmptyIfNull();
Hi I am using Entity Framework Code First, I have a collection of Entities that need to be saved, but I have my EF Repository created as below
public T Create(T item)
{
try
{
if (ufb != null && ufb.CurrentUser != null)
{
SetValue("CreatedByUserId", item, ufb.CurrentUser.Id);
SetValue("UpdatedByUserId", item, ufb.CurrentUser.Id);
}
SetValue("DateCreated", item, DateTime.Now);
SetValue("DateUpdated", item, DateTime.Now);
var newEntry = this.DbSet.Add(item);
this.Context.Database.Log = message => LogHandler.LogInfo(1111, message);
try
{
this.Context.SaveChanges();
}
catch (Exception ex)
{
LogHandler.LogInfo(2501, ex.Message);
}
BuildMetaData(item, true, true);
return newEntry;
}
catch (DbEntityValidationException dbEx)
{
// http://forums.asp.net/t/2014382.aspx?Validation+failed+for+one+or+more+entities+See+EntityValidationErrors+property+for+more+details+
string msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
msg += validationError.PropertyName;
msg += "---";
msg += validationError.ErrorMessage;
msg += "||";
}
}
throw new Exception("7777 CREATE EntityValidationErrors: " + msg);
}
}
My calling method is as below:
public List<VehicleInfo> Create(List<VehicleInfo> vehicleInfos, string Entity, int EntityId)
{
bool vehicleExists = false; List<VehicleInfo> newVehicleInfos = null;
if ((vehicleInfos != null) && (vehicleInfos.Count > 0))
{
newVehicleInfos = new List<VehicleInfo>();
foreach (VehicleInfo vehicleInfo in vehicleInfos)
{
vehicleExists = false;
if (vehicleInfo != null)
{
vehicleExists = this.VehicleExists(vehicleInfo.VehicleId, Entity, EntityId);
vehicleInfo.Entity = Entity;
vehicleInfo.EntityId = EntityId;
VehicleInfo v = this.UnitOfWork.VehicleInfoRepository.Create(vehicleInfo);
newVehicleInfos.Add(v);
}
}
}
return newVehicleInfos;
}
Hence when I am calling repositories create method for multiple times, its throwing me the above error, any help or suggestion would be very helpful, please thank you.
void BuildMetaDataNoThread(object item, bool active, bool isNew = false)
{
if (item.GetType() != typeof(JsonObject))
{
var dm = new DataAccessUnitOfWork(Constants.DefaultConnection);
var qtype = item.GetType();
if (qtype.BaseType.BaseType != null)
{
if ((isNew && qtype.BaseType.Name == typeof(ModelBase).Name) | qtype.BaseType.BaseType.Name == typeof(ModelBase).Name)
{
Thread.Sleep(500);
//collect data
var element = (ModelBase)item;
element.BuildMetaData(DataRequestType.CurrentItem);
var records = ModelBase.MetaData;
ModelBase.MetaData = new List<ModelRecord> { };
if (records == null) return;
foreach (ModelRecord r in records)
{
if (r!=null)
{
var jsr = new JavaScriptSerializer();
//object meta = r;
object rdata = r.Data;
var type = rdata.GetType();
var token = type.BaseType.Name;
List<string> include = r.Include;
// Cycle-through clieanup of models to be encoded into Json Data.
// this helper eliminates infinate relations by including records specified
// by a list of strings
if (include.Where(x => x.Contains("CreatedByUser")).Count() == 0)
include.Add("CreatedByUser");
if (include.Where(x => x.Contains("UpdatedByUser")).Count() == 0)
include.Add("UpdatedByUser");
var data = ClassCloner.CollectData(rdata, include);
List<string> tags = ClassCloner.CollectTags(data);
string _tags = "";
tags.ForEach((xtm) =>
{
_tags += xtm + ',';
});
var json = jsr.Serialize(data);
int id = 0;
//get identity
foreach (var prop in type.GetProperties())
{
if (id == 0)
{
foreach (var cp in prop.CustomAttributes)
{
if (cp.AttributeType.Name == "KeyAttribute")
{
var _id = ((Dictionary<string, object>)data)[prop.Name];
id = (int)_id;
break;
}
}
}
else { break; }
}
var query = dm.JsonObjectRepository.GetAll();
var key = "_" + token;
var _data = (Dictionary<string, object>)data;
var ExistingMetaData = (from x in query where x.SourceKey == key && x.SourceId == id select x).FirstOrDefault();
if (ExistingMetaData != null)
{
if (_data.ContainsKey("DateUpdated")) ExistingMetaData.Date = (DateTime)_data["DateUpdated"];
ExistingMetaData.SourceData = data;
ExistingMetaData.Encode();
ExistingMetaData.Active = active;
ExistingMetaData.SearchTags = _tags;
dm.JsonObjectRepository.Update(ExistingMetaData);
}
else
{
var newData = new JsonObject
{
Active = true,
Date = (DateTime)_data["DateUpdated"],
SourceData = data,
SourceId = id,
SourceKey = key,
SearchTags = _tags,
TargetKey = "GlobalSearchMetaData"
};
newData.Encode();
dm.JsonObjectRepository.Create(newData);
}
}
}
}
}
}
}
void BuildMetaData(object dataRecord, bool active, bool isNew)
{
new Thread((item) => { BuildMetaDataNoThread(item, active, isNew); }).Start(dataRecord);
}
I want to pass real time signals from emotive to octave.
I tried to write a c# wrapper for octave. Here is the code.
namespace LibSharpTave {
public class Octave {
Process OctaveProcess { get; set; }
private string OctaveEchoString { get; set; }
public Octave(string PathToOctaveBinaries) {
StartOctave(PathToOctaveBinaries, false);
}
public Octave(string PathToOctaveBinaries, bool CreateWindow) {
StartOctave(PathToOctaveBinaries, CreateWindow);
}
string ptob;
bool cw;
private void StartOctave(string PathToOctaveBinaries, bool CreateWindow) {
ptob = PathToOctaveBinaries;
cw = CreateWindow;
this.OctaveEchoString = Guid.NewGuid().ToString();
OctaveProcess = new Process();
ProcessStartInfo pi = new ProcessStartInfo();
if (PathToOctaveBinaries[PathToOctaveBinaries.Length - 1] != '\\')
PathToOctaveBinaries = PathToOctaveBinaries + "\\";
pi.FileName = PathToOctaveBinaries + "octave.exe";
pi.RedirectStandardInput = true;
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = !CreateWindow;
pi.Verb = "open";
//
pi.WorkingDirectory = ".";
OctaveProcess.StartInfo = pi;
OctaveProcess.Start();
OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
OctaveProcess.BeginOutputReadLine();
OctaveEntryText = ExecuteCommand(null);
//OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(Oc
}
public double GetScalar(string scalar) {
string rasp = ExecuteCommand(scalar, 30000);
string val = rasp.Substring(rasp.LastIndexOf("\\") + 1).Trim();
return double.Parse(val);
}
public double[] GetVector(string vector) {
string rasp = ExecuteCommand(vector, 30000);
string[] lines = rasp.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int i = 0;
//catam urmatorul entry
List<double> data = new List<double>();
while (i != lines.Length) {
string line = lines[i];
if (line.Contains("through") || line.Contains("and")) {
i++;
line = lines[i];
string[] dataS = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
for (int k = 0; k < dataS.Length; k++) {
data.Add(double.Parse(dataS[k]));
}
}
i++;
}
//caz special in care a pus toate rezultatele pe o singura linie
if (data.Count == 0) {
string[] dataS = lines[lines.Length - 1].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (dataS.Length != 0)
for (int k = 0; k < dataS.Length; k++) {
data.Add(double.Parse(dataS[k]));
}
}
return data.ToArray();
}
public double[][] GetMatrix(string matrix) {
//string rasp = ExecuteCommand(matrix);
//aflam numarul de randuri
string rasp = ExecuteCommand(matrix + "(:,1)", 30000);
string[] lines = rasp.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
double[][] mat = new double[lines.Length - 1][];
for (int i = 0; i < mat.Length; i++) {
mat[i] = GetVector(matrix + "(" + (i + 1) + ",:)");
}
return mat;
}
StringBuilder SharedBuilder = new StringBuilder();
ManualResetEvent OctaveDoneEvent = new ManualResetEvent(false);
public string OctaveEntryText { get; internal set; }
public void WorkThread(object o) {
string command = (string)o;
SharedBuilder.Clear();
OctaveDoneEvent.Reset();
if (command != null) {
OctaveProcess.StandardInput.WriteLine(command);
}
//ca sa avem referinta pentru output
OctaveProcess.StandardInput.WriteLine("\"" + OctaveEchoString + "\"");
OctaveDoneEvent.WaitOne();
}
public string ExecuteCommand(string command, int timeout) {
if (OctaveProcess.HasExited) {
StartOctave(ptob, cw);
if (OctaveRestarted != null) OctaveRestarted(this, EventArgs.Empty);
}
exitError = false;
Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
tmp.Start(command);
if (!tmp.Join(timeout)) {
tmp.Abort();
throw new Exception("Octave timeout");
}
if (exitError) {
throw new Exception(errorMessage);
}
return SharedBuilder.ToString();
}
public string ExecuteCommand(string command) {
// Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
// tmp.Start(command);
// tmp.Join();
// return SharedBuilder.ToString();
if (OctaveProcess.HasExited)
{
OctaveProcess.Start();
}
SharedBuilder.Clear();
if (command != null)
{
OctaveProcess.StandardInput.WriteLine(command);
OctaveDoneEvent.Reset();
OctaveDoneEvent.WaitOne();
return SharedBuilder.ToString();
}
Octave octave = new Octave(#"c:\software\Octave-3.6.4",false);
octave.ExecuteCommand("a=[1,2;3,4];");
octave.ExecuteCommand("result=a;");
double[][] m = octave.GetMatrix("result");
}
bool exitError = false;
string errorMessage = null;
void OctaveProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) {
if (e.Data == null) {
SharedBuilder.Clear();
//errorMessage = OctaveProcess.StandardError.ReadToEnd();
SharedBuilder.Append("Octave has exited with the following error message: \r\n" + errorMessage);
//exitError = true;
OctaveDoneEvent.Set();
return;
}
if (e.Data.Trim() == "ans = " + OctaveEchoString)
OctaveDoneEvent.Set();
else
SharedBuilder.Append(e.Data + "\r\n");
}
public event OctaveRestartedEventHandler OctaveRestarted;
public delegate void OctaveRestartedEventHandler(object sender, EventArgs e);
}
//custom class
// void OctaveProcess_OutputDataReceived (object sender, DataReceivedeEventArgs e)
/*{
if (e.data == null)
{
SharedBuilder.Clear();
SharedBuilder.Append("Octave has exited with the following error message: \r\n" + OctaveProcess.StandardError.ReadToEnd());
OctaveDoneEvent.Set();
return;
}
if (e.data.Trim == "ans =" + OctaveEchoString())
OctaveDoneEvent.set();
else
SharedBuilder.Append(e.Data + "\r\n");
}*/
}
And it is returning the error: "Not all code paths return a value".
How can I fix this error?
Your ExecuteCommand function should return a string, but doesn't. This is the ExecuteCommand overload that accepts one argument.
This function has string as return type but does not return anything when if (command != null) statement is false -
public string ExecuteCommand(string command) {
// Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
// tmp.Start(command);
// tmp.Join();
// return SharedBuilder.ToString();
if (OctaveProcess.HasExited)
{
OctaveProcess.Start();
}
SharedBuilder.Clear();
if (command != null)
{
OctaveProcess.StandardInput.WriteLine(command);
OctaveDoneEvent.Reset();
OctaveDoneEvent.WaitOne();
return SharedBuilder.ToString();
}
Octave octave = new Octave(#"c:\software\Octave-3.6.4",false);
octave.ExecuteCommand("a=[1,2;3,4];");
octave.ExecuteCommand("result=a;");
double[][] m = octave.GetMatrix("result");
//**** The Error is here *****
//return a string here
}
Return a string at the mention section. I highlighted in the comment as - //**** The Error is here *****
Your
public string ExecuteCommand(string command) {
has no return statement even though you specified return type string.
Either return some string or make its return type void as in :
public void ExecuteCommand(string command) {
I am extracting text from a PDF file and converting that text to HTML while extracting.
When doing this, an overlap of the text occurs, making it very difficult to read. I am using itextsharp to perform the extraction.
What in this code is causing that error?
public void Extract_inputpdf()
{
string pdf_of_inputFile = targetPathip;
StringBuilder sb_inputpdf = new StringBuilder();
PdfReader reader_inputPdf = new PdfReader(LblFleip.Text); //read PDF
divip.InnerHtml = "";
divop.InnerHtml = "";
sb_inputpdf.Length = 0;
text_output_File = string.Empty;
text_output_File_report = string.Empty;
text_input_File = string.Empty;
text_input_File_report = string.Empty;
input_pdf = string.Empty;
input_pdf_report = string.Empty;
output_pdf = string.Empty;
output_pdf_report = string.Empty;
rtbxinput_box_input = string.Empty;
rtbxinput_box_output = string.Empty;
Pagesize_input = 0;
FinalPagesize_input = 0;
Pagesize_output = 0;
FinalPagesize_output = 0;
for (i = 1;i <= reader_inputPdf.NumberOfPages;i++)
{
Pagesize_input = FinalPagesize_input;
height_input = reader_inputPdf.GetPageSizeWithRotation(i).Height;
pagenumber_input = i;
TextWithFont_inputPdf inputpdf = new TextWithFont_inputPdf();
text_input_File = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader_inputPdf, i, inputpdf);
sb_inputpdf.Append(text_input_File);
divip.InnerHtml = sb_inputpdf.ToString();
input_pdf = sb_inputpdf.ToString();
}
reader_inputPdf.Close();
}
//read input pdf ----------
public class TextWithFont_inputPdf : iTextSharp.text.pdf.parser.ITextExtractionStrategy
{
private StringBuilder result = new StringBuilder();
private Vector lastBaseLine;
private string lastFont;
private float lastFontSize;
public void RenderText(iTextSharp.text.pdf.parser.TextRenderInfo renderInfo)
{
string curFont = renderInfo.GetFont().PostscriptFontName;
string curfontweight = renderInfo.GetFont().PostscriptFontName;
float height_extract_input = Publishing.height_input;
int pagenumber_input = Publishing.i;//page number
string fontweight = string.Empty;
string fontstyle = string.Empty;
string presentfont = string.Empty;
string divide = curFont;
string[] fontnames = null;
//--------------------------------------------------------
Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
Vector topRight = renderInfo.GetAscentLine().GetEndPoint();
y_direction_input = 10 + Publishing.Pagesize_input + (height_extract_input - curBaseline[Vector.I2]);
Publishing.FinalPagesize_input = y_direction_input;
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
Single curFontSize = rect.Height;
//---------------------------------------
if ((this.lastBaseLine == null) || (curBaseline[Vector.I2] != lastBaseLine[Vector.I2]) || (curFontSize != lastFontSize) || (curFont != lastFont))
{
if ((this.lastBaseLine != null))
{
this.result.AppendLine("</span>");
}
if ((this.lastBaseLine != null) && curBaseline[Vector.I2] != lastBaseLine[Vector.I2])
{
//this.result.AppendLine("<br />");
}
this.result.AppendFormat("<span style=\"font-family:{0};font-weight:{1};font-style:{2};margin-left:{3}pt;top:{4}pt; position:absolute;\">", curFont, fontweight, fontstyle, curBaseline[Vector.I1], y_direction_input);
}
this.result.Append(renderInfo.GetText());
this.lastBaseLine = curBaseline;
this.lastFontSize = curFontSize;
this.lastFont = curFont;
}
catch (Exception ex)
{
logWriter.Error("TextWithFont_inputPdf() : " + ex.Message);
}
}
public string GetResultantText()
{
if (result.Length > 0)
{
result.Append("</span>");
}
return result.ToString();
}
public void BeginTextBlock() { }
public void EndTextBlock() { }
public void RenderImage(ImageRenderInfo renderInfo) { }
}
How to make meeting (in calendar) in outlook 2007 using C# ?
thank's in advance
This code sample from MSDN should get you started:
private void SetRecipientTypeForAppt()
{
Outlook.AppointmentItem appt =
Application.CreateItem(
Outlook.OlItemType.olAppointmentItem)
as Outlook.AppointmentItem;
appt.Subject = "Customer Review";
appt.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;
appt.Location = "36/2021";
appt.Start = DateTime.Parse("10/20/2006 10:00 AM");
appt.End = DateTime.Parse("10/20/2006 11:00 AM");
Outlook.Recipient recipRequired =
appt.Recipients.Add("Ryan Gregg");
recipRequired.Type =
(int)Outlook.OlMeetingRecipientType.olRequired;
Outlook.Recipient recipOptional =
appt.Recipients.Add("Peter Allenspach");
recipOptional.Type =
(int)Outlook.OlMeetingRecipientType.olOptional;
Outlook.Recipient recipConf =
appt.Recipients.Add("Conf Room 36/2021 (14) AV");
recipConf.Type =
(int)Outlook.OlMeetingRecipientType.olResource;
appt.Recipients.ResolveAll();
appt.Display(false);
}
MSDN
Create object of outlook app using:
private Microsoft.Office.Interop.Outlook.Application outlookApp =
new Microsoft.Office.Interop.Outlook.Application();
and replace Application.CreateItem in code provided by Kyle Rozendo, with outlookApp.
Hope this will help.
This is probably a bit of an overkill but, here is a method that handles Adding, Updating, Deleting events. It also uses almost every calendar event function possible (recurrence by various types, attendees, responses etc.). If you're interested, let me know, I can explain more. It should work off the bat, but I could have missed something, typing this really fast
////BEGIN OUTLOOK DECLARATIONS
public static dynamic objOutlook = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application"));
public static int appointmentItem = 1;
public static int mailItem = 0;
public static int inboxItem = 6;
public static dynamic mapiNamespace = objOutlook.GetNamespace("MAPI");
public static dynamic inboxFolder = mapiNamespace.GetDefaultFolder(inboxItem);
public static dynamic mailObject = objOutlook.CreateItem(mailItem);
public static dynamic appointmentObject = objOutlook.CreateItem(appointmentItem);
public static string defaultEmail = mapiNamespace.DefaultStore.DisplayName; //mapiNamespace.CurrentUser.DefaultStore.DisplayName;
////END OUTLOOK DECLARATIONS
public static string CreateAppointmentOutlookDirect(char StatusType, int ID, string EventID, string EventIDRef, string Subject, string Description, string Location, DateTime EventStart, DateTime EventEnd, string TimeZone, int Duration,
string Recepients, bool isAllDayEvent, bool hasReminder, string ReminderType, int ReminderMinutes, bool isRecurring, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd,
DateTime CreatedDate, DateTime ModifiedDate)
{
RefreshOutlookConstants();
//ITEM TYPES
var olMailItem = 0;
var olAppointmentItem = 1;
//
//FOLDER TYPES
var olFolderCalendar = 9;
//
int RecurrenceMask = 0;
var objAppointment = objOutlook.CreateItem(olAppointmentItem);
var objMail = objOutlook.CreateItem(olMailItem);
var OlNamspace = objOutlook.GetNamespace("MAPI");
var AppointmentFolder = OlNamspace.GetDefaultFolder(olFolderCalendar);
var StoreID = AppointmentFolder.StoreID;
AppointmentFolder.Items.IncludeRecurrences = true;
string StatusTypeDesc = "";
string[] Attendees = Recepients.Split(';');
//UPDATE YEARLY RECURRENCE TYPE - BECAUSE THE NUMBER 4 DOES NOT EXIST ACCORDING TO MICROSOFT ( -_-)
if (RecurrenceType == 3)
{
RecurrenceType = 5;
}
//GET DAY OF WEEK
if (RecurrenceDesc.Trim().ToUpper() == "MONDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "TUESDAY")
{
RecurrenceMask = 4;
}
else if (RecurrenceDesc.Trim().ToUpper() == "WEDNESDAY")
{
RecurrenceMask = 8;
}
else if (RecurrenceDesc.Trim().ToUpper() == "THURSDAY")
{
RecurrenceMask = 16;
}
else if (RecurrenceDesc.Trim().ToUpper() == "FRIDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SATURDAY")
{
RecurrenceMask = 64;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SUNDAY")
{
RecurrenceMask = 1;
}
else
{
RecurrenceMask = 0;
}
//CHECK ALL DAY EVENT
if (isAllDayEvent)
{
EventStart = Convert.ToDateTime(EventStart.ToString("dd/MM/yyyy") + " 12:00 AM");
EventEnd = Convert.ToDateTime(EventEnd.AddDays(1).ToString("dd/MM/yyyy") + " 12:00 AM");
}
//--RESOLVE EVENT START - END - DURATION
GetEventDates(EventStart, EventEnd, Duration, out EventEnd, out Duration);
if (EventStart == null)
{
return EventID + "#FAIL";
}
//ADD - DELETE - UPDATE MEETING ACCORDINGLY
if (StatusType == 'D')
{
var aObject = OlNamspace.GetItemFromID(EventID, StoreID);
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
if (attendee.Trim() != "")
{
string NewAttendee = ExtractEmail(attendee);
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
aObject = null;
}
else
{
if (StatusType == 'U')
{
foreach (var aObject in AppointmentFolder.Items)
{
var EntryID = aObject.EntryID;
if (Convert.ToString(EntryID) == EventID.Trim())
{
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
}
}
}
objAppointment.MeetingStatus = 1;
objAppointment.Subject = Subject;
objAppointment.Body = Description;
objAppointment.Location = Location;
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
objAppointment.Recipients.Add(NewAttendee.Trim());
}
}
}
if (isAllDayEvent)
{
objAppointment.AllDayEvent = isAllDayEvent;
}
else
{
objAppointment.Start = EventStart;
objAppointment.End = EventEnd; //Optional if Event has Duration
objAppointment.Duration = Duration; //Optional if Event has Start and End
}
objAppointment.ReminderSet = hasReminder;
if (hasReminder)
{
objAppointment.ReminderMinutesBeforeStart = ReminderMinutes;
}
objAppointment.Importance = 2;
objAppointment.BusyStatus = 2;
if (isRecurring)
{
var pattern = objAppointment.GetRecurrencePattern();
pattern.RecurrenceType = RecurrenceType;
if (RecurrenceType == 1)
{
pattern.DayOfWeekMask = RecurrenceMask;
}
else if (RecurrenceType == 4)
{
pattern.MonthOfYear = RecurrenceMask;
}
if (DateTime.Compare(RecurrenceStart, DateTime.Now) > 1)
{
pattern.PatternStartDate = DateTime.Parse(RecurrenceStart.ToString("dd/MM/yyyy"));
}
if (DateTime.Compare(RecurrenceEnd, DateTime.Now) > 1)
{
pattern.PatternEndDate = DateTime.Parse(RecurrenceEnd.ToString("dd/MM/yyyy"));
}
}
objAppointment.Save();
if (Recepients.Trim() != "")
{
objAppointment.Send();
}
EventID = objAppointment.EntryID;
}
objAppointment = null;
//objOutlook = null;
// CREATE--UPDATE--DELETE EVENT OR APPOINTMENTS
StatusTypeDesc = GetStatusType(StatusType).Trim();
if (StatusTypeDesc == "")
{
clsGlobalFuncs.WriteServiceLog(String.Format("Error Creating Outlook Event: Unknown Status Type [{0}]. Event was Treated as a new event and may contain errors", StatusType));
return EventID + "#FAIL";
}
clsGlobalFuncs.WriteServiceLog(String.Format("Outlook Event Succesfully {2}. [EventID: {0}] ][EventRef: {1}]", EventID, EventIDRef, StatusTypeDesc));
return EventID + "#PASS";
}
public static void SendEmail(string Recepients, string CC, string BCC, string Subject, string Body, string Attachment)
{
RefreshOutlookConstants();
string[] EmailArr = Recepients.Split(';');
foreach (string email in EmailArr)
{
if (email.IndexOf('#') == -1)
{
WriteServiceLog(String.Format("EMAIL ERROR: Invalid Email Address:- [{0}]. This email will be skipped", email));
Recepients = Recepients.Replace(email + ";", "");
Recepients = Recepients.Replace(email, "");
}
}
if (Recepients.Trim() == "")
{
WriteServiceLog(String.Format("Error Sending Email. No recpients were found in string [{0}]", Recepients));
return;
}
try
{
Recepients = StringClean(Recepients);
// SEND EMAIL WITH ATTACHMENT
mailObject.To = Recepients;
if (CC.Trim() != "") { mailObject.CC = CC; }
if (BCC.Trim() != "") { mailObject.BCC = BCC; }
mailObject.Subject = Subject;
mailObject.HTMLBody = Body;
mailObject.Importance = 2;
if (Attachment.Trim() != "")
{
string[] attachmentList = Attachment.Split(';');
foreach (string attachmentFile in attachmentList)
{
if (attachmentFile.Trim() != "")
{
mailObject.Attachments.Add(attachmentFile.Trim());
}
}
}
mailObject.Send();
//objEmail.Display(false);
WriteServiceLog(String.Format("Email Sent [{0}] TO [{1}]", Subject, Recepients));
}
catch (Exception ex)
{
WriteServiceLog("Error sending email");
WriteErrorLog(ex);
}
}
public static string GetStatusType(char StatusCode)
{
string returnValue = "";
if (StatusCode == 'A')
{
returnValue = "Created";
}
else if (StatusCode == 'U')
{
returnValue = "Updated";
}
else if (StatusCode == 'D')
{
returnValue = "Deleted";
}
return returnValue;
}
public static string GetRecurData(bool RecurFlag, string EventType, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd, DateTime EventStart)
{
string returnValue = String.Format("RRULE:FREQ=DAILY;UNTIL={0:yyyyMMdd};", EventStart);
if (RecurFlag == true)
{
returnValue = "";
if (RecurrenceType == 0)
{
returnValue = String.Format("{0}RRULE:FREQ=DAILY;", returnValue);
}
else if (RecurrenceType == 1)
{
returnValue = returnValue + "RRULE:FREQ=WEEKLY;";
}
else if (RecurrenceType == 2)
{
returnValue = returnValue + "RRULE:FREQ=MONTHLY;";
}
else
{
returnValue = returnValue + "RRULE:FREQ=YEARLY;";
}
if (RecurrenceEnd != null)
{
returnValue = String.Format("{0}UNTIL={1:yyyyMMdd}T{2:HHmmss}Z;", returnValue, RecurrenceEnd, RecurrenceEnd);
}
if (EventType == "GM")
{
if (RecurrenceType == 1)
{
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYDAY={1};", returnValue, RecurrenceDesc.Substring(0, 2).ToUpper());
}
}
if (RecurrenceType == 3)
{
int i = DateTime.ParseExact(RecurrenceDesc, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month;
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYMONTH={1};", returnValue, i);
}
}
}
}
return returnValue;
}
public static string GetReminderType(bool ReminderFlag, string EventType, string ReminderCode)
{
string returnValue = "NONE";
if (ReminderFlag == true)
{
if (ReminderCode.Trim() == "PROMPT")
{
if (EventType == "GM")
{
returnValue = "popup";
}
else if (EventType == "OC")
{
returnValue = "DISPLAY";
}
}
else
{
returnValue = "email";
if (EventType == "OC") { returnValue = returnValue.ToUpper(); }
}
}
return returnValue;
}
public static void GetEventDates(DateTime EventStart, DateTime EventEnd, int Duration, out DateTime EventEnd_Ret, out int Duration_Ret)
{
EventEnd_Ret = EventEnd;
Duration_Ret = 0;
if (!(EventStart == null))
{
if (((EventEnd == null) || (DateTime.Compare(EventEnd, EventStart) < 1)) && (Duration > 0))
{
EventEnd_Ret = EventStart.AddMinutes(Duration);
}
else if ((Duration_Ret <= 0) && ((EventEnd != null) && (DateTime.Compare(EventEnd, EventStart) >= 0)))
{
Duration_Ret = Convert.ToInt32((EventEnd - EventStart).TotalMinutes);
}
if ((Duration_Ret <= 0) || ((EventEnd_Ret == null) || (DateTime.Compare(EventEnd_Ret, EventStart) < 1)))
{
WriteServiceLog(String.Format("ERROR UPDATING EVENT - COULD NOT RESOLVE WHEN THE EVENT MUST END USING [END DATE: {0:dd/MM/yyyy HH:mm}] OR [DURATION: {1}] - PLEASE SPECIFY A VALID END DATE OR DURATION", EventEnd, Duration));
}
}
else
{
WriteServiceLog("ERROR UPDATING EVENT - START DATE NOT FOUND");
}
}
public static string StringClean(string StringValue)
{
StringValue = StringValue.Replace(':',' ');
StringValue = StringValue.Replace('[', ' ');
StringValue = StringValue.Replace(']', ' ');
StringValue = StringValue.Replace('\'', ' ');
StringValue = StringValue.Replace('<', ' ');
StringValue = StringValue.Replace('>', ' ');
return StringValue.Trim();
}
And to call it, use this
CreateAppointmentOutlookDirect
(
'A', //'A' = ADD, 'U' = UPDATE, 'D' = DELETE
0,
"EVENT SUBJECT",
"OUTLOOK",
"",
"WHAT IS IT ABOUT",
"EVENT DESCRIPTION",
"EVENT LOCATION",
DateTime.Now,
DateTime.Now.AddMinutes(60),
TimeZone.CurrentTimeZone.StandardName,
0,
"attendee1#email.com; attendee2#email.com",
false,
true,
"PROMPT",
30,
false,
0,
"",
DateTime.Now,
DateTime.Now,
false,
'A',
"APPOINTMENT TEST SYSTEM"
);