Display sequence messages - c#

I'm trying to display the messages from a sequence diagram, but so far no luck
Here's my code:
The function browse recursively calls itself to discover the diagrams, but i'm having no luck with DiagramLinks or DiagramObjects, any hint ?
private void browse(EA.Repository Repository, int ID, EA.ObjectType otype)
{
if (otype == EA.ObjectType.otPackage)
{
EA.Package pack = Repository.GetPackageByID(ID);
foreach(EA.Element el in pack.Elements)
{
ID = el.ElementID;
otype = el.ObjectType;
this.browse(Repository, ID, otype);
}
}
if (otype == EA.ObjectType.otElement)
{
EA.Element el = Repository.GetElementByID(ID);
foreach (EA.Diagram diag in el.Diagrams)
{
ID = diag.DiagramID;
otype = diag.ObjectType;
this.browse(Repository, ID, otype);
}
}
if (otype == EA.ObjectType.otDiagram)
{
EA.Diagram diag = Repository.GetDiagramByID(ID);
//foreach (EA.DiagramLink dobj in diag.DiagramLinks)
//{
MessageBox.Show(diag.Name+diag.Type);
//}
}
}
Here's the function that recognizes if the addin is launched from mainmenu, treeview or diagram.
It calls the above function Browse
private string simplify(EA.Repository Repository, string Location)
{
String s = "";
if (Location == "MainMenu") {
s = "ROOT";
MessageBox.Show("test");
}
else if (Location == "TreeView")
{
//Get the element in the tree view which was clicked
Object obj = null;
EA.ObjectType otype = Repository.GetTreeSelectedItem(out obj);
//Si le type n'arrive pas a etre determiné
if (!Enum.IsDefined(typeof(EA.ObjectType), otype))
{
//Should not occur
String error = "Type indeterminé.";
MessageBox.Show(error, "Erreur");
}
//The user clicked on a package - try to determine the stereotype
else if (otype == EA.ObjectType.otPackage)
{
EA.Package p = (EA.Package)obj;
//If the package has no superpackage, it must be the very top package
//-> if the very top package is clicked, ALL will be validated
int ID = p.PackageID;
bool hasParent = false;
try
{
int dummy = p.ParentID;
if (dummy != 0)
hasParent = true;
}
catch (Exception e) { }
if (!hasParent)
{
s = "ROOT";
}
else
{
this.browse(Repository, ID, otype);
}
}
else
{
int ID = 0;
if (otype == EA.ObjectType.otDiagram)
{
ID = ((EA.Diagram)obj).DiagramID;
EA.Diagram d = Repository.GetDiagramByID(ID);
this.browse(Repository, ID, otype);
}
else if (otype == EA.ObjectType.otElement)
{
ID = ((EA.Element)obj).ElementID;
EA.Element e = Repository.GetElementByID(ID);
this.browse(Repository, ID, otype);
}
}
if (obj == null)
s = "From Main Menu";
}
//If the users clicks into a diagram we must determine to which package
//the diagram belongs
else if (Location == "Diagram")
{
int ID = 0;
try
{
Object obj = null;
EA.ObjectType otype = Repository.GetContextItem(out obj);
if (otype == EA.ObjectType.otDiagram)
{
ID = ((EA.Diagram)obj).DiagramID;
EA.Diagram d = Repository.GetDiagramByID(ID);
this.browse(Repository, ID, otype);
}
else if (otype == EA.ObjectType.otElement)
{
ID = ((EA.Element)obj).ElementID;
EA.Element e = Repository.GetElementByID(ID);
this.browse(Repository, ID, otype);
}
else
{
Repository.Models.GetAt(0);
s = "From Main Menu";
}
}
catch (Exception ex)
{ }
}
return s;
this.encours = true;
}

