How to make meeting (in calendar) in outlook 2007 using C#? - 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"
);
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); }
Why photon room properties not found in lobby?
The player can create a room with certain properties that once created I set them and for lobby so that I can then display them in the lobby. Function to create room: public void OnCreateRoomButtonClicked() { RoomOptions roomOptions = new RoomOptions(); roomOptions.IsOpen = true; roomOptions.IsVisible = true; string roomName; string gameMap; if (gameMode.Equals("CarMeeting")) { gameMap = carMeetingModeMaps[mapIndex].sceneName; roomName = roomNameCarMeetingModeInputField.text; roomOptions.MaxPlayers = 4; } else { gameMap = racingModeMaps[mapIndex].sceneName; roomName = roomNameRacingModeInputField.text; roomOptions.MaxPlayers = 2; } if (!CheckIfRoomAlreadyExists(roomName)) { StartCoroutine(EShowWarning()); } else { roomOptions.CustomRoomProperties = new Hashtable(); roomOptions.CustomRoomProperties.Add("GameMap", gameMap); roomOptions.CustomRoomProperties.Add("GameMode", gameMode); roomOptions.CustomRoomProperties.Add("RaceMode", raceMode); roomOptions.CustomRoomProperties.Add("InRace", false); string[] customLobbyProperties = new string[4]; customLobbyProperties[0] = "GameMap"; customLobbyProperties[1] = "GameMode"; customLobbyProperties[2] = "RaceMode"; customLobbyProperties[3] = "InRace"; roomOptions.CustomRoomPropertiesForLobby = customLobbyProperties; PhotonNetwork.CreateRoom(roomName, roomOptions, null, null); } } Function display rooms in lobby: public override void OnRoomListUpdate(List<RoomInfo> roomInfo) { Debug.Log("Rooms found " + roomInfo.Count); bool roomFound = false; foreach (RoomInfo room in roomInfo) { if (room.RemovedFromList) { int index = roomUIs.FindIndex(x => x.roomNameString.Equals(room.Name)); if (index != -1) { Destroy(roomUIs[index].gameObject); roomUIs.RemoveAt(index); } } else { CMRoomUI cacheRoomUI = roomUIs.Find(x => x.roomNameString.Equals(room.Name)); if (cacheRoomUI != null) { if (room.CustomProperties["GameMode"].ToString().Equals("CarMeeting")) cacheRoomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString()); else cacheRoomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString() , room.CustomProperties["RacingMode"].ToString()); } else { if (room.IsOpen) { CMRoomUI roomUI = Instantiate(roomUIPrefab.gameObject, roomUIParent).GetComponent<CMRoomUI>(); roomUIs.Add(roomUI); if (room.CustomProperties["GameMode"].ToString().Equals("CarMeeting")) roomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString()); else cacheRoomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString() , room.CustomProperties["RaceMode"].ToString()); } } } } if (roomUIs.Count > 0) roomFound = true; noRoomTextObj.SetActive(!roomFound); } After I create a room if another player connects to the looby, I display the cameras visible with those properties, but the property "RaceMode" does not exist.
How to fill entry with missing when nothing was writte in in xamarin app?
I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this: if (liveryEntry.Text == null) { liveryEntry.Text = "Missing"; } if (registrationEntry.Text == null) { registrationEntry.Text = "Missing"; } if (airportEntry == null) { airportEntry.Text = "Missing"; } if (commentEntry == null) { commentEntry.Text = "Missing"; } But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that? Here is full code of method: private async void buttonImport_Clicked(object sender, EventArgs e) { var db = new SQLiteConnection(_dbPath); db.CreateTable<Airplane>(); collectionPlane.IsVisible = false; collectionAirline.IsVisible = false; collectionLivery.IsVisible = false; collectionRegistration.IsVisible = false; collectionAirport.IsVisible = false; try { if (liveryEntry.Text == null) { liveryEntry.Text = "Missing"; } if (registrationEntry.Text == null) { registrationEntry.Text = "Missing"; } if (airportEntry == null) { airportEntry.Text = "Missing"; } if (commentEntry == null) { commentEntry.Text = "Missing"; } if (planeEntry.Text != null && airlineEntry.Text != null) { var url = PhotoPick(); int i = 1; int same = 0; string fileName = registrationEntry.Text; for (int b = 1; b <= GetNumberPhotos(); b++) { if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null) { var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b); string match = rowData.Registration; if (fileName == match) { same++; } } } i = 1 + same; fileName = registrationEntry.Text + "-" + i; var thumbUrl = CreateThumbnail(await url, fileName); var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault(); Airplane airplane = new Airplane() { Id = (maxPK == null ? 1 : maxPK.Id + 1), SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text, Plane = planeEntry.Text.ToUpper(), Airline = airlineEntry.Text, Livery = liveryEntry.Text, Registration = registrationEntry.Text.ToUpper(), Airport = airportEntry.Text.ToUpper(), Date = datePicker.Date, Comment = commentEntry.Text, Url = await url, ThumbnailUrl = thumbUrl }; db.Insert(airplane); await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK"); planeEntry.Text = ""; airlineEntry.Text = ""; liveryEntry.Text = ""; registrationEntry.Text = ""; airportEntry.Text = ""; commentEntry.Text = ""; } else await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK"); } catch { await DisplayAlert("Error", "Something went wrong", "Try again"); } }
It is probably some kind of bug or missunderstanding #Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.
why my oxi file still in the IN Folder and integrated 2 times and more in the data base?
I have an automaton to integrate my files (.oxi = xml file ) in the DB, but i have a problem that the same file is integrated 2 times and more . I did many precaution to prevent that using the move function from the IN path to the archive path after the integration but it still not working . After that i used the copy to the archive path and delete the file from the IN path after the integration succed but it still not working. Can any body explain to me what the problem exactly ? public class Doc { public XmlDocument xDoc { get; set; } public String Path { get; set; } public String file_name { get; set; } } public class Job { public String Name { get; set; } public String PathIn { get; set; } public String PathArchive { get; set; } public String PathError { get; set; } public String StatutLotOut { get; set; } } // start the job called every period by the timer public void start() { //General.addLog("hello, i am started"); UpdateText(); List<Job> jobs = get_jobs(); foreach (Job job in jobs) { List<Doc> docs = new List<Doc>(); //read all xml document inside the IN forlder path in docs = gen.read_oxi(job); foreach (Doc doc in docs) { try { TransferOpex.doc = doc; TransferOpex.job = job; xml_serialisation(doc.xDoc, job); gen.moveDocToArchiverPath(); break; } catch (Exception ex) { General.addText("\n error : " + ex.ToString()); General.addLog(ex.ToString()); gen.moveDocToErrorPath(); } } } } public void moveDocToArchiverPath() { if (File.Exists(TransferOpex.doc.Path)) { string Path2 = Path.Combine(TransferOpex.job.PathArchive, TransferOpex.doc.file_name + ".oxi"); if (File.Exists(Path2)) File.Delete(Path2); File.Copy(TransferOpex.doc.Path, Path2,true); addText("\n file " + TransferOpex.doc.Path + " copied to Archive path at" + DateTime.Now); General.addLog("\n file " + TransferOpex.doc.Path + " copied to Archive path at" + DateTime.Now); if (File.Exists(TransferOpex.doc.Path)) { while (!IsFileReady(TransferOpex.doc.Path)) { } File.Delete(TransferOpex.doc.Path); addText("\n file " + TransferOpex.doc.Path + " deleted from in path at" + DateTime.Now); General.addLog("\n file " + TransferOpex.doc.Path + " deleted from in path at" + DateTime.Now); } } } public static bool IsFileReady(string filename) { // If the file can be opened for exclusive access it means that the file // is no longer locked by another process. try { using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None)) return inputStream.Length > 0; } catch (Exception) { return false; } } I use timer to check every time if there are new files in the IN Forlder SetTimer(); private void SetTimer() { TextAffichage += "\n The application started at " + DateTime.Now; General.addText("\n Timer = " + gen.ReadSetting("Timer") + "ms"); General.addText("\n configPath = " + configPath); General.addText(" \n connectionStrings = " + gen.ReadSetting("connectionStrings")); General.addLog("Started"); UpdateText(); // Create a timer with a x second interval, you can find the value of x inside app.config. aTimer = new System.Timers.Timer(int.Parse(gen.ReadSetting("Timer"))); // Hook up the Elapsed event for the timer. aTimer.Elapsed += OnTimedEvent; aTimer.AutoReset = true; aTimer.Enabled = true; } private void OnTimedEvent(Object source, ElapsedEventArgs e) { start(); } And this the function that make the integration in the DB public void xml_serialisation(XmlDocument doc, Job job) { Lot lot = new Lot(); classes.Image image = new classes.Image(); XmlNodeList batchs = doc.GetElementsByTagName("Batch"); XmlNode batch = batchs[0]; String BatchIdentifier = batch.Attributes["BatchIdentifier"] != null ? batch.Attributes["BatchIdentifier"].Value : "Unknow value"; String NUM_LOT = BatchIdentifier; String TransportId = batch.Attributes["TransportId"] != null ? batch.Attributes["TransportId"].Value : "Unknow value"; String NUM_SCANNER = TransportId; String StartTime = doc.GetElementsByTagName("Batch")[0].Attributes["StartTime"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["StartTime"].Value : "Unknow value"; //String ID_lot = DateTime.Parse(StartTime).ToString("yyyyMMdd") + "" + NUM_LOT + "" + NUM_SCANNER; String ID_lot = TransferOpex.doc.file_name; String NUM_NB_IMAGE = doc.GetElementsByTagName("EndInfo")[0].Attributes["NumPages"] != null ? doc.GetElementsByTagName("EndInfo")[0].Attributes["NumPages"].Value : "Unknow value"; String EndTime = doc.GetElementsByTagName("EndInfo")[0].Attributes["EndTime"] != null ? doc.GetElementsByTagName("EndInfo")[0].Attributes["EndTime"].Value : "Unknow value"; String JobName = doc.GetElementsByTagName("Batch")[0].Attributes["JobName"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["JobName"].Value : "Unknow value"; String ImageFilePath = doc.GetElementsByTagName("Batch")[0].Attributes["ImageFilePath"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["ImageFilePath"].Value : "Unknow value"; //String OperatorName = doc.GetElementsByTagName("Batch")[0].Attributes["OperatorName"] != null ? doc.GetElementsByTagName("Batch")[0].Attributes["OperatorName"].Value : "Unknow value"; String OperatorName = gen.ReadSetting("OperatorName"); //instatiate Class lot lot.TXT_TYPE_LOT = JobName; lot.ID_LOT = long.Parse(ID_lot); lot.NUM_NB_IMAGE = int.Parse(NUM_NB_IMAGE); lot.DAT_DEBUT_NUM = DateTime.Parse(StartTime); lot.DAT_FIN_NUM = DateTime.Parse(EndTime); lot.ID_STATUT = int.Parse(job.StatutLotOut);// attention!!!!!!!!!!!, faut le recuperer de la configuration lot.NUM_SCANNER = int.Parse(NUM_SCANNER); lot.TXT_OPERATEUR = OperatorName; XmlNodeList pages = doc.GetElementsByTagName("Page"); List<classes.Image> images = new List<classes.Image>(); List<Icr> icrs = new List<Icr>(); foreach (XmlNode page in pages) { String BatchSequence = page.Attributes["BatchSequence"] != null ? page.Attributes["BatchSequence"].Value : "Unknow value"; XmlNodeList imgs = null; if (page.SelectNodes("Image") != null && page.SelectNodes("Image").Count > 0) { imgs = page.SelectNodes("Image"); } String AuditTrail = ""; if (page.SelectNodes("AuditTrail") != null && page.SelectNodes("AuditTrail").Count >0) { AuditTrail = page.SelectNodes("AuditTrail")[0].Attributes["Text"] != null ? page.SelectNodes("AuditTrail")[0].Attributes["Text"].Value : "Unknow value"; } String PageName = page.Attributes["PageName"] != null ? page.Attributes["PageName"].Value : "Unknow value"; // get node list from the config.xml file XmlNodeList Recos = gen.getNodelList("Reco"); foreach (XmlNode Reco in Recos) { String Balise = Reco.Attributes["Balise"] != null ? Reco.Attributes["Balise"].Value : ""; String TagValue = Reco.Attributes["TagValue"] != null ? Reco.Attributes["TagValue"].Value : ""; String TypeIcr = Reco.Attributes["TypeIcr"] != null ? Reco.Attributes["TypeIcr"].Value : ""; XmlNodeList Balises = page.SelectNodes(Balise) != null ? page.SelectNodes(Balise) : null; if (Balises != null) { foreach (XmlNode balise in Balises) { //instatiate Class Icr String Index = balise.Attributes["Index"] != null ? balise.Attributes["Index"].Value : ""; Icr icr = new Icr(); // this instance will be saved icr.save_it = true; icr.ID_LOT = lot.ID_LOT; icr.NUM_SEQUENCE = int.Parse(BatchSequence); icr.NUM_INDEX = Index; if (Balise == "Barcode") { icr.TXT_ICR = balise.Attributes["Value"].Value; if (balise.Attributes["Type"] != null) { if (balise.Attributes["Type"].Value == TagValue) { icr.TXT_TYPE = TypeIcr; } else { icr.TXT_TYPE = "unknow value"; // prevent the instance to be saved in the DB icr.save_it = false; } } } else if (Balise == "markDetect") { icr.TXT_ICR = balise.Attributes["Result"].Value; icr.TXT_TYPE = Reco.Attributes["TypeIcr"].Value; } else if (Balise == "Micr") { icr.TXT_ICR = balise.Attributes["Value"].Value; icr.TXT_TYPE = Reco.Attributes["TypeIcr"].Value; } else if (Balise == "OCR") { icr.TXT_ICR = balise.Attributes["Value"].Value; icr.TXT_TYPE = Reco.Attributes["TypeIcr"].Value; } else { icr.save_it = false; } if (icr.TXT_ICR == "") { icr.save_it = false; } if (icr.save_it) icrs.Add(icr); } } } if(imgs !=null) foreach (XmlNode img in imgs) { String Filename = img.Attributes["Filename"] != null ? img.Attributes["Filename"].Value : "Unknow value"; if (Filename == "" && gen.ReadSetting("acceptBlankImage") == "0") { General.addLog("can't add blank image( image without path ), in order to do that please change the value of acceptBlankImage to 1 "); //create exceprion intentionally outside of the catch int i = 0; int j = 1 / i; } try { String Length = img.Attributes["Length"] != null ? img.Attributes["Length"].Value : "Unknow value"; String Height = img.Attributes["Height"] != null ? img.Attributes["Height"].Value : "Unknow value"; image = new classes.Image(); image.ID_LOT = lot.ID_LOT; image.TXT_CHEMIN_IMAGE = ImageFilePath + "\\" + Filename; String machine = gen.ReadSetting("machine"); //String index = ""; //if (machine == "IBML") //{ // index = Filename[0] + "" + Filename[1]; //} //else if (machine == "OPEX") //{ // String file_name_without_extension = Path.GetFileNameWithoutExtension(Filename); // int Lenght = file_name_without_extension.Length; // int firstrightcharindex = Lenght - 1; // index = file_name_without_extension[firstrightcharindex] + ""; //} String expression = gen.ReadSetting("EXPRESSION_NUM_TYPE_PAGE"); String index = ""; if (expression[0] == 'g' || expression[0] == 'G') { int gauche = (int)char.GetNumericValue(expression[1]);//donne le number de caratère faut le recuperer à droite for (int i = 0; i < gauche; i++) { index += Filename[i] + ""; } } else if (expression[0] == 'd' || expression[0] == 'D') { int droite = (int)char.GetNumericValue(expression[1]);//donne le number de caratère faut le recuperer à droite String file_name_without_extension = Path.GetFileNameWithoutExtension(Filename); int Lenght = file_name_without_extension.Length; int firstrightcharindex = Lenght - 1; for (int i = firstrightcharindex; i > firstrightcharindex - droite; i--) { index += file_name_without_extension[i] + ""; } index = General.Reverse(index); } image.TXT_ENDOS = AuditTrail; image.NUM_SEQUENCE = int.Parse(BatchSequence); image.NUM_PAGE = int.Parse(BatchSequence); image.NUM_TYPE_PAGE = int.Parse(getTypeImage(PageName, index)); //attention !!!!!!, faut le recuperer de la configuration image.ID_STATUT = int.Parse(gen.ReadSetting("ID_STATUT")); //attention!!!!!!!, faut le recuperer de la configuration image.Length = Length; image.Height = Height; images.Add(image); } catch (Exception ex) { } } } DB.Database db = new DB.Database(); // save into data base db.save_to_db(lot, images, icrs); } //get the job list from config.xml and serialize into object public List<classes.Job> get_jobs() { XmlNodeList jobsNodelist = gen.getNodelList("Job"); List<Job> jobs = new List<Job>(); foreach (XmlNode j in jobsNodelist) { Job job = new Job(); job.Name = j.Attributes["Name"] != null ? j.Attributes["Name"].Value : "unknow value"; job.PathArchive = j.Attributes["PathArchive"] != null ? j.Attributes["PathArchive"].Value : "unknow value"; job.PathIn = j.Attributes["PathIn"] != null ? j.Attributes["PathIn"].Value : "unknow job"; job.StatutLotOut = j.Attributes["StatutLotOut"] != null ? j.Attributes["StatutLotOut"].Value : "unknow job"; job.PathError = j.Attributes["PathError"] != null ? j.Attributes["PathError"].Value : "unknow job"; jobs.Add(job); } return jobs; }
Not all code paths return error in c#
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) {