예제 #1
0
        private void HandleCheckConnectedMessage(ClientPacket protocolPacket, IClientProtocol protocol, IPAddress address)
        {
            var port = int.Parse(protocol.DataJson);

            if (!CConstant.UdpListenerPort.Contains(port))
            {
                return;
            }

            var client = Clients.FirstOrDefault(x => x.Id == protocolPacket.Id) as CClient;

            var responseProtocol = new ServerProtocol();

            if (client == null || client.State != ClientState.Accepted)
            {
                responseProtocol.Message = ServerMessage.Refuse;
            }
            else
            {
                responseProtocol.Message = ServerMessage.Accept;
                client.Port = port;
            }

            SendServerPacket(ServerPacketType.Protocol, JsonConvert.SerializeObject(responseProtocol), address, port);
        }
예제 #2
0
        private void HandlePasscodeMessage(String id, String passcode)
        {
            var client = Clients.FirstOrDefault(x => x.Id == id && x.State == ClientState.WaitingPasscode) as CClient;

            if (client == null || client.State != ClientState.WaitingPasscode)
            {
                return;
            }

            var responseProtocol = new ServerProtocol();

            if (passcode == client.Passcode)
            {
                RunOnUiThread(delegate
                {
                    client.State = ClientState.Accepted;
                });

                responseProtocol.Message = ServerMessage.Accept;
            }
            else
            {
                RemoveClient(client);

                responseProtocol.Message = ServerMessage.Refuse;
            }

            SendServerPacket(ServerPacketType.Protocol, JsonConvert.SerializeObject(responseProtocol), client);
        }
예제 #3
0
        private static void CloseServer(ServerProtocol server, Logic logic)
        {
            try
            {
                server.Socket.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("Closing the thread that is listening for connections.");
            }

            if (connections.Count > 0)
            {
                foreach (Connection connection in connections)
                {
                    try
                    {
                        connection.Close();
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Forcing socket to close.");
                    }
                }
            }
            CloseThreads();
        }
예제 #4
0
        private async Task ProcessConfigRequestAsync(TcpClient client)
        {
            try
            {
#if DEBUG
                //Server.Logger.Debug("config request received.");
#endif
                ServerContext.ClientConnectCount += 1;
                var nstream = client.GetStream();

                //0.读取协议名
                int    protoRequestLength = 1;
                byte[] protoRequestBytes  = new byte[protoRequestLength];

                int resultByte0 = await nstream.ReadAsync(protoRequestBytes, 0, protoRequestBytes.Length, Global.DefaultConnectTimeout);

                if (resultByte0 < 1)
                {
                    Server.Logger.Debug("服务端read失败,关闭连接");
                    client.Client.Close();
                    return;
                }

                ServerProtocol proto = (ServerProtocol)protoRequestBytes[0];
#if DEBUG
                //Server.Logger.Debug("appRequestBytes received.");
#endif

                switch (proto)
                {
                case ServerProtocol.ClientNewAppRequest:
                    await ProcessAppRequestProtocol(client);

                    break;

                case ServerProtocol.Heartbeat:
                    await ProcessHeartbeatProtocol(client);

                    break;

                case ServerProtocol.CloseClient:
                    await ProcessCloseClientProtocol(client);

                    break;

                case ServerProtocol.Reconnect:
                    await ProcessAppRequestProtocol(client, true);

                    break;

                default:
                    throw new Exception("接收到异常请求。");
                }
            }
            catch (Exception e)
            {
                Logger.Debug(e);
                throw;
            }
        }
예제 #5
0
        static void Main(string[] args)
        {
            var    server = new ServerProtocol();
            int    port   = GetServerPortFromConfigFile();
            string ip     = GetServerIpFromConfigFile();

            server.Start(ip, port);
            var gameLogic = new GameLogic(new Store());

            DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), SC_CLOSE, MF_BYCOMMAND);
            var thread = new Thread(() =>
            {
                var router = new Router(new ServerController(gameLogic));
                while (!endServer)
                {
                    try
                    {
                        var clientSocket = server.Socket.Accept();
                        var clientThread = new Thread(() =>
                        {
                            try
                            {
                                Connection conn = new Connection(clientSocket);
                                connections.Add(conn);
                                router.Handle(conn);
                            }
                            catch (Exception)
                            {
                                endServer = true;
                            }
                        });
                        threads.Add(clientThread);
                        clientThread.Start();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(" -> The server has stopped listening for connections.");
                    }
                }
            });

            threads.Add(thread);
            thread.Start();
            bool exit = false;

            while (!exit)
            {
                int option = Menus.ServerMainMenu();

                GoToMenuOption(option, gameLogic);

                if (option == 3)
                {
                    endServer = true;
                    exit      = true;
                }
            }
            CloseServer(server, gameLogic);
        }
예제 #6
0
        private byte[] CreateMessage(ServerProtocol msg, byte[] data)
        {
            byte[] newData = new byte[1 + data.Length];

            newData[0] = (byte)msg;
            data.CopyTo(newData, 1);
            return(newData);
        }
예제 #7
0
    public ServerController(IGameController controller)
    {
        _controller = controller;

        var serverProtocol = new ServerProtocol (this);
        _transport = new ServerTransport (serverProtocol);

        _transport.StartListening ();
    }
