internal static OgDocument FromNotes(NotesDocument document) { var outRegStr = document.GetFieldValue("Out_RegistrationDate"); DateTime?outRegDate = null; if (!string.IsNullOrEmpty(outRegStr)) { outRegDate = DateTime.Parse(outRegStr); } return(new OgDocument(document.GetFieldValue("id")) { DeliveryType = document.GetFieldValue("delivery_type"), Solution = ParseSolution(document.GetFieldValue("solution")), Specialization = document.GetFieldValue("Specialization"), OutRegistrationDate = outRegDate, OutRegistrationNumber = document.GetFieldValue("Out_RegistrationNumber"), AcceptanceDate = DateTime.Parse(document.GetFieldValue("acceptance_date")), RegistrationDate = DateTime.Parse(document.GetFieldValue("registration_date")), Subject = document.GetFieldValue("subject"), GroudId = document.GetFieldValue("group_id"), DeclarantTitle = document.GetFieldValue("declarant_title"), Number = document.GetFieldValue("registration_number") }); }
/// <summary> /// Sends the via notes. /// </summary> /// <param name="settings">Any settings needed</param> /// <param name="month">The month.</param> /// <param name="year">The year.</param> /// <param name="fullFilename">The full filename.</param> /// <param name="emailAddress">The email address.</param> /// <param name="password">The password required to submit</param> public void Send(Settings settings, string month, string year, string fullFilename, string emailAddress, SecureString password = null) { // Two digit month and four digit year NotesSession session = new NotesSession(); session.Initialize(); NotesDatabase database = session.GetDatabase("Pride/Tessella", "mail\\waldm.nsf"); if (!database.IsOpen) { database.Open(); } NotesDocument document = database.CreateDocument(); document.ReplaceItemValue("Form", "Memo"); document.ReplaceItemValue("Sendto", emailAddress); string subject = settings.StaffID + " " + month + "/" + year; document.ReplaceItemValue("Subject", subject); NotesRichTextItem attachment = document.CreateRichTextItem("Attachment"); attachment.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, string.Empty, fullFilename, "Attachment"); document.SaveMessageOnSend = true; document.ReplaceItemValue("PostedDate", DateTime.Now); document.Send(false, emailAddress); }
public IEnumerable <string> GetAttachments(NotesDocument doc, string filterName = null) { bool hasAttachment = false; if (doc.HasEmbedded) { foreach (NotesItem item in (object[])doc.Items) { if (item.Name.Equals("$FILE")) { object[] values = (object[])item.Values; var filename = values[0].ToString(); if (!string.IsNullOrEmpty(filterName) && !filename.Contains(filterName)) { continue; } var path = Path.Combine(Path.GetTempPath(), filename); var attach = doc.GetAttachment(filename); attach.ExtractFile(path); hasAttachment = true; yield return(path); } } if (!hasAttachment) { throw new NoAttachmentException(); } yield break; } throw new NoAttachmentException(); }
private IEnumerable <NotesItem> GetNoteItem(NotesDocument doc) { Array itemArray = (Array)doc.Items; if (itemArray.Length > 0) { UpdateText(lblStatus, "Get Notes Items..."); UpdateText(lblNotesItemTotal, itemArray.Length.ToString()); for (int index = 0; index < itemArray.Length; index++) { UpdateText(lblNotesItemCount, (index + 1).ToString()); NotesItem item = (NotesItem)itemArray.GetValue(index); yield return(item); UpdateText(lblStatus, "Get Next Notes Items..."); //Application.DoEvents(); } UpdateText(lblStatus, "Get Notes Items Completed."); } }
/// <summary> /// Lotus Send E-Mail /// </summary> /// <param name="sendTo"></param> /// <param name="copyTo"></param> /// <param name="subject"></param> /// <param name="content"></param> /// Owner:Andy Gao 2011-08-22 09:32:50 public static void LotusSendEMail(string[] sendTo, string[] copyTo, string subject, string content) { NotesSession ns = new NotesSession(); ns.Initialize(lotusPassword); NotesDatabase ndb = ns.GetDatabase(lotusServer, lotusFile, false); NotesDocument doc = ndb.CreateDocument(); doc.ReplaceItemValue(LOTUS_SENDTO, sendTo); doc.ReplaceItemValue(LOTUS_COPYTO, copyTo); doc.ReplaceItemValue(LOTUS_SUBJECT, subject); NotesRichTextItem rti = doc.CreateRichTextItem(LOTUS_BODY); rti.AppendText(content); object recipients = doc.GetItemValue(LOTUS_SENDTO); doc.Send(false, ref recipients); Marshal.ReleaseComObject(rti); Marshal.ReleaseComObject(doc); Marshal.ReleaseComObject(ndb); Marshal.ReleaseComObject(ns); rti = null; doc = null; ndb = null; ns = null; }
public void SendMail() { try { NotesSession ns = new NotesSessionClass(); ns.Initialize(pwd); NotesDatabase ndb = ns.GetDatabase(serverName, nsfFile, false); NotesDocument doc = ndb.CreateDocument(); doc.ReplaceItemValue("Form", "Memo"); string[] sendtoString = mailTo.ToArray(); doc.ReplaceItemValue("SendTo", sendtoString); doc.ReplaceItemValue("Subject", subject); NotesRichTextItem rt = doc.CreateRichTextItem("Body"); rt.AppendText(body); if ((attFileName != null) && (attFileName.Count > 0)) { NotesRichTextItem item = doc.CreateRichTextItem("attachment"); foreach (string att in attFileName) { item.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, "", att, "attachment"); } } object obj = doc.GetItemValue("SendTo"); doc.Send(false, ref obj); } catch (Exception ex) { throw ex; } }
internal static OgResult FromNotes(NotesDocument document) { return(new OgResult(document.GetFieldValue("id")) { CloseDate = DateTime.Parse(document.GetFieldValue("date_fact")), ReferenceNumber = document.GetFieldValue("reference_number"), DocumentGroupId = document.GetFieldValue("document_groupID") }); }
internal static LetterDocument FromNotes(NotesDocument document) { return(new LetterDocument(document.GetFieldValue("id")) { OutNum = document.GetFieldValue("Out_RegistrationNumber"), Recipient = document.GetFieldValue("Recipient"), RecipientId = document.GetFieldValue("recipient_id"), OutDate = DateTime.Parse(document.GetFieldValue("Out_RegistrationDate")), GroudId = document.GetFieldValue("group_id") }); }
private static void SendUsingLotusNotes(string[] mailingList, IMessage message) { string serverName = WebConfigurationManager.AppSettings["LotusNotesServerName"]; string mailFile = WebConfigurationManager.AppSettings["LotusNotesMailFileName"]; string password = WebConfigurationManager.AppSettings["LotusNotesPassword"]; string[] sendTo = mailingList; string[] copyTo = { }; string replyTo = message.ReplyTo; string blindCopyTo = ""; string subject = message.Subject; //Create new notes session NotesSession notesSession = new NotesSession(); notesSession.Initialize(password); //Get and open NotesDataBase NotesDatabase notesDataBase = notesSession.GetDatabase(serverName, mailFile, false); if (!notesDataBase.IsOpen) { notesDataBase.Open(); } //Create the notes document NotesDocument notesDocument = notesDataBase.CreateDocument(); //Set document type notesDocument.ReplaceItemValue("Form", "Memo"); //Set notes memo fields (To: CC: Bcc: Subject etc) notesDocument.ReplaceItemValue("SendTo", sendTo); notesDocument.ReplaceItemValue("CopyTo", copyTo); notesDocument.ReplaceItemValue("BlindCopyTo", blindCopyTo); notesDocument.ReplaceItemValue("ReplyTo", replyTo); notesDocument.ReplaceItemValue("Subject", subject); //Set notes Body as HTML NotesStream notesStream = notesSession.CreateStream(); notesStream.WriteText(message.Body); notesStream.WriteText(""); notesStream.WriteText(message.Link); NotesMIMEEntity mimeItem = notesDocument.CreateMIMEEntity("Body"); mimeItem.SetContentFromText(notesStream, "text/html; charset=UTF-8", MIME_ENCODING.ENC_NONE); notesDocument.Send(false); }
public IActionResult Put([FromBody] NotesDocument note) { if (string.IsNullOrEmpty(note.Id)) { return(BadRequest("Note does not have an Id")); } using (var session = _store.OpenSession()) { session.Store(note); session.SaveChanges(); return(Ok(new { id = note.Id })); } }
public IActionResult Post([FromBody] NotesDocument note) { if (!string.IsNullOrEmpty(note.Id)) { return(BadRequest("Note Id is already populated")); } note.TimeOfEntry = DateTime.Now; using (var session = _store.OpenSession()) { session.Store(note); session.SaveChanges(); return(Ok(new { id = note.Id })); } }
/// <summary> /// 发送新信件 /// </summary> /// <param name="pSupervisors">抄送人</param> /// <param name="pSendSecret">密送人</param> /// <param name="pSubject">主题</param> /// <param name="strMailContent">内容</param> /// <returns></returns> public bool SendMailInfo(object pSupervisors, object pSendSecret, object pSubject, string strMailContent) { bool bResult = false; NotesDocument pMailDocument = null; NotesRichTextItem pContentItem = null; try { pMailDocument = this.pNotesDatabase.CreateDocument(); pMailDocument.ReplaceItemValue("Form", "Memo"); pMailDocument.ReplaceItemValue("CopyTo", pSupervisors); //抄送 pMailDocument.ReplaceItemValue("BlindCopyTo", pSendSecret); //密送 pMailDocument.ReplaceItemValue("Subject", pSubject); pMailDocument.ReplaceItemValue("PostedDate", DateTime.Now.ToString()); pContentItem = pMailDocument.CreateRichTextItem("Body"); pContentItem.AppendText(strMailContent); object pSendOwner = this._strUserName; pMailDocument.Send(false, ref pSendOwner); bResult = true; } catch (Exception ex) { this.strMessage = ex.Message; bResult = false; } finally { if (pContentItem != null) { Marshal.ReleaseComObject(pContentItem); } if (pMailDocument != null) { Marshal.ReleaseComObject(pMailDocument); } pContentItem = null; pMailDocument = null; } return(bResult); }
internal static string GetFieldValue(this NotesDocument doc, string name) { foreach (NotesItem item in (object[])doc.Items) { if (item.Name.ToLower().Equals(name.ToLower())) { object[] values = (object[])item.Values; //return values[0].ToString(); return(values.First(value => value != null) .ToString() .Trim()); } } //throw new NoFieldFoundException(); return(null); }
public AttachmentModel(NotesDocument document, NotesItem item) { if (!IsAttachmentItem(item)) { throw new ArgumentException("Item is not an attachment", nameof(item)); } var name = ((IEnumerable)item.Values).Cast <string>().First(); embeddedObject = document.GetAttachment(name); FileSize = embeddedObject.FileSize; Name = embeddedObject.Name; Source = embeddedObject.Source; EmbedType = embeddedObject.type; }
public NotesDocument GetNotesDocument(string xmlString) { var document = new NotesDocument(); document.Header.LineI = Obveznik.Naziv; document.Header.LineII = Obveznik.NazivGradaIliOpcine + "," + Obveznik.UlicaIKucniBroj; document.TitleI = "Bilješke uz financijske izvještaje poduzetnika"; document.TitleII = String.Format("za razdoblje {0:dd.MM.yyyy.} do {1:dd.MM.yyyy.} godine", this.DatumOd, this.DatumDo); var SectionI = new Section("I. INFORMACIJE O DRUŠTVU", Obveznik.GetNotes()); document.Sections.Add(SectionI); document.Sections.AddRange(GetStaticSections(xmlString)); var SectionV = new Section("V. RAČUN DOBITI I GUBITKA", RDG.GetNotes()); document.Sections.Add(SectionV); var SectionVI = new Section("VI. BILANCA", Bilanca.GetNotes()); document.Sections.Add(SectionVI); var endNote = new Paragraph() { Title = "Objava financijskih izvještaja", Text = String.Format("Uprava društva je svojom odlukom i ovjerom financijskih izvještaja prihvatila financijske izvještaje za {0}. godinu i odobrila njihovu objavu.", Godina) }; var SectionVII = new Section("VII. PRIHVAĆANJE I OBJAVA FINANCIJSKIH IZVJEŠTAJA OD STRANE UPRAVE DRUŠTVA", new List <Entry>() { endNote }); document.Sections.Add(SectionVII); document.Footer.Left = new Paragraph() { Title = "Voditelj računovodstva:", Text = Obveznik.VoditeljRacunovodstva }; document.Footer.Right = new Paragraph() { Title = "Direktor", Text = Obveznik.OvlastenaOsoba }; return(document); }
private CalendarEvent GetCallendarEvent(NotesDocument Current, int RepeatIndex) { CalendarEvent e = new CalendarEvent(); try { e.Starts = (DateTime)((object[])Current.GetItemValue("StartDateTime"))[RepeatIndex]; e.Ends = (DateTime)((object[])Current.GetItemValue("EndDateTime"))[RepeatIndex]; e.Title = (string)((object[])Current.GetItemValue("Subject"))[0]; e.Location = (string)((object[])Current.GetItemValue("Room"))[0] + " " + (string)((object[])Current.GetItemValue("Location"))[0]; } catch (Exception ex) { throw ex; } return e; }
public DocumentModel(LotusNotesWrapper wrapper, NotesDocument document) { this.document = document; LoadEmailContent(wrapper); Authors = ((IEnumerable)document.Authors).Cast <string>().ToArray(); Created = document.Created; EmbeddedObjects = document.EmbeddedObjects; HasEmbedded = document.HasEmbedded; HttpURL = document.HttpURL; IsDeleted = document.IsDeleted; IsNewNote = document.IsNewNote; IsProfile = document.IsProfile; IsResponse = document.IsResponse; IsSigned = document.IsSigned; IsUIDocOpen = document.IsUIDocOpen; IsValid = document.IsValid; Key = document.Key; LastAccessed = document.LastAccessed; LastModified = document.LastModified; NameOfProfile = document.NameOfProfile; NoteID = document.NoteID; NotesURL = document.NotesURL; ParentView = document.ParentView; Responses = document.Responses; SentByAgent = document.SentByAgent; Signer = document.Signer; SignOnSend = document.SignOnSend; Size = document.Size; Unid = document.UniversalID; IsEncrypted = document.IsEncrypted; Items = new Lazy <DocumentItemModel[]>(() => GetItems(document)); Subject = document.GetItemValue(ItemFieldNames.Subject)[0]; From = document.GetItemValue(ItemFieldNames.From).ToString(); To = ((IEnumerable)document.GetItemValue(ItemFieldNames.SendTo)).Cast <string>().ToArray(); Cc = ((IEnumerable)document.GetItemValue(ItemFieldNames.CopyTo)).Cast <string>().ToArray(); }
public KeyValuePair <string, NotesViewResultSet[]>[] PullNotesView(string[] ViewNames, string server, string database, string password) { if (ViewNames == null || ViewNames.Length == 0 || ViewNames.ToList().Distinct().Count() != ViewNames.Length) { throw new ArgumentException(); } else { List <KeyValuePair <string, NotesViewResultSet[]> > results = new List <KeyValuePair <string, NotesViewResultSet[]> >(); NotesSession notesSession = new Domino.NotesSession(); notesSession.Initialize(password); NotesDatabase notesDatabase = notesSession.GetDatabase(server, database, false); for (int i = 0; i < ViewNames.Length; i++) { List <NotesViewResultSet> result = new List <NotesViewResultSet>(); Domino.NotesView notesView; string view = ViewNames[i]; notesView = notesDatabase.GetView(view); NotesViewEntryCollection notesViewCollection = notesView.AllEntries; for (int rowCount = 1; rowCount <= notesViewCollection.Count; rowCount++) { NotesViewEntry viewEntry = notesViewCollection.GetNthEntry(rowCount); NotesDocument document = viewEntry.Document; Array notesThings = document.Items as Array; for (int j = 0; j < notesThings.Length; j++) { NotesItem notesItem = (notesThings.GetValue(j) as Domino.NotesItem); result.Add(new NotesViewResultSet() { RecordID = rowCount, Name = notesItem.Name, Value = notesItem.Text }); } } results.Add(new KeyValuePair <string, NotesViewResultSet[]>(view, result.ToArray())); } return(results.ToArray()); } }
public void SendMailIBM(string mailTo, List <string> mailCC, string mailTitle, string IDyc, string date, string username, string mbody) { try { NotesSession nSession = new NotesSession(); nSession.Initialize("12345678"); NotesDatabase nDatabase = nSession.GetDatabase("meiko_notes_hanoi2/SOUMU", "mail\\hrsystem.nsf"); NotesDocument nDocument = nDatabase.CreateDocument(); string[] recipients = { "tu.nguyenduy/SOUMU", "*****@*****.**" }; nDocument.ReplaceItemValue("Form", "Memo"); nDocument.ReplaceItemValue("SentTo", recipients); //To field nDocument.ReplaceItemValue("Subject", "Message subject"); //message subject nDocument.ReplaceItemValue("Body", "Something in the message body"); //set body text nDocument.SaveMessageOnSend = true; //save message after it's sent nDocument.Send(false, recipients); //send } catch { } }
private void bExportDocuments_Click(object sender, EventArgs ea) { if (treeView1.SelectedNode == null || treeView1.SelectedNode.Nodes.Count > 0) { MessageBox.Show("Select a database."); return; } int total = 0; long startTicks = 0; long lastTicks = 0; string timeLeft = ""; string timeElapsed = "0:00:00"; string databasePath = treeView1.SelectedNode.Name; ProgressDialog pDialog = new ProgressDialog(); pDialog.Title = "Exporting Documents"; #region Export Documents pDialog.DoWork += delegate(object dialog, DoWorkEventArgs e) { try { //export documents NotesSession nSession = initSession(notesPassword); Dictionary <string, Table> tables = new Dictionary <string, Table>(); NotesDatabase db; if (onLocalComputer) { db = nSession.GetDatabase("", databasePath, false); } else { db = nSession.GetDatabase(notesServer + "//" + notesDomain, databasePath, false); } //get all documents total = db.AllDocuments.Count; NotesDocumentCollection allDocuments = db.AllDocuments; NotesDocument doc = allDocuments.GetFirstDocument(); startTicks = DateTime.Now.Ticks; for (int i = 0; i < total; i++) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } if (doc.HasItem("Form") && (string)doc.GetItemValue("Form")[0] != "") { //get form string form = (string)doc.GetItemValue("Form")[0]; if (!tables.ContainsKey(form)) { tables.Add(form, new Table(form)); } int row = tables[form].AddRow(); //get fields //set multiple values foreach (NotesItem item in doc.Items) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } string field = item.Name; //exclude fields that start with $ and the Form field and Readers field if (field == null || excludeField.IsMatch(field)) { continue; } string type = ""; switch (item.type) {//TODO: get more types case IT_TYPE.NUMBERS: type = "decimal(20,10)"; break; case IT_TYPE.DATETIMES: type = "datetime"; break; default: type = "text"; break; } object values = item.Values; bool multiple = item.Values.Length > 1; if (!tables[form].Columns.ContainsKey(field)) { tables[form].Columns.Add(field, new Column(field, type)); } if (multiple && !tables[form].Columns[field].MultipleValues) { tables[form].Columns[field].MultipleValues = multiple; } if (!tables[form].Columns[field].Values.ContainsKey(row)) { tables[form].Columns[field].Values.Add(row, values); } else { int j = 1; while (tables[form].Columns.ContainsKey(field + j) && tables[form].Columns[field + j].Values.ContainsKey(row)) { j++; } field += j; if (!tables[form].Columns.ContainsKey(field)) { tables[form].Columns.Add(field, new Column(field, type)); } if (multiple && !tables[form].Columns[field].MultipleValues) { tables[form].Columns[field].MultipleValues = multiple; } tables[form].Columns[field].Values.Add(row, values); } } } //update progress pDialog.ReportProgress(i, "Parsing Documents"); doc = allDocuments.GetNextDocument(doc); } //add tables for columns with multiple values Dictionary <string, Table> newTables = new Dictionary <string, Table>(tables.Count); lastTicks = 0; startTicks = DateTime.Now.Ticks; total = tables.Count; int count = 0; foreach (Table table in tables.Values) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } pDialog.ReportProgress(++count, "Formatting Tables"); Dictionary <string, Column> columns = new Dictionary <string, Column>(table.Columns); foreach (Column column in columns.Values) { if (column.MultipleValues) { string tableName = table.Name + "_" + column.Name; Table newTable = new Table(tableName, table.Name); Column values = new Column(column.Name, column.Type); Column ids = new Column(table.Name + "id", "int"); foreach (KeyValuePair <int, object> cell in column.Values) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } int id = cell.Key; object[] valueArray; if (cell.Value.GetType().IsArray) { valueArray = (object[])cell.Value; } else { valueArray = new object[] { cell.Value }; } foreach (object value in valueArray) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } int row = newTable.AddRow(); ids.Values.Add(row, id); values.Values.Add(row, value); } } newTable.Columns.Add(table.Name + "id", ids); newTable.Columns.Add(column.Name, values); newTables.Add(tableName, newTable); table.Columns.Remove(column.Name); } else { Dictionary <int, object> values = new Dictionary <int, object>(column.Values); foreach (KeyValuePair <int, object> cell in values) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } int id = cell.Key; object value; if (cell.Value.GetType().IsArray) { if (((object[])cell.Value).Length > 0) { value = ((object[])cell.Value)[0]; } else { value = null; } } else { value = cell.Value; } column.Values[id] = value; } } } newTables.Add(table.Name, table); } //format to sql total = newTables.Count; bool complete = false; do { lastTicks = 0; count = 0; DialogResult result = DialogResult.Cancel; Invoke((MethodInvoker) delegate() { result = MessageBox.Show(pDialog.Window, "Do you want to export to a MySQL server?", "Export to a server?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); }); if (result == DialogResult.Yes) { InputBox input = null; Invoke((MethodInvoker) delegate() { input = InputBox.Show(pDialog.Window, "SQL server info?", new InputBoxItem[] { new InputBoxItem("Server", mysqlServer), new InputBoxItem("Database", mysqlDatabase), new InputBoxItem("Username", mysqlUsername), new InputBoxItem("Password", mysqlPassword, true), new InputBoxItem("Number of rows per INSERT", mysqlNumRowsPerInsert.ToString()) }, InputBoxButtons.OKCancel); }); if (input.Result == InputBoxResult.OK) { mysqlServer = input.Items["Server"]; mysqlDatabase = input.Items["Database"]; mysqlUsername = input.Items["Username"]; mysqlPassword = input.Items["Password"]; int.TryParse(input.Items["Number of rows per INSERT"], out mysqlNumRowsPerInsert); MySqlConnection conn = new MySqlConnection("SERVER=" + mysqlServer + ";USERNAME="******";PASSWORD="******";"); try { startTicks = DateTime.Now.Ticks; conn.Open(); MySqlCommand command = conn.CreateCommand(); command.CommandText = createDatabase(mysqlDatabase); command.ExecuteNonQuery(); foreach (Table table in newTables.Values) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } pDialog.ReportProgress(++count, "Inserting SQL"); if (table.Columns.Count > 0) { command.CommandText = createTable(table); command.ExecuteNonQuery(); List <string> rows = insertTableRows(table); for (int i = 0; i < rows.Count; i += mysqlNumRowsPerInsert) { command.CommandText = beginInsertTable(table); command.CommandText += String.Join(",", rows.GetRange(i, Math.Min(rows.Count - i, mysqlNumRowsPerInsert))) + ";\n"; command.CommandText += endInsertTable(table); command.ExecuteNonQuery(); pDialog.ReportProgress(count, "Inserting SQL"); } } } command.CommandText = restoreVariables(); command.ExecuteNonQuery(); complete = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } } } else if (result == DialogResult.No) { saveFileDialog1.FileName = "export.sql"; result = DialogResult.Cancel; Invoke((MethodInvoker) delegate() { result = saveFileDialog1.ShowDialog(pDialog.Window); }); if (result == DialogResult.OK) { InputBox input = null; Invoke((MethodInvoker) delegate() { input = InputBox.Show(pDialog.Window, "Database name?", "Database Name", mysqlDatabase, InputBoxButtons.OKCancel); }); if (input.Result == InputBoxResult.OK) { mysqlDatabase = input.Items["Database Name"]; StreamWriter file = new StreamWriter(saveFileDialog1.FileName, false); try { startTicks = DateTime.Now.Ticks; file.WriteLine(createDatabase(mysqlDatabase)); foreach (Table table in newTables.Values) { //check if cancelled if (pDialog.IsCancelled) { e.Cancel = true; return; } pDialog.ReportProgress(++count, "Formatting SQL"); if (table.Columns.Count > 0) { file.WriteLine(createTable(table)); file.WriteLine(beginInsertTable(table)); file.WriteLine(String.Join(",", insertTableRows(table)) + ";"); file.WriteLine(endInsertTable(table)); } } file.WriteLine(restoreVariables()); complete = true; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { file.Close(); } } } } else { e.Cancel = true; return; } } while (!complete); } catch (Exception ex) { MessageBox.Show(ex.ToString()); e.Cancel = true; } }; #endregion pDialog.ProgressChanged += delegate(object dialog, ProgressChangedEventArgs e) { if (lastTicks == 0) { lastTicks = DateTime.Now.Ticks; timeLeft = "Calculating..."; } else if (e.ProgressPercentage > 0 && DateTime.Now.Ticks > lastTicks + 10000000) { lastTicks = DateTime.Now.Ticks; long ticksPassed = lastTicks - startTicks; long thingsCompleted = e.ProgressPercentage; long thingsLeft = total - thingsCompleted; long ticks = thingsLeft * ticksPassed / thingsCompleted; timeLeft = ticksToString(ticks); timeElapsed = ticksToString(ticksPassed); } pDialog.Message = e.UserState.ToString() + ": " + e.ProgressPercentage + "/" + total + " Time Remaining: " + timeLeft + " Time Elapsed: " + timeElapsed; if (total == 0) { pDialog.Progress = 0; } else { pDialog.Progress = (100 * e.ProgressPercentage / total) % 101; } }; pDialog.Completed += delegate(object dialog, RunWorkerCompletedEventArgs e) { if (!e.Cancelled) { MessageBox.Show("Completed Successfully"); } }; pDialog.Run(); }
/// <summary> /// 将超过指定时间的邮件移动到指定目录下 /// </summary> /// <returns></returns> public bool MoveMailInfo() { bool bResult = false; NotesView pMailView = null; NotesDocument pMailDocument = null; try { if (this._strDataBase == "names.nsf") { this.pNotesDatabase = this._pNotesSession.GetDatabase(this._strDomain, this._strDataBase, false); } if (null == this.pNotesDatabase) { throw new Exception("不能打开数据库:" + this._strDataBase); } pMailView = this.pNotesDatabase.GetView("($inbox)"); pMailDocument = pMailView.GetFirstDocument(); DateTime NowTime = DateTime.Now.AddDays(-2); int MailCount = 0; for (int i = 0; i < pMailView.EntryCount; i++) { if (null != pMailDocument) { DateTime MailTime = Convert.ToDateTime(((object[])pMailDocument.GetItemValue("DeliveredDate"))[0].ToString()); string str_subject = ((object[])pMailDocument.ColumnValues)[5].ToString(); if (NowTime > MailTime || 0 < str_subject.IndexOf("服务器正常", 0) || 0 < str_subject.IndexOf("服务器一切正常", 0)) { pMailDocument.PutInFolder("超时邮件", false); NotesDocument oldMailDocument = pMailDocument; if (null != oldMailDocument) { oldMailDocument.RemoveFromFolder("($inbox)"); } pMailDocument = pMailView.GetFirstDocument(); i = -1; MailCount++; } else { pMailDocument = pMailView.GetNextDocument(pMailDocument); } } } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("共移动了:" + MailCount); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(""); bResult = true; } catch (Exception ex) { this.strMessage = ex.Message; Console.WriteLine(ex.Message); bResult = false; } finally { if (pMailDocument != null) { Marshal.ReleaseComObject(pMailDocument); } if (pMailView != null) { Marshal.ReleaseComObject(pMailView); } pMailDocument = null; pMailView = null; } return(bResult); }
/// <summary> /// 获取新信件 /// </summary> /// <returns></returns> public bool GetMailInfo() { bool bResult = false; NotesView pMailView = null; NotesDocument pMailDocument = null; int iCount = 0; try { if (this._strDataBase == "names.nsf") { this.pNotesDatabase = this._pNotesSession.GetDatabase(this._strDomain, this._strDataBase, false); } if (this.pNotesDatabase == null) { throw new Exception("不能打开数据库:" + this._strDataBase); } pMailView = this.pNotesDatabase.GetView("($inbox)"); pMailDocument = pMailView.GetFirstDocument(); Console.WriteLine("共计:" + pMailView.EntryCount.ToString()); CustomDataCollection pMailStruct = new CustomDataCollection(StructType.CUSTOMDATA); while (pMailDocument != null) { if (((object[])pMailDocument.GetItemValue("Reader"))[0].ToString() != "YES") { string strPUID = string.Empty; string strSubject = (((object[])pMailDocument.ColumnValues)[5] == null) ? "N/A" : ((object[])pMailDocument.ColumnValues)[5].ToString(); string strSupervisors = (((object[])pMailDocument.GetItemValue("CopyTo")).Length == 0) ? "N/A" : ((object[])pMailDocument.GetItemValue("CopyTo"))[0].ToString(); string strSendTo = (((object[])pMailDocument.GetItemValue("SendTo")).Length == 0) ? "N/A" : ((object[])pMailDocument.GetItemValue("SendTo"))[0].ToString(); if (strSendTo != "N/A") { for (int i = 0; i < ((object[])pMailDocument.GetItemValue("SendTo")).Length; i++) { strSupervisors = strSupervisors + ";" + ((object[])pMailDocument.GetItemValue("SendTo"))[i].ToString(); } } if (strSupervisors != "N/A") { for (int i = 1; i < ((object[])pMailDocument.GetItemValue("CopyTo")).Length; i++) { strSupervisors = strSupervisors + ";" + ((object[])pMailDocument.GetItemValue("CopyTo"))[i].ToString(); } } string strBody = ((object[])pMailDocument.GetItemValue("Body"))[0].ToString(); if (((object[])pMailDocument.GetItemValue("SSM_Agent"))[0].ToString().Length != 0) { strPUID = ((object[])pMailDocument.GetItemValue("SSM_Agent"))[0].ToString(); } else if (((object[])pMailDocument.GetItemValue("SSM_Agent"))[0].ToString().Length == 0 && pMailDocument.ParentDocumentUNID == null) { strPUID = "N/A"; } else { strPUID = pMailDocument.ParentDocumentUNID; } /* * if (pMailDocument.HasItem("SMS Agent")) * { * strPUID = ((object[])pMailDocument.GetItemValue("SMS Agent"))[0].ToString(); * } * else if (!pMailDocument.HasItem("SMS Agent") && pMailDocument.ParentDocumentUNID == null) * { * strPUID = "N/A"; * } * else * { * strPUID = pMailDocument.ParentDocumentUNID; * } */ //剔除--服务器正常和服务器一切正常 if (strSubject.IndexOf("服务器正常", StringComparison.CurrentCulture) > 0 || strSubject.IndexOf("服务器一切正常", StringComparison.CurrentCulture) > 0) { if (pMailDocument.HasItem("Reader")) { pMailDocument.ReplaceItemValue("Reader", "YES"); } else { pMailDocument.AppendItemValue("Reader", "YES"); } pMailDocument.Save(true, true, true); } else { pMailStruct.Add(DataField.NOTES_UID, DataFormat.STRING, pMailDocument.UniversalID); pMailStruct.Add(DataField.NOTES_UID, DataFormat.STRING, strPUID); pMailStruct.Add(DataField.NOTES_SUBJECT, DataFormat.STRING, strSubject); pMailStruct.Add(DataField.NOTES_FROM, DataFormat.STRING, ((object[])pMailDocument.GetItemValue("Principal"))[0].ToString()); pMailStruct.Add(DataField.NOTES_DATE, DataFormat.STRING, ((object[])pMailDocument.ColumnValues)[2].ToString()); pMailStruct.Add(DataField.NOTES_SUPERVISORS, DataFormat.STRING, (strSupervisors == "") ? "N/A" : strSupervisors); pMailStruct.Add(DataField.NOTES_CONTENT, DataFormat.STRING, (strBody == "") ? "N/A" : strBody); try { pMailStruct.Add(DataField.NOTES_ATTACHMENTCOUNT, DataFormat.STRING, (((NotesRichTextItem)pMailDocument.GetFirstItem("Body")).EmbeddedObjects == null) ? "0" : ((object[])((NotesRichTextItem)pMailDocument.GetFirstItem("Body")).EmbeddedObjects).Length.ToString()); } catch { pMailStruct.Add(DataField.NOTES_ATTACHMENTCOUNT, DataFormat.STRING, "信件内包含多个信件主体,请查阅自己的信箱!"); } pMailStruct.AddRows(); //GlobalStruct[] pMailStruct = new GlobalStruct[8]; //pMailStruct[0].oFieldsName = "Notes_UID"; //pMailStruct[0].oFiledsTypes = "String"; //pMailStruct[0].oFieldValues = pMailDocument.UniversalID; //pMailStruct[1].oFieldsName = "Notes_PUID"; //pMailStruct[1].oFiledsTypes = "String"; //pMailStruct[1].oFieldValues = strPUID; // (pMailDocument.ParentDocumentUNID == null) ? "N/A" : pMailDocument.ParentDocumentUNID; //pMailStruct[2].oFieldsName = "Notes_Subject"; //pMailStruct[2].oFiledsTypes = "String"; //pMailStruct[2].oFieldValues = strSubject; //pMailStruct[3].oFieldsName = "Notes_From"; //pMailStruct[3].oFiledsTypes = "String"; //pMailStruct[3].oFieldValues = ((object[])pMailDocument.GetItemValue("Principal"))[0].ToString(); //((object[])pMailDocument.ColumnValues)[1].ToString(); //pMailStruct[4].oFieldsName = "Notes_Date"; //pMailStruct[4].oFiledsTypes = "String"; //pMailStruct[4].oFieldValues = ((object[])pMailDocument.ColumnValues)[2].ToString(); //pMailStruct[5].oFieldsName = "Notes_Supervisors"; //pMailStruct[5].oFiledsTypes = "String"; //pMailStruct[5].oFieldValues = (strSupervisors == "") ? "N/A" : strSupervisors; //pMailStruct[6].oFieldsName = "Notes_Content"; //pMailStruct[6].oFiledsTypes = "String"; //pMailStruct[6].oFieldValues = (strBody == "") ? "N/A" : strBody; //pMailStruct[7].oFieldsName = "Notes_AttachmentCount"; //pMailStruct[7].oFiledsTypes = "String"; //try //{ // pMailStruct[7].oFieldValues = (((NotesRichTextItem)pMailDocument.GetFirstItem("Body")).EmbeddedObjects == null) ? "0" : ((object[])((NotesRichTextItem)pMailDocument.GetFirstItem("Body")).EmbeddedObjects).Length.ToString(); //} //catch //{ // pMailStruct[7].oFieldValues = "信件内包含多个信件主体,请查阅自己的信箱!"; //} this.pInfoList.Add(pMailStruct); if (pMailDocument.HasItem("Reader")) { pMailDocument.ReplaceItemValue("Reader", "YES"); } else { pMailDocument.AppendItemValue("Reader", "YES"); } //pMailStruct = null; pMailDocument.Save(true, true, true); iCount++; } } //pMailDocument.PutInFolder("历史纪录", false); pMailDocument = pMailView.GetNextDocument(pMailDocument); //if (pMailDocument != null) //{ // pMailView.GetPrevDocument(pMailDocument).Remove(false); //} } this.pRecords = pMailStruct; bResult = true; } catch (Exception ex) { this.strMessage = ex.Message; Console.WriteLine("丢失Notes个数" + iCount.ToString()); bResult = false; //this.pInfoList.Clear(); } finally { if (pMailDocument != null) { Marshal.ReleaseComObject(pMailDocument); } if (pMailView != null) { Marshal.ReleaseComObject(pMailView); } pMailDocument = null; pMailView = null; } return(bResult); }
/// <summary> /// 获取联系人 /// </summary> /// <param name="strCategory">联系人分组</param> /// <returns></returns> public bool GetLinkerInfo(string strCategory) { bool bResult = false; NotesView pLinkerView = null; NotesDocument pLinkerDocument = null; try { if (this._strDataBase != "names.nsf") { this.pNotesDatabase = this._pNotesSession.GetDatabase(this._strDomain, "names.nsf", false); } pLinkerView = this.pNotesDatabase.GetView(strCategory); pLinkerDocument = pLinkerView.GetFirstDocument(); CustomDataCollection pLinkerStruct = new CustomDataCollection(StructType.CUSTOMDATA); while (pLinkerDocument != null) { pLinkerStruct.Add(DataField.LINKER_NAME, DataFormat.STRING, pLinkerDocument.GetFirstItem("ListName").Text); pLinkerStruct.Add(DataField.LINKER_CONTENT, DataFormat.STRING, (pLinkerDocument.GetFirstItem("Members") == null) ? "N/A" : pLinkerDocument.GetFirstItem("Members").Text); pLinkerStruct.AddRows(); //pLinkerStruct[0].oFieldsName = "Linker_Name"; //pLinkerStruct[0].oFiledsTypes = "String"; //pLinkerStruct[0].oFieldValues = pLinkerDocument.GetFirstItem("ListName").Text; //pLinkerStruct[1].oFieldsName = "Linker_Content"; //pLinkerStruct[1].oFiledsTypes = "String"; //pLinkerStruct[1].oFieldValues = (pLinkerDocument.GetFirstItem("Members") == null) ? "N/A" : pLinkerDocument.GetFirstItem("Members").Text; //this.pInfoList.Add(pLinkerStruct); pLinkerDocument = pLinkerView.GetNextDocument(pLinkerDocument); } this.pRecords = pLinkerStruct; bResult = true; } catch (Exception ex) { this.strMessage = ex.Message; bResult = false; //this.pInfoList.Clear(); } finally { if (pLinkerDocument != null) { Marshal.ReleaseComObject(pLinkerDocument); } if (pLinkerView != null) { Marshal.ReleaseComObject(pLinkerView); } pLinkerDocument = null; pLinkerView = null; } return(bResult); }
/// <summary> /// 获取信件中的附件内容 /// </summary> /// <param name="strNotesUID"></param> /// <returns></returns> public bool GetMailAttachment(string strNotesUID) { bool bResult = false; NotesView pMailView = null; NotesDocument pMailDocument = null; int iCount = 0; try { if (this._strDataBase == "names.nsf") { this.pNotesDatabase = this._pNotesSession.GetDatabase(this._strDomain, this._strDataBase, false); } if (this.pNotesDatabase == null) { throw new Exception("不能打开数据库:" + this._strDataBase); } pMailView = this.pNotesDatabase.GetView("($inbox)"); pMailDocument = pMailView.GetFirstDocument(); CustomDataCollection pAttachmentStruct = new CustomDataCollection(StructType.CUSTOMDATA); while (pMailDocument != null) { if (pMailDocument.UniversalID == strNotesUID) { object[] arrItemObject = (object[])((NotesRichTextItem)pMailDocument.GetFirstItem("Body")).EmbeddedObjects; for (int i = 0; i < arrItemObject.Length; i++) { NotesEmbeddedObject pEmbeddedObject = (NotesEmbeddedObject)arrItemObject[i]; pEmbeddedObject.ExtractFile(System.AppDomain.CurrentDomain.BaseDirectory + "\\Attachment\\" + pEmbeddedObject.Source); FileStream pAttachmentStream = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + "\\Attachment\\" + pEmbeddedObject.Source, FileMode.Open, FileAccess.Read); byte[] pAttachmentContent = new byte[pAttachmentStream.Length]; pAttachmentStream.Read(pAttachmentContent, 0, pAttachmentContent.Length); pAttachmentStream.Close(); pAttachmentStream.Dispose(); File.Delete(System.AppDomain.CurrentDomain.BaseDirectory + "\\Attachment\\" + pEmbeddedObject.Source); pAttachmentStruct.Add(DataField.NOTES_ATTACHMENTNAME, DataFormat.STRING, pEmbeddedObject.Source); pAttachmentStruct.Add(DataField.NOTES_ATTACHMENTCOUNT, DataFormat.NONE, pAttachmentContent); pAttachmentStruct.AddRows(); //GlobalStruct[] pAttachmentStruct = new GlobalStruct[2]; //pAttachmentStruct[0].oFieldsName = "Notes_AttachmentName"; //pAttachmentStruct[0].oFiledsTypes = "String"; //pAttachmentStruct[0].oFieldValues = pEmbeddedObject.Source; //pAttachmentStruct[1].oFieldsName = "Notes_AttachmentCount"; //pAttachmentStruct[1].oFiledsTypes = "Byte[]"; //pAttachmentStruct[1].oFieldValues = pAttachmentContent; pAttachmentContent = null; this.pInfoList.Add(pAttachmentStruct); } } pMailDocument = pMailView.GetNextDocument(pMailDocument); iCount++; } this.pRecords = pAttachmentStruct; bResult = true; } catch (Exception ex) { this.strMessage = ex.Message; bResult = false; //this.pInfoList.Clear(); } finally { if (pMailDocument != null) { Marshal.ReleaseComObject(pMailDocument); } if (pMailView != null) { Marshal.ReleaseComObject(pMailView); } pMailDocument = null; pMailView = null; } if (iCount == 0) { return(false); } return(bResult); }
private void SetMailAsRead(NotesDocument profileDocument, IDocumentCollection documentCollection) { try { profileDocument.ReplaceItemValue("UntilTime", documentCollection.UntilTime); profileDocument.Save(true, true, true); } catch (Exception e) { Logger logger = LogManager.GetCurrentClassLogger(); logger.Log(LogLevel.Error, e); } }
public bool RelayMailInfo(object pSupervisors, object pSendSecret, string strNotesUID, string strMailContent, object strSender) { bool bResult = false; NotesView pParentView; NotesDocument pParentDocument; try { if (this._strDataBase == "names.nsf") { this.pNotesDatabase = this.pNotesSession.GetDatabase(this._strDomain, this._strDataBase, false); } pParentView = this.pNotesDatabase.GetView("($inbox)"); pParentDocument = pParentView.GetFirstDocument(); while (pParentDocument != null) { if (pParentDocument.UniversalID == strNotesUID) { NotesDocument pRelayDocument = pParentDocument.CreateReplyMessage(false); string strRelaySubject = (((object[])pParentDocument.GetItemValue("Subject"))[0] == null) ? "N/A" : ((object[])pParentDocument.GetItemValue("Subject"))[0].ToString(); pParentDocument.ReplaceItemValue("Form", "Reply"); pParentDocument.ReplaceItemValue("CopyTo", pSupervisors); //抄送 pParentDocument.ReplaceItemValue("BlindCopyTo", pSendSecret); //密送 pParentDocument.ReplaceItemValue("Subject", "回复:" + strRelaySubject); pParentDocument.ReplaceItemValue("PostedDate", DateTime.Now.ToString()); pParentDocument.ReplaceItemValue("Principal", "CN=tcsadmin/OU=技术支持部/OU=产品运营中心/O=runstar"); //pParentDocument.ReplaceItemValue("Principal", strSender); pParentDocument.ReplaceItemValue("Body", ""); pParentDocument.ReplaceItemValue("客服中心", strNotesUID); if (pParentDocument.HasItem("Reader")) { pParentDocument.ReplaceItemValue("Reader", "NO"); } NotesRichTextItem pOldItem = (NotesRichTextItem)pParentDocument.GetFirstItem("Body"); pOldItem.AppendText(strMailContent); pOldItem.AddNewLine(5, false); pOldItem.AppendRTItem((NotesRichTextItem)pRelayDocument.GetFirstItem("Body")); object pSendOwner = strSender; //"孙露" pParentDocument.Send(false, ref pSendOwner); bResult = true; break; } else { bResult = false; this.strMessage = "不能找到原始信件,原信件可能已删除,请新建一封信的信件给接收人!"; } pParentDocument = pParentView.GetNextDocument(pParentDocument); } } catch (Exception ex) { this.strMessage = ex.Message; bResult = false; } finally { pParentDocument = null; pParentView = null; } return(bResult); }
public void Pub() { try { NotesSession ns = new NotesSessionClass(); ns.Initialize(pwd); NotesDatabase ndb = ns.GetDatabase(serverName, nsfFile, false); NotesDocument doc = ndb.CreateDocument(); doc.ReplaceItemValue("Form", "中央气象台产品记录"); doc.ReplaceItemValue("dbname_11", "juece.nsf"); doc.ReplaceItemValue("dbname_12", "juece.nsf"); doc.ReplaceItemValue("dbname_13", "juece.nsf"); doc.ReplaceItemValue("dbname_21", "juece.nsf"); doc.ReplaceItemValue("dbname_22", "juece.nsf"); doc.ReplaceItemValue("dbname_222", "juece.nsf"); doc.ReplaceItemValue("dbname_23", "juece.nsf"); doc.ReplaceItemValue("dbname_24", "juece.nsf"); doc.ReplaceItemValue("dbname_30", "juece.nsf"); doc.ReplaceItemValue("doctype", "OCX"); doc.ReplaceItemValue("Encrypt", "0"); doc.ReplaceItemValue("img", ""); doc.ReplaceItemValue("issuetime", this.dateNum); doc.ReplaceItemValue("SendTo", "CMA决策"); doc.ReplaceItemValue("SendTobyHub", "各省气象信息共享数据库"); doc.ReplaceItemValue("sendOk", "0"); doc.ReplaceItemValue("role", "周军"); doc.ReplaceItemValue("role_1", "短期科"); doc.ReplaceItemValue("标题域", this.Title); doc.ReplaceItemValue("标题域_1", this.Title); doc.ReplaceItemValue("部委", "0"); doc.ReplaceItemValue("草稿", "0"); doc.ReplaceItemValue("产品", "天气预报"); doc.ReplaceItemValue("产品_1", "天气预报"); doc.ReplaceItemValue("发布单位", "国家气象中心"); doc.ReplaceItemValue("发布单位_1", "中央气象台"); doc.ReplaceItemValue("发布单位_1_1", "中央气象台"); doc.ReplaceItemValue("发布单位_2", "国家气象中心"); doc.ReplaceItemValue("发布单位_e", "qxt"); doc.ReplaceItemValue("发布时间", this.dateNum); doc.ReplaceItemValue("发布时间_1", this.datePy); doc.ReplaceItemValue("发布时间_2", this.dateNum); //doc.ReplaceItemValue("内容", this.Content); doc.ReplaceItemValue("日期1", this.dateNum); doc.ReplaceItemValue("状态", "1"); if ((attFileName != null) && (attFileName.Count > 0)) { NotesRichTextItem item = doc.CreateRichTextItem("attachment"); foreach (string att in attFileName) { item.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, "", att, "attachment"); doc.ReplaceItemValue("fname", System.IO.Path.GetFileName(att)); } } doc.ComputeWithForm(true, false); object obj = doc.GetItemValue("SendTo"); doc.Send(false, ref obj); } catch (Exception ex) { throw ex; } }
/* To begin with, retrieving mail using WCF is not a great idea because of binary attachments. It will work perfectly however if if we save all attachments of picked-up mail on server disk and return file names with the returned mail. Using the web service client we later pick up the attachments using GetEmailAttachments(Email) method, at which time these files will also be removed. */ private List<Attachment> ExtractAttachments(NotesDocument lotusNotesEmail) { List<Attachment> attachmentFileNames = new List<Attachment>(); List<string> filePathsToDelete = new List<string>(); object[] items = (object[])lotusNotesEmail.Items; foreach (var item in items) { NotesItem notesItem = (NotesItem)item; if (notesItem != null && notesItem.Values != null && !(notesItem.Values is string)) { object[] itemValues = (object[])notesItem.Values; if (itemValues != null) { if (notesItem.type == Domino.IT_TYPE.ATTACHMENT) { if (itemValues[0] != null && notesItem.Name != null) { string fileNameOriginal = itemValues[0].ToString(); string fileNameValid = GetValidFileName(fileNameOriginal); string fileNameDated = GetPrependedDateTime() + fileNameValid; string filePath = Config["FilepathLocalTempFiles"] + fileNameDated; try { int existingDocumentsWithSameName = (from att in attachmentFileNames where att.FileNameOriginal.Equals(fileNameOriginal) select att).Count(); // Beware of duplicates from Lotus Notes if (existingDocumentsWithSameName == 0) { var attachment = lotusNotesEmail.GetAttachment(fileNameOriginal); // Extracting attachment using the original name (fileNameOriginal) attachment.ExtractFile(filePath); // Saving file to disk using valid filename (filePath) attachmentFileNames.Add(new Attachment { FileName = fileNameDated, FilePath = filePath, FileNameOriginal = fileNameOriginal }); // Putting in filepath for now, load byte[] data later } } catch (Exception e) { Logger logger = LogManager.GetCurrentClassLogger(); logger.Log(LogLevel.Debug, e); } } } } } } return attachmentFileNames; }
//private NotesDatabase _serverDatabase = null; //private NotesView _peopleView = null; //private string _lotusCientPassword = null; //private string _lotusnotesserverName = null; //private bool _IsfetchServerData = false; #region Methods /// <summary> /// Overrides virtual read method for full list of elements /// </summary> /// <param name="clientFolderName"> /// the information from where inside the source the elements should be read - /// This does not need to be a real "path", but need to be something that can be expressed as a string /// </param> /// <param name="result"> /// The list of elements that should get the elements. The elements should be added to /// the list instead of replacing it. /// </param> /// <returns> /// The list with the newly added elements /// </returns> protected override List <StdElement> ReadFullList(string clientFolderName, List <StdElement> result) { if (result == null) { throw new ArgumentNullException("result"); } string currentElementName = string.Empty; try { this.LogProcessingEvent(Resources.uiLogginIn); //Lotus Notes Object Creation _lotesNotesSession = new Domino.NotesSessionClass(); //Initializing Lotus Notes Session _lotesNotesSession.Initialize(this.LogOnPassword); //Passwort _localDatabase = _lotesNotesSession.GetDatabase("", "names.nsf", false); //Database for Contacts default names.nsf this.LogProcessingEvent(Resources.uiPreparingList); string viewname = "$People"; _contactsView = _localDatabase.GetView(viewname); // TODO: implement reading from the Lotus Notes server and map the entities to StdContact instances if (_contactsView == null) { this.LogProcessingEvent(Resources.uiNoViewFound, viewname); } else { NotesViewEntryCollection notesViewCollection = _contactsView.AllEntries; //ArrayList notesUIDSList = new ArrayList(); for (int rowCount = 1; rowCount <= notesViewCollection.Count; rowCount++) { //Get the nth entry of the selected view according to the iteration. NotesViewEntry viewEntry = notesViewCollection.GetNthEntry(rowCount); //Get the first document of particular entry. NotesDocument document = viewEntry.Document; object documentItems = document.Items; Array itemArray = (System.Array)documentItems; StdContact elem = new StdContact(); PersonName name = new PersonName(); elem.Name = name; AddressDetail businessAddress = new AddressDetail(); elem.BusinessAddressPrimary = businessAddress; AddressDetail address = new AddressDetail(); elem.PersonalAddressPrimary = address; elem.ExternalIdentifier.SetProfileId(ProfileIdentifierType.LotusNotesId, document.NoteID); for (int itemCount = 0; itemCount < itemArray.Length; itemCount++) { NotesItem notesItem = (Domino.NotesItem)itemArray.GetValue(itemCount); string itemname = notesItem.Name; string text = notesItem.Text; switch (notesItem.Name) { //Name case "FirstName": name.FirstName = notesItem.Text; break; case "LastName": name.LastName = notesItem.Text; break; case "Titel": { if (notesItem.Text != "0") { name.AcademicTitle = notesItem.Text; } } break; //Geburtstag case "Birthday": DateTime dt; if (DateTime.TryParse(notesItem.Text, out dt)) { elem.DateOfBirth = dt; } break; case "Comment": elem.AdditionalTextData = notesItem.Text; break; //Business adress case "InternetAddress": elem.BusinessEmailPrimary = notesItem.Text; break; case "OfficePhoneNumber": businessAddress.Phone = new PhoneNumber(); businessAddress.Phone.DenormalizedPhoneNumber = notesItem.Text; break; case "OfficeStreetAddress": businessAddress.StreetName = notesItem.Text; break; case "OfficeState": businessAddress.StateName = notesItem.Text; break; case "OfficeCity": businessAddress.CityName = notesItem.Text; break; case "OfficeZIP": businessAddress.PostalCode = notesItem.Text; break; case "OfficeCountry": businessAddress.CountryName = notesItem.Text; break; //Business case "Department": elem.BusinessDepartment = notesItem.Text; break; case "CompanyName": elem.BusinessCompanyName = notesItem.Text; break; case "JobTitle": elem.BusinessPosition = notesItem.Text; break; case "WebSite": elem.PersonalHomepage = notesItem.Text; break; //Address case "PhoneNumber": address.Phone = new PhoneNumber(); address.Phone.DenormalizedPhoneNumber = notesItem.Text; break; case "StreetAddress": address.StreetName = notesItem.Text; break; case "State": address.StateName = notesItem.Text; break; case "City": address.CityName = notesItem.Text; break; case "Zip": address.PostalCode = notesItem.Text; break; case "country": address.CountryName = notesItem.Text; break; //Mobile case "CellPhoneNumber": elem.PersonalPhoneMobile = new PhoneNumber(); elem.PersonalPhoneMobile.DenormalizedPhoneNumber = notesItem.Text; break; //Categories case "Categories": elem.Categories = new List <string>(notesItem.Text.Split(';')); break; } } this.LogProcessingEvent("mapping contact {0} ...", elem.Name.ToString()); result.Add(elem); } this.ThinkTime(1000); result.Sort(); } } catch (Exception ex) { this.LogProcessingEvent( string.Format(CultureInfo.CurrentCulture, Resources.uiErrorAtName, currentElementName, ex.Message)); } finally { //outlookNamespace.Logoff(); _lotesNotesSession = null; } return(result); }
/// <summary> /// Overrides virtual write method for full list of elements /// </summary> /// <param name="elements"> /// the list of elements that should be written to the target system. /// </param> /// <param name="clientFolderName"> /// the information to where inside the source the elements should be written - /// This does not need to be a real "path", but need to be something that can be expressed as a string /// </param> /// <param name="skipIfExisting"> /// specifies whether existing elements should be updated or simply left as they are /// </param> protected override void WriteFullList(List <StdElement> elements, string clientFolderName, bool skipIfExisting) { string currentElementName = string.Empty; try { this.LogProcessingEvent(Resources.uiLogginIn); //Lotus Notes Object Creation _lotesNotesSession = new Domino.NotesSessionClass(); //Initializing Lotus Notes Session _lotesNotesSession.Initialize(this.LogOnPassword); //Passwort _localDatabase = _lotesNotesSession.GetDatabase("", "names.nsf", false); //Database for Contacts default names.nsf this.LogProcessingEvent(Resources.uiPreparingList); string viewname = "$People"; _contactsView = _localDatabase.GetView(viewname); // TODO: implement reading from the Lotus Notes server and map the entities to StdContact instances if (_contactsView == null) { this.LogProcessingEvent(Resources.uiNoViewFound, viewname); } else { foreach (StdContact item in elements) { NotesViewEntryCollection notesViewCollection = _contactsView.AllEntries; //ArrayList notesUIDSList = new ArrayList(); bool gefunden = false; for (int rowCount = 1; rowCount <= notesViewCollection.Count; rowCount++) { //Get the nth entry of the selected view according to the iteration. NotesViewEntry viewEntry = notesViewCollection.GetNthEntry(rowCount); //Get the first document of particular entry. NotesDocument document = viewEntry.Document; string noteId = document.NoteID;; // string id = string.Empty; if (item.ExternalIdentifier != null) { ProfileIdInformation info = item.ExternalIdentifier.GetProfileId(ProfileIdentifierType.LotusNotesId); if (info != null) { id = document.NoteID; } } if (id == noteId) { gefunden = true; // object documentItems = document.Items; Array itemArray = (System.Array)documentItems; //Daten übernehmen for (int itemCount = 0; itemCount < itemArray.Length; itemCount++) { NotesItem notesItem = (Domino.NotesItem)itemArray.GetValue(itemCount); //string itemname = notesItem.Name; string text = notesItem.Text; switch (notesItem.Name) { //Name case "FirstName": // notesItem.Text = item.Name.FirstName; break; } break; } } } } } } catch (Exception ex) { this.LogProcessingEvent( string.Format(CultureInfo.CurrentCulture, Resources.uiErrorAtName, currentElementName, ex.Message)); } finally { //outlookNamespace.Logoff(); _lotesNotesSession = null; } }
private DocumentItemModel[] GetItems(NotesDocument document) { return(GetNoteItems().Select(ni => new DocumentItemModel(ni)).ToArray()); }
public Program() { ns = new NotesSession(); ns.Initialize("password"); string mailServer = ns.GetEnvironmentString("MailServer", true); string mailFile = ns.GetEnvironmentString("MailFile", true); string userName = ns.UserName; System.Console.WriteLine($"mailServer: {mailServer}"); System.Console.WriteLine($"mailFile: {mailFile}"); System.Console.WriteLine($"userName: {userName}"); StringBuilder fullpathName = new StringBuilder(512); OSPathNetConstruct(null, mailServer, mailFile, fullpathName); System.Console.WriteLine($"fullpathName: {fullpathName.ToString()}"); HANDLE hNotesDB; HANDLE hUnreadListTable; NSFDbOpen(fullpathName.ToString(), out hNotesDB); System.Console.WriteLine($"hNotesDB: {hNotesDB.ToString()}"); NSFDbGetUnreadNoteTable(hNotesDB, userName, (ushort)userName.Length, true, out hUnreadListTable); System.Console.WriteLine($"hUnreadListTable: {hUnreadListTable.ToString()}"); db = ns.GetDatabase(mailServer, mailFile, false); int numUnreadMail = 0; bool first = true; HANDLE id; while (true) { numUnreadMail = 0; first = true; while (IDScan(hUnreadListTable, first, out id)) { doc = db.GetDocumentByID(id.ToString("X")); string subject = (string)((object[])doc.GetItemValue("Subject"))[0]; string sender = (string)((object[])doc.GetItemValue("From"))[0]; if (!sender.Equals("")) { System.Console.WriteLine($" Doc: {subject} / *{sender}*"); if (!sender.Equals(userName)) { numUnreadMail++; } } first = false; } //numUnreadMail -= 3; System.Console.WriteLine($"Unread mail: {numUnreadMail.ToString()}"); System.Threading.Thread.Sleep(3000); NSFDbUpdateUnread(hNotesDB, hUnreadListTable); } IDDestroyTable(hUnreadListTable); NSFDbClose(hNotesDB); /* * db = ns.GetDatabase(mailServer, mailFile, false); * * NotesView inbox = db.GetView("($Inbox)"); * doc = inbox.GetFirstDocument(); * System.Console.WriteLine($"Notes database: /{db.ToString()}"); * * // NotesViewEntryCollection vc = inbox.GetAllUnreadEntries(); * * while (doc != null) * { * System.DateTime lastAccessed = doc.LastAccessed; * System.DateTime lastModified = doc.LastModified; * System.DateTime created = doc.Created; * * //if ( (lastAccessed.Subtract(lastModified)).TotalSeconds==(double)0.0 && (created.Subtract(lastModified)).TotalSeconds<(double)60.0 ) * if (lastAccessed.CompareTo(lastModified) < 0) * * { * string subject = (string)((object[])doc.GetItemValue("Subject"))[0]; * System.Console.WriteLine($"LastAccessed: {doc.LastAccessed} | LastModified: {doc.LastModified} | Created: {doc.Created} | Subject: {subject}"); * } * doc = inbox.GetNextDocument(doc); * } * * db = null; * ns = null; * */ System.Console.WriteLine("Hello world!"); System.Console.ReadLine(); // as pause }
public string SendMail(MailBody mailBody, MailSettings mailSettings) { _MailBody = mailBody; InitSettings(mailSettings); Validation(); NotesSession ns; NotesDatabase ndb; try { ns = new NotesSession(); ns.Initialize(_Password); //初始化NotesDatabase ndb = ns.GetDatabase(_SMTPHost, "names.nsf", false); NotesDocument doc = ndb.CreateDocument(); doc.ReplaceItemValue("Form", "Memo"); //收件人信息 doc.ReplaceItemValue("SendTo", ConvertToString(_MailBody.MailTo)); if (_MailBody.MailCc != null && _MailBody.MailCc.Count > 0) { doc.ReplaceItemValue("CopyTo", ConvertToString(_MailBody.MailCc)); } if (_MailBody.MailBcc != null && _MailBody.MailBcc.Count > 0) { doc.ReplaceItemValue("BlindCopyTo", ConvertToString(_MailBody.MailBcc)); } //邮件主题 doc.ReplaceItemValue("Subject", _MailBody.Subject); //邮件正文 if (_MailBody.IsHtmlBody) { NotesStream body = ns.CreateStream(); body.WriteText(_MailBody.Body, EOL_TYPE.EOL_PLATFORM); NotesMIMEEntity mime = doc.CreateMIMEEntity("Body"); mime.SetContentFromText(body, "text/HTML;charset=gb2312", MIME_ENCODING.ENC_NONE); body.Truncate(); } else { NotesRichTextItem rt = doc.CreateRichTextItem("Body"); rt.AppendText(_MailBody.Body); } //NotesRichTextItem rt = doc.CreateRichTextItem("Body"); //if (_MailBody.IsHtmlBody) //{ // NotesRichTextStyle richtextStyle = ns.CreateRichTextStyle(); // richtextStyle.PassThruHTML = 1; // rt.AppendStyle(richtextStyle); //} //rt.AppendText(_MailBody.Body); //附件 //if (_MailBody.MailAttachments != null) //{ // NotesRichTextItem attachment = doc.CreateRichTextItem("attachment"); // foreach (MailAttachment a in _MailBody.MailAttachments) // { // if (!string.IsNullOrEmpty(a.Location)) // { // attachment.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, "", a.Location, "attachment"); // } // } //} //发送邮件 object obj = doc.GetItemValue("SendTo"); doc.Send(false, ref obj); doc = null; return(""); } catch (Exception ex) { if (ex.InnerException == null) { HandleMailLogs(ex.Message + "内部错误信息为:null"); } else { HandleMailLogs(ex.Message + "内部错误信息为:" + ex.InnerException.Message); } return("发送邮件失败"); } finally { ndb = null; ns = null; RecordTheMail(); } }