コード例 #1
0
        private void Initialize(string userAgentStringsPath, string crawlerOnlyUserAgentStringsPath)
        {
            List <XElement> crawlerItems        = null;
            var             needSaveCrawlerOnly = false;

            if (!string.IsNullOrEmpty(crawlerOnlyUserAgentStringsPath) && _fileProvider.FileExists(crawlerOnlyUserAgentStringsPath))
            {
                //try to load crawler list from crawlers only file
                using (var sr = new StreamReader(crawlerOnlyUserAgentStringsPath))
                {
                    crawlerItems = XDocument.Load(sr).Root?.Elements("browscapitem").ToList();
                }
            }

            if (crawlerItems == null || !crawlerItems.Any())
            {
                //try to load crawler list from full user agents file
                using (var sr = new StreamReader(userAgentStringsPath))
                {
                    crawlerItems = XDocument.Load(sr).Root?.Element("browsercapitems")?.Elements("browscapitem")
                                   //only crawlers
                                   .Where(IsBrowscapItemIsCrawler).ToList();
                    needSaveCrawlerOnly = true;
                }
            }

            if (crawlerItems == null || !crawlerItems.Any())
            {
                throw new Exception("Incorrect file format");
            }

            _crawlerUserAgentsRegexp.AddRange(crawlerItems
                                              //get only user agent names
                                              .Select(e => e.Attribute("name"))
                                              .Where(e => !string.IsNullOrEmpty(e?.Value))
                                              .Select(e => e.Value)
                                              .Select(ToRegexp));

            if ((string.IsNullOrEmpty(crawlerOnlyUserAgentStringsPath) || _fileProvider.FileExists(crawlerOnlyUserAgentStringsPath)) && !needSaveCrawlerOnly)
            {
                return;
            }

            //try to write crawlers file
            using (var sw = new StreamWriter(crawlerOnlyUserAgentStringsPath))
            {
                var root = new XElement("browsercapitems");

                foreach (var crawler in crawlerItems)
                {
                    foreach (var element in crawler.Elements().ToList())
                    {
                        if ((element.Attribute("name")?.Value.ToLower() ?? string.Empty) == "crawler")
                        {
                            continue;
                        }
                        element.Remove();
                    }

                    root.Add(crawler);
                }

                root.Save(sw);
            }
        }
コード例 #2
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        /// <param name="attachedDownloadId">Attachment download ID (another attachment)</param>
        /// <param name="headers">Headers</param>
        public virtual void SendEmail(EmailAccount emailAccount, string subject, string body,
                                      string fromAddress, string fromName, string toAddress, string toName,
                                      string replyTo            = null, string replyToName = null,
                                      IEnumerable <string> bcc  = null, IEnumerable <string> cc           = null,
                                      string attachmentFilePath = null, string attachmentFileName         = null,
                                      int attachedDownloadId    = 0, IDictionary <string, string> headers = null)
        {
            var message = new MailMessage
            {
                //from, to, reply to
                From = new MailAddress(fromAddress, fromName)
            };

            message.To.Add(new MailAddress(toAddress, toName));
            if (!string.IsNullOrEmpty(replyTo))
            {
                message.ReplyToList.Add(new MailAddress(replyTo, replyToName));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }

            //content
            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = true;

            //headers
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            //create the file attachment for this e-mail message
            if (!string.IsNullOrEmpty(attachmentFilePath) &&
                _fileProvider.FileExists(attachmentFilePath))
            {
                var attachment = new Attachment(attachmentFilePath);
                attachment.ContentDisposition.CreationDate     = _fileProvider.GetCreationTime(attachmentFilePath);
                attachment.ContentDisposition.ModificationDate = _fileProvider.GetLastWriteTime(attachmentFilePath);
                attachment.ContentDisposition.ReadDate         = _fileProvider.GetLastAccessTime(attachmentFilePath);
                if (!string.IsNullOrEmpty(attachmentFileName))
                {
                    attachment.Name = attachmentFileName;
                }

                message.Attachments.Add(attachment);
            }
            //another attachment?
            if (attachedDownloadId > 0)
            {
                var download = _downloadService.GetDownloadById(attachedDownloadId);
                if (download != null)
                {
                    //we do not support URLs as attachments
                    if (!download.UseDownloadUrl)
                    {
                        var fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id.ToString();
                        fileName += download.Extension;

                        var ms         = new MemoryStream(download.DownloadBinary);
                        var attachment = new Attachment(ms, fileName);
                        //string contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream";
                        //var attachment = new Attachment(ms, fileName, contentType);
                        attachment.ContentDisposition.CreationDate     = DateTime.UtcNow;
                        attachment.ContentDisposition.ModificationDate = DateTime.UtcNow;
                        attachment.ContentDisposition.ReadDate         = DateTime.UtcNow;
                        message.Attachments.Add(attachment);
                    }
                }
            }

            //send email

            /*1st: https://www.google.com/settings/security/lesssecureapps : Should be Turned on.
             *
             * //2nd: https://accounts.google.com/b/0/displayunlockcaptcha
             */
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host        = emailAccount.Host;
                smtpClient.Port        = emailAccount.Port;
                smtpClient.EnableSsl   = emailAccount.EnableSsl;
                smtpClient.Credentials = emailAccount.UseDefaultCredentials ?
                                         CredentialCache.DefaultNetworkCredentials :
                                         new NetworkCredential(emailAccount.Username, emailAccount.Password);
                smtpClient.Send(message);
            }
        }
