예제 #1
0
        public static string GetTipo(string folderid)
        {
            string           tipo             = string.Empty;
            MailLocalService mailLocalService = new MailLocalService();
            string           azione           = string.Empty;
            List <Folder>    getFolders       = CacheManager <List <Folder> > .get(CacheKeys.FOLDERS, VincoloType.NONE);

            if (getFolders == null)
            {
                getFolders = mailLocalService.getAllFolders();
            }
            int id = 0;

            int.TryParse(folderid, out id);
            var idnome = (from f in getFolders
                          where f.Id == id
                          select f.IdNome).FirstOrDefault();

            if (idnome == "3")
            {
                return("R");
            }
            var t = (from a in getFolders
                     where a.Id == id
                     select a.TipoFolder);

            tipo = t.FirstOrDefault();
            return(tipo);
        }
예제 #2
0
        private void SearchByParams(string APageIndex)
        {
            btnStampaDistinta.Visible = false;
            ddlCartellaSposta.Visible = false;
            pnlSposta.Visible         = btnSposta.Visible = false;
            btnUnLetta.Visible        = false;
            btnLetta.Visible          = false;
            HideMail(null, null);
            Dictionary <MailTypeSearch, string> idx = new Dictionary <MailTypeSearch, string>();

            idx = getDictionaryChoice();
            if (ddlManagedAccounts.SelectedItem.Text != string.Empty && ddlCartella.SelectedValue != string.Empty &&
                rblIOBox.SelectedValue != string.Empty && rblTipoFolder.SelectedValue != string.Empty)
            {
                MailLocalService mailLocalService      = new MailLocalService();
                ResultList <MailHeaderExtended> result = mailLocalService.GetMailsGridByParams(ddlManagedAccounts.SelectedItem.Text, ddlCartella.SelectedValue, rblIOBox.SelectedValue, rblTipoFolder.SelectedValue, idx, 1, 5);
                gridBox.DataSource = result.List;
                gridBox.DataBind();
                if (result.List.Count > 0)
                {
                    btnStampaDistinta.Visible = true;
                    ddlCartellaSposta.Visible = true;
                    btnSposta.Visible         = true;
                    if (rblIOBox.SelectedValue == "I")
                    {
                        if (ddlInboxStato.SelectedValue == "1")
                        {
                            btnLetta.Visible   = false;
                            btnUnLetta.Visible = true;
                        }
                        if (ddlInboxStato.SelectedValue == "0")
                        {
                            btnLetta.Visible   = true;
                            btnUnLetta.Visible = false;
                        }
                        else if (ddlInboxStato.SelectedValue != "1" && ddlInboxStato.SelectedValue != "0")
                        {
                            btnLetta.Visible   = false;
                            btnUnLetta.Visible = false;
                        }
                    }
                    else
                    {
                        btnLetta.Visible   = false;
                        btnUnLetta.Visible = false;
                    }
                    gridBox.BottomPagerRow.Controls[0].Controls[1].Visible = true;
                    gridBox.BottomPagerRow.Visible = true;
                    int resPag = int.Parse(Properties.Settings.Default.ListaRisultatiPerPagina);
                    ((Paging)gridBox.BottomPagerRow.Controls[0].Controls[1]).configureControl("1", resPag.ToString(), result.Totale.ToString());
                }
            }
            else
            {
                (this.Page as BasePage).info.AddMessage("Selezionare tutti i campi obbligatori", Com.Delta.Messaging.MapperMessages.LivelloMessaggio.INFO);
            }
        }
예제 #3
0
        protected void btnStampa_Click(object sender, EventArgs e)
        {
            Dictionary <MailTypeSearch, string> idx = new Dictionary <MailTypeSearch, string>();
            MailLocalService mailLocalService       = new MailLocalService();

            idx = getDictionaryChoice();
            ResultList <MailHeaderExtended> result = mailLocalService.GetMailsGridByParams(ddlManagedAccounts.SelectedItem.Text, ddlCartella.SelectedValue, rblIOBox.SelectedValue, rblTipoFolder.SelectedValue, idx, 1, 1000);

            byte[] b = Helpers.StampaEmailAttoITEXT(result.List.ToList(), ddlManagedAccounts.SelectedItem.Text, ddlCartella.SelectedItem.Text, dtInizio.DateString(), dtFine.DateString(), rblIOBox.SelectedValue, ddlManagedAccounts.SelectedValue);
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=DistintaMail_" + ddlManagedAccounts.SelectedItem.Text + ".pdf");
            Response.OutputStream.Write(b, 0, b.Length);
            Response.End();
        }
예제 #4
0
        protected void OnPagerIndexChanged(string sPaginaRichiesta, int pag)
        {
            MailLocalService mailLocalService = new MailLocalService();
            int da  = (pag * int.Parse(Properties.Settings.Default.ListaRisultatiPerPagina)) + 1;
            int per = int.Parse(Properties.Settings.Default.ListaRisultatiPerPagina);
            Dictionary <MailTypeSearch, string> idx = new Dictionary <MailTypeSearch, string>();

            idx = getDictionaryChoice();
            ResultList <MailHeaderExtended> result = mailLocalService.GetMailsGridByParams(ddlManagedAccounts.SelectedItem.Text, ddlCartella.SelectedValue, rblIOBox.SelectedValue, rblTipoFolder.SelectedValue, idx, da, per);

            gridBox.DataSource = result.List;
            gridBox.DataBind();
            gridBox.BottomPagerRow.Visible = true;
            ((Paging)gridBox.BottomPagerRow.Controls[0].Controls[1]).configureControl((pag + 1).ToString(), Properties.Settings.Default.ListaRisultatiPerPagina.ToString(), result.Totale.ToString());
        }
