Ejemplo n.º 1
0
 void grdMain_ItemCommand(object source, DataGridCommandEventArgs e)
 {
     if (e.CommandName == "Select")
     {
         int    selId             = int.Parse(e.Item.Cells[0].Text);
         string containerKey      = "EMailAttach";
         CS.BaseIbnContainer bic2 = CS.BaseIbnContainer.Create(ContainerName, containerKey);
         CS.FileStorage      fs2  = (CS.FileStorage)bic2.LoadControl("FileStorage");
         CS.DirectoryInfo    di   = fs2.GetDirectory(fs2.Root.Id, guid, true);
         try
         {
             fs.CopyFile(selId, di.Id);
         }
         catch { }
         string        sFiles = "";
         CS.FileInfo[] _fi    = fs2.GetFiles(di);
         foreach (CS.FileInfo fi in _fi)
         {
             sFiles += String.Format("<div style='padding-bottom:1px;'><img align='absmiddle' src='{0}' width='16' height='16'/>&nbsp;{1}&nbsp;&nbsp;<img src='{2}' align='absmiddle' width='16' height='16' style='cursor:pointer;' onclick='_deleteFile({3})' title='{4}' /></div>",
                                     ResolveUrl("~/Common/ContentIcon.aspx?IconID=" + fi.FileBinaryContentTypeId),
                                     Util.CommonHelper.GetShortFileName(fi.Name, 40),
                                     ResolveUrl("~/Layouts/Images/delete.gif"),
                                     fi.Id, LocRM.GetString("tDelete"));
         }
         Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), String.Format("CloseAll(\"{0}\");", sFiles), true);
     }
 }
Ejemplo n.º 2
0
        public ArrayList DeleteAttachment(string _guid, string _id)
        {
            string    sFiles         = "";
            ArrayList values         = new ArrayList();
            string    _containerName = "FileLibrary";
            string    _containerKey  = "EMailAttach";

            CS.BaseIbnContainer bic = CS.BaseIbnContainer.Create(_containerName, _containerKey);
            CS.FileStorage      fs  = (CS.FileStorage)bic.LoadControl("FileStorage");
            fs.DeleteFile(int.Parse(_id));
            CS.DirectoryInfo di = fs.GetDirectory(fs.Root.Id, _guid, false);
            if (di != null)
            {
                CS.FileInfo[] _fi = fs.GetFiles(di);
                foreach (CS.FileInfo fi in _fi)
                {
                    sFiles += String.Format(CultureInfo.InvariantCulture,
                                            "<div style='padding-bottom:1px;'><img align='absmiddle' src='{0}' width='16' height='16'>&nbsp;{1}&nbsp;&nbsp;<img src='{2}' align='absmiddle' width='16' height='16' style='cursor:pointer;' onclick='_deleteFile({3})' title='{4}' /></div>",
                                            CHelper.GetAbsolutePath("/Common/ContentIcon.aspx?IconID=" + fi.FileBinaryContentTypeId),
                                            Util.CommonHelper.GetShortFileName(fi.Name, 40),
                                            CHelper.GetAbsolutePath("/Layouts/Images/delete.gif"),
                                            fi.Id,
                                            LocRM.GetString("Delete"));
                }
            }
            values.Add(sFiles);
            return(values);
        }
Ejemplo n.º 3
0
 private void GetCurrentFolder()
 {
     ContainerKey = ViewState["ContainerKey"].ToString();
     bic          = CS.BaseIbnContainer.Create(ContainerName, ContainerKey);
     fs           = (CS.FileStorage)bic.LoadControl("FileStorage");
     if (!Page.IsPostBack && Request["FolderId"] != null && Request["FolderId"] != String.Empty)
     {
         FolderId = int.Parse(Request["FolderId"]);
     }
     else if (FolderId < 0 && pc["fs_FolderId_" + ContainerKey] != null)
     {
         int iFolder         = int.Parse(pc["fs_FolderId_" + ContainerKey]);
         CS.DirectoryInfo di = fs.GetDirectory(iFolder);
         if (di != null)
         {
             FolderId = iFolder;
         }
         else
         {
             FolderId = fs.Root.Id;
         }
     }
     else
     {
         FolderId = fs.Root.Id;
     }
     RootId = fs.Root.Id;
     pc["fs_FolderId_" + ContainerKey] = FolderId.ToString();
 }
