Exemplo n.º 1
0
        private void OnButtonDelete(object sender)
        {
            Gtk.Application.Invoke(delegate {
                FileProgressObject obj = sender as FileProgressObject;
                obj.Delete            -= new BlankEventHandler(OnButtonDelete);

                FileSender fileSender = null;
                lock (progressObjects) {
                    foreach (FileSender fileSnd in progressObjects.Keys)
                    {
                        if (progressObjects[fileSnd] == obj)
                        {
                            fileSender = fileSnd;
                            break;
                        }
                    }

                    if (obj.Finished != true)
                    {
                        fileSender.Abort();
                    }

                    progressObjects.Remove(fileSender);
                    vbox.Remove(obj);
                }
            });
        }
Exemplo n.º 2
0
        private void ImageDelete(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show(
                    _dtLink.Rows[ImageIndex]["FILE_DESC"] + " File을 삭제 하시겠습니까?", "File 제거"
                    , MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                FileSender snd = new FileSender(_dtLink.Rows[ImageIndex]["LINK_CD"].ToString(), _dtLink.Rows[ImageIndex]["LINK"].ToString(), false);
                snd.Close();

                _dtLink.Rows.RemoveAt(ImageIndex--);

                if (ImageIndex > -1)
                {
                    ViewImage(ImageIndex);
                }
                else
                {
                    PicVer.Image      = null;
                    btnImgDel.Enabled = false;
                    btnLeft.Enabled   = false;
                    btnRight.Enabled  = false;
                    btnFirst.Enabled  = false;
                    btnLast.Enabled   = false;
                }
            }
        }
Exemplo n.º 3
0
        public async Task PutFileAsync(Profile profile, string file, SharingHandler <ISharingFileSender> handler)
        {
            if (profile == null || handler == null || !(profile is NotifyClientProfile receiver))
            {
                throw new ArgumentNullException();
            }
            var fileInfo = new FileInfo(file);

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException("File not found!", file);
            }
            var length = fileInfo.Length;
            var packet = new { name = fileInfo.Name, length };

            _ = await this.network.ConnectAsync("link.sharing.file", packet, receiver.GetTcpEndPoint(), async stream =>
            {
                var result = await stream.ReadBlockWithHeaderAsync(this.settings.TcpBufferLimits, this.cancellationToken);
                var data   = new Token(this.generator, result);
                if (data["status"].As <string>() != "wait")
                {
                    throw new NetworkException(NetworkError.InvalidData);
                }
                using (var sender = new FileSender(this.context, receiver, stream, fileInfo.FullName, length))
                {
                    await this.dispatcher.InvokeAsync(() => handler.Invoke(sender));
                    await sender.LoopAsync();
                }
                return(new Unit());
            }, this.cancellationToken);
        }
Exemplo n.º 4
0
        private async void Send(object parameter)
        {
            Client = new Client(Host, Port);

            ClientTaskResult connectionResult = await Client.Connect();

            if (connectionResult.Success)
            {
                FileSender fileManager = new FileSender(this, Client.TcpClient.GetStream());

                tokenSource = new CancellationTokenSource();

                await Task.Delay(SEND_DELAY);

                ClientTaskResult result = await fileManager.SendFile(FilePath, FileName, Progress, tokenSource.Token);

                if (!result.Success)
                {
                    OnClientMessage(result.Message);
                }
            }
            else
            {
                OnClientMessage(connectionResult.Message);
            }

            Sending = false;
            ResetStatus();

            OnProgressReport(new ProgressBarUpdateEventArgs(true));
        }