예제 #5
0
        public static string GetAzione(string ActionId)
        {
            string           azione       = string.Empty;
            MailLocalService localService = new MailLocalService();
            List <ActiveUp.Net.Common.DeltaExt.Action> getActions = localService.GetFolderDestinationForAction();
            int id = 0;

            int.TryParse(ActionId, out id);
            var t = (from a in getActions
                     where a.Id == id
                     select a.NomeAzione);

            azione = t.First();
            return(azione);
        }
예제 #6
0
        void Application_Start(object sender, EventArgs e)
        {
            // Codice eseguito all'avvio dell'applicazione
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //inizializza log4net
            log4net.Config.XmlConfigurator.Configure();
            //inizializza il routing
            RegisterRoutes(RouteTable.Routes);
            MailLocalService mailLocalService = new MailLocalService();

            CacheManager <List <ActiveUp.Net.Common.DeltaExt.Action> > .set(CacheKeys.FOLDERS_ACTIONS, mailLocalService.GetFolderDestinationForAction());

            List <UserMail> l = Helpers.GetAllUsers();

            CacheManager <List <UserMail> > .set(CacheKeys.ALL_USERS, l);
        }
예제 #7
0
        protected void btnUnLetta_Click(object sender, EventArgs e)
        {
            Dictionary <MailTypeSearch, string> idx = new Dictionary <MailTypeSearch, string>();
            MailLocalService mailLocalService       = new MailLocalService();

            idx = getDictionaryChoice();
            try
            {
                bool ok = mailLocalService.UpdateAllMails(MailStatus.SCARICATA, ddlManagedAccounts.SelectedItem.Text, ddlCartella.SelectedValue, MySecurityProvider.CurrentPrincipal.MyIdentity.UserName, idx);
                if (ok == true)
                {
                    (this.Page as BasePage).info.AddMessage("Aggiornamento effettuato", Com.Delta.Messaging.MapperMessages.LivelloMessaggio.INFO);
                }
            }
            catch (Exception ex)
            {
                (this.Page as BasePage).info.AddMessage("Attenzione mails non aggiornate", Com.Delta.Messaging.MapperMessages.LivelloMessaggio.ERROR);
            }
        }
예제 #8
0
        protected void btnOk_Click(object sender, EventArgs e)
        {
            Dictionary <MailTypeSearch, string> idx = new Dictionary <MailTypeSearch, string>();
            MailLocalService mailLocalService       = new MailLocalService();

            idx = getDictionaryChoice();
            try
            {
                decimal idaccount = decimal.Parse(ddlManagedAccounts.SelectedValue);
                bool    ok        = mailLocalService.MoveAllMails(ddlManagedAccounts.SelectedItem.Text, idaccount, ddlCartellaSposta.SelectedValue, ddlCartella.SelectedValue, MySecurityProvider.CurrentPrincipal.MyIdentity.UserName, rblIOBox.SelectedValue, idx);
                if (ok == true)
                {
                    (this.Page as BasePage).info.AddMessage("Spostamento effettuato", Com.Delta.Messaging.MapperMessages.LivelloMessaggio.INFO);
                }
            }
            catch (Exception ex)
            {
                (this.Page as BasePage).info.AddMessage("Attenzione mails non spostate", Com.Delta.Messaging.MapperMessages.LivelloMessaggio.ERROR);
            }
        }