Ejemplo n.º 4
0
        protected void grdMain_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                int selId = int.Parse(e.Item.Cells[0].Text);

                string sText  = "";
                string sTitle = "";
                using (IDataReader reader = Mediachase.IBN.Business.Common.GetArticle(selId))
                {
                    if (reader.Read())
                    {
                        sTitle = reader["Question"].ToString();
                        sText  = String.Format("<div style='border-top: solid 1px #95B7F3; padding:0px;background-color:ffffe1;'>" +
                                               "<div style='padding:5px; cursor:default;background-color:#FFD275;'><b>{0}</b></div>" +
                                               "<div style='padding:5px;'>{1}</div>" +
                                               "</div>", reader["Question"].ToString(), reader["AnswerHTML"].ToString());
                    }
                }

                Common.AddHistory(ObjectTypes.KnowledgeBase, selId, sTitle);
                Common.IncreaseArticleCounter(selId);

                string sFiles           = "";
                string containerName    = "FileLibrary";
                string containerKey     = UserRoleHelper.CreateArticleContainerKey(selId);
                CS.BaseIbnContainer bic = CS.BaseIbnContainer.Create(containerName, containerKey);
                CS.FileStorage      fs  = (CS.FileStorage)bic.LoadControl("FileStorage");
                CS.FileInfo[]       _fi = fs.Root.GetFiles();
                if (_fi.Length > 0)
                {
                    string _containerName    = "FileLibrary";
                    string _containerKey     = "EMailAttach";
                    CS.BaseIbnContainer _bic = CS.BaseIbnContainer.Create(_containerName, _containerKey);
                    CS.FileStorage      _fs  = (CS.FileStorage)_bic.LoadControl("FileStorage");
                    CS.DirectoryInfo    di   = _fs.GetDirectory(_fs.Root.Id, guid, true);
                    foreach (CS.FileInfo fi in _fi)
                    {
                        fs.CopyFile(fi.Id, di.Id, true);
                    }

                    _fi = _fs.GetFiles(di);
                    foreach (CS.FileInfo fi in _fi)
                    {
                        sFiles += String.Format("<div style='padding-bottom:1px;'><img align='absmiddle' src='{0}' width='16' height='16'>&nbsp;{1}&nbsp;&nbsp;<img src='{2}' align='absmiddle' width='16' height='16' style='cursor:pointer;' onclick='_deleteFile({3})' title='{4}' /></div>",
                                                ResolveUrl("~/Common/ContentIcon.aspx?IconID=" + fi.FileBinaryContentTypeId),
                                                Util.CommonHelper.GetShortFileName(fi.Name, 40),
                                                ResolveUrl("~/Layouts/Images/delete.gif"),
                                                fi.Id,
                                                LocRM2.GetString("tDelete"));
                    }
                }
                sText = sText.Replace("\r\n", "");
                sText = sText.Replace("\t", "");
                sText = sText.Replace("\\", "\\\\");
                sText = sText.Replace("\"", "\\\"");
                Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), String.Format("CloseAll(\"{0}\", \"{1}\");", sFiles, sText), true);
            }
        }
