/// <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);
        }
示例#2
0
 private void bSearchComputer_Click(object sender, EventArgs e)
 {
     if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         try
         {
             treeView1.Nodes.Clear();
             InputBox input = InputBox.Show("Lotus Notes Password", new InputBoxItem("Password", notesPassword, true), InputBoxButtons.OKCancel);
             if (input.Result == InputBoxResult.OK)
             {
                 notesPassword = input.Items["Password"];
                 NotesSession nSession = initSession(notesPassword);
                 onLocalComputer = true;
                 foreach (string file in openFileDialog1.FileNames)
                 {
                     NotesDatabase db = nSession.GetDatabase("", file, false);
                     treeView1.Nodes.Add(file, db.Title, "database", "database");
                 }
                 treeView1.Sort();
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
         openFileDialog1.FileName = "";
     }
 }
示例#3
0
        /// <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;
        }
示例#4
0
        private void ListAvailableView()
        {
            UpdateText(lblStatus, "Listing available view(s)...");

            cboView.Items.Clear();
            rtbOutput.Clear();

            NotesSession session = new NotesSession();

            session.Initialize("");

            _db = session.GetDatabase("", txtNsfFilePath.Text, false);

            foreach (NotesView view in GetNotesView(_db))
            {
                if (view != null)
                {
                    if (cboView.Items.Contains(view.Name) == false)
                    {
                        cboView.Items.Add(view.Name);
                    }
                }
            }

            if (cboView.Items.Count > 0)
            {
                cboView.Items.Insert(0, "--All--");
                cboView.SelectedIndex = 0;
            }
        }
示例#5
0
        static void Main(string[] args)
        {
            NotesSession session = null;

            try
            {
                session = new NotesSession();
                session.Initialize("MonPetitJulien1");
                var database   = session.GetDatabase("CancerS_A1/Serveurs/SSSS", @"TEST\PQDCS\PRINCIP.NSF", false);
                var collection = database.AllDocuments;
                var document   = collection.GetFirstDocument();
                while (document != null)
                {
                    var form = document.GetItemValue("form");
                    foreach (NotesItem item in document.Items)
                    {
                    }
                    document = collection.GetNextDocument(document);
                }
            }
            finally
            {
                Marshal.ReleaseComObject(session);
            }
        }
示例#6
0
        /// <summary>
        /// Данный класс служит для подключения к Базе данных Lotus
        /// </summary>
        /// <param name="password">Пароль для подключеня к сесии</param>
        /// <param name="server">Сам сервер локальный или удаленный</param>
        /// <param name="database">База даных полный путь с названием</param>
        /// <param name="createofjncreatedb">Данное булевское значение говорит если false мы открываем BD true создаем БД</param>
        /// <returns></returns>
        public static NotesDatabase Databaseconect(string password, string server, string database, bool createofjncreatedb)
        {
            NotesSession session = new NotesSession();

            session.Initialize(password);
            var db = session.GetDatabase(server, database, createofjncreatedb);

            return(db);
        }
示例#7
0
        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);
        }
示例#8
0
        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
            {
            }
        }
示例#9
0
        public void GetAllItemsInDb(string dbPath, string filename)
        {
            if (!IsInitialize)
            {
                throw new NotInitializeException();
            }
            var serverDatabase = _lotusNotesServerSession.GetDatabase(CurrentServer, dbPath, false);

            var docs = serverDatabase.AllDocuments;

            using (var fileStream = new StreamWriter(filename))
            {
                var totalCount = docs.Count;
                for (var count = 1; count <= totalCount; count++)
                {
                    Console.WriteLine("Current: " + count);
                    var mail = docs.GetNthDocument(count);
                    var ni   = (object[])mail.Items;
                    if (ni == null)
                    {
                        continue;
                    }
                    var namesValues = "";
                    for (var x = 0; x < ni.Length; x++)
                    {
                        var item = (NotesItem)ni[x];
                        if (!string.IsNullOrEmpty(item.Name))
                        {
                            namesValues += x + ": " + item.Name + "\t\t" + item.Text + "\r\n";
                        }
                    }
                    fileStream.WriteLine("DocUrl: '{0}'", mail.NotesURL);
                    fileStream.WriteLine(namesValues);
                    GetDocIndexRaise?.Invoke(((100 * count) / totalCount));
                }
            }
        }