예제 #9
0
        public HttpResponseMessage GetMails(int start, int limit, string folder, string parFolder, string mailAction, string mailIds, string filter, int page)
        {
            IEnumerable <Carrier> listCarrier = new List <Carrier>();
            CarrierModel          model       = new CarrierModel();
            int mailAct = 0;

            start++;
            if (mailAction.ToString() != "NaN")
            {
                mailAct = int.Parse(mailAction);
            }
            string   message = null;
            MailUser acc     = WebMailClientManager.getAccount();

            if (string.IsNullOrEmpty(mailIds))
            {
                mailIds = string.Empty;
            }
            message = DoAction(folder, parFolder, mailAct, mailIds, message, acc);
            ResultList <MailHeader> m = new ResultList <MailHeader>(start, limit, new List <MailHeader>(), 0);

            // IEnumerable<string> items = null;
            if (acc != null && acc.IsManaged && !String.IsNullOrEmpty(filter))
            {
                DataContractJsonSerializer s  = new DataContractJsonSerializer(typeof(Filter));
                System.IO.MemoryStream     ms = new System.IO.MemoryStream();
                byte[] res = new byte[filter.Length];
                Encoding.UTF8.GetBytes(filter, 0, filter.Length, res, 0);
                ms.Write(res, 0, res.Length);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                Filter filtro = (Filter)s.ReadObject(ms);

                Dictionary <MailIndexedSearch, List <string> > sValues = new Dictionary <MailIndexedSearch, List <string> >();
                if (filtro.text.tipo != MailIndexedSearch.UNKNOWN &&
                    (filtro.text.values != null && filtro.text.values.Length > 0))
                {
                    sValues.Add(filtro.text.tipo, filtro.text.values.ToList());
                }
                if (filtro.status.tipo != MailIndexedSearch.UNKNOWN &&
                    (filtro.status.values != null && filtro.status.values.Length > 0))
                {
                    sValues.Add(filtro.status.tipo, filtro.status.values.Select(e => ((int)e).ToString()).ToList());
                }
                MailLocalService mailService       = new MailLocalService();
                ResultList <MailHeaderExtended> rl = mailService.GetMailsByParams(acc.EmailAddress, folder, parFolder, sValues, start, limit);

                m.Per    = rl.Per;
                m.List   = (rl.List == null) ? null : rl.List.Cast <MailHeader>().ToList() as ICollection <MailHeader>;
                m.Totale = rl.Totale;
            }
            else
            {
                MailServerFacade mailServerFacade = MailServerFacade.GetInstance(acc);
                m = mailServerFacade.MailHeader_ResultList_Fetch(folder, parFolder, start, limit);
            }

            if (m != null && m.List != null)
            {
                CultureInfo ci = CultureInfo.InvariantCulture;
                System.Runtime.Serialization.Json.DataContractJsonSerializer ser =
                    new DataContractJsonSerializer(typeof(Carrier));
                if (acc.IsManaged)
                {
                    listCarrier = m.List.Cast <MailHeaderExtended>().Select(h =>
                    {
                        string mStatus      = "";
                        string destinatario = "";
                        switch (parFolder)
                        {
                        case "I":
                            mStatus      = h.MailRating.ToString();
                            destinatario = h.From;
                            break;

                        case "O":
                        case "AO":
                            mStatus = ((int)h.MailStatus).ToString();
                            //per gestire il semaforo per gli invii da server non PEC
                            if (!acc.IsPec && h.MailStatus == MailStatus.SENT)
                            {
                                mStatus = ((int)MailStatus.AVVENUTA_CONSEGNA).ToString();
                            }
                            destinatario = h.To;
                            break;

                        default:
                            MailUser muser = WebMailClientManager.getAccount();
                            string idnome  = (from f in muser.Folders
                                              where f.Id.ToString() == folder
                                              select f.IdNome).First();
                            string tipo = (from f in muser.Folders
                                           where f.Id.ToString() == folder
                                           select f.TipoFolder).First();
                            switch (idnome)
                            {
                            case "1":
                            case "3":
                                mStatus      = h.MailRating.ToString();
                                destinatario = h.From;
                                break;

                            case "2":
                                mStatus = ((int)h.MailStatus).ToString();
                                //per gestire il semaforo per gli invii da server non PEC
                                if (!acc.IsPec && h.MailStatus == MailStatus.SENT)
                                {
                                    mStatus = ((int)MailStatus.AVVENUTA_CONSEGNA).ToString();
                                }
                                destinatario = h.To;
                                break;

                            default:
                                switch (tipo)
                                {
                                case "E":
                                    mStatus      = h.MailRating.ToString();
                                    destinatario = h.From;
                                    break;

                                case "D":
                                    mStatus = ((int)h.MailStatus).ToString();
                                    //per gestire il semaforo per gli invii da server non PEC
                                    if (!acc.IsPec && h.MailStatus == MailStatus.SENT)
                                    {
                                        mStatus = ((int)MailStatus.AVVENUTA_CONSEGNA).ToString();
                                    }
                                    destinatario = h.To;
                                    break;
                                }
                                break;
                            }
                            break;
                        }

                        ActiveUp.Net.Mail.Address add = ActiveUp.Net.Mail.Parser.ParseAddress(destinatario);
                        if (String.IsNullOrEmpty(add.Name))
                        {
                            destinatario = add.Email;
                        }
                        else
                        {
                            destinatario = System.Text.RegularExpressions.Regex.Replace(add.Name,
                                                                                        "Per conto di:?", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Trim();
                            if (destinatario.EndsWith("\""))
                            {
                                destinatario.Replace("\"", "");
                            }
                        }

                        Carrier c = new Carrier
                        {
                            id      = h.UniqueId,
                            from    = destinatario.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "\\\""),
                            date    = h.Date.ToString("dd/MM/yyyy HH:mm:ss", ci),
                            subject = h.Subject.Replace("\"", "\\\""),
                            sStatus = mStatus,
                            mStatus = ((int)h.MailStatus).ToString(),
                            attach  = Convert.ToInt16(h.HasAttachments).ToString(),
                            utente  = ((h.MailStatus == MailStatus.SCARICATA) ? "" : h.Utente),
                            dimen   = h.Dimensione
                        };
                        return(c);
                        //System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        //ser.WriteObject(ms, c);
                        //string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                        //ms.Close();
                        //return jsonString;
                    });
                }
                else
                {
                    listCarrier = m.List.Select(h =>
                    {
                        Carrier c = new Carrier()
                        {
                            id      = h.UniqueId,
                            from    = h.From.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "\\\""),
                            date    = h.Date.ToString("dd/MM/yyyy HH:mm:ss", ci),
                            subject = h.Subject.Replace("\"", "\\\""),
                            mStatus = ((int)MailStatus.UNKNOWN).ToString(),
                            sStatus = "",
                            attach  = ""
                        };
                        return(c);
                        //System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        //ser.WriteObject(ms, c);
                        //string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                        //ms.Close();
                        //return jsonString;
                    });
                }
            }
            else
            {
                model.Message = "Nessun ritrovamento";
                return(this.Request.CreateResponse <CarrierModel>(HttpStatusCode.OK, model));
                //message = "Nessun ritrovamento";
            }

            //StringBuilder sb = new StringBuilder();
            //sb.Append("{\"TotalCount\":\"" + m.Totale.ToString() + "\",");
            //sb.Append("\"Message\":\"" + message + "\"");
            //if (items != null)
            //{
            //    sb.Append(",\"Data\":[" + String.Join(",", items.ToArray()) + "]");
            //}
            //else
            //{
            //    sb.Append(",\"Data\": []");
            //}
            //sb.Append("}");
            model.TotalCount = m.Totale.ToString();
            model.data       = listCarrier.ToList();
            model.success    = "true";
            return(this.Request.CreateResponse <CarrierModel>(HttpStatusCode.OK, model));
            //context.Response.ContentType = "application/json";
            //context.Response.AppendHeader("Content-type", "text/json");
            //context.Response.Write(sb.ToString());
        }