예제 #8
0
        private void HandleRequestConnectMessage(ClientPacket protocolPacket, IClientProtocol protocol, IPAddress address)
        {
            var client = Clients.FirstOrDefault(x => x.Id == protocolPacket.Id) as CClient;

            if (client != null)
            {
                return;
            }

            var port = int.Parse(protocol.DataJson);

            if (!CConstant.UdpListenerPort.Contains(port))
            {
                return;
            }

            client = new CClient()
            {
                Id      = protocolPacket.Id,
                Name    = protocolPacket.Name,
                Port    = port,
                Address = address,
            };

            client.CalculateChecksum();
            client.Refresh();

            lock (Clients)
            {
                Clients.Add(client);
            }

            RunOnUiThread(delegate
            {
                ClientNew?.Invoke(client);

                ClientsChanged?.Invoke(Clients);

                var generator   = new Random();
                var r           = generator.Next(1, 1000000);
                var passcode    = r.ToString().PadLeft(6, '0');
                client.Passcode = passcode;
            });

            var responseProtocol = new ServerProtocol()
            {
                Message = ServerMessage.RequestPasscode
            };

            SendServerPacket(ServerPacketType.Protocol, JsonConvert.SerializeObject(responseProtocol), client);

            RunOnUiThread(delegate
            {
                client.State = ClientState.WaitingPasscode;
            });
        }
예제 #9
0
 private Protocol Convert(ServerProtocol source)
 {
     if (source == ServerProtocol.Udp)
     {
         return(Protocol.Udp);
     }
     if (source == ServerProtocol.Tls)
     {
         return(Protocol.Tls);
     }
     return(Protocol.Tcp);
 }
        public const int UploadFileChunkSize = 8000000; //8MB

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="serverName">Server IP, hostname or FQDN</param>
        /// <param name="siteName">Tableau Site Name</param>
        /// <param name="protocol">HTTP protocol</param>
        /// <param name="pageSize">Page size, defaults to 1000</param>
        /// <param name="serverVersion">Tableau Server version</param>
        public TableauServerUrls(ServerProtocol protocol, string serverName, string siteName, int pageSize = 1000, ServerVersion serverVersion = ServerVersion.Server9)
        {
            PageSize       = 1000;
            ServerProtocol = protocol;

            PageSize = pageSize;
            var serverNameWithProtocol = (protocol == ServerProtocol.Http ? "http://" : "https://") + serverName;

            ServerVersion         = serverVersion;
            SiteUrlSegement       = siteName;
            ServerName            = serverName;
            ServerUrlWithProtocol = serverNameWithProtocol;
            UrlLogin = serverNameWithProtocol + "/api/3.3/auth/signin";
            _urlListWorkbooksForUserTemplate     = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/users/{{iwsUserId}}/workbooks?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
            _urlViewsListForSiteTemplate         = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/views?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
            _urlViewThumbnailTemplate            = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}/views/{{iwsViewId}}/previewImage";
            _urlViewDataTemplate                 = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/views/{{iwsViewId}}/data";
            _urlListViewsForWorkbookTemplate     = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}/views";
            _urlListWorkbookConnectionsTemplate  = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}/connections";
            _urlWorkbookTemplate                 = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}";
            _urlListDatasourcesTemplate          = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/datasources?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
            _urlListProjectsTemplate             = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/projects?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
            _urlListGroupsTemplate               = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/groups?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
            _urlListUsersTemplate                = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/users?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
            _urlListUsersInGroupTemplate         = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/groups/{{iwsGroupId}}/users?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
            _urlDownloadDatasourceTemplate       = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/datasources/{{iwsRepositoryId}}/content";
            _urlDatasourceConnectionsTemplate    = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/datasources/{{iwsRepositoryId}}/connections";
            _urlDownloadWorkbookTemplate         = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/workbooks/{{iwsRepositoryId}}/content";
            _urlSiteInfoTemplate                 = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}";
            _urlInitiateUploadTemplate           = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/fileUploads";
            _urlAppendUploadChunkTemplate        = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/fileUploads/{{iwsUploadSession}}";
            _urlFinalizeUploadDatasourceTemplate = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/datasources?uploadSessionId={{iwsUploadSession}}&datasourceType={{iwsDatasourceType}}&overwrite=true";
            _urlFinalizeUploadWorkbookTemplate   = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/workbooks?uploadSessionId={{iwsUploadSession}}&workbookType={{iwsWorkbookType}}&overwrite=true";
            _urlCreateProjectTemplate            = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/projects";
            _urlDeleteWorkbookTagTemplate        = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}/tags/{{iwsTagText}}";
            _urlDeleteDatasourceTagTemplate      = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/datasources/{{iwsDatasourceId}}/tags/{{iwsTagText}}";
            _urlUpdateUserTemplate               = serverNameWithProtocol + "/api/3.3/sites/{{iwsSiteId}}/users/{{iwsUserId}}";

            //Any server version specific things we want to do?
            switch (serverVersion)
            {
            case ServerVersion.Server9:
                break;

            default:
                AppDiagnostics.Assert(false, "Unknown server version");
                throw new Exception("Unknown server version");
            }
        }
예제 #11
0
    public static Transports ToTransport(this ServerProtocol protocol)
    {
        switch (protocol)
        {
        case ServerProtocol.Udp:
            return(Transports.Udp);

        case ServerProtocol.Tcp:
            return(Transports.Tcp);

        case ServerProtocol.Tls:
            return(Transports.Tls);
        }

        throw new InvalidCastException();
    }
예제 #12
0
 public static SelectList ProtocolList(ServerProtocol protocol)
 {
     return(new SelectList(
                new List <SelectListItem>
     {
         new SelectListItem {
             Text = "SMTP", Value = "0"
         },
         new SelectListItem {
             Text = "EWS - Exchange 2007-2019/Office 365", Value = "1"
         },
         new SelectListItem {
             Text = "WebDAV - Exchange 2000/2003", Value = "2"
         }
     },
                "Value",
                "Text", ((int)protocol).ToString()));
 }