示例#10
0
        public void TestAddDocumentReplace()
        {
            var session = new NotesSession();

            session.Initialize("12345");
            var HtmlBody = session.CreateStream();
            var path     = @"D:\Вложение 10.zip";
            var mailBody = @"<div><br/>
                               </div><div>
                    <br/>
                    </div>
                    <div class=""c611af8754f78aa8normalize"">
                    <div><div><div><div>Добрый день!</div>
                    <div>Реквизиты:</div>
                    <div>Валюта получаемого перевода: Рубли(RUB)</div>
                    <div>Получатель: НОВИКОВ АЛЕКСЕЙ ВАЛЕРЬЕВИЧ</div>
                    <div>Номер счёта: 
                    <span class=""1f1ea193f6735cf0wmi-callto"">40817810038180282453</span>
                    </div><div>Банк получателя: ПАО СБЕРБАНК</div>
                    <div>БИК: 
                    <span class=""1f1ea193f6735cf0wmi-callto"">044525225</span>
                    </div><div>Корр.счёт: <span class=""1f1ea193f6735cf0wmi-callto"">30101810400000000225</span></div>
                    <div>ИНН: <span class=""1f1ea193f6735cf0wmi-callto"">7707083893</span>
                    </div><div>КПП: <span class=""1f1ea193f6735cf0wmi-callto"">773643001</span>
                    </div><div>SWIFT-код: SABRRUMM</div><div> </div><div>С уважением,</div>
                    <div>Алексей Новиков</div></div></div></div></div><div><br /></div><div>
                    <br /></div><div><br /></div><div><br /></div>
                    <div class=""86e3a5cbc83439f6js-compose-signature""></div><div><br />
                    </div>";
            var db       = session.GetDatabase("Lotus7751/I7751/R77/МНС", "mail\\акоряг.nsf", false);
            var document = db.CreateDocument();

            //  document.ComputeWithForm(true,)
            document.AppendItemValue("Subject", "Тема");
            document.AppendItemValue("Recipients", "Алекcандр Сергеевич Корягин/I7751/R77/МНС@MNS_R77");
            document.AppendItemValue("OriginalTo", "Алекcандр Сергеевич Корягин/I7751/R77/МНС@MNS_R77");
            document.AppendItemValue("From", "Алекcандр Сергеевич Корягин/I7751/R77/МНС@MNS_R77");
            document.AppendItemValue("OriginalFrom", "Алекcандр Сергеевич Корягин/I7751/R77/МНС@MNS_R77");
            document.AppendItemValue("SendTo", "Алекcандр Сергеевич Корягин/I7751/R77/МНС@MNS_R77");


            //  document.AppendItemValue("Body","");
            var MIMEEntity = document.CreateMIMEEntity("Body");

            var MimeHeader = MIMEEntity.CreateHeader("MIME-Version");

            MimeHeader.SetHeaderVal("1.0");

            MimeHeader = MIMEEntity.CreateHeader("Content-Type");
            MimeHeader.SetHeaderValAndParams("multipart/mixed");

            var MimeChilds = MIMEEntity.CreateChildEntity();

            HtmlBody.WriteText(mailBody);

            MimeChilds.SetContentFromText(HtmlBody, "text/html;charset=\"utf-8\"", Domino.MIME_ENCODING.ENC_NONE);
            MimeChilds = MIMEEntity.CreateChildEntity();



            HtmlBody = session.CreateStream();
            HtmlBody.Open(path, "");
            MimeHeader = MimeChilds.CreateHeader("Content-Disposition");

            MimeHeader.SetHeaderVal("attachment; filename=\"16.03.2020_09.35.31_e.safonov.r7700.zip\"");
            MimeChilds.SetContentFromBytes(HtmlBody, "application/zip; name=\"16.03.2020_09.35.31_e.safonov.r7700.zip\"", Domino.MIME_ENCODING.ENC_IDENTITY_BINARY);


            document.CloseMIMEEntities(true);

            session.ConvertMime = true;
            document.CloseMIMEEntities(true);
            if (document.ComputeWithForm(true, false))
            {
                document.Save(true, true);
                document.Send(false);
            }
        }