예제 #10
0
        public HttpResponseMessage GetTreeStructure(string idM)
        {
            JSONTreeNodeModel model = new JSONTreeNodeModel();

            if (string.IsNullOrEmpty(idM))
            {
                ManagedException mEx = new ManagedException("Il parametro idNode è nullo", "ERR_G005", string.Empty, string.Empty, null);
                ErrorLogInfo     er  = new ErrorLogInfo(mEx);
                er.objectID = idM;
                log.Error(er);
                model.success = "false";
                model.Message = mEx.Message;
                return(this.Request.CreateResponse <JSONTreeNodeModel>(HttpStatusCode.OK, model));
            }
            long idMail = -1;

            if (!long.TryParse(idM, out idMail))
            {
                ManagedException mEx = new ManagedException("Il parametro idNode non è numerico", "ERR_G006", string.Empty, string.Empty, null);
                ErrorLogInfo     er  = new ErrorLogInfo(mEx);
                er.objectID = idM;
                log.Error(er);
                model.success = "false";
                model.Message = mEx.Message;
                return(this.Request.CreateResponse <JSONTreeNodeModel>(HttpStatusCode.OK, model));
            }

            MailUser us = WebMailClientManager.getAccount();

            if (us == null)
            {
                ManagedException mEx = new ManagedException("Non esiste un account loggato", "ERR_G007", string.Empty, string.Empty, null);
                ErrorLogInfo     er  = new ErrorLogInfo(mEx);
                er.objectID = idM;
                log.Error(er);
                model.success = "false";
                model.Message = mEx.Message;
                return(this.Request.CreateResponse <JSONTreeNodeModel>(HttpStatusCode.OK, model));
            }

            MailLocalService mailService = new MailLocalService();
            IEnumerable <HierarchyNode <SimpleTreeItem> > hl = null;
            List <SimpleTreeItem> result = mailService.LoadMailTree(us.EmailAddress, idMail) as List <SimpleTreeItem>;

            if (result.Count > 0)
            {
                Func <List <SimpleTreeItem>, SimpleTreeItem> getRoot = l => l.FirstOrDefault(x => !l.Select(y => y.Value).Contains(x.Padre));
                hl = result.AsHierarchy(
                    e => e.Value,
                    e => e.Padre,
                    e => e.Value,
                    getRoot(result).Value);
            }
            JSONTreeNode[] nodes = ConvertToJSON(hl);
            model.success    = "true";
            model.data       = nodes.ToList();
            model.TotalCount = model.data.Count.ToString();
            return(this.Request.CreateResponse <JSONTreeNodeModel>(HttpStatusCode.OK, model));
            //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JSONTreeNode[]));
            //System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //ser.WriteObject(ms, nodes);
            //string json = Encoding.UTF8.GetString(ms.ToArray());
            //ms.Close();

            //context.Response.ContentType = "application/json";
            //context.Response.AddHeader("Content-Type", "text/json");
            //context.Response.Write(json);
        }
예제 #11
0
        private void CartellaAccess()
        {
            List <Folder>    list             = new List <Folder>();
            MailLocalService mailLocalService = new MailLocalService();

            if (ddlManagedAccounts.SelectedValue != null && ddlManagedAccounts.SelectedValue != string.Empty && ddlManagedAccounts.SelectedValue != "-1")
            {
                string io = rblIOBox.SelectedValue;
                string m  = "E";
                string f  = "I";
                if (io == "I")
                {
                    switch (rblTipoFolder.SelectedValue)
                    {
                    case "O":
                        f = "I";
                        m = "I";
                        break;

                    case "A":
                        f = "A";
                        m = "E";
                        break;

                    case "C":
                        f = "C";
                        m = "I";
                        break;
                    }
                }
                else
                {
                    switch (rblTipoFolder.SelectedValue)
                    {
                    case "O":
                        f = "O";
                        m = "O";
                        break;

                    case "A":
                        f = "A";
                        m = "D";
                        break;

                    case "C":
                        f = "C";
                        m = "O";
                        break;
                    }
                }
                if (SessionManager <List <Folder> > .exist(SessionKeys.FOLDERS))
                {
                    list = SessionManager <List <Folder> > .get(SessionKeys.FOLDERS);
                }
                else
                {
                    list = mailLocalService.getFoldersByAccount(decimal.Parse(ddlManagedAccounts.SelectedValue)).Where(x => x.TipoFolder == f || x.TipoFolder == m).ToList();
                }
                if (f == "C" && m == "I")
                {
                    list = list.Where(x => x.TipoFolder == f && (x.IdNome == "1" || x.IdNome == "3")).ToList();
                }
                if (f == "C" && m == "O")
                {
                    list = list.Where(x => x.TipoFolder == f && x.IdNome == "2").ToList();
                }
                ddlCartellaSposta.DataTextField  = ddlCartella.DataTextField = "Nome";
                ddlCartellaSposta.DataValueField = ddlCartella.DataValueField = "Id";
                ddlCartellaSposta.DataSource     = ddlCartella.DataSource = list;
                ddlCartella.DataBind();
                ddlCartellaSposta.DataBind();
                ListItem item  = new ListItem();
                ListItem itema = new ListItem();
                item.Value     = "0";
                item.Text      = "-- Tutte --";
                item.Selected  = true;
                itema.Value    = "";
                itema.Text     = "Effettuare una scelta";
                itema.Selected = true;
                ddlCartella.Items.Insert(0, item);
                ddlCartellaSposta.Items.Insert(0, itema);
                UpdCartella.Update();
                UpdCartellaSposta.Update();
            }
        }