예제 #13
0
        public const int UploadFileChunkSize = 8000000; //8MB

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="serverName">Server IP, hostname or FQDN</param>
        /// <param name="siteName">Tableau Site Name</param>
        /// <param name="protocol">HTTP protocol</param>
        /// <param name="pageSize">Page size, defaults to 1000</param>
        /// <param name="serverVersion">Tableau Server version</param>
        public TableauServerUrls(ServerProtocol protocol, string serverName, string siteName, int pageSize = 1000, ServerVersion serverVersion = ServerVersion.Server9)
        {
            PageSize       = 1000;
            ServerProtocol = protocol;

            PageSize = pageSize;
            var serverNameWithProtocol = (protocol == ServerProtocol.Http ? "http://" : "https://") + serverName;

            ServerVersion         = serverVersion;
            SiteUrlSegement       = siteName;
            ServerName            = serverName;
            ServerUrlWithProtocol = serverNameWithProtocol;
            var apiVersion = ServerVersionLookup.APIVersion(serverVersion);

            UrlLogin = serverNameWithProtocol + $"/api/{apiVersion}/auth/signin";
            _urlListWorkbooksForUserTemplate     = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/users/%%iwsUserId%%/workbooks?pageSize=%%iwsPageSize%%&pageNumber=%%iwsPageNumber%%";
            _urlViewsListForSiteTemplate         = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/views?pageSize=%%iwsPageSize%%&pageNumber=%%iwsPageNumber%%";
            _urlViewThumbnailTemplate            = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/workbooks/%%iwsWorkbookId%%/views/%%iwsViewId%%/previewImage";
            _urlViewDataTemplate                 = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/views/%%iwsViewId%%/data";
            _urlListViewsForWorkbookTemplate     = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/workbooks/%%iwsWorkbookId%%/views";
            _urlListWorkbookConnectionsTemplate  = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/workbooks/%%iwsWorkbookId%%/connections";
            _urlWorkbookTemplate                 = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/workbooks/%%iwsWorkbookId%%";
            _urlListDatasourcesTemplate          = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/datasources?pageSize=%%iwsPageSize%%&pageNumber=%%iwsPageNumber%%";
            _urlListProjectsTemplate             = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/projects?pageSize=%%iwsPageSize%%&pageNumber=%%iwsPageNumber%%";
            _urlListGroupsTemplate               = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/groups?pageSize=%%iwsPageSize%%&pageNumber=%%iwsPageNumber%%";
            _urlListUsersTemplate                = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/users?pageSize=%%iwsPageSize%%&pageNumber=%%iwsPageNumber%%";
            _urlListUsersInGroupTemplate         = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/groups/%%iwsGroupId%%/users?pageSize=%%iwsPageSize%%&pageNumber=%%iwsPageNumber%%";
            _urlDownloadDatasourceTemplate       = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/datasources/%%iwsRepositoryId%%/content";
            _urlDatasourceConnectionsTemplate    = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/datasources/%%iwsRepositoryId%%/connections";
            _urlDownloadWorkbookTemplate         = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/workbooks/%%iwsRepositoryId%%/content";
            _urlSiteInfoTemplate                 = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%";
            _urlInitiateUploadTemplate           = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/fileUploads";
            _urlAppendUploadChunkTemplate        = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/fileUploads/%%iwsUploadSession%%";
            _urlFinalizeUploadDatasourceTemplate = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/datasources?uploadSessionId=%%iwsUploadSession%%&datasourceType=%%iwsDatasourceType%%&overwrite=true";
            _urlFinalizeUploadWorkbookTemplate   = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/workbooks?uploadSessionId=%%iwsUploadSession%%&workbookType=%%iwsWorkbookType%%&overwrite=true";
            _urlCreateProjectTemplate            = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/projects";
            _urlCreateUserTemplate               = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/users";
            _urlDeleteWorkbookTagTemplate        = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/workbooks/%%iwsWorkbookId%%/tags/%%iwsTagText%%";
            _urlDeleteDatasourceTagTemplate      = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/datasources/%%iwsDatasourceId%%/tags/%%iwsTagText%%";
            _urlUpdateUserTemplate               = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/users/iwsUserId";
            _urlViewImageTemplate                = serverNameWithProtocol + $"/api/{apiVersion}/sites/%%iwsSiteId%%/views/%%iwsViewId%%/image";

            //Any server version specific things we want to do?
        }
예제 #14
0
 public static bool TryConvertTo(this string protocolName, out ServerProtocol protocol)
 {
     if (string.Compare(protocolName, "udp", true) == 0)
     {
         protocol = ServerProtocol.Udp;
         return(true);
     }
     if (string.Compare(protocolName, "tcp", true) == 0)
     {
         protocol = ServerProtocol.Tcp;
         return(true);
     }
     if (string.Compare(protocolName, "tls", true) == 0)
     {
         protocol = ServerProtocol.Tls;
         return(true);
     }
     protocol = ServerProtocol.Udp;
     return(false);
 }
예제 #15
0
        private byte[] ConnectSendRecv(ClientProtocol msg, byte[] data, ServerProtocol waitMsg = ServerProtocol.svc_noop)
        {
            TcpClient client = new TcpClient();

            client.Connect(IPAddress.Parse("127.0.0.1"), 29015);
            if (!client.Connected)
            {
                MessageBox.Show("Вы не видите у нас обед?");
                return(null);
            }
            NetworkStream ns = client.GetStream();

            // craft message
            byte[] msgData = new byte[data.Length + 1];
            msgData[0] = (byte)msg;
            data.CopyTo(msgData, 1);

            ns.Write(msgData, 0, msgData.Length);

            byte[] response = new byte[4096];



            if (waitMsg != (byte)ServerProtocol.svc_noop)
            {
                int len = ns.Read(response, 0, response.Length);
                if (len > 0)
                {
                    if (response[0] == (byte)waitMsg)
                    {
                        return(response.Skip(1).ToArray());
                    }
                }
            }


            ns.Close();
            client.Close();

            return(null);
        }