示例#11
0
        private void cmdOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_LocalNotesSession == null)
                {
                    _LocalNotesSession = new NotesSessionClass();
                    //Initializing Lotus Notes Session
                    try
                    {
                        _LocalNotesSession.Initialize(txtPassword.Password);
                    }
                    catch (COMException cex)
                    {
                        if (cex.ErrorCode != -2147217504)
                        {
                            throw;
                        }
                        PNMessageBox.Show(PNLang.Instance.GetMessageText("pwrd_not_match", "Invalid password"),
                                          PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                //Creating Lotus Notes DataBase Object
                var localDatabase = _LocalNotesSession.GetDatabase("", "names.nsf", false);

                if (_ServerNotesSession == null)
                {
                    _ServerNotesSession = new NotesSessionClass();
                    //Initializing Lotus Notes Session
                    try
                    {
                        _ServerNotesSession.Initialize(txtPassword.Password);
                    }
                    catch (COMException cex)
                    {
                        if (cex.ErrorCode != -2147217504)
                        {
                            throw;
                        }
                        PNMessageBox.Show(PNLang.Instance.GetMessageText("pwrd_not_match", "Invalid password"),
                                          PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                //Creating Lotus Notes DataBase Object
                var serverDatabase = _ServerNotesSession.GetDatabase(txtServer.Text.Trim(), "names.nsf", false);

                //creating Lotus Notes Contact View
                NotesView contactsView = null, peopleView = null;
                if (localDatabase != null)
                {
                    contactsView = localDatabase.GetView("Contacts");
                }
                if (serverDatabase != null)
                {
                    peopleView = serverDatabase.GetView("$People");
                }

                if (LotusCredentialSet != null)
                {
                    LotusCredentialSet(this, new LotusCredentialSetEventArgs(contactsView, peopleView));
                }
                DialogResult = true;
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
        public List<Email> GetMail(bool getAllMail = false)
        {
            LoadConfig();
            List<Email> emails = new List<Email>();

            try
            {
                NotesSession notesSession = new NotesSession();
                notesSession.Initialize(Config["PasswordLotusNotesAccount"]);
                NotesDatabase notesDb = notesSession.GetDatabase(Config["HostLotusNotesServer"], Config["PathLotusNotesDatabase"], false);
                NotesDateTime startDateMailAll = notesSession.CreateDateTime(Config["StartDateMailAll"]);
                NotesDateTime startDateMailNew = notesSession.CreateDateTime(Config["StartDateMailNew"]);
                NotesDocument profileDocument = notesDb.GetProfileDocument("Profile");

                if (!getAllMail) // If only new mail get the last time we checked email
                {
                    if (profileDocument != null && profileDocument.HasItem("UntilTime"))
                    {
                        object[] dateTime = profileDocument.GetItemValue("UntilTime");
                        if (dateTime != null && dateTime.Length > 0)
                            startDateMailNew = notesSession.CreateDateTime(Convert.ToString(dateTime[0]));
                    }
                }

                NotesDateTime startingDateTime = (getAllMail) ? startDateMailAll : startDateMailNew;
                var documentCollection = notesDb.GetModifiedDocuments(startingDateTime);
                NotesDocument lotusNotesEmail = documentCollection.GetFirstDocument();

                while (lotusNotesEmail != null)
                {
                    if (lotusNotesEmail.IsValid
                        && (!lotusNotesEmail.IsDeleted))
                    {
                        NotesItem fromNotesItem = lotusNotesEmail.GetFirstItem("From");
                        NotesItem toNotesItem = lotusNotesEmail.GetFirstItem("INetSendTo");
                        NotesItem subjectNotesItem = lotusNotesEmail.GetFirstItem("Subject");
                        NotesItem bodyNotesItem = lotusNotesEmail.GetFirstItem("Body");

                        emails.Add(new Email
                        {
                            From = fromNotesItem == null ? "N/A" : fromNotesItem.Text,
                            To = toNotesItem == null ? "N/A" : toNotesItem.Text,
                            Subject = subjectNotesItem == null ? "N/A" : subjectNotesItem.Text,
                            Body = bodyNotesItem == null ? "N/A" : bodyNotesItem.Text,
                            Date = lotusNotesEmail.Created == null ? DateTime.MinValue : Convert.ToDateTime(lotusNotesEmail.Created.ToString()),
                            Attachments = ExtractAttachments(lotusNotesEmail)
                        });

                        ReleaseComResources(new object[] { fromNotesItem, toNotesItem, subjectNotesItem, bodyNotesItem });
                        // Always last line:
                        lotusNotesEmail = documentCollection.GetNextDocument(lotusNotesEmail);
                    }
                }

                // Time-stamp most recent mail pick-up (if not getting all mail)
                if (!getAllMail)
                {
                    SetMailAsRead(profileDocument, documentCollection);
                }

                // Release Notes objects
                ReleaseComResources(new object[] { notesDb, notesSession, profileDocument, documentCollection });

            }
            catch (Exception e)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Log(LogLevel.Error, e);
            }

            return emails;
        }
示例#13
0
        public CalendarEvent GetCurrentMeeting(string password)
        {
            NotesSession notesSession = new NotesSession();
            NotesDatabase notesDatabase;

            try
            {
                notesSession.Initialize(password);
                string MailServer = notesSession.GetEnvironmentString("MailServer", true);
                string MailFile = notesSession.GetEnvironmentString("MailFile", true);
                notesDatabase = notesSession.GetDatabase(MailServer, MailFile, false);

                NotesDateTime minStartDate = notesSession.CreateDateTime("Today");
                NotesDateTime maxEndDate = notesSession.CreateDateTime("Tomorrow");
                // Query Lotus Notes to get calendar entries in our date range.
                // To understand this SELECT, go to http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp
                // and search for the various keywords. Here is an overview:
                //   !@IsAvailable($Conflict) will exclude entries that conflicts with another.
                //     LN doesn't show conflict entries and we should ignore them.
                //   @IsAvailable(CalendarDateTime) is true if the LN document is a calendar entry
                //   @Explode splits a string based on the delimiters ",; "
                //   The operator *= is a permuted equal operator. It compares all entries on
                //     the left side to all entries on the right side. If there is at least one
                //     match, then true is returned.
                String calendarQuery = "SELECT (!@IsAvailable($Conflict) & @IsAvailable(CalendarDateTime) & (@Explode(CalendarDateTime) *= @Explode(@TextToTime(\""
                    + minStartDate.LocalTime
                    + "-" + maxEndDate.LocalTime + "\"))))";

                NotesDocumentCollection appointments = notesDatabase.Search(calendarQuery, null, 25);
                //appointments.Count
                NotesDocument Current = appointments.GetFirstDocument();
                DateTime rightNow = DateTime.Now;
                CalendarEvent closestMeeting = null;
                TimeSpan ts = new TimeSpan(2, 0, 0, 0); //set for 2 days as longest time span

                while (Current != null)
                {
                    int repeatCount = ((object[])Current.GetItemValue("StartDateTime")).Length;
                    for (int i = 0; i < repeatCount; i++)
                    {
                        var calendarEvent = GetCallendarEvent(Current, i);
                        if (calendarEvent.Starts <= rightNow && calendarEvent.Ends > rightNow)
                        {
                            //ding ding ding, winner
                            return calendarEvent;
                        }
                        TimeSpan timeToMeeting = calendarEvent.Starts.Subtract(rightNow);
                        if (timeToMeeting < ts && calendarEvent.Starts > rightNow)
                        {
                            ts = timeToMeeting;
                            closestMeeting = calendarEvent;
                        }
                    }

                    Current = appointments.GetNextDocument(Current);
                }
                return closestMeeting;

            }
            catch (Exception)
            {
                //TODO: Catch bad stuff here and provide a message
                throw;
            }
        }
        public void SetMailAsRead(DateTime dateTime)
        {
            LoadConfig();

            NotesSession notesSession = new NotesSession();
            notesSession.Initialize(Config["PasswordLotusNotesAccount"]);
            NotesDatabase notesDb = notesSession.GetDatabase(Config["HostLotusNotesServer"], Config["PathLotusNotesDatabase"], false);
            NotesDateTime lnDateTime = notesSession.CreateDateTime(dateTime.ToShortDateString());
            NotesDocument profileDocument = notesDb.GetProfileDocument("Profile");

            try
            {
                profileDocument.ReplaceItemValue("UntilTime", lnDateTime);
                profileDocument.Save(true, true, true);
            }
            catch (Exception e)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Log(LogLevel.Error, e);
            }

            ReleaseComResources(new object[] { notesDb, notesSession, profileDocument, lnDateTime });
        }
示例#15
0
        /// <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;
            }
        }
示例#16
0
        //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);
        }
示例#17
0
        Regex excludeField        = new Regex("^(Form)$");//new Regex("^(\\$.*|Form|Readers)$");

        public Form1()
        {
            InitializeComponent();
            saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            treeView1.TreeViewNodeSorter     = new NodeSorter();
            #region Command Line Arguments
            string[]      args      = Environment.GetCommandLineArgs();
            string        notesFile = "";
            bool          showHelp  = false;
            List <string> error     = new List <string>();
            for (int i = 1; i < args.Length; i++)
            {
                switch (args[i])
                {
                case "-notesServer":
                    if (args.Length > i + 1)
                    {
                        notesServer = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -notesServer");
                        showHelp = true;
                    }
                    break;

                case "-notesDomain":
                    if (args.Length > i + 1)
                    {
                        notesDomain = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -notesDomain");
                        showHelp = true;
                    }
                    break;

                case "-notesPassword":
                    if (args.Length > i + 1)
                    {
                        notesPassword = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -notesPassword");
                        showHelp = true;
                    }
                    break;

                case "-mysqlServer":
                    if (args.Length > i + 1)
                    {
                        mysqlServer = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -mysqlServer");
                        showHelp = true;
                    }
                    break;

                case "-mysqlDatabase":
                    if (args.Length > i + 1)
                    {
                        mysqlDatabase = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -mysqlDatabase");
                        showHelp = true;
                    }
                    break;

                case "-mysqlUsername":
                    if (args.Length > i + 1)
                    {
                        mysqlUsername = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -mysqlUsername");
                        showHelp = true;
                    }
                    break;

                case "-mysqlPassword":
                    if (args.Length > i + 1)
                    {
                        mysqlPassword = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -mysqlPassword");
                        showHelp = true;
                    }
                    break;

                case "-notesFile":
                    if (args.Length > i + 1)
                    {
                        notesFile = args[++i];
                    }
                    else
                    {
                        error.Add("Need argument after -notesFile");
                        showHelp = true;
                    }
                    break;

                case "/?":
                case "-?":
                case "/help":
                case "-help":
                    showHelp = true;
                    break;

                default:
                    error.Add(args[i] + " is not a valid argument.");
                    showHelp = true;
                    break;
                }
            }
            if (notesFile != "")
            {
                try
                {
                    NotesSession  nSession = initSession(notesPassword);
                    NotesDatabase db;
                    if (File.Exists(notesFile) || (notesServer == "" && notesDomain == ""))
                    {
                        db = nSession.GetDatabase("", notesFile, false);
                        onLocalComputer = true;
                    }
                    else
                    {
                        db = nSession.GetDatabase(notesServer + "//" + notesDomain, notesFile, false);
                        onLocalComputer = false;
                    }
                    treeView1.Nodes.Add(db.FilePath, db.Title, "database", "database");
                }
                catch (Exception ex)
                {
                    error.Add("Error loading -notesFile: " + ex.Message);
                }
            }
            if (showHelp)
            {
                string argString =
                    "Arguments:\n" +
                    "\n" +
                    "-notesServer: The Domino server name\n" +
                    "-notesDomain: The Domino server domain\n" +
                    "-notesPassword: The password for Lotus Notes\n" +
                    "-notesFile: The file path to the nsf database\n" +
                    "-mysqlDatabase: The database name for the exported documents\n" +
                    "-mysqlServer: The mysql server address or IP address\n" +
                    "-mysqlUsername: The username for the mysql server\n" +
                    "-mysqlPassword: The password for the mysql server\n" +
                    "\n" +
                    "Examples:\n" +
                    "\n" +
                    "nsf2sql.exe -notesServer domino -notesDomain company -notesPassword \"your password\" -notesFile banner.nsf -mysqlDatabase banner_nsf";
                if (error.Count > 0)
                {
                    string messageText = "Errors:\n\n" + String.Join("\n\n", error);
                    messageText += "\n\n" + argString;
                    MessageBox.Show(messageText, "NSF2SQL Command Line Arguments", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(argString, "NSF2SQL Command Line Arguments", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            #endregion
        }
示例#18
0
        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();
        }
示例#19
0
        public string Send(MailBody mailBody)
        {
            _MailBody = mailBody;
            InitSettings();
            Validation();
            NotesSession  ns;
            NotesDatabase ndb;

            try
            {
                ns = new NotesSession();
                ns.Initialize(_MailSet.Password);
                //初始化NotesDatabase
                ndb = ns.GetDatabase(_MailSet.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);
                }

                //发送邮件
                object obj = doc.GetItemValue("SendTo");
                doc.Send(false, ref obj);
                doc = null;
                return("");
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                return("发送邮件失败");
            }
            finally
            {
                ndb = null;
                ns  = null;
            }
        }
示例#20
0
        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();
            }
        }
示例#21
0
        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
        }