Ejemplo n.º 5
0
        private void BuildPath()
        {
            if (FolderId <= 0)
            {
                return;
            }
            string sPath = "";

            int iFolder = FolderId;

            while (true)
            {
                CS.DirectoryInfo di = fs.GetDirectory(iFolder);
                string           sFullFolderName = di.Name;
                if (iFolder == RootId)
                {
                    sFullFolderName = LocRM.GetString("tRoot");
                }
                string sFolderName = sFullFolderName;
                if (sFolderName.Length > 13)
                {
                    sFolderName = sFolderName.Substring(0, 10) + "...";
                }
                if (sPath == "")
                {
                    sPath = String.Format("<a href='{0}' title=\"{2}\">{1}</a>", GetCurrentLink(iFolder), sFolderName, sFullFolderName);
                }
                else
                {
                    sPath = String.Format("<a href='{0}' title=\"{2}\">{1}</a> \\ {3}", GetCurrentLink(iFolder), sFolderName, sFullFolderName, sPath);
                }
                if (iFolder == RootId)
                {
                    break;
                }
                iFolder = di.ParentDirectoryId;
            }
            lblPath.Text = sPath;
        }
        private void Process()
        {
            string _containerName = "FileLibrary";
            string _containerKey  = "EMailAttach";

            CS.BaseIbnContainer bic = CS.BaseIbnContainer.Create(_containerName, _containerKey);
            CS.FileStorage      fs  = (CS.FileStorage)bic.LoadControl("FileStorage");
            CS.DirectoryInfo    di  = fs.GetDirectory(fs.Root.Id, guid, true);

            for (int Index = 0; Index < Request.Files.Count; Index++)
            {
                if (!String.IsNullOrEmpty(Request.Files[Index].FileName))
                {
                    using (McHttpPostedFile PostedFile = new McHttpPostedFile(Request.Files[Index]))
                    {
                        if (PostedFile.InputStream != null)
                        {
                            fs.SaveFile(di.Id, PostedFile.FileName, PostedFile.InputStream);
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        void lbSelectChecked_Click(object sender, EventArgs e)
        {
            string    sIds  = hidForSelect.Value;
            ArrayList alIds = new ArrayList();

            while (sIds.Length > 0)
            {
                alIds.Add(sIds.Substring(0, sIds.IndexOf(",")));
                sIds = sIds.Remove(0, sIds.IndexOf(",") + 1);
            }
            string _containerKey = "EMailAttach";

            CS.BaseIbnContainer bic2 = CS.BaseIbnContainer.Create(ContainerName, _containerKey);
            CS.FileStorage      fs2  = (CS.FileStorage)bic2.LoadControl("FileStorage");
            CS.DirectoryInfo    di   = fs2.GetDirectory(fs2.Root.Id, guid, true);
            foreach (string scId in alIds)
            {
                int assetID = int.Parse(scId);
                try
                {
                    fs.CopyFile(assetID, di.Id);
                }
                catch { }
            }
            string sFiles = "";

            CS.FileInfo[] _fi = fs2.GetFiles(di);
            foreach (CS.FileInfo fi in _fi)
            {
                sFiles += String.Format("<div style='padding-bottom:1px;'><img align='absmiddle' src='{0}' width='16' height='16'/>&nbsp;{1}&nbsp;&nbsp;<img src='{2}' align='absmiddle' width='16' height='16' style='cursor:pointer;' onclick='_deleteFile({3})' title='{4}' /></div>",
                                        ResolveUrl("~/Common/ContentIcon.aspx?IconID=" + fi.FileBinaryContentTypeId),
                                        Util.CommonHelper.GetShortFileName(fi.Name, 40),
                                        ResolveUrl("~/Layouts/Images/delete.gif"),
                                        fi.Id, LocRM.GetString("tDelete"));
            }
            Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), String.Format("CloseAll(\"{0}\");", sFiles), true);
        }
Ejemplo n.º 8
0
        private void BindStorage()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("Id", typeof(int)));
            dt.Columns.Add(new DataColumn("Weight", typeof(int)));              //0- Root, 1- Folder, 2-File
            dt.Columns.Add(new DataColumn("Icon", typeof(string)));
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("sortName", typeof(string)));
            DataRow dr;

            CS.DirectoryInfo diCur = fs.GetDirectory(FolderId);
            if (diCur.ParentDirectoryId > 0)
            {
                dr             = dt.NewRow();
                dr["Id"]       = diCur.Id;
                dr["Weight"]   = 0;
                dr["Icon"]     = ResolveUrl("~/layouts/images/blank.gif");
                dr["Name"]     = String.Format("<a href='{0}'>{1}</a>", GetCurrentLink(diCur.ParentDirectoryId), "[..]");
                dr["sortName"] = "";
                dt.Rows.Add(dr);
            }
            if (fs.CanUserRead(diCur.Id))
            {
                CS.DirectoryInfo[] _di = fs.GetDirectories(FolderId);
                bool CanWrite          = fs.CanUserWrite(diCur.Id);
                foreach (CS.DirectoryInfo di in _di)
                {
                    if (!fs.CanUserRead(di.Id))
                    {
                        continue;
                    }
                    dr           = dt.NewRow();
                    dr["Id"]     = di.Id;
                    dr["Weight"] = 1;
                    if (Mediachase.IBN.Business.Common.IsPop3Folder(di.Id))
                    {
                        dr["Icon"] = ResolveUrl("~/layouts/images/folder_mailbox.gif");
                    }
                    else
                    {
                        dr["Icon"] = ResolveUrl("~/layouts/images/FileTypes/Folder.gif");
                    }
                    dr["Name"] = String.Format("<a href='{0}' title='{2}'>{1}</a>", GetCurrentLink(di.Id),
                                               (di.Name.Length > 40) ? di.Name.Substring(0, 37) + "..." : di.Name, di.Name);
                    dr["sortName"] = di.Name;
                    dt.Rows.Add(dr);
                }

                CS.FileInfo[] _fi = fs.GetFiles(FolderId);
                foreach (CS.FileInfo fi in _fi)
                {
                    dr             = dt.NewRow();
                    dr["Id"]       = fi.Id;
                    dr["Weight"]   = 2;
                    dr["Icon"]     = ResolveUrl("~/Common/ContentIcon.aspx?IconID=" + fi.FileBinaryContentTypeId);
                    dr["Name"]     = Util.CommonHelper.GetShortFileName(fi.Name, 40);
                    dr["sortName"] = fi.Name;
                    dt.Rows.Add(dr);
                }
            }
            DataView dv = dt.DefaultView;

            dv.Sort = "Weight, " + pc["fs_Sort1_" + ContainerKey].ToString();

            int i = 4;

            grdMain.Columns[i++].HeaderText = LocRM.GetString("DocTitle");

            if (pc["fs_PageSize1_" + ContainerKey] == null)
            {
                pc["fs_PageSize1_" + ContainerKey] = "10";
            }

            grdMain.PageSize = int.Parse(pc["fs_PageSize1_" + ContainerKey].ToString());

            if (pc["fs_Page1_" + ContainerKey] == null)
            {
                pc["fs_Page1_" + ContainerKey] = "0";
            }
            int PageIndex = int.Parse(pc["fs_Page1_" + ContainerKey].ToString());
            int ppi       = dv.Count / grdMain.PageSize;

            if (dv.Count % grdMain.PageSize == 0)
            {
                ppi = ppi - 1;
            }
            if (PageIndex <= ppi)
            {
                grdMain.CurrentPageIndex = PageIndex;
            }
            else
            {
                grdMain.CurrentPageIndex       = 0;
                pc["fs_Page1_" + ContainerKey] = "0";
            }

            grdMain.DataSource = dv;
            grdMain.DataBind();

            /*foreach (DataGridItem dgi in grdMain.Items)
             * {
             * }*/
        }