The following Perl script snippet (hopefully it's readable) demonstrates what to do to get the connectors:
my $dia = $rep->GetDiagramByGUID("{7EA250AD-F37A-4e9a-9C52-BF8FCA3D87F7}"); # access the diagram
for (my $i = 0 ; $i < $dia->DiagramObjects->Count; $i++) { # every object inside the diagram
my $do = $dia->DiagramObjects->GetAt($i);
my $e = $rep->GetElementByID($do->ElementID); # the according element
next unless $e->Type eq "Sequence"; # look only at life lines
for (my $j = 0 ; $j < $e->Connectors->Count; $j++) { # now go through its connectors
my $con = $e->Connectors->GetAt($j);
print $con->Type . "\n"; # will print Sequence
}
}

Thanks a lot for your help Thomas
Here's the code i translated in C#
if (otype == EA.ObjectType.otDiagram)
{
EA.Diagram diag = Repository.GetDiagramByID(ID);
foreach (EA.DiagramObject dobj in diag.DiagramObjects)
{
EA.Element el = Repository.GetElementByID(dobj.ElementID);
foreach (EA.Connector con in el.Connectors)
{
if (con.Type == "Sequence")
{
MessageBox.Show(con.Name);
}
}
}
}

Related

How to handle New transaction is not allowed because there are other threads running in the session for multiple calls or to save as list of Entities

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);
}

C# code works when it hits breakpoint otherwise does not when i disable all breakpoint [Winforms]

