Esempio n. 1
0
        public DownloadFile(Guid fileGuid, string userName)
        {
            DirectoryInfo objDirectoryInfo = new DirectoryInfo(FileStorage.Provider.ConnectionString);

            _File     = FileBroker.SelectByGuid(fileGuid, objDirectoryInfo);
            _UserName = userName;
        }
        /// <summary>
        /// Gets the size of a file
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <returns></returns>
        public long GetFileSize(Uri remoteFile)
        {
            //Get path to file storage
            string sPath = FileStorage.Provider.ConnectionString;

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);

            //Get the file guid
            string sFileGuid = System.IO.Path.GetFileNameWithoutExtension(remoteFile.LocalPath);
            Guid   gFileGuid = new Guid(sFileGuid);

            //Get file definition
            File f = FileBroker.SelectByGuid(gFileGuid, di);

            System.Diagnostics.Debug.Assert(f.Guid == gFileGuid);

#if DEBUG
            _StorageStream = FileStorage.GetFileStream(f.Key, AccessMode.Read);
            System.Diagnostics.Debug.Assert(_StorageStream.Length.Equals(f.Size));
            _StorageStream.Close();
#endif

            //Return file size
            return(f.Size);
        }
        /// <summary>
        /// Download a file
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public RemoteFileDescriptor Download(RemoteFileIdentifier request)
        {
            //Get path to file storage
            string sPath = FileStorage.Provider.ConnectionString;

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);

            //Get the file guid
            string sFileGuid = System.IO.Path.GetFileNameWithoutExtension(request.RemoteFile.LocalPath);
            Guid   gFileGuid = new Guid(sFileGuid);

            //Get file definition
            File f = FileBroker.SelectByGuid(gFileGuid, di);

            System.Diagnostics.Debug.Assert(f.Guid == gFileGuid);

            //Report start
            System.Diagnostics.Trace.WriteLine("Start downloading " + f.FileName);

            //Open stream
            _StorageStream = FileStorage.GetFileStream(f.Key, AccessMode.Read);
            System.Diagnostics.Debug.Assert(f.Size == _StorageStream.Length);

            //Note that we cannot close the stream before returning the stream to the client
            //Otherwise the client gets a closed stream.
            //So we need to monitor the use of the stream made by the client to close it on a separate thread
            //once the client has entirely read it or once the connection is closed
            //System.Threading.Thread objMonitoringThread = new System.Threading.Thread(
            //    new System.Threading.ParameterizedThreadStart(this.MonitorAndClose));
            //objMonitoringThread.Start(objStorageStream);

            RemoteFileDescriptor objRemoteFileInfoRet = new RemoteFileDescriptor();

            objRemoteFileInfoRet.ContentType  = f.ContentType;
            objRemoteFileInfoRet.Email        = null;
            objRemoteFileInfoRet.FileGuid     = f.Guid;
            objRemoteFileInfoRet.FileName     = f.FileName;
            objRemoteFileInfoRet.HashCode     = f.HashValue;
            objRemoteFileInfoRet.Length       = f.Size;
            objRemoteFileInfoRet.SecurityCode = null;
            objRemoteFileInfoRet.Stream       = _StorageStream;

            // report end
            System.Diagnostics.Trace.WriteLine("Download complete!");

            // return result
            return(objRemoteFileInfoRet);
        }
        public MainViewModel()
        {
            var IDE = new FastColoredTextBox
            {
                Language = new LuaSyntax()
            };

            var settings = new SettingsViewModel(new Settings(IDE));

            IFileBroker fileBroker = new FileBroker();

            MenuBar = new MenuBar(settings, IDE, fileBroker);

            _view = new MainWindow(this, IDE);
            _view.Show();
        }