Ejemplo n.º 9
0
        protected override void OnProcessPop3Message(Pop3Box box, Mediachase.Net.Mail.Pop3Message message)
        {
            try
            {
                // Step 0. Get settings
                FileSettings settings = GetSettings(box);

                // Step 0.5 Create storage
                string containerKey = "Workspace";
                if (settings.ContainerKey != String.Empty)
                {
                    containerKey = settings.ContainerKey;
                }
                BaseIbnContainer baseContainer = BaseIbnContainer.Create("FileLibrary", containerKey);
                FileStorage      storage       = (FileStorage)baseContainer.LoadControl("FileStorage");

                // Step 1. Get Email sender info
                MailAddress from = message.Sender;
                if (from == null)
                {
                    from = message.From;
                }

                // Step 2. Get Ibn User
                int userId = GetUserIdByEmail(from.Address, settings.OnlyExternalSenders);

                if (userId != -1)
                {
                }
                else
                {
                    if (settings.AutoKillForUnknown)
                    {
                        return;
                    }
                }

                // Step 3. Find Folder
                int FolderId = settings.FolderId;
                if (settings.FolderPattern != String.Empty)
                {
                    String FolderName = ValidatePatternPath(ParseFolderPattern(settings.FolderPattern, message, userId));

                    Mediachase.IBN.Business.ControlSystem.DirectoryInfo dirInfo = storage.GetDirectory(FolderId, FolderName, true);
                    if (dirInfo != null)
                    {
                        FolderId = dirInfo.Id;
                    }
                    else
                    {
                        FolderId = -1;
                    }
                }

                // Step 3. Create Files
                AddAttachments(storage, FolderId, message, userId);

                // Step 4. Create EML File
                if (settings.SaveMessageBodyAsEml)
                {
                    UploadEmlFile(storage, FolderId, userId, message);
                }
                // Step 5. Create MHT File
                if (settings.SaveMessageBodyAsMht)
                {
                    UploadMhtFile(storage, FolderId, userId, message);
                }
                // Step 5. Create MSG File
                if (settings.SaveMessageBodyAsMsg)
                {
                    UploadMsgFile(storage, FolderId, userId, message);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
                throw;
            }
        }
Ejemplo n.º 10
0
 public static void SendMessage(string[] To, string Subject, string Body, Mediachase.IBN.Business.ControlSystem.DirectoryInfo Attachments)
 {
     SendMessage(To, Subject, Body, Attachments, string.Empty, new NameValueCollection());
 }
Ejemplo n.º 11
0
        internal static Pop3Message Create(string From, string[] To, string Subject, string Body, Mediachase.IBN.Business.ControlSystem.DirectoryInfo Attachments)
        {
            MemoryStream emlMessage = new MemoryStream();

            byte[] tmpBuffer = null;

            string ToEmail = string.Join(", ", To);

            #region Fill Pop3 Message Stream
            // Create Pop3 Message Headers
            StringBuilder sbHeaders = new StringBuilder();

            sbHeaders.AppendFormat("Date: {0}", DateTime.UtcNow.ToString("r")).Append("\r\n");

            sbHeaders.AppendFormat("From: {0}", Rfc822HeaderCollection.Encode2AsciiString(From)).Append("\r\n");
            sbHeaders.AppendFormat("To: {0}", Rfc822HeaderCollection.Encode2AsciiString(ToEmail)).Append("\r\n");

            sbHeaders.AppendFormat("Subject: {0}", Rfc822HeaderCollection.Encode2AsciiString(Subject)).Append("\r\n");
            sbHeaders.Append("MIME-Version: 1.0").Append("\r\n");
            sbHeaders.Append("Content-Type: multipart/mixed; boundary=\"----------7E143249668A83E\"").Append("\r\n");
            sbHeaders.Append("\r\n");

            tmpBuffer = Encoding.ASCII.GetBytes(sbHeaders.ToString());
            emlMessage.Write(tmpBuffer, 0, tmpBuffer.Length);

            // Create Pop3 Message Entry
            StringBuilder sbMessage = new StringBuilder();

            sbMessage.Append("------------7E143249668A83E").Append("\r\n");

            // IF MESSAGE IS PLAIN TEXT
            //sbMessage.Append("Content-Type: text/plain; charset=utf-8").Append("\r\n");

            // IF MESSAGE IS HTML TEXT
            sbMessage.Append("Content-Type: text/html; charset=utf-8").Append("\r\n");

            sbMessage.Append("Content-Transfer-Encoding: base64").Append("\r\n");
            sbMessage.Append("\r\n");

            string FullMessage = Body;

            sbMessage.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(FullMessage), Base64FormattingOptions.InsertLineBreaks)).Append("\r\n");

            tmpBuffer = Encoding.ASCII.GetBytes(sbMessage.ToString());
            emlMessage.Write(tmpBuffer, 0, tmpBuffer.Length);

            if (Attachments != null)
            {
                Hashtable contentTypeHash = new Hashtable();

                using (IDataReader reader = ContentType.GetListContentTypes())
                {
                    while (reader.Read())
                    {
                        contentTypeHash.Add(((string)reader["Extension"]).ToLower(), (string)reader["ContentTypeString"]);
                    }
                }

                // Add Pop3 Message Attachements
                foreach (Mediachase.IBN.Business.ControlSystem.FileInfo fileInfo in Attachments.GetFiles())
                {
                    StringBuilder sbFile = new StringBuilder();

                    sbFile.Append("------------7E143249668A83E").Append("\r\n");
                    sbFile.AppendFormat("Content-Type: {0}; name=\"{1}\"", fileInfo.FileBinaryContentType, Rfc822HeaderCollection.Encode2AsciiString(fileInfo.Name)).Append("\r\n");
                    sbFile.Append("Content-Transfer-Encoding: base64").Append("\r\n");
                    sbFile.AppendFormat("Content-Disposition: attachment; filename=\"{0}\"", Rfc822HeaderCollection.Encode2AsciiString(fileInfo.Name)).Append("\r\n");
                    sbFile.Append("\r\n");

                    using (MemoryStream fs = new MemoryStream())
                    {
                        FileStorage.LightLoadFile(fileInfo, fs);
                        fs.Capacity = (int)fs.Length;

                        sbFile.Append(Convert.ToBase64String(fs.GetBuffer(), Base64FormattingOptions.InsertLineBreaks));
                    }

                    sbFile.Append("\r\n");

                    tmpBuffer = Encoding.ASCII.GetBytes(sbFile.ToString());
                    emlMessage.Write(tmpBuffer, 0, tmpBuffer.Length);
                }
            }

            // Add Final Line
            tmpBuffer = Encoding.ASCII.GetBytes("------------7E143249668A83E--\r\n\r\n");
            emlMessage.Write(tmpBuffer, 0, tmpBuffer.Length);

            #endregion

            return(new Pop3Message(emlMessage));
        }