My code below runs perfectly when i try to debug applying breakpoint but when i disable breakpoints and run it again, it does not work perfectly. Here i am creating a non-stock item, now when it navigates to other page it does not show all the inserted rows.
I tried to make submit call async and put SaveNonStockItems() in await but it did not work
private void btnSubmit_Click(object sender, EventArgs e)
{
StringBuilder quoteDetailIDs = new StringBuilder();
foreach (DataGridViewRow dataGridViewRow in grdQuoteDetail.Rows)
{
if (dataGridViewRow.Cells["colSelected"].Value != null &&
dataGridViewRow.Cells["colSelected"].Value != DBNull.Value &&
(bool)dataGridViewRow.Cells["colSelected"].Value)
{
quoteDetailIDs.Append(dataGridViewRow.Cells["colQuoteDetailID"].Value + ", ");
}
}
StringBuilder quoteDetailIDsNonStock = new StringBuilder();
if(SaveNonStockItems())
{
foreach (DataGridViewRow dataGridViewRow in grdNonStocks.Rows)
{
if (dataGridViewRow.Cells["colSelectedNonStock"].Value != null &&
dataGridViewRow.Cells["colSelectedNonStock"].Value != DBNull.Value &&
(bool)dataGridViewRow.Cells["colSelectedNonStock"].Value)
{
quoteDetailIDsNonStock.Append(dataGridViewRow.Cells["colQuoteDetailID2"].Value + ", ");
}
}
// Remove trailing ', '
quoteDetailIDs.Append(quoteDetailIDsNonStock.ToString());
quoteDetailIDs.Remove(quoteDetailIDs.Length - 2, 2);
Guid orderID = Guid.Empty;
try
{
BeginInit("Converting " + _quotesModule.QuoteTypeInfo.TypeName + "# " + _quotesModule.QuoteHeader[0].QuoteHeaderID + " To Order...");
_quotesModule.ConvertToOrder(_quotesModule.QuoteHeader[0].QuoteHeaderID, _quotesModule.QuoteHeader[0].CustTreeNodeID,Guid.Empty,_quotesModule.QuoteHeader[0].SupplyChainNodeID, txtPONumber.Text, quoteDetailIDs.ToString(),
chkCopyItemNotes.Checked, rdoOpenOrder.Checked ? 1 : 2,
rdoOpenOrder.Checked ? 0 : ctrlVendor.SelectedSupplyChainNodeID,
ref orderID, SessionModule.Current.User.UnityUserID);
EndInit();
Global.AppResume();
if (orderID != Guid.Empty)
{
Navigate.ReOpenOrder(orderID);
}
DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
ErrorDialog.DisplayModal(ex);
EndInit();
Global.AppResume();
DialogResult = DialogResult.Cancel;
}
}
private bool SaveNonStockItems()
{
if (grdNonStocks.Rows.Count > 0)
{
foreach (DataGridViewRow dataGridViewRow in grdNonStocks.Rows)
{
if (dataGridViewRow.Cells["colSelectedNonStock"].Value != null &&
dataGridViewRow.Cells["colSelectedNonStock"].Value != DBNull.Value &&
(bool)dataGridViewRow.Cells["colSelectedNonStock"].Value)
{
string xml = CreateXml(dataGridViewRow);
if (xml != string.Empty)
{
try
{
int _skuID = ProductMaint.CreateNonStockingSku(xml, SessionModule.UserID); //Proc that inserts this
/* capture the item number for adding to the order (hack-ish) */
dataGridViewRow.Cells["colSkuID"].Value = _skuID;
}
catch (MercuryException mex)
{
/* non-stock creation failed */
ErrorDialog.DisplayModal("Non-stock creation failed.", mex.Message, true);
throw mex;
}
}
else
{
ErrorDialog.DisplayModal("Failed to generate creation parameters.");
return false;
}
}
}
}
return true;
}
private string CreateXml(DataGridViewRow dataGridViewRow)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlNode root = doc.CreateElement("NonStockingSku");
System.Xml.XmlNode sku = doc.CreateElement("Sku");
System.Xml.XmlAttribute attr = null;
doc.AppendChild(root);
root.AppendChild(sku);
attr = doc.CreateAttribute("ItemNumber");
attr.Value = dataGridViewRow.Cells["colItemNumber2"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("Description");
attr.Value = dataGridViewRow.Cells["colItemDescription2"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("ProductTypeID");
attr.Value = dataGridViewRow.Cells["colType"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("ProductLineID");
attr.Value = dataGridViewRow.Cells["colProductLine"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("ProductDepartmentID");
attr.Value = dataGridViewRow.Cells["colDepartment"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("Landed");
attr.Value = dataGridViewRow.Cells["colLanded"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("VendorSupplyChainNodeID");
attr.Value = dataGridViewRow.Cells["colVendor"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("ListPrice");
attr.Value = dataGridViewRow.Cells["colListPrice"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("Cost");
attr.Value = dataGridViewRow.Cells["colCost"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("QuoteDetailID");
attr.Value = dataGridViewRow.Cells["colQuoteDetailID2"].Value.ToString();
sku.Attributes.Append(attr);
attr = doc.CreateAttribute("Quantity");
attr.Value = dataGridViewRow.Cells["colQuantity"].Value.ToString();
sku.Attributes.Append(attr);
return doc.OuterXml;
}
}
public static int CreateNonStockingSku(string parametersXml, int unityUserID)
{
Proc p = new Proc("NonStockingSku_i");
p["#ParametersXml"] = parametersXml;
p["#UnityUserID"] = unityUserID;
p.Exec();
int skuID;
string message;
if (p["#SkuID"] != DBNull.Value)
{
skuID = (int)p["#SkuID"];
return skuID;
}
else
{
if (p["#Message"] != DBNull.Value)
{
message = p["#Message"].ToString();
}
else
{
message = "Unspecified error.";
}
throw new MercuryException(message);
}
}
I just want to know the reson for it to behave like this. I have never encountered such problem in winforms, Is it because i am saving in loop or what i can't find problem, its a headache cuz only way is find problem is DEBUGGING however when i debug the code it works fine and results show fine.
Also, Data is getting stored in DB correctly it just does not load correctly at the form it navigates to.

Get the count of resultsets/Tables returned from dapper .QueryMultiple Method

While using Dapper for multiple Query:
var result = sqlConnection.QueryMultiple(query, Parameters, commandType: commandType);
How can i get the table count returned from query? It has two overloaded implementation of .Read() method, which each time called, moves to next available result set (No result.Count() property). Eventually i want to put that number in a loop to iterate as many time as number of tables returned from query.
var reader = this.DbConnection.QueryMultipleAsync(sql, Params, commandType: CommandType.StoredProcedure).Result;
if(reader.IsConsumed == false)
{
DeviceTypeReport = reader?.ReadAsync<dynamic>().Result;
}
This is probably what you are looking for hope it helps.
This is probably what you are looking for hope it helps.
List<dynamic> data = new List<dynamic>();
while (reader.IsConsumed == false)
{
data.Add(await reader?.ReadAsync<dynamic>());
}
int totalRecordSet = data.Count;
public List NotificationExecuteMultiple(OutdoorRequest objreq, IConfiguration configuration)
{
var lst = new List<dynamic>();
using (DbConnection connection = new MySqlConnection(configuration.GetConnectionString("SquareHrConn")))
{
using (var dr = connection.QueryMultiple(ProcedureName, GetParamenter(objreq), commandType: CommandType.StoredProcedure))
{
while (dr.IsConsumed == false)
{
lst.Add(dr.Read());
}
}
}
return lst;
}
Consider the follwoing method to cover all cases
protected List<object> ExecuteMultiQuery<A, B, C, D, E, F, G, H, I, J>(string procedureName, DynamicParameters param = null)
{
List<object> result = new List<object>();
using (var connection = new SqlConnection(ConnectionManager.ConnectionString))
{
try
{
connection.Open();
using (var multi = connection.QueryMultiple(procedureName, param, commandType: CommandType.StoredProcedure, commandTimeout: 120))
{
var varA = multi.Read<A>();
if (varA != null) { result.Add(varA.ToList()); }
var varB = multi.Read<B>();
if (varB != null) { result.Add(varB.ToList()); }
var varC = multi.Read<C>();
if (varC != null) { result.Add(varC.ToList()); }
var varD = multi.Read<D>();
if (varD != null) { result.Add(varD.ToList()); }
var varE = multi.Read<E>();
if (varE != null) { result.Add(varE.ToList()); }
var varF = multi.Read<F>();
if (varF != null) { result.Add(varF.ToList()); }
var varG = multi.Read<G>();
if (varG != null) { result.Add(varG.ToList()); }
var varH = multi.Read<H>();
if (varH != null) { result.Add(varH.ToList()); }
var varI = multi.Read<I>();
if (varI != null) { result.Add(varI.ToList()); }
var varJ = multi.Read<J>();
if (varJ != null) { result.Add(varJ.ToList()); }
//if (varA != null) { result.Add(varA.ToList()); }
//if (resultSets > 1) { result.Add(multi.Read<B>().ToList()); }
//if (resultSets > 2) { result.Add(multi.Read<C>().ToList()); }
//if (resultSets > 3) { result.Add(multi.Read<D>().ToList()); }
//if (resultSets > 4) { result.Add(multi.Read<E>().ToList()); }
//if (resultSets > 5) { result.Add(multi.Read<F>().ToList()); }
//if (resultSets > 6) { result.Add(multi.Read<G>().ToList()); }
//if (resultSets > 7) { result.Add(multi.Read<H>().ToList()); }
//if (resultSets > 8) { result.Add(multi.Read<I>().ToList()); }
//if (resultSets > 9) { result.Add(multi.Read<J>().ToList()); }
return result;
}
}
catch (System.Exception e)
{
string message = e.Message;
}
}
return result;
}

How to insert ContentContol in footnote with specific range word.interop

How to go add content control in specific start and end range of footnote? I can add content control in document.range, but I am unable to add in footnote, please help to do this. If anyone reply quickly, I will be proved of you.
public void FindItalicFootnote(String FindText)
{
foreach (Word.Footnote footNote in Word.Document.Footnotes)
{
Word.Range RngFind = footNote.Range;
RngFind.Find.Forward = true;
if (RngFind.Find.Execute(FindText))
{
while (RngFind.Find.Found)
{
RngFind.Select();
object strtRange = Word.Selection.Range.Start;
object endRange = Word.Selection.Range.End;
string placeHolder = "";
bool findCase = false;
if (Word.Selection.Range.ParentContentControl == null && Word.Selection.Range.ContentControls.Count == 0)
{
RngFind.Select();
while (Word.Selection.Previous(Unit: Word.WdUnits.wdWord, Count: 1).Font.Italic == -1)
{
Word.Selection.Previous(Unit: Word.WdUnits.wdWord, Count: 1).Select();
strtRange = Word.Selection.Range.Start;
placeHolder = "{VerifiedBy='Italic'}";
findCase = true;
}
Word.ContentControl CC = RngFind.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText,
footNote.range(strtRange, endRange));
//my query is, how to say footNote.range(start, end), in main part I wrote as Word.Document.range(startRange, endRange)
CC.Title = "Case Reference";
CC.Tag = Guid.NewGuid().ToString();
CC.SetPlaceholderText(Text: placeHolder);
}
RngFind.Find.Execute(FindText);
}
}
}
}
Regards,
Saran

How to make meeting (in calendar) in outlook 2007 using C#?

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"
);

Categories

Resources