Exemplo n.º 5
0
        [InlineData(134217728)]                       // 128 MByte
        public async Task SendInChunksCallsPublishOk(int fileSizeInBytes)
        {
            Action <Message> senderHandler = null;
            var messaging = Substitute.For <IMessagingInfrastructure>();

            messaging.When(m => m.Subscribe(Arg.Any <string>(), Arg.Any <Action <Message> >()))
            .Do(args => senderHandler = args.Arg <Action <Message> >());

            var testChannel = $"tests/fileSender/{fileSizeInBytes}";
            var buffer      = new byte[fileSizeInBytes];

            messaging.When(m => m.Publish(Arg.Is <Message>(msg => msg.Topic == testChannel)))
            .Do(args =>
            {
                var msg = args.Arg <Message>();
                var req = JsonSerializer.Deserialize <TransportFileEnvelope>(msg.Payload);
                senderHandler?.Invoke(new Message {
                    Topic = req.ReplyTo, Payload = "OK"
                });
            });
            using (var tempFile = new TemporaryFile($"file{fileSizeInBytes}.tmp", buffer))
            {
                var fileSender = new FileSender(messaging, null);
                var sendResult = await fileSender.SendInChunks(testChannel, tempFile.TempFilePath);

                Assert.Equal(FileTransferStatus.Delivered, sendResult);
            }

            var expectedCalls = fileSizeInBytes / FileSender.MaxChunkSize;

            expectedCalls += (fileSizeInBytes % FileSender.MaxChunkSize) != 0 ? 1 : 0;
            messaging.Received(Convert.ToInt32(expectedCalls)).Publish(Arg.Is <Message>(msg => msg.Topic == testChannel));
        }
Exemplo n.º 6
0
        // ============================================
        // PRIVATE (Methods) Event Handlers
        // ============================================
        private void OnAdded(object sender)
        {
            Gtk.Application.Invoke(delegate {
                FileSender fileSender = sender as FileSender;

                FileProgressObject obj = new FileProgressObject();
                obj.Delete            += new BlankEventHandler(OnButtonDelete);

                // Setup Image
                string ext = FileUtils.GetExtension(fileSender.Name);
                obj.Image  = StockIcons.GetFileIconPixbuf(TextUtils.UpFirstChar(ext));

                // Set Transfer Info
                SetTransferInfo(obj, fileSender);

                // Set Info
                UserInfo userInfo = fileSender.Peer.Info as UserInfo;
                obj.SetName(fileSender.Name, userInfo.Name);

                // Add Update
                progressObjects.Add(fileSender, obj);
                vbox.PackStart(obj, false, false, 2);
                obj.ShowAll();
            });
        }
Exemplo n.º 7
0
        private void Save(object sender, EventArgs e)
        {
            if ("".Equals(ACC_CD))
            {
                FileSender file = new FileSender("", txtBankImage.Text);

                Link = file.GetLinkCode();
                file.Close();
            }

            ClearSearchData();
            SetSearchData("ACC_CD", ACC_CD);
            SetSearchData("ACC_TYPE", cboType.ValueList);
            SetSearchData("OUT_BANK_NM", cboBank.ValueList);
            SetSearchData("OUT_BANK_NO", txtBankCode.Text);
            SetSearchData("USER_ID", cboUser.ValueList);
            SetSearchData("ACCOUNT_DESC", txtBankDesc.Text);
            SetSearchData("LINK_CODE", Link);
            SetSearchData("UPT_USER_ID", DTOFactory.UserId);
            SetServiceId("SetBankAccountList");

            try
            {
                DTOFactory.Transaction(new AccountDTO());

                DialogResult = DialogResult.OK;
                ViewMessage.Info("등록이 완료 되었습니다.");
                Close();
            }
            catch (Exception ex)
            {
                ViewMessage.Error(ex.Message);
            }
        }
Exemplo n.º 8
0
 private void MessageServer_MessageReceived(Message message, System.Net.IPEndPoint endPoint)
 {
     if (message is FileMessage)
     {
         var fileMessage = message as FileMessage;
         filesList.Add(fileMessage.ID, null);
         if (fileMessage.ID > lastFileIndex)
         {
             lastFileIndex = fileMessage.ID;
         }
     }
     if (message is Introduction)
     {
         Introduction intro = new Introduction
         {
             Name = Name
         };
         SendMessage(intro);
     }
     if (message is FileRequest)
     {
         var        fileRequest = message as FileRequest;
         var        file        = filesList[fileRequest.ID];
         FileSender fileSender  = new FileSender(fileRequest.RecieverEndPoint.ToIPEndPoint());
         fileSender.SendFile(file);
     }
     else
     {
         MessageReceived?.Invoke(message);
     }
 }