예제 #16
0
        public static async Task <TcpClient> ConnectAndSend(string addess, int port, ServerProtocol protocol, byte[] data, bool isClose = false)
        {
            TcpClient configClient = new TcpClient();
            bool      isConnected  = false;

            for (int j = 0; j < 3; j++)
            {
                var delayDispose = Task.Delay(Global.DefaultConnectTimeout).ContinueWith(_ => configClient.Dispose());
                var connectAsync = configClient.ConnectAsync(addess, port);
                //超时则dispose掉
                var completedTask = await Task.WhenAny(delayDispose, connectAsync);

                if (!connectAsync.IsCompleted)
                {
                    Console.WriteLine("ConnectAndSend连接超时,5秒后重试");
                    await Task.Delay(5000);
                }
                else
                {
                    isConnected = true;
                    break;
                }
            }
            if (!isConnected)
            {
                Console.WriteLine("重试次数达到限制。"); throw new Exception("重试次数达到限制。");
            }

            var configStream = configClient.GetStream();
            await configStream.WriteAsync(new byte[] { (byte)protocol }, 0, 1);

            await configStream.WriteAndFlushAsync(data, 0, data.Length);

            //Console.Write(protocol.ToString() + " proceed.");
            Console.Write("->");
            if (isClose)
            {
                configClient.Close();
            }
            return(configClient);
        }
예제 #17
0
파일: Global.cs 프로젝트: vf1/serversockets
        public static bool TryConvertTo(this string protocolName, out ServerProtocol protocol)
        {
            if (string.Compare(protocolName, @"udp", true) == 0)
            {
                protocol = ServerProtocol.Udp;
                return true;
            }
            else if (string.Compare(protocolName, @"tcp", true) == 0)
            {
                protocol = ServerProtocol.Tcp;
                return true;
            }
            else if (string.Compare(protocolName, @"tls", true) == 0)
            {
                protocol = ServerProtocol.Tls;
                return true;
            }

            protocol = ServerProtocol.Udp;
            return false;
        }
예제 #18
0
 public ProtocolPort(ServerProtocol protocol, int port)
 {
     Protocol = protocol;
     Port     = port;
 }
예제 #19
0
 private static int GetDefaultPort( ServerProtocol protocol )
 {
     switch ( protocol ) {
         case ServerProtocol.Imap:
             return 143;
         case ServerProtocol.Pop3:
             return 110;
         case ServerProtocol.Smtp:
             return 25;
     }
     return 0;
 }