예제 #12
0
        public static void Receive(string mail)
        {
            ApplicationCodeConfigSection configSection =
                (ApplicationCodeConfigSection)ConfigurationManager.GetSection("ApplicationCode");

            if (configSection != null)
            {
                APP_CODE = configSection.AppCode;
            }

            IList <ActiveUp.Net.Mail.DeltaExt.MailUser> listUsers = null;

            try
            {
                //listUsers = ServiceLocator.GetServiceFactory().MailAccountService.GetAllManaged();
                List <string> mails = new List <string>();
                mails.Add(mail);
                MailAccountService mailaccountservice = new MailAccountService();
                listUsers = mailaccountservice.GetUsersByMails(mails);
                listUsers = listUsers.Where(x => x.FlgManaged != 0).ToList();
            }
            catch (Exception ex)
            {
                if (ex.GetType() != typeof(ManagedException))
                {
                    ManagedException mEx = new ManagedException("Errore nel caricamento degli utenti di posta dettagli: " + ex.Message,
                                                                "RMA_001",
                                                                string.Empty,
                                                                string.Empty,
                                                                ex.InnerException);
                    ErrorLogInfo err = new ErrorLogInfo(mEx);
                    _log.Error(err);
                }
            }

            // IMailServerService mailService = null
            MailServerService mailService        = new MailServerService();
            MailLocalService  mailMessageService = null;

            foreach (ActiveUp.Net.Mail.DeltaExt.MailUser user in listUsers)
            {
                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                          user.EmailAddress, (string)null));
                try
                {
                    mailService        = MailServerService.Instance.GetInstance(user);
                    mailMessageService = MailLocalService.Instance;
                }
                catch (Exception e)
                {
                    //TASK: Allineamento log - Ciro
                    if (e.GetType() != typeof(ManagedException))
                    {
                        ManagedException mEx = new ManagedException("Errore nel caricamento degli utenti di posta dettagli: " + e.Message,
                                                                    "RMA_002",
                                                                    string.Empty,
                                                                    string.Empty,
                                                                    e.InnerException);
                        ErrorLogInfo err = new ErrorLogInfo(mEx);
                        _log.Error(err);
                    }
                    //ManagedException mEx = new ManagedException(String.Format("Account {0} non valido", user.EmailAddress), "RMA_002", "", "", e);
                    //ErrorLog err = new ErrorLog(APP_CODE, mEx);
                    //_log.Error(err);
                    continue;
                }
                user.Validated = true;

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Account: " + user.EmailAddress);
                Console.ResetColor();
                int retries = 0;
                do
                {
                    mailService.IncomingConnect();
                    if (mailService.IsIncomingConnected())
                    {
                        break;
                    }
                    ++retries;
                }while (retries <= 5);

                if (!mailService.IsIncomingConnected())
                {
                    //TASK: Allineamento log - Ciro
                    ManagedException mEx = new ManagedException("Impossibile connettersi al server remoto",
                                                                "RMA_022",
                                                                string.Empty,
                                                                string.Empty,
                                                                null);
                    ErrorLogInfo err = new ErrorLogInfo(mEx);
                    err.loggingAppCode = string.Empty;
                    err.objectID       = mail.ToString() + " - " + System.DateTime.Now.Date + "_" + System.DateTime.Now.Ticks;
                    err.userID         = user.UserId.ToString();
                    _log.Error(err);
                    //_log.Error(new ErrorLogInfo(APP_CODE, "RMA_002", "Impossibile connettersi al server remoto.",
                    //    user.EmailAddress, null, null, null, null, null, null,
                    //    null, null, null));
                    continue;
                }
                ///pensiamo a qualcosa di più decente che così non si può vedere
                System.Threading.Thread.Sleep(500);
                List <MessageUniqueId> listUIds = mailService.RetrieveUIds();
                if (listUIds == null || listUIds.Count == 0)
                {
                    if (mailService.IsIncomingConnected())
                    {
                        Disconnect(mailService);
                    }
                    _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                              user.EmailAddress, "Nessun messaggio da scaricare"));
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Non vi sono messaggi da scaricare");
                    Console.ResetColor();
                    continue;
                }

                listUIds = listUIds.OrderBy(x => x.Ordinal).ToList();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(String.Format("Vi sono {0} messaggi da scaricare", listUIds.Count()));
                Console.ResetColor();
                List <ActiveUp.Net.Common.DeltaExt.MailStatusServer> stSer = new List <ActiveUp.Net.Common.DeltaExt.MailStatusServer>();
                stSer.Add(ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE);
                stSer.Add(ActiveUp.Net.Common.DeltaExt.MailStatusServer.DA_NON_CANCELLARE);
                Dictionary <ActiveUp.Net.Common.DeltaExt.MailStatusServer, List <string> > savedUidsAll = (Dictionary <ActiveUp.Net.Common.DeltaExt.MailStatusServer, List <string> >)mailMessageService.GetAllUIDsByAccount(user.EmailAddress, stSer);
                List <string> savedUids = null;
                if (savedUidsAll != null && savedUidsAll.Count > 0)
                {
                    savedUids = savedUidsAll.SelectMany(x => x.Value).ToList();
                }
                else
                {
                    savedUids = new List <string>();
                }
                //cancello dal server
                bool   toCancel  = false;
                string cancelKey = System.Configuration.ConfigurationManager.AppSettings.Get("DeleteFromServer");
                bool.TryParse(cancelKey, out toCancel);
                int idx = 0;
                //se abilitato alla cancellazione
                if (user.FlgManaged == 2 && toCancel)
                {
                    //se ci sono email da cencellare
                    if (savedUidsAll != null && savedUidsAll.ContainsKey(ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE) && savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE].Count != 0)
                    {
                        try
                        {
                            //seleziona gli uid da cancellare
                            var mailToCancel = listUIds.Where(x =>
                                                              savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE].Contains(x.UId.Replace(',', '§')));
                            foreach (var uid in mailToCancel)
                            {
                                //cancella dal server
                                mailService.DeleteMessageFromServer(uid.UId);
                                Disconnect(mailService);
                                Connect(mailService);
                                mailMessageService.UpdateMessageServerStatus(user.EmailAddress, uid.UId, ActiveUp.Net.Common.DeltaExt.MailStatusServer.CANCELLATA);
                                idx = mailToCancel.IndexOf(uid) + 1;
                                //disconnect ogni 10 mail per committare sul server
                                if ((idx % 10) == 0)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("Cancellati " + idx + " messaggi");
                                    Console.ResetColor();
                                    if (Disconnect(mailService))
                                    {
                                        if (!Connect(mailService))
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                      user.EmailAddress, "Cancellati " + idx + " messaggi"));
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Cancellati " + idx + " messaggi");
                            Console.ResetColor();
                            if (Disconnect(mailService))
                            {
                                if (!Connect(mailService))
                                {
                                    continue;
                                }
                            }
                            //aggiorna gli uid dal server di posta
                            listUIds = mailService.RetrieveUIds();
                            if (listUIds == null || listUIds.Count == 0)
                            {
                                if (mailService.IsIncomingConnected())
                                {
                                    Disconnect(mailService);
                                }
                                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                          user.EmailAddress, "Nessun messaggio da scaricare"));
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Non vi sono messaggi da scaricare");
                                Console.ResetColor();
                                continue;
                            }
                            //esclude quelli da già in banca dati, se vi sono
                            var lUids = listUIds.Where(x => !savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE].Contains(x.UId));
                            if (lUids.Count() == 0)
                            {
                                continue;
                            }
                            listUIds = lUids.OrderBy(x => x.Ordinal).ToList();
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(String.Format("Vi sono {0} messaggi da scaricare", listUIds.Count()));
                            Console.ResetColor();
                            _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                      user.EmailAddress, "Vi sono " + listUIds.Count + " messaggi da scaricare"));
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                idx = 0;
                foreach (MessageUniqueId uId in listUIds)
                {
                    if (!savedUids.Contains(uId.UId.Replace(',', '§')))
                    {
                        _log.Debug("WORKING UID:" + uId.UId);
                        _log.Debug("WORKING ORDINAL:" + uId.Ordinal);
                        List <ActiveUp.Net.Mail.DeltaExt.MailHeader> ml = ((MailServerService)mailService).Pop3.RetrieveHeaders(uId.Ordinal, 1);
                        if (ml == null || ml.Count == 0)
                        {
                            ml = new List <ActiveUp.Net.Mail.DeltaExt.MailHeader>();
                            ml.Add(new ActiveUp.Net.Mail.DeltaExt.MailHeader {
                                UniqueId = uId.UId
                            });
                        }
                        _log.Debug(string.Format("WORKING HEADER: FROM - {0} ; SUBJECT - {1} ; UID - {2}", ml[0].From, ml[0].Subject, ml[0].UniqueId));
                        //maxSize da configurazione
                        int    maxSize         = 0;
                        string confMaxMailSize = ConfigurationManager.AppSettings.Get("MaxMailSizeInMB");
                        if (!String.IsNullOrEmpty(confMaxMailSize))
                        {
                            int.TryParse(confMaxMailSize, out maxSize);
                            // limite alzato a 8 mega
                            //     maxSize *= (int)Math.Pow(1024, 2);
                            maxSize *= (int)Math.Pow(1024, 8);
                        }
                        if (maxSize > 0)//se è definito un maxSize positivo
                        {
                            //dimensione del messaggio in byte
                            int size = mailService.GetMessageSize(uId.UId);
                            if (size > maxSize) // 4MB
                            {
                                //TASK: Allineamento log - Ciro
                                ManagedException mEx = new ManagedException(string.Format("Messaggio: {0} - Mail superiore a {1}MB! Controllare sul server", uId.UId, ConfigurationManager.AppSettings.Get("MaxMailSizeInMB")),
                                                                            "RMA_031",
                                                                            string.Empty,
                                                                            string.Empty,
                                                                            null);
                                ErrorLogInfo err = new ErrorLogInfo(mEx);
                                _log.Error(err);
                                //_log.Error(new ErrorLogInfo(APP_CODE, "RMA_003",
                                //    string.Format("Messaggio: {0} - Mail superiore a {1}MB! Controllare sul server",
                                //    uId.UId,
                                //    ConfigurationManager.AppSettings.Get("MaxMailSizeInMB")),
                                //    user.EmailAddress, null, null, null, null,
                                //    null, null, null, null, null));
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine("WORKING HEADER: FROM - {0} ; SUBJECT - {1} ; UID - {2} ; SIZE - {3} ", ml[0].From, ml[0].Subject, ml[0].UniqueId, size);
                                Console.ResetColor();
                                continue;
                            }
                        }

                        ActiveUp.Net.Mail.Message m = mailService.getMessage(uId.UId, false);

                        if (m == null) //messaggio non trovato dall'UID!!!!
                        {
                            byte[] msx;
                            try
                            {
                                //provo a prendere il messaggio per progressivo
                                if (!mailService.IsIncomingConnected())
                                {
                                    Connect(mailService);
                                }
                                msx = ((MailServerService)mailService).Pop3.Pop3Client.RetrieveMessage(uId.Ordinal);
                                if (mailService.IsIncomingConnected())
                                {
                                    mailService.IncomingDisconnect();
                                }
                            }
                            catch (Exception ex)
                            {
                                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName, user.EmailAddress,
                                                          "Messaggio " + uId.UId + " non trovato"));
                                msx = null;
                            }
                            if (msx == null || msx.Length == 0)
                            {
                                continue;
                            }
                            ActiveUp.Net.Mail.Message msg = new Message();
                            try
                            {
                                //provo il parser dal binary content
                                //Parser.BodyParsed += new Parser.OnBodyParsedEvent(Parser_BodyParsed);
                                //Parser.ErrorParsing += new Parser.OnErrorParsingEvent(Parser_ErrorParsing);
                                msg     = Parser.ParseMessage(msx);
                                msg.Uid = uId.UId;
                            }
                            catch (Exception ex)
                            {
                                //costruisco il messaggio a mano
                                msg.OriginalData = msx;
                                msg.Uid          = uId.UId;
                                msg.From         = new Address();
                                msg.From.Email   = ml[0].From ?? "UNDEFINED";
                                if (!String.IsNullOrEmpty(ml[0].To))
                                {
                                    msg.To = new AddressCollection();
                                    string[] to_emails = ml[0].To.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    msg.To.AddRange(to_emails.Select(to => new Address(to.Trim())));
                                }
                                msg.Subject = ml[0].Subject;
                                msg.Date    = ml[0].Date;

                                if (ex.GetType() != typeof(ManagedException))
                                {
                                    ManagedException mEx = new ManagedException("Messaggio costruito a mano: " + ex.Message,
                                                                                "ERR_H100",
                                                                                string.Empty,
                                                                                string.Empty,
                                                                                ex);
                                    ErrorLogInfo er = new ErrorLogInfo(mEx);
                                    _log.Error(er);
                                }
                            }
                            //assegno il messaggio al messaggio in lavorazione
                            m = msg;
                        }

                        try
                        {
                            if (savedUidsAll != null && savedUidsAll.ContainsKey(ActiveUp.Net.Common.DeltaExt.MailStatusServer.DA_NON_CANCELLARE) && savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.DA_NON_CANCELLARE].Contains(m.Uid))
                            {
                                mailMessageService.Update(user, m);
                            }
                            else
                            {
                                mailMessageService.Insert(user, m);
                            }

                            if (!String.IsNullOrEmpty(m.HeaderFields["X-Ricevuta"]))
                            {
                                string ric = m.HeaderFields["X-Ricevuta"].ToLower();
                                ActiveUp.Net.Common.DeltaExt.MailStatus newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.UNKNOWN;

                                switch (ric)
                                {
                                case "accettazione":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ACCETTAZIONE;
                                    break;

                                case "non-accettazione":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.NON_ACCETTAZIONE;
                                    break;

                                case "presa-in-carico":
                                    break;

                                case "avvenuta-consegna":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.AVVENUTA_CONSEGNA;
                                    break;

                                case "posta-certificata":
                                    break;

                                case "errore-consegna":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ERRORE_CONSEGNA;
                                    break;

                                case "preavviso-errore-consegna":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ERRORE_CONSEGNA;
                                    break;

                                case "rilevazione-virus":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ERROR;
                                    break;
                                }

                                if (newSt != ActiveUp.Net.Common.DeltaExt.MailStatus.UNKNOWN)
                                {
                                    string idOldString = m.HeaderFields["X-Riferimento-Message-ID"];
                                    if (idOldString.StartsWith("<"))
                                    {
                                        idOldString = idOldString.Substring(1);
                                    }
                                    if (idOldString.EndsWith(">"))
                                    {
                                        idOldString = idOldString.Substring(0, idOldString.Length - 1);
                                    }
                                    string[] idOldStr = idOldString.Split('.');
                                    Int64    idOld    = -1;
                                    if (idOldStr.Length > 0 && Int64.TryParse(idOldStr[0], out idOld))
                                    {
                                        //IComunicazioniService comS = ServiceLocator.GetServiceFactory().ComunicazioniService;
                                        ComunicazioniService comS = new ComunicazioniService();
                                        SendMail.Model.ComunicazioniMapping.Comunicazioni com = comS.LoadComunicazioneByIdMail(idOld);
                                        if (com != null)
                                        {
                                            SendMail.Model.ComunicazioniMapping.ComFlusso flusso = com.ComFlussi[SendMail.Model.TipoCanale.MAIL].Last();

                                            //se si trova in stato di errore non aggiorno
                                            if (flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.ERROR ||
                                                flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.CANCELLED ||
                                                flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.NON_ACCETTAZIONE ||
                                                flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.ERRORE_CONSEGNA)
                                            {
                                                idx = listUIds.ToList().IndexOf(uId);
                                                if ((idx != 0) && ((idx % 50) == 0))
                                                {
                                                    Console.ForegroundColor = ConsoleColor.Red;
                                                    Console.WriteLine("Inseriti " + idx + " messaggi");
                                                    Console.ResetColor();
                                                    _log.Info(new MailLogInfo(APP_CODE,
                                                                              "", user.DisplayName, user.EmailAddress,
                                                                              "Inseriti " + idx + " messaggi"));
                                                }
                                                continue;
                                            }

                                            SendMail.Model.ComunicazioniMapping.ComFlusso newFl = new SendMail.Model.ComunicazioniMapping.ComFlusso();
                                            newFl.Canale                = SendMail.Model.TipoCanale.MAIL;
                                            newFl.DataOperazione        = m.Date;
                                            newFl.RefIdComunicazione    = flusso.RefIdComunicazione;
                                            newFl.StatoComunicazioneNew = newSt;
                                            newFl.StatoComunicazioneOld = flusso.StatoComunicazioneNew;
                                            newFl.UtenteOperazione      = "SYSTEM";
                                            com.ComFlussi[SendMail.Model.TipoCanale.MAIL].Add(newFl);
                                            comS.UpdateFlussoComunicazione(SendMail.Model.TipoCanale.MAIL, com);
                                        }
                                        else
                                        {
                                            try
                                            {
                                                Message msg = mailMessageService.GetById(idOld);
                                                if (msg != null)
                                                {
                                                    List <string> uidMails = new List <string>();
                                                    uidMails.Add(msg.Uid);
                                                    mailMessageService.UpdateMailStatus(user.EmailAddress, uidMails, newSt, null, null, "I");
                                                }
                                            }
                                            catch
                                            {
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (ManagedException mEx)
                        {
                            if (mEx.CodiceEccezione.Equals("WRN_INS_ML_001"))
                            {
                                mailService.DeleteMessageFromServer(uId.UId);
                            }
                        }
                        catch (Exception ex)
                        {
                            //TASK: Allineamento log - Ciro
                            if (ex.GetType() != typeof(ManagedException))
                            {
                                ManagedException mEx = new ManagedException(String.Format("Errore nel salvataggio della mail uid: {0} from: {1} subject:{2} dell'account {3}", m.Uid, m.From.Email, m.Subject, user.EmailAddress),
                                                                            "RMA_003",
                                                                            string.Empty,
                                                                            string.Empty,
                                                                            ex.InnerException);
                                ErrorLogInfo err = new ErrorLogInfo(mEx);
                                _log.Error(err);
                            }
                            //ManagedException mEx = new ManagedException(
                            //    String.Format("Errore nel salvataggio della mail uid: {0} from: {1} subject:{2} dell'account {3}", m.Uid, m.From.Email, m.Subject, user.EmailAddress),
                            //    "RCV_MAIL_003", "", "", ex);
                            //ErrorLog err = new ErrorLog(APP_CODE, mEx);
                            //_log.Error(err);
                        }

                        idx = listUIds.IndexOf(uId) + 1;
                        if ((idx % 50) == 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Inseriti " + idx + " messaggi");
                            Console.ResetColor();
                            _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                      user.EmailAddress, "Inseriti " + idx + " messaggi"));
                        }
                    }
                }
                if (mailService.IsIncomingConnected())
                {
                    Disconnect(mailService);
                }
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Inseriti " + listUIds.Count + " messaggi");
                Console.ResetColor();
                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                          user.EmailAddress, "Inseriti " + listUIds.Count + " messaggi"));
            }
        }