Exemplo n.º 9
0
        protected override void OnStart(string[] args)
        {
            try
            {
                OptionsManager manager = new OptionsManager(@"E:\LR4\DataManagerService\bin\Release\AppSettings.xml");
                dataManagerOptions = manager.GetOptions <DataManagerOptions>();

                errorDb  = new Database(dataManagerOptions.ErrorConnectionString);
                personDb = new Database(dataManagerOptions.ConnectionString);
                var persons = personDb.GetPersons(dataManagerOptions.SearchCriteria);

                XmlXsdGenerator <Person> generator = new XmlXsdGenerator <Person>(persons);
                var xmlString = generator.GenerateXml();
                var xsdString = generator.GenerateXsd();

                FileManagerService fileManager = new FileManagerService();
                fileManager.Launch();

                FileSender sender = new FileSender(dataManagerOptions.FtpSourceFolder);
                sender.Send(xmlString, xsdString);
            }
            catch (Exception ex)
            {
                Error error = new Error(ex.Source, ex.Message, ex.StackTrace, DateTime.Now);
                errorDb.LogError(error);
            }
        }
        public void Add(FileSender fileSender)
        {
            FileProgressObject widget = AddFileProgress(fileSender);

            this.vbox.PackStart(widget, false, false, 2);
            this.ShowAll();
        }
Exemplo n.º 11
0
        private void SendFile(object sender, RoutedEventArgs e)
        {
            FileAndDirAttributes files = (FileAndDirAttributes)DirsAndFiles.SelectedItem;
            FileSender           send  = new FileSender();
            Partners             pr    = new Partners();
            string code = "";

            code = ContactsData.GetShareCode(ContactName.Text);
            string ip = "";

            if (code != "")
            {
                ip = ShareCode.GetIPFromCode(code);
            }
            if (ip != "" && pr.IsContactAvailable(ip))
            {
                if (InMyFiles == true)
                {
                    string             path = FileData.SelectedVersionPath(files.FileDirectory + "\\" + files.FileName, VersionsList.SelectedIndex);
                    DataGridController dgc  = new DataGridController();
                    send.SendFile(path, ip);
                    System.Diagnostics.Process.Start(@path);
                }
                else
                {
                    send.SendFile(files.FileDirectory + "\\" + files.FileName, "127.0.0.1");
                }
            }
            else
            {
                MessageBox.Show("Error", "Couldn't connect with partner");
            }
        }
 public void UseDefaultFileSender()
 {
     FileSender = new FileSender(Settings);
     FileSender.EventOccurred        += HandleServerEventOccurred;
     FileSender.SocketEventOccurred  += HandleSocketEventOccurred;
     FileSender.FileTransferProgress += HandleFileTransferProgress;
 }
        // ============================================
        // PROTECTED Methods
        // ============================================
        private void UpdateFileSender(FileSender snd)
        {
            UserInfo userInfo = snd.Peer.Info as UserInfo;

            SetName(snd.FileName, userInfo.Name);
            SetTransferInfo(snd.FileSendedSize, snd.FileSize, snd.SendedPercent);
        }
Exemplo n.º 14
0
 private void BeginListen()
 {
     try
     {
         listensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 3477);
         listensocket.Bind(ep);
         listensocket.Listen(20);
         while (true)
         {
             Socket newsocket = listensocket.Accept();
             //task = new FileTransmission(FileTransmission.TransmissionMode.Send);
             task = new FileSender();
             task.FullFileName     = FullFileName;
             task.Socket           = newsocket;
             task.EnabledIOBuffer  = true;
             task.BlockFinished   += new BlockFinishedEventHandler(task_BlockFinished);
             task.CommandReceived += new CommandReceivedEventHandler(task_CommandReceived);
             task.ConnectLost     += new EventHandler(task_ConnectLost);
             task.ErrorOccurred   += new FileTransmissionErrorOccurEventHandler(task_ErrorOccurred);
             task.Start();
         }
     }
     catch (ThreadAbortException)
     {
         if (task != null && task.IsAlive)
         {
             task.Stop(true);
         }
     }
 }
