Exemple #1
0
        private NotesSession initSession(string password)
        {
            NotesSession nSession = new NotesSession();

            nSession.Initialize(password);
            return(nSession);
        }
        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);
            }
        }
Exemple #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;
        }
        /// <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);
        }
        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;
            }
        }
Exemple #6
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);
            }
        }
Exemple #7
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);
        }
Exemple #8
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);
        }
Exemple #9
0
 public void Init(string password)
 {
     if (_lotusNotesServerSession != null)
     {
         return;
     }
     _lotusNotesServerSession = new NotesSession();
     try
     {
         _lotusNotesServerSession.Initialize(password);
         OnInitEvent();
     }
     catch
     {
         _lotusNotesServerSession = null;
     }
 }
Exemple #10
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
            {
            }
        }
Exemple #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);
            }
        }
Exemple #12
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);
            }
        }
        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;
        }
Exemple #14
0
 /// <summary>
 /// Инициализация Пароль
 /// </summary>
 /// <param name="password">Пароль</param>
 public LotusConnectedDataBase(string password)
 {
     Dispose();
     Session = new NotesSession();
     Session.Initialize(password);
 }
        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 });
        }
        //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;
            }
        }
        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();
            }
        }
Exemple #21
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;
            }
        }