예제 #13
0
        public HttpResponseMessage AbilitaFolders(string idemail, string itemselector)
        {
            FoldersSendersModel   model = new FoldersSendersModel();
            SendersFoldersService sfs   = new SendersFoldersService();

            if (string.IsNullOrEmpty(idemail) && string.IsNullOrEmpty(itemselector))
            {
                model.success = "false";
                model.message = "Valori insufficienti nella richiesta";
                this.Request.CreateResponse <FoldersSendersModel>(HttpStatusCode.OK, model);
            }
            try
            {
                // model.FoldersList = listaCartelleNonAbilitate.ToArray();
                string[] folders          = itemselector.Split(';');
                var      foldersAbilitati = sfs.GetFoldersAbilitatiByIdSender(int.Parse(idemail)).Select(z => z.IdNome).ToArray();
                var      ff        = Array.ConvertAll(foldersAbilitati, x => x.ToString());
                var      foldersda = folders.Except(ff);
                var      foldersa  = ff.Except(folders);
                foreach (string s in foldersda)
                {
                    sfs.InsertAbilitazioneFolder(Convert.ToInt32(s), Convert.ToInt32(idemail), 0);
                }
                foreach (string s in foldersa)
                {
                    if (s != "1" && s != "2" && s != "3")
                    {
                        sfs.DeleteAbilitazioneFolder(Convert.ToInt32(s), Convert.ToInt32(idemail));
                    }
                }
                MailUser m = WebMailClientManager.getAccount();
                if (m != null)
                {
                    WebMailClientManager.AccountRemove();
                    MailServerConfigFacade facade = MailServerConfigFacade.GetInstance();
                    MailUser         account      = facade.GetUserByUserId(m.UserId);
                    MailServerFacade serverFacade = MailServerFacade.GetInstance(account);
                    account.Validated = true;
                    WebMailClientManager.SetAccount(account);
                }
                model.success = "true";
                MailLocalService mailLocalService = new MailLocalService();
                CacheManager <List <ActiveUp.Net.Common.DeltaExt.Action> > .set(CacheKeys.FOLDERS_ACTIONS, mailLocalService.GetFolderDestinationForAction());
            }
            catch (Exception ex)
            {
                if (!ex.GetType().Equals(typeof(ManagedException)))
                {
                    ManagedException mEx = new ManagedException("Eccezione nella lettura delle cartelle", "ERR_F005", string.Empty, ex.Message, null);
                    ErrorLogInfo     er  = new ErrorLogInfo(mEx);
                    er.objectID = idemail.ToString();
                    log.Error(er);
                    model.success = "false";
                    model.message = mEx.Message;
                }
                else
                {
                    model.success = "false";
                    model.message = ex.Message;
                }
            }
            return(this.Request.CreateResponse <FoldersSendersModel>(HttpStatusCode.OK, model));
        }