Exemplo n.º 15
0
 public void Setup(IPEndPoint clientinfo, IPEndPoint serverinfo)
 {
     this._sender             = new TcpSender(clientinfo, serverinfo);
     this._fileSender         = new FileSender(this._sender);
     this._directoryRequester = new DirectoryResquestSender(this._sender);
     this._sender.Connect();
 }
Exemplo n.º 16
0
        public async Task SendFileAsync(LinkProfile profile, string filePath, FileSenderHandler handler)
        {
            if (profile == null || handler == null)
            {
                throw new ArgumentNullException();
            }
            var fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException("File not found!", filePath);
            }
            var length = fileInfo.Length;
            var packet = new { name = fileInfo.Name, length };

            using (var tcp = await Network.ConnectAsync("link.share.file", packet, profile.GetTcpEndPoint(), CancellationToken))
            {
                var stream = tcp.GetStream();
                var result = await stream.ReadBlockWithHeaderAsync(Environment.TcpBufferLimits, CancellationToken);

                var data = Generator.AsToken(result);
                if (data["status"].As <string>() != "wait")
                {
                    throw new LinkException(LinkError.InvalidData);
                }
                using (var sender = new FileSender(this, profile, stream, fileInfo.FullName, length))
                {
                    await UpdateUIAsync(() => handler.Invoke(sender));

                    await sender.LoopAsync();
                }
            }
        }
Exemplo n.º 17
0
        protected override async void OnStart(string[] args)
        {
            try
            {
                OptionsManager manager = new OptionsManager(@"E:\LR5\DataManagerService\bin\Release\AppSettings.xml");
                dataManagerOptions = await manager.GetOptionsAsync <DataManagerOptions>();

                errorDb  = new Database(dataManagerOptions.ErrorConnectionString);
                personDb = new Database(dataManagerOptions.ConnectionString);
                var persons = await personDb.GetPersonsAsync(dataManagerOptions.SearchCriteria);

                XmlXsdGenerator <Person> generator = new XmlXsdGenerator <Person>(persons);
                var xmlString = generator.GenerateXml();
                var xsdString = generator.GenerateXsd();

                FileManagerService filemanager = new FileManagerService();
                await filemanager.LaunchAsync();

                FileSender sender = new FileSender(dataManagerOptions.FtpSourceFolder);
                await sender.SendAsync(xmlString, xsdString);
            }
            catch (Exception e)
            {
                await errorDb.LogErrorAsync(new Error(e.Message, e.Source, e.StackTrace, DateTime.Now));
            }
        }
Exemplo n.º 18
0
        public static async Task WriteFile(this HttpResponse response, string filePath, string contentType = "application/octet-stream", IRange?range = null)
        {
            await using var fileSender = new FileSender(response, filePath, contentType, range);

            response.StatusCode = fileSender.IsPartialContent ? 206 : 200;

            await fileSender.Send();
        }
        // ============================================
        // PROTECTED (Methods) Event Handlers
        // ============================================
        protected FileProgressObject AddFileProgress(FileSender fileSender)
        {
            FileProgressObject widget = new FileProgressObject(fileSender);

            widget.Delete += new BlankEventHandler(OnDeleteClicked);
            this.progressObjects.Add(fileSender, widget);
            return(widget);
        }
Exemplo n.º 20
0
 // ============================================
 // PRIVATE Methods
 // ============================================
 private void SetTransferInfo(FileProgressObject obj, FileSender fs)
 {
     if (obj == null)
     {
         return;
     }
     obj.SetTransferInfo(fs.SendedSize, fs.Size, fs.SendedPercent);
 }
        // ============================================
        // PUBLIC Constructors
        // ============================================
        public FileProgressObject(FileSender snd)
        {
            this.fileSender = snd;
            InitializeObject(false);

            // Initialize Info
            UpdateFileSender(this.fileSender);
        }