Ejemplo n.º 12
0
        public static void SendMessage(string[] To, string Subject, string Body, Mediachase.IBN.Business.ControlSystem.DirectoryInfo Attachments, string Mode, NameValueCollection Params)
        {
            // Cleanup Temporary files
            DbEMailTempFile.CleanUp();

            #region Validate Arguments
            if (To == null)
            {
                throw new ArgumentNullException("To");
            }

            if (Subject == null)
            {
                throw new ArgumentNullException("Subject");
            }

            if (Body == null)
            {
                throw new ArgumentNullException("Body");
            }

            //if (To.Length == 0)
            //    throw new ArgumentOutOfRangeException("To", "Email recipient list is empty.");

            if (Mode == null)
            {
                Mode = string.Empty;
            }

            if (Params == null)
            {
                Params = new NameValueCollection();
            }
            #endregion

            string FromEmail = string.Empty;

            switch (Mode)
            {
            case EMailClient.IssueMode:
            case EMailClient.SmtpTestMode:
                FromEmail = Alerts2.AlertSenderEmail;
                break;

            default:
                FromEmail = Security.CurrentUser.Email;
                break;
            }

            string FullFromEmail = string.Format("\"{0} {1}\" <{2}>",
                                                 Security.CurrentUser.LastName,
                                                 Security.CurrentUser.FirstName,
                                                 FromEmail);

            using (DbTransaction tran = DbTransaction.Begin())
            {
                EMailMessageLogSetting EmailLogSettings = EMailMessageLogSetting.Current;
                if (EmailLogSettings.IsActive)
                {
                    EMailMessageLog.CleanUp(EmailLogSettings.Period);
                }
                else
                {
                    EmailLogSettings = null;
                }

                Mode = Mode.ToLower();

                #region Pre-format incoming arguments
                switch (Mode)
                {
                case EMailClient.IssueMode:
                    if (Params["IssueId"] == null)
                    {
                        throw new ArgumentNullException("Params[\"IssueId\"]");
                    }

                    int IssueId = int.Parse(Params["IssueId"]);

                    // TODO: Validate Subject & Ticket
                    if (TicketUidUtil.LoadFromString(Subject) == string.Empty)
                    {
                        IncidentBox incidentBox = IncidentBox.Load(Incident.GetIncidentBox(IssueId));

                        string IncidentTicket = Incident.GetIdentifier(IssueId);

                        if (incidentBox.Document.GeneralBlock.AllowOutgoingEmailFormat)
                        {
                            StringBuilder sb = new StringBuilder(incidentBox.Document.GeneralBlock.OutgoingEmailFormatSubject, 4096);

                            sb.Replace("[=Title=]", Subject);
                            sb.Replace("[=Ticket=]", IncidentTicket);
                            //sb.Replace("[=Text=]", Body);
                            sb.Replace("[=FirstName=]", Security.CurrentUser.FirstName);
                            sb.Replace("[=LastName=]", Security.CurrentUser.LastName);

                            Subject = sb.ToString();
                        }
                        else
                        {
                            Subject = string.Format("RE: [{0}] {1}",
                                                    IncidentTicket,
                                                    Subject);
                        }
                    }
                    break;

                default:
                    break;
                }

                #endregion

                Pop3Message msg = Create(FullFromEmail, To, Subject, Body, Attachments);

                switch (Mode)
                {
                case EMailClient.IssueMode:
                    #region Issue
                    int IssueId = int.Parse(Params["IssueId"]);

                    IncidentBox incidentBox = IncidentBox.Load(Incident.GetIncidentBox(IssueId));

                    bool AllowEMailRouting = true;

                    EMailRouterIncidentBoxBlock settings = IncidentBoxDocument.Load(incidentBox.IncidentBoxId).EMailRouterBlock;
                    if (!settings.AllowEMailRouting)
                    {
                        AllowEMailRouting = false;
                    }

                    EMailRouterPop3Box internalPop3Box = EMailRouterPop3Box.ListInternal();
                    if (internalPop3Box == null)
                    {
                        AllowEMailRouting = false;
                    }

                    // Register Email Message
                    // OZ: [2007--05-25] Fix Problem Object reference not set to an instance of an object If (internalPop3Box == NULL)
                    int EMailMessageId = EMailMessage.Create(internalPop3Box != null?
                                                             internalPop3Box.EMailRouterPop3BoxId : EMailRouterOutputMessage.FindEMailRouterPublicId(IssueId),
                                                             msg);

                    // Register Forume Node
                    int ThreadNodeId = EMailMessage.AddToIncidentMessage(true, IssueId, EMailMessageId, msg);

                    // Send Message

                    if (AllowEMailRouting)
                    {
                        ArrayList excludedUsers = EMailRouterOutputMessage.Send(IssueId, internalPop3Box, msg, To);
                        SystemEvents.AddSystemEvents(SystemEventTypes.Issue_Updated_Forum_MessageAdded, IssueId, -1, excludedUsers);
                    }
                    else
                    {
                        FromEmail     = EMailRouterOutputMessage.FindEMailRouterPublicEmail(IssueId);
                        FullFromEmail = string.Format("\"{0} {1}\" <{2}>",
                                                      Security.CurrentUser.LastName,
                                                      Security.CurrentUser.FirstName,
                                                      FromEmail);

                        // Create OutputMessageCreator
                        OutputMessageCreator issueOutput = new OutputMessageCreator(msg,
                                                                                    -1,
                                                                                    FromEmail,
                                                                                    FullFromEmail);

                        // Fill Recipent
                        foreach (string ToItem in To)
                        {
                            issueOutput.AddRecipient(ToItem);
                        }

                        foreach (EMailIssueExternalRecipient exRecipient in EMailIssueExternalRecipient.List(IssueId))
                        {
                            issueOutput.AddRecipient(exRecipient.EMail);
                        }

                        int emailBoxId = EMail.EMailRouterOutputMessage.FindEMailRouterPublicId(IssueId);

                        //Send Smtp Message
                        foreach (OutputMessage outputMsg in issueOutput.Create())
                        {
                            SmtpClientUtility.SendMessage(OutgoingEmailServiceType.HelpDeskEmailBox, emailBoxId, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                        }

                        ArrayList excludedUsers = new ArrayList();

                        foreach (string ToItem in To)
                        {
                            int emailUserId = DBUser.GetUserByEmail(ToItem, false);
                            if (emailUserId > 0)
                            {
                                excludedUsers.Add(emailUserId);
                            }
                        }

                        SystemEvents.AddSystemEvents(SystemEventTypes.Issue_Updated_Forum_MessageAdded, IssueId, -1, excludedUsers);
                    }
                    #endregion
                    break;

                case EMailClient.SmtpTestMode:
                    throw new NotImplementedException();
                //OutputMessageCreator smtpTestOutput = new OutputMessageCreator(msg,
                //    -1,
                //    FromEmail,
                //    FullFromEmail);

                //// Fill Recipent
                //foreach (string ToItem in To)
                //{
                //    smtpTestOutput.AddRecipient(ToItem);
                //}

                ////Send Smtp Message
                //foreach (OutputMessage outputMsg in smtpTestOutput.Create())
                //{
                //    //SmtpClientUtility.DirectSendMessage(outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                //    //SmtpBox.SendTestEmail(
                //}
                //break;
                default:
                    #region Default
                    // Create OutputMessageCreator
                    OutputMessageCreator defaultOutput = new OutputMessageCreator(msg,
                                                                                  -1,
                                                                                  FromEmail,
                                                                                  FullFromEmail);

                    // Fill Recipent
                    foreach (string ToItem in To)
                    {
                        defaultOutput.AddRecipient(ToItem);
                    }

                    //Send Smtp Message
                    foreach (OutputMessage outputMsg in defaultOutput.Create())
                    {
                        SmtpClientUtility.SendMessage(OutgoingEmailServiceType.SendFile, null, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                    }

                    #endregion
                    break;
                }

                if (Attachments != null)
                {
                    FileStorage.InnerDeleteFolder(Attachments.Id);
                }

                tran.Commit();
            }
        }
Ejemplo n.º 13
0
        protected void lbSend_Click(object sender, System.EventArgs e)
        {
            string sTo = txtTo.Text.Trim();

            // all recipients string
            string allRecipients = String.Empty;

            if (sTo != String.Empty)
            {
                allRecipients = sTo;
            }
            if (allRecipients != String.Empty)
            {
                allRecipients += "; ";
            }
            allRecipients += lblCC.Text;
            CommonHelper.AddToContext(ForumThreadNodeSetting.AllRecipients, allRecipients);

            string regex = "([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\\w]*[0-9a-zA-Z])*\\.)+[a-zA-Z]" +
                           "{2,9})";
            List <string> dic = new List <string>();

            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                                                                   | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);


            foreach (Match item in reg.Matches(sTo))
            {
                if (!dic.Contains(item.Value))
                {
                    dic.Add(item.Value);
                }
            }
            string[] masTo = dic.ToArray();

            if (masTo.Length == 0 && lblCC.Text == String.Empty)
            {
                lblException.Text  = LocRM.GetString("NoRecipients");
                divMessage.Visible = true;
                Page.ClientScript.RegisterStartupScript(this.GetType(), "_getFiles",
                                                        "window.setTimeout('updateAttachments()', 500);", true);
                return;
            }


            string _containerName = "FileLibrary";
            string _containerKey  = "EMailAttach";

            CS.BaseIbnContainer bic = CS.BaseIbnContainer.Create(_containerName, _containerKey);
            CS.FileStorage      fs  = (CS.FileStorage)bic.LoadControl("FileStorage");
            CS.DirectoryInfo    di  = fs.GetDirectory(fs.Root.Id, _guid, true);

            try
            {
                if (IncidentId > 0)
                {
                    NameValueCollection _params = new NameValueCollection();
                    _params["IssueId"] = IncidentId.ToString();
                    EMailClient.SendMessage(masTo, txtSubject.Text, fckEditor.Text, di, EMailClient.IssueMode, _params);
                    string sUrl = "../Incidents/IncidentView.aspx?IncidentId=" + IncidentId;
                    if (Request["back"] != null)
                    {
                        sUrl = HttpUtility.UrlDecode(Request["back"]);
                    }
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "_close", "try{window.opener.location.href='" + sUrl + "';}catch(ex){}window.close();", true);
                }
                else
                {
                    EMailClient.SendMessage(masTo, txtSubject.Text, fckEditor.Text, di);
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "_close", "window.close();", true);
                }
            }
            catch (Exception ex)
            {
                string sException = "";
                switch (ex.GetType().ToString())
                {
                case "System.Net.Sockets.SocketException":
                    sException = ex.Message;
                    break;

                case "Mediachase.IBN.Business.EMail.SmtpClientException":
                    sException = LocRM2.GetString("tServerSMTPError") + ":&nbsp;<span style='color:#444;font-style:italic;'>" + ex.Message + "</span>";
                    break;

                default:
                    // TODO: Save Exception to IBN Log And Show Friendly Link to Log
                    sException = ex.Message;
                    CHelper.GenerateErrorReport(ex);
                    break;
                }
                lblException.Text = LocRM2.GetString("SMTPSettingsIncorrect") + "&nbsp;" +
                                    LocRM2.GetString("tWereErrorsSMTP") + "<br/>" + sException;
                if (Security.IsUserInGroup(InternalSecureGroups.Administrator))
                {
                    lblSMTP.Text = "<a href='javascript:ToSMTPSettings();'><font style='color:Red;'><b><u>" + LocRM2.GetString("tSetupSMTPServer") + "</u></b></font></a>";
                }
                else
                {
                    lblSMTP.Text = LocRM2.GetString("tContactSMTPError");
                }
                divMessage.Visible = true;
                Page.ClientScript.RegisterStartupScript(this.GetType(), "_getFiles",
                                                        "window.setTimeout('updateAttachments()', 500);", true);
            }
        }