예제 #20
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                string server, user, password;
                //server = textServer.Text.Trim();
                //user = textUser.Text.Trim();
                //password = textPassword.Text.Trim();

                server   = "mail.it-corp.com";
                user     = "******";
                password = "******";

                //user = "******";
                //password = "******";

                if (server.Length == 0 || user.Length == 0 || password.Length == 0)
                {
                    MessageBox.Show("Por favor ingrese servidor, usuario y contraseña.");
                    return;
                }

                btnStart.Enabled  = false;
                btnCancel.Enabled = true;

                ServerAuthType authType = ServerAuthType.AuthLogin;
                if (lstAuthType.SelectedIndex == 1)
                {
                    authType = ServerAuthType.AuthCRAM5;
                }
                else if (lstAuthType.SelectedIndex == 2)
                {
                    authType = ServerAuthType.AuthNTLM;
                }

                ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex;

                MailServer oServer = new MailServer(server, user, password,
                                                    chkSSL.Checked, authType, protocol);

                // Para el uso de la evaluación, por favor utilice "TryIt" como el código de licencia, de lo contrario el
                // será lanzado  excepción "código de licencia no válida". Sin embargo, el objeto expirará en 1-2 meses, y luego
                // "versión de prueba expiró" se lanzará una excepción.

                MailClient oClient = new MailClient("EG-B1374632949-00215-D3BEB6416TE2E729-A84ADDF9C5A1C85F");

                //Catching the following events is not necessary,
                //just make the application more user friendly.
                //If you use the object in asp.net/windows service or non-gui application,
                //You need not to catch the following events.
                //To learn more detail, please refer to the code in EAGetMail EventHandler region

                oClient.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
                oClient.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
                oClient.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
                oClient.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
                oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

                bool bLeaveCopy = chkLeaveCopy.Checked;

                // UIDL es el identificador de cada correo electrónico de POP3 / IMAP4 / servidor de Exchange, para evitar recuperar
                // El mismo correo electrónico desde el servidor más de una vez, que registra el email UIDL recuperada cada vez
                // Si elimina el correo electrónico desde el servidor cada vez y no dejar una copia del correo electrónico en
                // El servidor, por favor, elimine toda la función sobre uidl.
                // UIDLManager envuelve la función de escribir / leer el registro uidl desde un archivo de texto.

                UIDLManager oUIDLManager = new UIDLManager();

                try
                {
                    // Carga existían registros UIDL a UIDLManager
                    string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
                    oUIDLManager.Load(uidlfile);

                    string mailFolder = String.Format("{0}\\inbox", m_curpath);
                    if (!Directory.Exists(mailFolder))
                    {
                        Directory.CreateDirectory(mailFolder);
                    }

                    m_bcancel      = false;
                    lblStatus.Text = "Connecting ...";
                    oClient.Connect(oServer);
                    MailInfo[] infos = oClient.GetMailInfos();
                    lblStatus.Text = String.Format("Total {0} email(s)", infos.Length);

                    // Eliminar el uidl local que no se existía en el servidor.
                    oUIDLManager.SyncUIDL(oServer, infos);
                    oUIDLManager.Update();

                    int count = infos.Length;

                    if (count > 0)
                    {
                        lista_Mensaje = new List <mail_Mensaje_Info>();
                    }

                    for (int i = 0; i < count; i++)
                    {
                        MailInfo info = infos[i];

                        //verificar en base
                        if (Bus_Mensaje.Verifica_codMensajeId(info.UIDL) == false)
                        {
                            //}
                            //if (oUIDLManager.FindUIDL(oServer, info.UIDL) != null /*&& "si esta en base"|| oUIDLManager.FindUIDL(oServer, info.UIDL) == null && "si esta en base"*/ )
                            //{
                            //    // este correo electrónico se ha descargado antes.
                            //    continue;
                            //}

                            lblStatus.Text = String.Format("Retrieving {0}/{1}...", info.Index, count);

                            Mail            oMail = oClient.GetMail(info);
                            System.DateTime d     = System.DateTime.Now;
                            System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                            string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                            string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i);
                            oMail.SaveAs(fileName, true);

                            //llenar grid

                            //int conta = oMail.Headers.Count;
                            //string MessageID = "";
                            //for (int y = 0; y < conta; y++)
                            //{

                            //        string valida = "Message-ID";
                            //        string extrae = oMail.Headers[y].ToString().Substring(0, 10);

                            //        string result = "";
                            //        if (extrae == valida)
                            //        {
                            //            MessageID = oMail.Headers[y].ToString();
                            //            break;
                            //        }

                            //       // break;
                            //}

                            conta = 0;
                            conta = oMail.To.ToList().Count();
                            sec   = 0;
                            foreach (var itemTo in oMail.To.ToList())
                            {
                                sec = sec + 1;
                                if (sec != conta)
                                {
                                    para += itemTo.Address + "; ";
                                }
                                else
                                {
                                    para += itemTo.Address;
                                }
                            }

                            conta = 0;
                            conta = oMail.Cc.ToList().Count();
                            sec   = 0;
                            foreach (var itemCopia in oMail.Cc.ToList())
                            {
                                sec = sec + 1;
                                if (sec != conta)
                                {
                                    CC += itemCopia.Address + "; ";
                                }
                                else
                                {
                                    CC += itemCopia.Address;
                                }
                            }

                            infoMensaje        = new mail_Mensaje_Info();
                            infoMensaje.Asunto = oMail.Subject;
                            infoMensaje.Asunto_texto_mostrado = oMail.Subject;
                            // infoMensaje.codMensajeId = MessageID;
                            infoMensaje.codMensajeId = info.UIDL;

                            infoMensaje.fileName      = fileName;
                            infoMensaje.Para          = para;
                            infoMensaje.Para_CC       = CC;
                            infoMensaje.Fecha         = oMail.ReceivedDate;
                            infoMensaje.Texto_mensaje = oMail.TextBody;

                            infoMensaje.Tiene_Adjunto = oMail.Attachments.Count() == 0 ? false : true;

                            if (Convert.ToString(oMail.Priority) == "Normal")
                            {
                                infoMensaje.Prioridad = 0;
                            }
                            if (Convert.ToString(oMail.Priority) == "Alta")
                            {
                                infoMensaje.Prioridad = 1;
                            }
                            if (Convert.ToString(oMail.Priority) == "Baja")
                            {
                                infoMensaje.Prioridad = -1;
                            }

                            infoMensaje.Leido      = false;
                            infoMensaje.Respondido = false;
                            infoMensaje.No_Leido   = false;

                            infoMensaje.mail_remitente = correo;
                            infoMensaje.Eliminado      = false;
                            infoMensaje.IdTipo_Mensaje = eTipoMail.Buzon_Ent;


                            infoMensaje.IdCuenta = IdCuenta;

                            foreach (var itemAdju in oMail.Attachments)
                            {
                                mail_Mensaje_Archi_Adjunto_Info infoAdju = new mail_Mensaje_Archi_Adjunto_Info();

                                string nomAdju = itemAdju.Name;

                                string extAdj = Path.GetExtension(nomAdju);
                                if (extAdj == ".pdf" || extAdj == ".xml")
                                {
                                    infoAdju.extensionArchivo  = extAdj;
                                    infoAdju.Archivo_adjunto   = itemAdju.Content;
                                    infoAdju.descripcion_archi = itemAdju.Name;

                                    infoMensaje.list_Archivos_Adjuntos.Add(infoAdju);
                                }
                            }

                            infoMensaje.Archivo_correo = System.IO.File.ReadAllBytes(infoMensaje.fileName);

                            lista_Mensaje.Add(infoMensaje);


                            gridControl_Correo.DataSource = lista_Mensaje;

                            gridControl_Correo.RefreshDataSource();

                            oMail.Clear();

                            // si lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count);

                            if (bLeaveCopy)
                            {
                                // añadir el uidl correo electrónico a uidl archivo para evitar recuperamos la próxima vez.
                                oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                            }
                        }
                    }

                    if (!bLeaveCopy)
                    {
                        lblStatus.Text = "Deleting ...";
                        for (int i = 0; i < count; i++)
                        {
                            oClient.Delete(infos[i]);
                            // Eliminar UIDL de archivo uidl local.
                            oUIDLManager.RemoveUIDL(oServer, infos[i].UIDL);
                        }
                    }
                    // Eliminar método sólo marcar el correo electrónico como eliminado,
                    // Salir método puro los mensajes de correo electrónico desde el servidor exactamente.
                    oClient.Quit();

                    if (lista_Mensaje.Count() == 0)
                    {
                        MessageBox.Show("No existen Correos de Entrada Nuevos");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                    MessageBox.Show(ex.Message.ToString());
                }

                // Actualizar la lista uidl de archivo uidl local y luego podemos cargar la próxima vez.
                oUIDLManager.Update();

                lblStatus.Text    = "Completed";
                pgBar.Maximum     = 100;
                pgBar.Minimum     = 0;
                pgBar.Value       = 0;
                btnStart.Enabled  = true;
                btnCancel.Enabled = false;
            }
            catch (Exception ex)
            {
                BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                MessageBox.Show(ex.Message.ToString());
            }
        }