Esempio n. 5
0
    /// <summary>
    /// Click event handler for the Send button
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SendButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Get posted values
            string sSender    = SenderTextBox.Text.Trim().ToLowerInvariant();
            string sRecipient = String.Empty;
            if (this._DisplayFormat == DisplayFormat.DropBox)
            {
                sSender    = SenderTextBox.Text.Trim().ToLowerInvariant();
                sRecipient = RecipientDropDownList.SelectedValue;
            }
            else
            {
                sSender    = SenderDropDownList.SelectedValue;
                sRecipient = RecipientTextBox.Text.Trim().ToLowerInvariant();
            }
            string sText = MessageTextBox.Text; //.Trim();

            //Confirm that we have a muid to access upload data
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(MuidHiddenField.Value) && (MuidHiddenField.Value == Request.QueryString[UploadMonitor.UploadIdParam]));

            //We could access it from Url, but this confirms it is a genuine post
            UploadData objUploadData = UploadMonitor.GetUploadData(MuidHiddenField.Value);
            if (objUploadData == null)
            {
                throw new ApplicationException(Resources.Web.glossary.QuickMessageControl_MissingUploadData);
            }

            //Recheck security code
            if (_DisplayFormat == DisplayFormat.QuickSend)
            {
                string sSecurityCode = (string)HttpRuntime.Cache[Memba.Common.Presentation.Constants.SecurityCode];
                if (String.IsNullOrEmpty(sSecurityCode))
                {
                    sSecurityCode = WebConfigurationManager.AppSettings[Memba.Common.Presentation.Constants.SecurityCode];
                    HttpRuntime.Cache.Add(
                        Memba.Common.Presentation.Constants.SecurityCode,
                        sSecurityCode,
                        null,
                        Cache.NoAbsoluteExpiration,
                        new TimeSpan(0, Memba.Common.Presentation.Constants.SlidingExpiration, 0),
                        CacheItemPriority.Default,
                        null);
                }
                if (!sSecurityCode.Equals(SecurityCodeTextBox.Text))
                {
                    throw new ApplicationException(Resources.Web.glossary.QuickMessageControl_SecurityCodeFailInfo);
                }
            }

            //Check any exception
            Exception objUploadException = objUploadData.Exception;
            if (objUploadException != null)
            {
                throw new ApplicationException(objUploadException.Message, objUploadException);
            }

            //Ensure that upload is complete
            if (objUploadData.ProgressStatus != UploadProgressStatus.Completed)
            {
                throw new ApplicationException(Resources.Web.glossary.QuickMessageControl_UploadNotComplete);
            }

            //Ensure we have at least one uploaded file (we should have at least one file input control)
            if ((objUploadData.UploadFiles == null) || (objUploadData.UploadFiles.Count < 1))
            {
                throw new ApplicationException(Resources.Web.glossary.QuickMessageControl_NoCompleteFile);
            }

            //Get path to file storage
            string sPath = FileStorage.Provider.ConnectionString;
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);
            //Existence will be checked in FileBroker

            //Start building download links
            StringBuilder objStringBuilder = new StringBuilder();
            objStringBuilder.Append("<ul>");
            string sDownloadRoot = Request.Url.Scheme + Uri.SchemeDelimiter + Request.Url.Authority +
                                   this.ResolveUrl(Memba.Common.Presentation.PageUrls.Download);

            bool        bHasCompleteUploadFiles = false;
            List <File> lstAttachments          = new List <File>();
            foreach (UploadFile objUploadFile in objUploadData.UploadFiles)
            {
                if ((objUploadFile != null) && objUploadFile.IsComplete)
                {
                    bHasCompleteUploadFiles = true;

                    //Create file object
                    File f = new File(
                        objUploadFile.OriginalFileName,
                        objUploadFile.ContentType,
                        objUploadFile.ProviderFileKey.ToString(),
                        objUploadFile.ContentLength,
                        objUploadFile.HashValue);

                    //Add definition to file storage
                    FileBroker.Insert(f, di);

                    //Add to message attachments
                    lstAttachments.Add(f);

                    //Continue building download links
                    objStringBuilder.Append(
                        String.Format(
                            Resources.Web.glossary.Culture,
                            "<li><a href=\"{0}\" class=\"cssFieldHyperlink\">{1} ({2})</a></li>",
                            System.IO.Path.Combine(sDownloadRoot, f.Guid.ToString("N") + ".dat"),
                            f.FileName,
                            BODisplay.SizeFormat(f.Size, ByteFormat.Adapt)
                            )
                        );
                }
            }

            //Ensure we have at least one COMPLETED uploaded file to display
            if (!bHasCompleteUploadFiles)
            {
                throw new ApplicationException(Resources.Web.glossary.QuickMessageControl_NoCompleteFile);
            }

            //Create Message
            sText = BODisplay.RemoveAllHtmlTags(sText); //just in case

            Message m = new Message(
                sSender,
                sRecipient,
                sText,
                lstAttachments,
                sDownloadRoot);

            //Send message
            m.Send();

            //Release upload data
            UploadMonitor.Release(objUploadData.UploadId);

            //Finalize download links and display
            objStringBuilder.AppendLine("</ul>");
            FinalLinkLabel.Text = objStringBuilder.ToString();

            //Show InfoBox Message
            if (_InfoBox != null)
            {
                _InfoBox.Type = InfoBoxType.OK;
                _InfoBox.Text = Resources.Web.glossary.QuickMessageControl_SendOKInfo;
            }
        }
        catch (Exception Ex)
        {
            Session[Memba.Common.Presentation.Constants.LastError] = Ex.Message;
            //Response.Redirect(Memba.Common.Presentation.PageUrls.Error);
            throw; //Redirects to error handler in Global.asax
        }
    }
        /// <summary>
        /// Upload a file
        /// </summary>
        /// <param name="request"></param>
        public void Upload(RemoteFileDescriptor request)
        {
            //report start
            System.Diagnostics.Trace.WriteLine("Start uploading " + request.FileName);

            //TODO: We need to report exceptions properly using FaultContractAttribute and FaultException
            //In this particular example, we want to raise a proper exception as soon as possible if the file upload is too large.
            //Note that currently the upload progresses for a while before the exception is raised.

            //Using HttpContext to access configuration data (especially httpRuntime section in web.config)
            //from WCF services requires HttpContext which is only available to WCF services in Asp.Net compatibility mode
            //See: http://blogs.msdn.com/wenlong/archive/2006/01/23/516041.aspx

            //But the good news is apparently since .NET 3.0 SP1, WCF services are not dependant upon the httpRuntime section
            //See: http://blogs.msdn.com/wenlong/archive/2008/03/10/why-changing-sendtimeout-does-not-help-for-hosted-wcf-services.aspx
            //So we essentially need to check that request.Length (unless there is a way to access the Content-Length Htpp header)
            //is lower than the value of BasicHttpBinding.MaxReceivedMessageSize configured in web.config

#if NOTUSED
            //Raise error Http 413 asap
            //Use FaultContractAttribute and FaultException to report an error
            Binding objBinding = OperationContext.Current.Host.Description.Endpoints[0].Binding;
            System.Diagnostics.Debug.Assert(objBinding.Name == "BasicHttpBinding");
            BasicHttpBinding objBasicHttpBinding = objBinding as BasicHttpBinding;
            if (objBasicHttpBinding != null)
            {
                if (request.Length > objBasicHttpBinding.MaxReceivedMessageSize)
                {
                    throw new System.Web.HttpException(413, "Too large!");
                }
            }
#endif

            //Authenticate user
            if (!Authenticate(request.Email, request.SecurityCode))
            {
                throw new ApplicationException(Resources.Web.glossary.WebService_AuthenticationFailInfo);
            }

            //Stream file
            int    iBytesRead;
            byte[] arrBuffer = new byte[Constants.WcfStreamingBufferSize];

            //The file key is unknown from the client
            object objProviderFileKey = FileStorage.GetNewFileKey(request.FileName);

            //Create stream to write to
            _StorageStream = FileStorage.GetFileStream(objProviderFileKey, AccessMode.Create);
            do
            {
                // Read bytes from input stream
                iBytesRead = request.Stream.Read(arrBuffer, 0, Constants.WcfStreamingBufferSize);
                // Write bytes to output stream
                _StorageStream.Write(arrBuffer, 0, iBytesRead);
            } while (iBytesRead > 0);
            _StorageStream.Close();

            //Create file object
            File f = new File(
                request.FileGuid,
                request.FileName,
                request.ContentType,
                objProviderFileKey.ToString(),
                request.Length,
                request.HashCode);

            //Get path to file storage
            string sPath = FileStorage.Provider.ConnectionString;
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);

            //Add definition to file storage (Existence will be checked in FileBroker)
            FileBroker.Insert(f, di);

            // report end
            System.Diagnostics.Trace.WriteLine("Upload complete!");
        }