Ejemplo n.º 14
0
        private void BindDefaultValues()
        {
            string fromEmail = Security.CurrentUser.Email;

            if (IncidentId > 0)
            {
                fromEmail = EMailRouterOutputMessage.FindEMailRouterPublicEmail(IncidentId);
            }
            txtFrom.Text = String.Format(CultureInfo.InvariantCulture,
                                         "{1}&nbsp;&lt;{0}&gt;", fromEmail, Security.CurrentUser.DisplayName);
            lblCCTitle.Text = "";
            lblToTitle.Text = LocRM.GetString("tTo") + ":";
            if (IncidentId > 0)
            {
                NameValueCollection _params = new NameValueCollection();
                _params["IssueId"] = IncidentId.ToString();
                string[] erList = EMailClient.GetDefaultRecipientList(EMailClient.IssueMode, _params);
                for (int i = 0; i < erList.Length; i++)
                {
                    string sName = GetNameByEMail(erList[i]);
                    if (sName != "")
                    {
                        lblCC.Text += String.Format(CultureInfo.InvariantCulture, "{0} &lt;{1}&gt;; ", sName, erList[i]);
                    }
                    else
                    {
                        lblCC.Text += erList[i] + "; ";
                    }
                }

                string sValue = EMailMessage.GetOutgoingEmailFormatBodyPreview(IncidentId).Replace("[=Text=]", "");
                if (NodeId > 0)
                {
                    EMailMessageInfo mi = EMailMessageInfo.Load(NodeId);
                    sValue += "<br/>" + "<blockquote style='border-left: 2px solid rgb(0, 0, 0); padding-right: 0px; padding-left: 5px; margin-left: 5px; margin-right: 0px;' dir='ltr'>" + mi.HtmlBody + "</blockquote>";
                }
                fckEditor.Text = sValue;

                using (IDataReader reader = Incident.GetIncident(IncidentId))
                {
                    if (reader.Read())
                    {
                        txtSubject.Text = string.Format(CultureInfo.InvariantCulture
                                                        , "RE: [{0}] {1}"
                                                        , (reader["Identifier"] != DBNull.Value) ?
                                                        reader["Identifier"].ToString()
                                                                : TicketUidUtil.Create(IncidentBox.Load((int)reader["IncidentBoxId"]).IdentifierMask, IncidentId)
                                                        , HttpUtility.HtmlDecode(reader["Title"].ToString())
                                                        );
                    }
                }
            }
            if (FileIds != "")
            {
                string sFiles = FileIds.Trim();
                if (sFiles.EndsWith(","))
                {
                    sFiles = sFiles.Substring(0, sFiles.Length - 1);
                }
                string[] masFiles = sFiles.Split(',');
                if (masFiles.Length > 0)
                {
                    string _containerName   = "FileLibrary";
                    string _containerKey    = "EMailAttach";
                    CS.BaseIbnContainer bic = CS.BaseIbnContainer.Create(_containerName, _containerKey);
                    CS.FileStorage      fs  = (CS.FileStorage)bic.LoadControl("FileStorage");

                    CS.BaseIbnContainer bic2 = CS.BaseIbnContainer.Create(FilesContainerName, FilesContainerKey);
                    CS.FileStorage      fs2  = (CS.FileStorage)bic.LoadControl("FileStorage");

                    CS.DirectoryInfo di = fs.GetDirectory(fs.Root.Id, _guid, true);
                    for (int i = 0; i < masFiles.Length; i++)
                    {
                        fs2.CopyFile(int.Parse(masFiles[i]), di.Id);
                    }
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "_getFiles",
                                                            "window.setTimeout('updateAttachments()', 500);", true);
                }
            }
            if (ErrorId != "")
            {
                string support_email = GlobalResourceManager.Strings["SupportEmail"];
                //if (Security.CurrentUser != null && Security.CurrentUser.Culture.ToLower().IndexOf("ru") >= 0)
                //    support_email = "*****@*****.**";
                txtTo.Text = support_email + "; ";

                txtSubject.Text = String.Format("{0} {1} {2} Error Report", IbnConst.CompanyName, IbnConst.ProductFamilyShort, IbnConst.VersionMajorDotMinor);

                string prefix   = Request.Url.Host.Replace(".", "_");
                string FilePath = Server.MapPath("../Admin/Log/Error/" + prefix + "_" + ErrorId + ".html");
                string sTemp    = String.Empty;
                using (StreamReader sr = File.OpenText(FilePath))
                {
                    sTemp += sr.ReadToEnd();
                }

                Match match = Regex.Match(sTemp, @"<body[^>]*>(?<HtmlBody>[\s\S]*?)</body>", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
                if (match.Success)
                {
                    string body       = match.Groups["HtmlBody"].Value;
                    Match  matchStyle = Regex.Match(sTemp, @"<style[^>]*>(?<HtmlStyle>[\s\S]*?)</style>", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
                    if (matchStyle.Success)
                    {
                        body += matchStyle.Value;
                    }
                    sTemp = body;
                }
                fckEditor.Text = sTemp;
            }
            if (lblCC.Text != "")
            {
                lblCCTitle.Text = LocRM.GetString("tTo") + ":";
                lblToTitle.Text = LocRM.GetString("tCc") + ":";
            }
        }