예제 #21
0
        private void btndescargarcorreo_Click(object sender, EventArgs e)
        {
            try
            {
                string mensajError = "";
                if (InfoCuenta == null)
                {
                    mail_Cuentas_Correo_Bus         bus_correo   = new mail_Cuentas_Correo_Bus();
                    List <mail_Cuentas_Correo_Info> lista_Correo = new List <mail_Cuentas_Correo_Info>();
                    lista_Correo = bus_correo.consultar(ref mensajError);
                    InfoCuenta   = lista_Correo.FirstOrDefault(q => q.direccion_correo == dir_correo);
                }

                if (InfoCuenta.ServidorCorreoEntrante.Length == 0 || InfoCuenta.Usuario.Length == 0 || InfoCuenta.Password.Length == 0)
                {
                    MessageBox.Show("Por favor ingrese servidor, usuario y contraseña.");
                    return;
                }
                // cargo los ID de mensaje para no tener q ir a la DB
                lista_codMensajeId_Existentes = new List <string>();
                lista_codMensajeId_Existentes = Bus_Mensaje.consultar_CodMail_Existentes();
                btndescargarcorreo.Enabled    = false;
                btnCancel.Enabled             = true;
                lista_Mensaje = new List <mail_Mensaje_Info>();
                string mensajeError = "";

                ServerAuthType authType = ServerAuthType.AuthLogin;

                if (InfoCuenta.Tipo_Authenticacion == "APOP")
                {
                    authType = ServerAuthType.AuthCRAM5;
                }
                else if (InfoCuenta.Tipo_Authenticacion == "NTLM")
                {
                    authType = ServerAuthType.AuthNTLM;
                }
                // ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex;
                ServerProtocol protocol = new ServerProtocol();
                if (InfoCuenta.TipoCuenta == "POP3")
                {
                    protocol = ServerProtocol.Pop3;
                }
                if (InfoCuenta.TipoCuenta == "IMAP4")
                {
                    protocol = ServerProtocol.Imap4;
                }
                if (InfoCuenta.TipoCuenta == "EXCHA_WEB_SER")
                {
                    protocol = ServerProtocol.ExchangeEWS;
                }
                if (InfoCuenta.TipoCuenta == "EXCHA_WEB_DAV")
                {
                    protocol = ServerProtocol.ExchangeWebDAV;
                }


                usa_sll = (InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo == null) ? false : (Boolean)InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo;

                MailServer oServer = new MailServer(InfoCuenta.ServidorCorreoEntrante, InfoCuenta.Usuario, InfoCuenta.Password,
                                                    usa_sll, authType, protocol);



                // Para el uso de la evaluación, por favor utilice "TryIt" como el código de licencia, de lo contrario el
                // será lanzado  excepción "código de licencia no válida". Sin embargo, el objeto expirará en 1-2 meses, y luego
                // "versión de prueba expiró" se lanzará una excepción.

                MailClient oClient = new MailClient("EG-B1374632949-00215-D3BEB6416TE2E729-A84ADDF9C5A1C85F");

                //Catching the following events is not necessary,
                //just make the application more user friendly.
                //If you use the object in asp.net/windows service or non-gui application,
                //You need not to catch the following events.
                //To learn more detail, please refer to the code in EAGetMail EventHandler region

                oClient.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
                oClient.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
                oClient.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
                oClient.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
                oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

                bool bMantener_copia_correo = (InfoCuenta.Guardar_1_copia_de_corre_en_server_mail == null) ? false : (Boolean)InfoCuenta.Guardar_1_copia_de_corre_en_server_mail;

                UIDLManager oUIDLManager = new UIDLManager();

                try
                {
                    // Carga existían registros UIDL a UIDLManager
                    string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
                    oUIDLManager.Load(uidlfile);

                    string mailFolder = String.Format("{0}\\inbox", m_curpath);
                    if (!Directory.Exists(mailFolder))
                    {
                        Directory.CreateDirectory(mailFolder);
                    }

                    m_bcancel      = false;
                    lblStatus.Text = "Conectando ...";
                    oClient.Connect(oServer);
                    MailInfo[] infos = oClient.GetMailInfos();
                    lblStatus.Text = String.Format("Total {0} email(s)", infos.Length);

                    // Eliminar el uidl local que no se existía en el servidor.
                    oUIDLManager.SyncUIDL(oServer, infos);
                    oUIDLManager.Update();

                    int count = infos.Length;

                    if (count > 0)
                    {
                        lista_Mensaje = new List <mail_Mensaje_Info>();
                    }

                    int CountError = 0;

                    for (int i = 0; i < count; i++)
                    {
                        MailInfo info = infos[i];
                        CountError = i;
                        //if (i == 2587) { MessageBox.Show(""); }


                        //verificar en base NO debo ir a la base uno a uno sino se hace muy largo
                        if (lista_codMensajeId_Existentes.Contains(info.UIDL) == false)
                        {
                            lblStatus.Text = String.Format("Retrieving {0}/{1}...", info.Index, count);
                            Mail            oMail = oClient.GetMail(info);
                            System.DateTime d     = System.DateTime.Now;
                            System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                            string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                            string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i);


                            try//try1
                            {
                                oMail.SaveAs(fileName, true);

                                conta = 0;
                                conta = oMail.To.ToList().Count();
                                sec   = 0;
                                foreach (var itemTo in oMail.To.ToList())
                                {
                                    sec = sec + 1;
                                    if (sec != conta)
                                    {
                                        para += itemTo.Address + "; ";
                                    }
                                    else
                                    {
                                        para += itemTo.Address;
                                    }
                                }

                                conta = 0;
                                conta = oMail.Cc.ToList().Count();
                                sec   = 0;
                                foreach (var itemCopia in oMail.Cc.ToList())
                                {
                                    sec = sec + 1;
                                    if (sec != conta)
                                    {
                                        CC += itemCopia.Address + "; ";
                                    }
                                    else
                                    {
                                        CC += itemCopia.Address;
                                    }
                                }
                            }
                            catch (Exception EX)
                            {
                                MessageBox.Show(EX.Message + " try 1");
                            }


                            try//try2
                            {
                                infoMensaje        = new mail_Mensaje_Info();
                                infoMensaje.Asunto = oMail.Subject;
                                infoMensaje.Asunto_texto_mostrado = oMail.Subject;
                                // infoMensaje.codMensajeId = MessageID;
                                infoMensaje.codMensajeId = info.UIDL;

                                infoMensaje.fileName      = fileName;
                                infoMensaje.Para          = para;
                                infoMensaje.Para_CC       = CC;
                                infoMensaje.Fecha         = oMail.ReceivedDate;
                                infoMensaje.Texto_mensaje = oMail.TextBody;

                                infoMensaje.Tiene_Adjunto = oMail.Attachments.Count() == 0 ? false : true;

                                if (Convert.ToString(oMail.Priority) == "Normal")
                                {
                                    infoMensaje.Prioridad = 0;
                                }
                                if (Convert.ToString(oMail.Priority) == "Alta")
                                {
                                    infoMensaje.Prioridad = 1;
                                }
                                if (Convert.ToString(oMail.Priority) == "Baja")
                                {
                                    infoMensaje.Prioridad = -1;
                                }

                                infoMensaje.Leido      = false;
                                infoMensaje.Respondido = false;
                                infoMensaje.No_Leido   = false;

                                infoMensaje.mail_remitente = dir_correo;
                                infoMensaje.Eliminado      = false;
                                infoMensaje.IdTipo_Mensaje = eTipoMail.Buzon_Ent;


                                infoMensaje.IdCuenta = IdCuenta;

                                foreach (var itemAdju in oMail.Attachments)
                                {
                                    mail_Mensaje_Archi_Adjunto_Info infoAdju = new mail_Mensaje_Archi_Adjunto_Info();

                                    string nomAdju = itemAdju.Name;

                                    string extAdj = Path.GetExtension(nomAdju);
                                    if (extAdj.ToUpper() == ".PDF" || extAdj.ToUpper() == ".XML")
                                    {
                                        infoAdju.extensionArchivo  = extAdj;
                                        infoAdju.Archivo_adjunto   = itemAdju.Content;
                                        infoAdju.descripcion_archi = itemAdju.Name;

                                        infoMensaje.list_Archivos_Adjuntos.Add(infoAdju);
                                    }
                                }

                                infoMensaje.Archivo_correo = System.IO.File.ReadAllBytes(infoMensaje.fileName);


                                Bus_Mensaje.GrabarMensajeDB(infoMensaje, ref mensajeError);
                                //lista_Mensaje.Add(infoMensaje);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message + " try 2");
                            }


                            oMail.Clear();

                            // si lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count);

                            if (bMantener_copia_correo)
                            {
                                // añadir el uidl correo electrónico a uidl archivo para evitar recuperamos la próxima vez.
                                oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                            }
                        }
                    }

                    if (!bMantener_copia_correo)
                    {
                        lblStatus.Text = "Borrando ...";
                        for (int i = 0; i < count; i++)
                        {
                            oClient.Delete(infos[i]);
                            // Eliminar UIDL de archivo uidl local.
                            oUIDLManager.RemoveUIDL(oServer, infos[i].UIDL);
                        }
                    }
                    // Eliminar método sólo marcar el correo electrónico como eliminado,
                    // Salir método puro los mensajes de correo electrónico desde el servidor exactamente.
                    oClient.Quit();

                    //if (lista_Mensaje.Count() == 0)
                    //{
                    //    MessageBox.Show("No existen Correos de Entrada Nuevos");
                    //    btndescargarcorreo.Enabled = true;
                    //    btnCancel.Enabled = false;
                    //    return;
                    //}
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                    BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                }

                // Actualizar la lista uidl de archivo uidl local y luego podemos cargar la próxima vez.
                oUIDLManager.Update();

                lblStatus.Text             = "Completed";
                pgBar.Maximum              = 100;
                pgBar.Minimum              = 0;
                pgBar.Value                = 0;
                btndescargarcorreo.Enabled = true;
                btnCancel.Enabled          = false;


                //mostrar_mensajes(eTipoMail.Buzon_Ent, dtp_desde.Value, dtp_hasta.Value, dir_correo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
            }
        }