Exemplo n.º 22
0
        private void RemoveLink(object sender, EventArgs e)
        {
            Button  btn      = (Button)sender;
            DataRow row      = _dtModel.Rows[gd_List.SelectedRows[0].Index];
            string  linkcode = "";

            if ("btnPlanRemove".Equals(btn.Name))
            {
                if (LstPlan.SelectedIndex == -1)
                {
                    return;
                }

                linkcode = row["PLAN_CD"].ToString();
                row      = _dtPlan.Rows[LstPlan.SelectedIndex];
            }
            else if ("btnEstimateRemove".Equals(btn.Name))
            {
                if (LstEstimate.SelectedIndex == -1)
                {
                    return;
                }

                linkcode = row["ESTIMATE_CD"].ToString();
                row      = _dtEstimate.Rows[LstEstimate.SelectedIndex];
            }
            else if ("btnDocumentRemove".Equals(btn.Name))
            {
                if (LstDocument.SelectedIndex == -1)
                {
                    return;
                }

                linkcode = row["LINK_CD"].ToString();
                row      = _dtDocument.Rows[LstDocument.SelectedIndex];
            }

            if (System.Windows.Forms.MessageBox.Show(
                    row["FILE_DESC"] + " File을 삭제 하시겠습니까?", "File 제거"
                    , MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                FileSender snd = new FileSender(linkcode, row["LINK"].ToString(), false);
                snd.Close();

                if ("btnPlanImport".Equals(btn.Name))
                {
                    _dtPlan.Rows.RemoveAt(LstPlan.SelectedIndex);
                }
                else if ("btnEstimateImport".Equals(btn.Name))
                {
                    _dtEstimate.Rows.RemoveAt(LstEstimate.SelectedIndex);
                }
                else if ("btnDocumentImport".Equals(btn.Name))
                {
                    _dtDocument.Rows.RemoveAt(LstDocument.SelectedIndex);
                }
            }
        }
        public void Update(FileSender fileSender)
        {
            FileProgressObject widget = Lookup(fileSender);

            if (widget != null)
            {
                widget.Update();
            }
        }
        public void Remove(FileSender fileSender)
        {
            FileProgressObject widget = Lookup(fileSender);

            if (widget != null)
            {
                this.vbox.Remove(widget);
                DelFileProgress(widget, fileSender);
            }
        }
Exemplo n.º 25
0
        private void Save(object sender, EventArgs e)
        {
            if (!"".Equals(txtReceipt.Text))
            {
                FileSender file = new FileSender("", txtReceipt.Text);
                string     Link = file.GetLinkCode();
                file.Close();

                ClearSearchData();
                SetSearchData("ACC_DT", calAccDate.Value.ToString("yyyy-MM-dd"));
                SetSearchData("CASH", txtAccCash.Text.Replace(",", ""));
                SetSearchData("CASH_DESC", txtAccDesc.Text);
                SetSearchData("ACCOUNT_DESC", txtAccInfo.Text);
                SetSearchData("LINK_CODE", Link);
                SetSearchData("UPT_USER_ID", DTOFactory.UserId);
                if (rdoBank.Checked)
                {
                    SetSearchData("ACC_CD", cboBankCode.ValueList);
                    SetSearchData("IN_BANK_NM", txtInBankName.Text);
                    SetSearchData("IN_BANK_NO", txtInBankNo.Text);
                    SetSearchData("IN_NAME", txtInUserName.Text);
                    SetServiceId("SetBankAccountHistory");
                }
                else if (rdoCard.Checked)
                {
                    SetSearchData("ACC_TYPE", cboType.ValueList);
                    SetSearchData("ACC_CD", cboCard.ValueList);
                    SetSearchData("ACC_NO", txtAccNo.Text);
                    SetSearchData("OUT_COMP_NM", txtOutName.Text);
                    SetSearchData("OUT_COMP_REG_ID", txtOutRegId.Text);
                    SetServiceId("SetCardAccountHistory");
                }
                else
                {
                    ViewMessage.Error("잘못된 선택 입니다.");
                }

                try
                {
                    DTOFactory.Transaction(new AccountDTO());

                    DialogResult = DialogResult.OK;
                    ViewMessage.Info("등록이 완료 되었습니다.");
                    Close();
                }
                catch (Exception ex)
                {
                    ViewMessage.Error(ex.Message);
                }
            }
            else
            {
                ViewMessage.Error("첨부 파일이 없습니다.");
            }
        }
Exemplo n.º 26
0
        private void SendFiles()
        {
            Debugger.Log($"Start sending {_sendingFiles.Count} file(s) to ${_neighbor}");

            using (var factory = new SendingSessionFactory(_neighbor.Address, _sendingFiles.Select(file => file.File)))
            {
                var session = factory.CreateSessionAsync().Result;

                for (var i = 0; i < _sendingFiles.Count; i++)
                {
                    lock (this)
                    {
                        if (Canceled)
                        {
                            return;
                        }
                    }

                    var sendingFile = _sendingFiles[i];

                    using (var sender = session.CreateSender())
                    {
                        _currentSender = sender;

                        var sendingCount = i + 1;
                        ThreadUtils.RunOnUiAndWait(() =>
                        {
                            Status          = $"Sending {sendingCount}/{_sendingFiles.Count}";
                            var fileInfo    = new FileInfo(sendingFile.File);
                            CurrentFileName = $"{fileInfo.Name} ({FileUtils.BytesToString(fileInfo.Length)})";
                            Percent         = 0;
                        });

                        sender.Connect();

                        ThreadUtils.RunOnUiAndWait(() => { Title = $"Sending to {_neighbor.Name} [{sender.RemoteAddress}]"; });

                        Debugger.Log($"Sending {sendingFile.File} to {sender.RemoteAddress}");
                        sender.Send(sendingFile.File, sendingFile.BaseDir);
                        Debugger.Log($"Sent {sendingFile.File}: " + (sender.SentBytes < sender.TotalBytes ? "FAIL" : "OK"));

                        if (sender.SentBytes < sender.TotalBytes)
                        {
                            throw new Exception("Operation was aborted by receiver");
                        }

                        ThreadUtils.RunOnUiAndWait(() => Percent = 100);
                    }
                }
            }

            Debugger.Log($"Sent {_sendingFiles.Count} file(s) successfully");
        }
Exemplo n.º 27
0
        public void TestOfNotCorrectFileSending()
        {
            var smtpHandlerMoq = new Mock <ISmtpHandler>();

            var sendingFileFactoryMoq = new Mock <ISendingFileFactory>();

            sendingFileFactoryMoq.Setup(m => m.Create("*****@*****.**", "*****@*****.**", "pseudoIncorrectAddress")).Throws <FileNotFoundException>();

            FileSender fileSender = new FileSender("*****@*****.**", "*****@*****.**", smtpHandlerMoq.Object, sendingFileFactoryMoq.Object);

            NUnit.Framework.Assert.Throws <FileNotFoundException>(() => fileSender.Send("pseudoIncorrectAddress"));
        }
Exemplo n.º 28
0
        void handle(TcpClient client)
        {
            byte[] bytes = new byte[BUGGER_SIZE_LENGTH];
            Console.WriteLine("Polaczono");
            NetworkStream stream = client.GetStream();

            FileSender fileSender = serialization.readStream(stream);

            File.WriteAllBytes(fileSender.Name, fileSender.SerializedFile);
            Console.WriteLine("Plik pomyslnie skopiowiano");
            stream.Close();
            client.Close();
        }
Exemplo n.º 29
0
        void handle(TcpClient client)
        {
            byte[] bytes = new byte[BUGGER_SIZE_LENGTH];
            Console.WriteLine("Connected");
            NetworkStream stream = client.GetStream();

            FileSender fileSender = serialization.readStream(stream);

            File.WriteAllBytes(fileSender.Name, fileSender.SerializedFile);
            Console.WriteLine("File successfully copied");
            stream.Close();
            client.Close();
        }
Exemplo n.º 30
0
        public async Task StoresFileOnFileSystem_IfNotifyMessage()
        {
            // Arrange
            var sut = new FileSender();

            sut.Configure(new LocationMethod(ExpectedDirectoryPath));

            // Act
            SendResult r = await sut.SendAsync(AnonymousNotifyMessage());

            // Assert
            Assert.Equal(SendResult.Success, r);
            Assert.True(File.Exists(ExpectedFileName));
        }
Exemplo n.º 31
0
 /// <summary>
 /// Process a single request
 /// </summary>
 /// <param name="listenerContext"></param>
 void ProcessRequest(object listenerContext)
 {
     DateTime started = DateTime.Now;			// For timing response
     HttpListenerContext context = null;
     AppModule module = null;
     StringBuilder log = new StringBuilder();	// Session log writes to here, and it is displayed at the end
     try {
         context = (HttpListenerContext)listenerContext;
         log.AppendFormat("{0} {1}:{2}:[ms]:",
             context.Request.RemoteEndPoint.Address,
             context.Request.Headers["X-Forwarded-For"],
             context.Request.RawUrl);
         Session session = null;
         string filename = HttpUtility.UrlDecode(context.Request.Url.AbsolutePath).Substring(1);
         if (filename == "") filename = "company";			// Default page is Company
         string moduleName = null;
         string methodName = null;
         string baseName = filename.Replace(".html", "");	// Ignore .html - treat as a program request
         if (baseName.IndexOf(".") < 0) {
             // Urls of the form /ModuleName[/MethodName][.html] call a C# AppModule
             string[] parts = baseName.Split('/');
             if (parts.Length <= 2) {
                 Type type = AppModule.GetModule(parts[0]);
                 if (type != null) {
                     // The AppModule exists - create the object
                     module = (AppModule)Activator.CreateInstance(type);
                     moduleName = parts[0];
                     if (parts.Length == 2) methodName = parts[1];
                 }
             }
         }
         if (moduleName == null) {
             // No AppModule found - treat url as a file request
             moduleName = "FileSender";
             module = new FileSender(filename);
             session = new Session(null);
         } else {
             // AppModule found - retrieve or create a session for it
             Cookie cookie = context.Request.Cookies["session"];
             if (cookie != null) {
                 _sessions.TryGetValue(cookie.Value, out session);
                 if (AppSettings.Default.SessionLogging)
                     log.AppendFormat("[{0}{1}]", cookie.Value, session == null ? " not found" : "");
             }
             if (session == null) {
                 session = new Session(this);
                 cookie = new Cookie("session", session.Cookie, "/");
                 if (AppSettings.Default.SessionLogging)
                     log.AppendFormat("[{0} new session]", cookie.Value);
             }
             context.Response.Cookies.Add(cookie);
             cookie.Expires = session.Expires = Utils.Now.AddHours(1);
         }
         // Set up module
         module.Session = session;
         module.LogString = log;
         if (moduleName.EndsWith("Module"))
             moduleName = moduleName.Substring(0, moduleName.Length - 6);
         using (module) {
             // Call method
             module.Call(context, moduleName, methodName);
         }
     } catch (Exception ex) {
         while (ex is TargetInvocationException)
             ex = ex.InnerException;
         if (ex is System.Net.Sockets.SocketException) {
             log.AppendFormat("Request error: {0}\r\n", ex.Message);
         } else {
             log.AppendFormat("Request error: {0}\r\n", ex);
             if (module == null || !module.ResponseSent) {
                 try {
                     module = new AppModule();
                     module.Session = _empty;
                     module.LogString = log;
                     module.Context = context;
                     module.Module = "exception";
                     module.Method = "default";
                     module.Title = "Exception";
                     module.Exception = ex;
                     module.WriteResponse(module.Template("exception", module), "text/html", HttpStatusCode.InternalServerError);
                 } catch (Exception ex1) {
                     log.AppendFormat("Error displaying exception: {0}\r\n", ex1);
                     if (module == null || !module.ResponseSent) {
                         try {
                             module.WriteResponse("Error displaying exception:" + ex.Message, "text/plain", HttpStatusCode.InternalServerError);
                         } catch {
                         }
                     }
                 }
             }
         }
     }
     if (context != null) {
         try {
                 context.Response.Close();
         } catch {
         }
     }
     try {
         Log(log.ToString().Replace(":[ms]:", ":" + Math.Round((DateTime.Now - started).TotalMilliseconds, 0) + " ms:"));
     } catch {
     }
 }