Esempio n. 7
0
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Confirm that we have a muid to access upload data
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(Request.QueryString[UploadMonitor.UploadIdParam]));
            UploadData objUploadData = UploadMonitor.GetUploadData(Request.QueryString[UploadMonitor.UploadIdParam]);
            if (objUploadData == null)
            {
                throw new ApplicationException("Oops! No upload data");
            }

            //Check any exception
            Exception objUploadException = objUploadData.Exception;
            if (objUploadException != null)
            {
                throw new ApplicationException(objUploadException.Message, objUploadException);
            }

            //Ensure that upload is complete
            if (objUploadData.ProgressStatus != UploadProgressStatus.Completed)
            {
                throw new ApplicationException("Oops! Upload not complete");
            }

            //Ensure we have at least one uploaded file (we should have at least one file input control)
            if ((objUploadData.UploadFiles == null) || (objUploadData.UploadFiles.Count < 1))
            {
                throw new ApplicationException("Oops! No uploaded file");
            }

            //Keep it simple: we now there is only one file upload control on the page
            UploadFile objUploadFile = objUploadData.UploadFiles[0];
            if ((objUploadFile == null) || (!objUploadFile.IsComplete))
            {
                throw new ApplicationException("Oops! Uploaded file is not complete");
            }

            //Create file object
            File f = new File(
                objUploadFile.OriginalFileName,
                objUploadFile.ContentType,
                objUploadFile.ProviderFileKey.ToString(),
                objUploadFile.ContentLength,
                objUploadFile.HashValue);

            //Get path to file storage
            string sPath = FileStorage.Provider.ConnectionString;
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);

            //Add definition to file storage
            FileBroker.Insert(f, di);

            //Create download link
            DownloadLink.Text        = "Download: " + f.FileName + " (" + BODisplay.SizeFormat(f.Size, ByteFormat.Adapt) + ")";
            DownloadLink.NavigateUrl = System.IO.Path.Combine(this.Request.ApplicationPath, f.Guid.ToString("N") + ".dat");

            //Release upload data
            UploadMonitor.Release(objUploadData.UploadId);
        }
        catch (Exception Ex)
        {
            Response.Write(Ex.Message);
        }
    }