예제 #22
0
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            string server, user, password;

            server   = textServer.Text.Trim();
            user     = textUser.Text.Trim();
            password = textPassword.Text.Trim();

            if (server.Length == 0 || user.Length == 0 || password.Length == 0)
            {
                MessageBox.Show("Please input server, user and password.");
                return;
            }

            btnStart.Enabled  = false;
            btnCancel.Enabled = true;

            ServerAuthType authType = ServerAuthType.AuthLogin;

            if (lstAuthType.SelectedIndex == 1)
            {
                authType = ServerAuthType.AuthCRAM5;
            }
            else if (lstAuthType.SelectedIndex == 2)
            {
                authType = ServerAuthType.AuthNTLM;
            }

            ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex;

            MailServer oServer = new MailServer(server, user, password,
                                                chkSSL.Checked, authType, protocol);

            //For evaluation usage, please use "TryIt" as the license code, otherwise the
            //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
            //"trial version expired" exception will be thrown.
            MailClient oClient = new MailClient("TryIt");

            //Catching the following events is not necessary,
            //just make the application more user friendly.
            //If you use the object in asp.net/windows service or non-gui application,
            //You need not to catch the following events.
            //To learn more detail, please refer to the code in EAGetMail EventHandler region
            oClient.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
            oClient.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
            oClient.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
            oClient.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
            oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

            bool bLeaveCopy = chkLeaveCopy.Checked;

            // UIDL is the identifier of every email on POP3/IMAP4/Exchange server, to avoid retrieve
            // the same email from server more than once, we record the email UIDL retrieved every time
            // if you delete the email from server every time and not to leave a copy of email on
            // the server, then please remove all the function about uidl.
            // UIDLManager wraps the function to write/read uidl record from a text file.
            UIDLManager oUIDLManager = new UIDLManager();

            try
            {
                // load existed uidl records to UIDLManager
                string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
                oUIDLManager.Load(uidlfile);

                string mailFolder = String.Format("{0}\\inbox", m_curpath);
                if (!Directory.Exists(mailFolder))
                {
                    Directory.CreateDirectory(mailFolder);
                }

                m_bcancel      = false;
                lblStatus.Text = "Connecting ...";
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                lblStatus.Text = String.Format("Total {0} email(s)", infos.Length);

                // remove the local uidl which is not existed on the server.
                oUIDLManager.SyncUIDL(oServer, infos);
                oUIDLManager.Update();

                int count = infos.Length;

                ArrayList arReport = new ArrayList();
                for (int i = 0; i < count; i++)
                {
                    MailInfo info = infos[i];
                    if (oUIDLManager.FindUIDL(oServer, info.UIDL) != null)
                    {
                        // This email has been downloaded or checked before.
                        continue;
                    }

                    lblStatus.Text = String.Format("Retrieving mail header {0}/{1}...", info.Index, count);

                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i);

                    Mail oMail = new Mail("TryIt");
                    oMail.Load(oClient.GetMailHeader(info));

                    if (!oMail.IsReport)
                    {
                        // Not a report, continue
                        // Add the email uidl to uidl file to avoid we check it next time.
                        oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                        continue;
                    }

                    // This is a report, get the entire email.
                    oMail = oClient.GetMail(info);
                    oMail.SaveAs(fileName, true);

                    ListViewItem item = new ListViewItem(oMail.From.ToString());
                    item.SubItems.Add(oMail.Subject);
                    item.SubItems.Add(oMail.ReceivedDate.ToString("yyyy-MM-dd HH:mm:ss"));
                    item.Font = new System.Drawing.Font(item.Font, FontStyle.Bold);
                    item.Tag  = fileName;
                    lstMail.Items.Insert(0, item);
                    oMail.Clear();

                    lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count);

                    arReport.Add(info); // Add the report mail info to arraylist,
                    // then we can delete it later.
                    if (bLeaveCopy)
                    {
                        // Add the email uidl to uidl file to avoid we retrieve it next time.
                        oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                    }
                }

                if (!bLeaveCopy)
                {
                    lblStatus.Text = "Deleting ...";
                    count          = arReport.Count;
                    for (int i = 0; i < count; i++)
                    {
                        MailInfo info = arReport[i] as MailInfo;
                        oClient.Delete(info);
                        // Remove UIDL from local uidl file.
                        oUIDLManager.RemoveUIDL(oServer, info.UIDL);
                    }
                }
                // Delete method just mark the email as deleted,
                // Quit method pure the emails from server exactly.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                MessageBox.Show(ep.Message);
            }

            // Update the uidl list to local uidl file and then we can load it next time.
            oUIDLManager.Update();

            lblStatus.Text    = "Completed";
            pgBar.Maximum     = 100;
            pgBar.Minimum     = 0;
            pgBar.Value       = 0;
            btnStart.Enabled  = true;
            btnCancel.Enabled = false;
        }
 /// <summary>
 /// Ajoute le type d'action au tableau de bytes
 /// </summary>
 /// <param name="bytes">bytes à envoyer sur le réseau</param>
 /// <param name="id">offset d'écriture</param>
 /// <param name="p">type d'action</param>
 private void setType(ref Byte[] bytes, ref int id, ServerProtocol p)
 {
     addInt16(ref bytes, ref id, (UInt16)p);
 }