コード例 #3
0
        /// <summary>
        /// Load data settings
        /// </summary>
        /// <param name="filePath">File path; pass null to use the default settings file</param>
        /// <param name="reloadSettings">Whether to reload data, if they already loaded</param>
        /// <param name="fileProvider">File provider</param>
        /// <returns>Data settings</returns>
        public static DataSettings LoadSettings(string filePath = null, bool reloadSettings = false, IResearchFileProvider fileProvider = null)
        {
            if (!reloadSettings && Singleton <DataSettings> .Instance != null)
            {
                return(Singleton <DataSettings> .Instance);
            }

            fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
            filePath     = filePath ?? fileProvider.MapPath(ResearchDataSettingsDefaults.FilePath);

            //check whether file exists
            if (!fileProvider.FileExists(filePath))
            {
                //if not, try to parse the file that was used in previous nopCommerce versions
                filePath = fileProvider.MapPath(ResearchDataSettingsDefaults.ObsoleteFilePath);
                if (!fileProvider.FileExists(filePath))
                {
                    return(new DataSettings());
                }

                //get data settings from the old txt file
                var dataSettings = new DataSettings();
                using (var reader = new StringReader(fileProvider.ReadAllText(filePath, Encoding.UTF8)))
                {
                    string settingsLine;
                    while ((settingsLine = reader.ReadLine()) != null)
                    {
                        var separatorIndex = settingsLine.IndexOf(':');
                        if (separatorIndex == -1)
                        {
                            continue;
                        }

                        var key   = settingsLine.Substring(0, separatorIndex).Trim();
                        var value = settingsLine.Substring(separatorIndex + 1).Trim();

                        switch (key)
                        {
                        case "DataProvider":
                            dataSettings.DataProvider = System.Enum.TryParse(value, true, out DataProviderType providerType) ? providerType : DataProviderType.Unknown;
                            continue;

                        case "DataConnectionString":
                            dataSettings.DataConnectionString = value;
                            continue;

                        default:
                            dataSettings.RawDataSettings.Add(key, value);
                            continue;
                        }
                    }
                }

                //save data settings to the new file
                SaveSettings(dataSettings, fileProvider);

                //and delete the old one
                fileProvider.DeleteFile(filePath);

                Singleton <DataSettings> .Instance = dataSettings;
                return(Singleton <DataSettings> .Instance);
            }

            var text = fileProvider.ReadAllText(filePath, Encoding.UTF8);

            if (string.IsNullOrEmpty(text))
            {
                return(new DataSettings());
            }

            //get data settings from the JSON file
            Singleton <DataSettings> .Instance = JsonConvert.DeserializeObject <DataSettings>(text);

            return(Singleton <DataSettings> .Instance);
        }
コード例 #4
0
 /// <summary>
 /// Get a value indicating whether some file (thumb) already exists
 /// </summary>
 /// <param name="thumbFilePath">Thumb file path</param>
 /// <param name="thumbFileName">Thumb file name</param>
 /// <returns>Result</returns>
 protected virtual bool GeneratedThumbExists(string thumbFilePath, string thumbFileName)
 {
     return(_fileProvider.FileExists(thumbFilePath));
 }