예제 #24
0
 /// <summary>
 /// 获得服务器清单列表
 /// </summary>
 /// <returns></returns>
 public static Boolean LoadServerListConfig()
 {
     ServerList = new DataSet.ConfigDataTable();
     DataUtils.Arrange(ServerList, ServerProtocol.ListServer());
     return(SaveServerListConfig());
 }
예제 #25
0
 public ProtocolPort(ServerProtocol protocol, int port)
 {
     this.Protocol = protocol;
     this.Port     = port;
 }
예제 #26
0
 private static int ParsePort( String value, ServerProtocol protocol )
 {
     int port;
     try {
         port = Int32.Parse(value);
     } catch ( System.Exception e ) {
         if ( log.IsErrorEnabled )
             log.Error(System.String.Format("Error parsing port: {0}", value), e);
         port = anmar.SharpWebMail.EmailServerInfo.GetDefaultPort(protocol);
     }
     return port;
 }
예제 #27
0
 public ProtocolPort(ServerProtocol protocol, int port)
 {
     Protocol = protocol;
     Port = port;
 }
예제 #28
0
 public EmailServerInfo( ServerProtocol protocol, String host, int port )
 {
     this._protocol = protocol;
     this._host = host;
     this._port = port;
 }
예제 #29
0
 public bool Equals(ServerProtocol protocol, IPEndPoint endpoint)
 {
     return(AddressFamily == endpoint.AddressFamily && Port == endpoint.Port &&
            Address.Equals(endpoint.Address) && Protocol == protocol);
 }
예제 #30
0
 public ServerEndPoint(ServerProtocol protocol, IPEndPoint endpoint)
     : base(endpoint.Address, endpoint.Port)
 {
     Protocol = protocol;
 }
예제 #31
0
 public ServerEndPoint(ServerProtocol protocol, IPAddress address, int port)
     : base(address, port)
 {
     Protocol = protocol;
 }
예제 #32
0
 public ServerTransport(ServerProtocol serverProtocol)
 {
     _serverProtocol = serverProtocol;
 }
예제 #33
0
파일: Logger.cs 프로젝트: vf1/serversockets
 private Protocol Convert(ServerProtocol source)
 {
     if (source == ServerProtocol.Udp)
         return Protocol.Udp;
     if (source == ServerProtocol.Tls)
         return Protocol.Tls;
     return Protocol.Tcp;
 }
예제 #34
0
 public EmailServerInfo( String protocol, String host, String port )
 {
     this._protocol = EmailServerInfo.ParseProtocol(protocol);
     this._host = EmailServerInfo.ParseHost(host);
     this._port = EmailServerInfo.ParsePort(port, this._protocol);
 }