static bool IsImage(string extension) => AcceptedMimeTypesImage.Contains(MimeTypeMap.GetMimeType(extension));
Ejemplo n.º 2
0
        //public static void ShowOkAlert(Context context,string Message)
        //{
        //    AlertDialog.Builder alert = new AlertDialog.Builder(context);
        //    alert.SetMessage(Message);
        //    alert.SetPositiveButton("Ok", (senderAlert, args) => {
        //    });
        //    Dialog dialog = alert.Create();
        //    dialog.Show();

        //}

        //Download from url------------------------------------------
        public static async void DownLoadSource(string url, Java.IO.File _appDirectory, Java.IO.File newFile, string filePath, Context context, string FileName, int notificationId)
        {
            // ShowToast(context,  context.Resources.GetString(Resource.String.downloading) + Newsrc);

            var NotificationId = notificationId;

            string localPath;

            try
            {
                System.Uri uri       = new System.Uri(url);
                WebClient  webClient = new WebClient();
                string     localFileName;
                webClient.DownloadDataAsync(uri);



                Log.Debug("tag", "File to download = " + newFile.ToString());
                MimeTypeMap mime = MimeTypeMap.Singleton;
                String      ext  = newFile.Name.Substring(newFile.Name.IndexOf(".") + 1);
                String      type = mime.GetMimeTypeFromExtension(ext);

                Intent openFile = new Intent(Intent.ActionView, Android.Net.Uri.FromFile(newFile));
                openFile.SetDataAndType(Android.Net.Uri.FromFile(newFile), type);
                openFile.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop | ActivityFlags.NewTask);


                PendingIntent p = PendingIntent.GetActivity(context, 0, openFile, 0);

                var notification = new Android.Support.V4.App.NotificationCompat.Builder(context)
                                   .SetSmallIcon(Android.Resource.Drawable.StatNotifySync)
                                   .SetContentTitle(FileName)
                                   .SetContentText(" Downloading")

                                   .SetOngoing(false);
                notification.SetProgress(0, 0, true);
                NotificationManager notificationmanager = (NotificationManager)Android.App.Application.Context.GetSystemService(Service.NotificationService);
                // Build Notification with Notification Manager

                notificationmanager.Notify((int)NotificationId, notification.Build());


                webClient.DownloadDataCompleted += (s, e) =>
                {
                    try
                    {
                        if (!_appDirectory.Exists())
                        {
                            _appDirectory.Mkdirs();
                        }
                        var bytes = e.Result; // get the downloaded data
                        {
                            notification.SetContentText(" Downloaded");
                            notification.SetContentTitle(FileName);
                            notification.SetContentIntent(p);
                            notification.SetProgress(0, 0, false);
                            notification.SetAutoCancel(true);// Notification.Flags = NotificationFlags.AutoCancel;
                            //System.IO.File.WriteAllBytes(filePath, bytes);
                            notificationmanager.Notify((int)NotificationId, notification.Build());
                            // writes to local storage
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                };
            }
            catch (System.Exception ex)
            {
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// This is a method that responds to the customer according to the event received.
        /// </summary>
        /// <param name="requestEvent">HttpRequestEventArgs: Request event.</param>
        /// <returns>HttpOutputStream: Event respond of the argument received.</returns>
        public HttpOutputStream GetRespond(HttpRequestEventArgs requestEvent)
        {
            ActionRequest = new Dictionary <string, object>();
            Site site;

            /// Array of the URL path received.
            string[] UrlSplited = requestEvent.Request.Path.Replace("favicon.ico", string.Empty).Split('/');
            string   SiteName   = UrlSplited[1];

            // show state in the console.
            Console.WriteLine("Client: {0} makes request => {1}", SiteName, requestEvent.Request.Path);

            // Do it if the site not exist.
            if (!Exist(SiteName))
            {
                requestEvent.Response.ContentType = MimeTypeMap
                                                    .GetMimeType(Path.GetExtension(configurationManager.errorPages["404"]));
                requestEvent.Response.Status = "404";
                data = File.ReadAllBytes(configurationManager.errorPages["404"]);
            }
            // else: execute method of one of the apps loaded.
            else
            {
                string URLPath = requestEvent.Request.Path.Replace("/", "").ToLower();

                if (URLPath.Equals(SiteName.ToLower()))
                {
                    site = configurationManager.GetSiteByVirtualPath(SiteName);

                    if (string.IsNullOrEmpty(site.defaultDocument["index"]))
                    {
                        requestEvent.Response.ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(configurationManager.defaultDocument["index"]));
                        requestEvent.Response.Status      = "200";
                        data = File.ReadAllBytes(configurationManager.defaultDocument["index"]);
                    }
                    else
                    {
                        requestEvent.Response.ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(site.defaultDocument["index"]));
                        requestEvent.Response.Status      = "200";
                        data = File.ReadAllBytes(site.defaultDocument["index"]);
                    }
                }
                else
                {
                    ActionRequest.Add("URLPath", requestEvent.Request.Path.Replace("/" + SiteName, "").ToLower());
                    ActionRequest.Add("HttpMethod", requestEvent.Request.HttpMethod);
                    ActionRequest.Add("Params", requestEvent.Request.Form);
                    ActionRequest.Add("Header", requestEvent.Request.Headers);
                    ActionRequest.Add("QueryParams", requestEvent.Request.Params);

                    Dictionary <string, HttpFile> files = new Dictionary <string, HttpFile>();

                    for (int i = 0; i < requestEvent.Request.Files.Count; i++)
                    {
                        HttpPostedFile file     = requestEvent.Request.Files.Get(i);
                        HttpFile       httpFile = new HttpFile(file.ContentLength, file.ContentType, file.FileName, file.InputStream);
                        files.Add(requestEvent.Request.Files.GetKey(i), httpFile);
                    }
                    ActionRequest.Add("Files", files);

                    foreach (IPHttpApplication Application in AllApps.Result)
                    {
                        Site AppSite = (Site)Application.GetSite();

                        if (AppSite.virtualPath.ToLower() == SiteName.ToLower())
                        {
                            var response = Application.ExecuteAction(ActionRequest);
                            requestEvent.Response.Status      = ((ActionResult)response).GetStatusCode();
                            requestEvent.Response.ContentType = ((ActionResult)response).GetContentType();

                            try
                            {
                                stream = (MemoryStream)((ActionResult)response).GetRespond();
                                return(new HttpOutputStream(stream));
                            }
                            catch (Exception ex)
                            {
                                requestEvent.Response.ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(configurationManager.errorPages["404"]));
                                requestEvent.Response.Status      = "404";
                                data = File.ReadAllBytes(configurationManager.errorPages["404"]);
                            }
                        }
                    }
                }

                /// TODO:hacer que se actualize site en el js despues que el user cree algun view.
            }


            stream = new MemoryStream(data);
            return(new HttpOutputStream(stream));
        }
        public string GetMimeType(string fileName)
        {
            var extension = _rgx.Match(fileName).Value;

            return(MimeTypeMap.GetMimeType(extension));
        }
Ejemplo n.º 5
0
        public Intent SaveAndView(string fileName, string contentType, MemoryStream stream, PDFOpenContext context, Context appctx)
        {
            string exception = string.Empty;
            string root      = null;



            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            Java.IO.File myDir = new Java.IO.File(root + "/PDFFiles");
            myDir.Mkdir();

            Java.IO.File file = new Java.IO.File(myDir, fileName);

            if (file.Exists())
            {
                file.Delete();
            }

            try
            {
                FileOutputStream outs = new FileOutputStream(file);
                outs.Write(stream.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                exception = e.ToString();
                return(null);
            }

            if (file.Exists() && contentType != "application/html")
            {
                string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                string mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                Intent intent    = new Intent(Intent.ActionView);
                intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                Android.Net.Uri path = FileProvider.GetUriForFile(appctx, Android.App.Application.Context.PackageName + ".fileprovider", file);
                intent.SetDataAndType(path, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);

                return(intent);
                //switch (context)
                //{
                //    case PDFOpenContext.InApp:
                //        appctx.StartActivity(intent);
                //        break;
                //    case PDFOpenContext.ChooseApp:
                //        appctx.StartActivity(Intent.CreateChooser(intent, "Choose App"));
                //        break;
                //    default:
                //        break;
                //}
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 6
0
        public async void SearchForHigherResolutionOnlineAsync()
        {
            // Don't scan for videos.
            if (MediaData is VideoData)
            {
                return;
            }

            var onlineMedias = new Dictionary <Uri, (Size, long)>();

            // Get file size and dimensions of every fully matched image.
            foreach (var webImage in FullyMatchedImages)
            {
                // Parse URL.
                if (Uri.TryCreate(webImage.Url, UriKind.Absolute, out var uri))
                {
                    // Check to make sure this URL points to a file and not a webpage.
                    if (Path.HasExtension(uri.AbsoluteUri))
                    {
                        // Get MIME type of online file.
                        var mimeType = MimeTypeMap.GetMimeType(Path.GetExtension(uri.AbsoluteUri));
                        // Check if MIME type of online file is supported.
                        if (FileTypes.IsSupportedMIME(mimeType))
                        {
                            try
                            {
                                // Get dimensions of online image.
                                var dimensions = await ImageUtilities.GetWebDimensionsAsync(uri);

                                // If dimensions is empty, continue.
                                if (dimensions.IsEmpty)
                                {
                                    continue;
                                }
                                // Get file size of online image.
                                var contentLength = await OnlineUtil.GetContentSizeAsync(uri);

                                // Add to dictionary.
                                onlineMedias.Add(uri, (dimensions, contentLength));
                            }
                            catch (Exception e)
                            {
                                // Log Exception.
                                LifecycleLog.Exception(e);
                            }
                        }
                    }
                }
            }

            // If these are null then no comparisons can be made.
            if (MediaData?.Meta == null)
            {
                return;
            }
            if (MediaData?.BasicProperties == null)
            {
                return;
            }

            // Check if any of the fully matched images are higher resolution or larger than local file.
            var largerMedia = new KeyValuePair <Uri, (Size, long)>();

            foreach (var urlAndData in onlineMedias)
            {
                var url = urlAndData.Key;
                var(dimensions, contentLength) = urlAndData.Value;

                // If online media is larger in file size than local media.
                if (contentLength > (long)MediaData.BasicProperties.Size)
                {
                    // If size of this online media is larger than the currently largest media.
                    if (Math.Max(largerMedia.Value.Item2, contentLength) == contentLength)
                    {
                        largerMedia = urlAndData; // Update largerMedia.
                    }
                }
                else if (dimensions.Height > MediaData.Meta.Height && // If online media is larger in both width and height
                         dimensions.Width > MediaData.Meta.Width)     // than the local media.
                {
                    // If dimensions of this online media is larger than the currently largest media.
                    if (Math.Max(largerMedia.Value.Item1.Height, dimensions.Height) == dimensions.Height &&
                        Math.Max(largerMedia.Value.Item1.Width, dimensions.Width) == dimensions.Width)
                    {
                        largerMedia = urlAndData; // Update largerMedia.
                    }
                }
            }

            // If no larger media has been found, return.
            if (largerMedia.Key == null)
            {
                return;
            }

            // Set property.
            LargerMedia = largerMedia.Key;
        }
Ejemplo n.º 7
0
 private static string GetMimeType(string ext)
 {
     return(string.IsNullOrEmpty(ext) ? "text/html" : MimeTypeMap.GetMimeType(ext));
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Uploads the BLOB.
        /// </summary>
        /// <param name="containerName">Name of the container.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public async Task <Uri> UploadBlob(Guid containerName, Guid fileName, string connectionString, Stream stream)
        {
            string filePath = SaveFile(fileName.ToString(), stream);

            if (!string.IsNullOrEmpty(filePath))
            {
                // Get the file
                byte[] fileInfo = LoadFile(fileName.ToString("D"));
                if (fileInfo.Length > 0)
                {
                    string newFileName = fileName.ToString("D");

                    // Get the container
                    CloudBlobContainer container = await GetContainer(containerName, connectionString).ConfigureAwait(false);

                    CloudBlockBlob blob = container.GetBlockBlobReference(newFileName);

                    BlobRequestOptions options = new BlobRequestOptions {
                        ServerTimeout = new TimeSpan(12, 0, 0)
                    };

                    try
                    {
                        using (Stream fileStream = new MemoryStream(fileInfo))
                        {
                            // If file is larger than 4MB, split file into 250kb chunks and upload
                            int maxSize = 1 * 1024 * 1024; // 4 MB
                            if (fileStream.Length > maxSize)
                            {
                                byte[]        data        = ReadToEnd(fileStream);
                                int           id          = 0;
                                int           byteslength = data.Length;
                                int           bytesread;
                                int           index            = 0;
                                List <string> blocklist        = new List <string>();
                                const int     numBytesPerChunk = 250 * 1024;

                                do
                                {
                                    byte[] buffer = new byte[numBytesPerChunk];
                                    int    limit  = index + numBytesPerChunk;
                                    for (int loops = 0; index < limit; index++)
                                    {
                                        buffer[loops] = data[index];
                                        loops++;
                                    }

                                    bytesread = index;
                                    string blockIdBase64 = Convert.ToBase64String(BitConverter.GetBytes(id));

                                    await blob.PutBlockAsync(blockIdBase64, new MemoryStream(buffer, true), null).ConfigureAwait(false);

                                    blocklist.Add(blockIdBase64);
                                    id++;
                                }while (byteslength - bytesread > numBytesPerChunk);

                                int    final       = byteslength - bytesread;
                                byte[] finalbuffer = new byte[final];
                                for (int loops = 0; index < byteslength; index++)
                                {
                                    finalbuffer[loops] = data[index];
                                    loops++;
                                }

                                string blockId = Convert.ToBase64String(BitConverter.GetBytes(id));
                                await blob.PutBlockAsync(blockId, new MemoryStream(finalbuffer, true), null).ConfigureAwait(false);

                                blocklist.Add(blockId);

                                await blob.PutBlockListAsync(blocklist, null, options, null).ConfigureAwait(false);
                            }
                            else
                            {
                                await blob.UploadFromStreamAsync(fileStream).ConfigureAwait(false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is ArgumentException ||
                            ex is UnauthorizedAccessException ||
                            ex is FileNotFoundException ||
                            ex is NotSupportedException ||
                            ex is StorageException)
                        {
                            return(default(Uri));
                        }

                        throw;
                    }

                    // Update the mime type
                    await blob.FetchAttributesAsync().ConfigureAwait(false);

                    string type      = null;
                    var    extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.ToString().ToLower());

                    if (extension != null)
                    {
                        blob.Properties.ContentType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                        await blob.SetPropertiesAsync().ConfigureAwait(false);

                        // Success!
                        return(GenerateUrl(containerName, fileName, connectionString));
                    }
                }
            }

            return(default(Uri));
        }
Ejemplo n.º 9
0
        void UnZipAndProcess(string filename)
        {
            if (!File.Exists(filename))
            {
                throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_FILE_OR_DIR, filename));
            }

            //zip itself may be too huge for timely processing
            if (new FileInfo(filename).Length > MAX_ZIP_FILE_SIZE)
            {
                throw new OpException(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_FILESIZE_HALT, filename));
            }

            // Ignore images and other junk like that
            var  fileExtension = new FileInfo(filename).Extension;
            var  mimeType      = MimeTypeMap.GetMimeType(fileExtension);
            bool mimeMatch     = false;

            if (!IgnoreMimeRegex.IsMatch(mimeType))
            {
                var isValidExtension = COMPRESSED_EXTENSIONS.Any(fileExtension.Contains);
                if (isValidExtension || fileExtension == "ts")
                {
                    mimeMatch = true;
                }
                else if (mimeType.Contains("zip", StringComparison.CurrentCultureIgnoreCase) || // Should have been caught in file extensions above, but still OK.
                         mimeType.Contains("tar", StringComparison.CurrentCultureIgnoreCase) ||
                         mimeType.Contains("compressed", StringComparison.CurrentCultureIgnoreCase))
                {
                    mimeMatch = true;
                }

                if (mimeMatch)
                {
                    // Now process the file
                    switch (fileExtension)
                    {
                    case ".tgz":
                        ProcessTarGzFile(filename);
                        break;

                    case ".gz":
                        if (filename.Contains(".tar.gz"))
                        {
                            ProcessTarGzFile(filename);
                        }
                        else
                        {
                            WriteOnce.SafeLog("no support for .gz unless .tar.gz: " + fileExtension, LogLevel.Warn);
                            _appProfile.MetaData.PackageTypes.Add("compressed-unsupported");
                        }
                        break;

                    case ".jar":
                    case ".zip":
                        ProcessZipFile(filename);
                        break;

                    case ".gem":
                    case ".tar":
                    case ".nupkg":
                        WriteOnce.SafeLog($"Processing of {fileExtension} not implemented yet.", LogLevel.Warn);
                        break;

                    default:
                        WriteOnce.SafeLog("no support for compressed type: " + fileExtension, LogLevel.Warn);
                        break;
                    }

                    _appProfile.MetaData.PackageTypes.Add("compressed");
                }
                else
                {
                    _appProfile.MetaData.PackageTypes.Add("compressed-unsupported");
                }
            }
        }
        private static string GetMimeType(string filePath)
        {
            var fileInfo = new FileInfo(filePath);

            return(MimeTypeMap.GetMimeType(fileInfo.Extension));
        }
        private async Task SetVideoSourceKeepingPlaytime(bool newMovie)
        {
            var videoPath = $"/{string.Join("/", pathComponents)}";

            dlLinkAge = DateTimeOffset.UtcNow;
            lastRetry = DateTimeOffset.UtcNow;
            try
            {
                TimeSpan currentPlaytime = new TimeSpan(0);
                if (!newMovie)
                {
                    try
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            currentPlaytime = mediaPlayer.MediaPlayer.PlaybackSession.Position;
                        });
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("Error fetching current playtime: ", e.Message);
                    }
                }
                var builder = oneDriveClient.Drive.Root.ItemWithPath(videoPath);
                var file    = await builder.Request().GetAsync();

                string mimeType = MimeTypeMap.GetMimeType(file.Name);
                System.Diagnostics.Debug.WriteLine("Playing item with mime type: " + mimeType);
                try
                {
                    Analytics.TrackEvent("VideoUri Set", new Dictionary <string, string> {
                        { "MimeType", mimeType }
                    });
                }
                catch (Exception e)
                {
                    // let's not do anything more about this.
                    System.Diagnostics.Debug.WriteLine("Exception when submitting analytics: " + e.Message);
                }

                if (file.AdditionalData.TryGetValue("@content.downloadUrl", out object downloadUrl))
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                                  () =>
                    {
                        mediaPlayer.Source = MediaSource.CreateFromUri(new Uri((string)downloadUrl));
                    });
                }
                else
                {
                    // NOTE: this stream can lead to out of memory exceptions.
                    // might want to try also the VLC movie element again?
                    Stream contentStream = await builder.Content.Request().GetAsync();

                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        mediaPlayer.Source = MediaSource.CreateFromStream(contentStream.AsRandomAccessStream(), mimeType);
                    });
                }

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    mediaPlayer.MediaPlayer.PlaybackSession.Position = currentPlaytime;

                    // setup listeners
                    if (newMovie)
                    {
                        mediaPlayer.MediaPlayer.PlaybackSession.PlaybackStateChanged += PlaybackSession_PlaybackStateChangedAsync;
                    }
                });
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex, new Dictionary <string, string>
                {
                    { "On", "Setting Video Source" },
                    { "Where", "MoviePlayerPage.xaml:SetVideoSourceKeepingPlaytime" },
                    { "DueTo", ex.Message },
                    { "IsNewMovie", newMovie.ToString() }
                });
                try
                {
                    await ExitOrRetryWithMessage("Failed to load movie. Error: " + ex.ToString() + " (" + ex.Message + ")");
                }
                catch (Exception e)
                {
                    Crashes.TrackError(e, new Dictionary <string, string>
                    {
                        { "On", "Call Error Dialog" },
                        { "Where", "MoviePlayerPage.xaml:SetVideoSourceKeepingPlaytime" },
                        { "DueTo", ex.Message }
                    });
                }
            }
        }
Ejemplo n.º 12
0
        public async Task AppendStreamAsync(string blobName, Stream stream, string mimeType = null, NameValueCollection metadata = null, string cacheControl = null, string contentEncoding = null, bool acquireLease = false, int maxLeaseAttempts = 1, CancellationToken cancellationToken = default(CancellationToken))
        {
            var cleanBlobName = SanitizeBlobName(blobName);
            var blob          = await GetBlobReferenceAsync(cleanBlobName, cancellationToken).ConfigureAwait(false);

            var leaseId = string.Empty;

            if (acquireLease && blob != null)
            {
                maxLeaseAttempts = Math.Max(maxLeaseAttempts, 1);                   // At least one attempt
                maxLeaseAttempts = Math.Min(maxLeaseAttempts, 10);                  // No more than 10 attempts
                for (var attempts = 0; attempts < maxLeaseAttempts; attempts++)
                {
                    leaseId = await blob.TryAcquireLeaseAsync(null, maxLeaseAttempts, cancellationToken);

                    if (string.IsNullOrEmpty(leaseId))
                    {
                        break;
                    }
                    else if (attempts + 1 < maxLeaseAttempts)
                    {
                        await Task.Delay(500);                                                              // Make sure we don't attempt too quickly
                    }
                }

                if (string.IsNullOrEmpty(leaseId))
                {
                    throw new Exception("Unable to obtain blob lease");
                }
            }

            if (blob == null)
            {
                // We make the assumption that new blobs should be of type 'block blob'
                blob = _blobContainer.GetBlockBlobReference(cleanBlobName);
            }

            blob.Properties.ContentType = mimeType ?? MimeTypeMap.GetMimeType(Path.GetExtension(cleanBlobName));

            if (!string.IsNullOrEmpty(cacheControl))
            {
                blob.Properties.CacheControl = cacheControl;
            }
            if (!string.IsNullOrEmpty(contentEncoding))
            {
                blob.Properties.ContentEncoding = contentEncoding;
            }

            await blob.AppendStreamAsync(stream, leaseId, cancellationToken).ConfigureAwait(false);

            if (metadata != null)
            {
                foreach (var key in metadata.AllKeys)
                {
                    blob.Metadata[key] = metadata[key];
                }

                await blob.SetMetadataAsync(leaseId, cancellationToken);
            }

            if (!string.IsNullOrEmpty(leaseId))
            {
                await blob.ReleaseLeaseAsync(leaseId, cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 13
0
        public UploadModule(IRepository repository, IShareMappable edocFolder, ArcOnlineHttpClient client)
        {
            Post["/upload", true] = async(_, ctx) =>
            {
                var model = this.Bind <UploadAttachment>();
                var edoc  = repository.Get(model.Id);
                edoc = new EDocEntry(edoc, model.FacilityId);
                var filename = Path.GetFileName(edoc.Path);

                var extension   = Path.GetExtension(filename);
                var contentType = MimeTypeMap.GetMimeType(extension);

                try
                {
                    var file      = edocFolder.GetPathFrom(edoc.Path);
                    var fileInfo  = new FileInfo(file);
                    var byteCount = fileInfo.Length;

                    if (byteCount > MaxUpload)
                    {
                        var readableSize = ReadableFileSizer.MakeReadable(byteCount);
                        Log.Warning("{file} is larger than allowed upload. {size}", edoc.Path, readableSize);

                        return(Response.AsJson(new Errorable
                        {
                            Error = new Error
                            {
                                Message = $"This file is too large to be stored in ArcGIS Online. The file is around {readableSize} " +
                                          $"and the allowable size is {ReadableFileSizer.MakeReadable(MaxUpload)}."
                            }
                        }));
                    }

                    var token = await client.GetToken();

                    // upload to arcgis online
                    using (Stream document = File.OpenRead(file))
                        using (var formContent = new MultipartFormDataContent())
                        {
                            try
                            {
                                var streamContent = new StreamContent(document);
                                streamContent.Headers.Add("Content-Type", contentType);
                                streamContent.Headers.Add("Content-Disposition", $"form-data; name=\"file\"; filename=\"{edoc.File}\"");
                                formContent.Add(streamContent, "file", edoc.File);
                                formContent.Add(new StringContent("json"), "f");
                                formContent.Add(new StringContent(token), "token");
                            }
                            catch (ArgumentNullException ex)
                            {
                                Log.Error(ex, "Token expired?");
                                return(Response.AsJson(new Errorable
                                {
                                    Error = new Error
                                    {
                                        Message = "Your arcgis online token expired. Please sign in again."
                                    }
                                }));
                            }

                            var url      = $"{model.ServiceUrl}/{model.FeatureId}{AttachmentUrl}";
                            var response = await client.UploadDocument(url, formContent).ConfigureAwait(false);

                            return(Response.AsJson(response.Result));
                        }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Unknown error getting EDocs File");
                    return(Response.AsJson(new Errorable
                    {
                        Error = new Error
                        {
                            Message = $"Unknown error getting EDocs File. {ex.Message}"
                        }
                    }));
                }
            };

            Delete["/upload", true] = async(_, ctx) =>
            {
                var model = this.Bind <RemoveAttachment>();
                using (var formContent = new MultipartFormDataContent())
                {
                    try
                    {
                        var token = await client.GetToken();

                        formContent.Add(new StringContent("json"), "f");
                        formContent.Add(new StringContent(model.UploadId.ToString()), "attachmentIds");
                        formContent.Add(new StringContent(token), "token");
                    }
                    catch (ArgumentNullException ex)
                    {
                        Log.Error(ex, "Token expired?");
                        return(Response.AsJson(new Errorable
                        {
                            Error = new Error
                            {
                                Message = "Your arcgis online token expired. Please sign in again."
                            }
                        }));
                    }

                    var url      = $"{model.ServiceUrl}/{model.FeatureId}{DeleteAttachmentUrl}";
                    var response = await client.DeleteDocument(url, formContent);

                    return(Response.AsJson(response.Result));
                }
            };

            Post["/upload/external", true] = async(_, ctx) =>
            {
                var model      = this.Bind <UploadExternal>();
                var attachment = Request.Files.SingleOrDefault();
                if (attachment == null || attachment.Value.Length < 1)
                {
                    return(Response.AsJson(new Errorable
                    {
                        Error = new Error
                        {
                            Message = "The file is empty."
                        }
                    }));
                }

                var extension   = Path.GetExtension(attachment.Name);
                var contentType = MimeTypeMap.GetMimeType(extension);

                if (string.IsNullOrEmpty(extension))
                {
                    extension = "";
                }

                var filename  = attachment.Name.Replace(extension, "");
                var extLength = 0;

                if (!string.IsNullOrEmpty(extension))
                {
                    extLength = extension.Length;
                }

                const int maxSize = 100;
                var       stripNonAlphaNumeric = new Regex("[^a-zA-Z0-9-]");
                var       charactersAllowed    = maxSize - extLength;
                var       title = filename.Replace('/', '-');
                title = stripNonAlphaNumeric.Replace(title, "");

                if (title.Length > charactersAllowed)
                {
                    title = title.Substring(0, charactersAllowed);
                }

                var day   = DateTime.Today.Day.ToString("d2");
                var month = DateTime.Today.Month.ToString("d2");

                var renamed = $"x{month}-{day}x{title}{extension}";

                using (var document = attachment.Value)
                    using (var formContent = new MultipartFormDataContent())
                    {
                        try
                        {
                            var token = await client.GetToken();

                            var streamContent = new StreamContent(document);
                            streamContent.Headers.Add("Content-Type", contentType);
                            streamContent.Headers.Add("Content-Disposition", $"form-data; name=\"file\"; filename=\"{renamed}\"");
                            formContent.Add(streamContent, "file", attachment.Name);
                            formContent.Add(new StringContent("json"), "f");
                            formContent.Add(new StringContent(token), "token");
                        }
                        catch (ArgumentNullException)
                        {
                            return(Response.AsJson(new Errorable
                            {
                                Error = new Error
                                {
                                    Message = "Your arcgis online token expired. Please sign in again."
                                }
                            }));
                        }

                        var url      = $"{model.ServiceUrl}/{model.FeatureId}{AttachmentUrl}";
                        var response = await client.UploadDocument(url, formContent);

                        return(Response.AsJson(response.Result));
                    }
            };
        }
Ejemplo n.º 14
0
        public virtual FileResult DownloadFile(string path, string name)
        {
            var bytes = System.IO.File.ReadAllBytes(Environment.WebRootPath + path);

            return(File(bytes, MimeTypeMap.GetMimeType(Path.GetExtension(path)), name));
        }
Ejemplo n.º 15
0
 /// <summary>
 ///     Determines whether this instance is extension.
 /// </summary>
 /// <param name="extension">The extension.</param>
 /// <returns>
 ///     <c>true</c> if the specified extension is extension; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsExtension(this string extension)
 {
     return(extension.StartsWith(".") && MimeTypeMap.HasExtension(extension));
 }
Ejemplo n.º 16
0
        public void ShowAttachment(string AttachmentName)
        {
            File attachment = this.GetFilePath(AttachmentName);

            if (!attachment.Exists())
            {
                return;
            }
            Device.BeginInvokeOnMainThread((Action)(() =>
            {
                Uri uriForFile = FileProvider.GetUriForFile(Application.get_Context(), "hu.eKreta.KretaAndroid.provider", attachment);
                Intent intent = new Intent("android.intent.action.VIEW");
                string typeFromExtension = MimeTypeMap.get_Singleton().GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl(Object.op_Explicit((Object)uriForFile)).ToLower());
                intent.SetDataAndType(uriForFile, typeFromExtension);
                intent.SetFlags((ActivityFlags)268959744);
                intent.AddFlags((ActivityFlags)1);
                try
                {
                    Xamarin.Forms.Forms.get_Context().StartActivity(intent);
                }
                catch (Exception ex)
                {
                    Toast.MakeText(Xamarin.Forms.Forms.get_Context(), "No Application Available to View this file", (ToastLength)0).Show();
                }
            }));
        }
Ejemplo n.º 17
0
        public static async Task <(int, dynamic)> AddNewPost_Async(string postId, string postPage, string textContent, string privacy, string feelingType, string feeling, string location, ObservableCollection <Attachments> postAttachments, ObservableCollection <PollAnswers> pollAnswersList, string idColor, string albumName)
        {
            try
            {
                var client = new HttpClient()
                {
                    Timeout = TimeSpan.FromMinutes(5)
                };
                var multi = new MultipartFormDataContent(Guid.NewGuid().ToString())
                {
                    { new StringContent(textContent), "\"postText\"" },
                    { new StringContent(privacy), "\"postPrivacy\"" },
                    { new StringContent(UserDetails.AccessToken), "\"s\"" },
                    { new StringContent(UserDetails.UserId), "\"user_id\"" },
                };

                if (!string.IsNullOrEmpty(feelingType))
                {
                    multi.Add(new StringContent(feelingType), "\"feeling_type\"");
                }

                if (!string.IsNullOrEmpty(feeling))
                {
                    multi.Add(new StringContent(feeling), "\"feeling\"");
                }

                if (!string.IsNullOrEmpty(location))
                {
                    multi.Add(new StringContent(location), "\"postMap\"");
                }

                if (!string.IsNullOrEmpty(idColor))
                {
                    multi.Add(new StringContent(idColor), "\"post_color\"");
                }

                if (!string.IsNullOrEmpty(albumName))
                {
                    multi.Add(new StringContent(albumName), "\"album_name\"");
                }

                if (pollAnswersList != null)
                {
                    foreach (var item in pollAnswersList)
                    {
                        multi.Add(new StringContent(item.Answer), "\"answer[]\"");
                    }
                }

                switch (postPage)
                {
                case "SocialGroup":
                    multi.Add(new StringContent(postId), "\"group_id\"");
                    break;

                case "SocialPage":
                    multi.Add(new StringContent(postId), "\"page_id\"");
                    break;

                case "SocialEvent":
                    multi.Add(new StringContent(postId), "\"event_id\"");
                    break;
                }

                if (postAttachments.Count > 0)
                {
                    foreach (var attachment in postAttachments)
                    {
                        if (!attachment.FileUrl.Contains(".gif"))
                        {
                            FileStream    fs      = System.IO.File.OpenRead(attachment.FileUrl);
                            StreamContent content = new StreamContent(fs);
                            content.Headers.ContentType        = new MediaTypeHeaderValue(MimeTypeMap.GetMimeType(attachment.FileUrl?.Split('.').LastOrDefault()));
                            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name     = attachment.TypeAttachment,
                                FileName = attachment.FileUrl?.Split('\\').LastOrDefault()?.Split('/').LastOrDefault()
                            };

                            //video thumbnail
                            if (!string.IsNullOrEmpty(attachment.Thumb?.FileUrl))
                            {
                                FileStream    fs2      = System.IO.File.OpenRead(attachment.Thumb.FileUrl);
                                StreamContent content2 = new StreamContent(fs2);
                                content2.Headers.ContentType        = new MediaTypeHeaderValue(MimeTypeMap.GetMimeType(attachment.Thumb.FileUrl?.Split('.').LastOrDefault()));
                                content2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                                {
                                    Name     = attachment.Thumb.TypeAttachment,
                                    FileName = attachment.Thumb.FileUrl?.Split('\\').LastOrDefault()?.Split('/').LastOrDefault()
                                };

                                multi.Add(content2);
                            }

                            multi.Add(content);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(textContent) && !string.IsNullOrWhiteSpace(textContent))
                            {
                                var text = textContent;
                                multi.Add(new StringContent(text), "\"postText\"");

                                multi.Add(new StringContent(attachment.FileUrl), "\"postSticker\"");
                            }
                            else
                            {
                                multi.Add(new StringContent(attachment.FileUrl), "\"postSticker\"");
                            }
                        }
                    }
                }

                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(ApiAddNewPost),
                    Method     = System.Net.Http.HttpMethod.Post,
                    Content    = multi,
                };
                request.Headers.Add("Connection", new[] { "Keep-Alive" });
                var response = await client.SendAsync(request);

                //var response = await client.PostAsync(ApiAddNewPost, multi);
                string json = await response.Content.ReadAsStringAsync();

                var data = JsonConvert.DeserializeObject <AddPostObject>(json);
                if (data.ApiStatus == "200")
                {
                    return(200, data);
                }

                var error = JsonConvert.DeserializeObject <ErrorObject>(json);
                return(400, error);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(404, e.Message);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Host a static page
        /// </summary>
        /// <param name="app">The App Builder to use</param>
        /// <param name="path">The path to host the page on</param>
        /// <param name="resource">The name/path to the resource</param>
        /// <param name="getModel">A method that takes the context and returns any replacements required</param>
        public static void HostPageAsync(this IAppBuilder app, string path, string resource,
                                         Func <IOwinContext, Task <object> > getModel)
        {
            // check inputs
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentNullException(nameof(resource));
            }

            var assemblyName = new AssemblyName(ContentExtensions.ContentAssembly);

            app.Use(async(context, next) =>
            {
                var runNext = true;

                // get current request path
                var currentPath = context.Request.Path;

                // if we don't have a request for embedded content
                // run the next thing in the OWIN pipeline
                if (currentPath.HasValue)
                {
                    // get the value
                    var currentPathValue = currentPath.Value;

                    // check that it contains our path for embedded content
                    var hasContentPath = currentPathValue.Equals(path);

                    // if we don't have a request for embedded content
                    // run the next thing in the OWIN pipeline
                    if (hasContentPath)
                    {
                        // create a resource helper
                        var resourceHelper = new ResourceHelper();

                        // attempt to get the file parts
                        var fileParts = resource.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                        var extension = ".txt";

                        // if we have some file parts
                        if (fileParts.Length > 0)
                        {
                            // get the last one
                            var lastIndex = fileParts.Length - 1;

                            // if we have a valid index, grab the extension
                            if (lastIndex > -1)
                            {
                                extension = $".{fileParts[lastIndex]}";
                            }
                        }


                        // get resource from assembly
                        var view = resourceHelper.GetResourceAsString(assemblyName.FullName, resource);

                        // get replacements
                        var replacements = await getModel(context);

                        // always perform replacements
                        view = StringMapper.Replace(view, replacements);

                        // force response type to match resource type
                        context.Response.ContentType = MimeTypeMap.GetMimeType(extension);

                        // ensure nothing else runs after this
                        runNext = false;

                        // return content of resource
                        await context.Response.WriteAsync(view);
                    }
                }

                if (runNext)
                {
                    await next.Invoke();
                }
            });
        }
Ejemplo n.º 19
0
        public void Get([Url] string map)
        {
            if (Skip)
            {
                Response.Close();
                return;
            }

            Response.ContentType = MimeTypeMap.GetMimeType(".png");

            var bsp = Program.GetMap(map);

            var lightingLump = bsp.LightingHdr.Length > 0 ? bsp.LightingHdr.LumpType : bsp.Lighting.LumpType;

            using (var sampleStream = bsp.GetLumpStream(lightingLump))
            {
                var lightmap = bsp.LightmapLayout;
                var width    = lightmap.TextureSize.X;
                var height   = lightmap.TextureSize.Y;

                var pixels = new byte[width * height * 4];

                var sampleBuffer = new ColorRGBExp32[256 * 256];
                var faces        = bsp.FacesHdr.Length > 0 ? bsp.FacesHdr : bsp.Faces;

                for (int i = 0, iEnd = faces.Length; i < iEnd; ++i)
                {
                    var face = faces[i];
                    if (face.LightOffset == -1)
                    {
                        continue;
                    }

                    var rect        = lightmap.GetLightmapRegion(i);
                    var sampleCount = rect.Width * rect.Height;

                    sampleStream.Seek(face.LightOffset, SeekOrigin.Begin);

                    LumpReader <ColorRGBExp32> .ReadLumpFromStream(sampleStream, sampleCount, sampleBuffer);

                    for (var y = 0; y < rect.Height; ++y)
                    {
                        for (var x = 0; x < rect.Width; ++x)
                        {
                            var s = Math.Max(0, Math.Min(x, rect.Width - 1));
                            var t = Math.Max(0, Math.Min(y, rect.Height - 1));

                            var index       = (rect.X + x + width * (rect.Y + y)) * 4;
                            var sampleIndex = s + t * rect.Width;
                            var sample      = sampleBuffer[sampleIndex];

                            pixels[index + 0] = sample.B;
                            pixels[index + 1] = sample.G;
                            pixels[index + 2] = sample.R;
                            pixels[index + 3] = (byte)(sample.Exponent + 128);
                        }
                    }
                }

                using (var img = new MagickImage(pixels, new MagickReadSettings
                {
                    Width = width,
                    Height = height,
                    PixelStorage = new PixelStorageSettings(StorageType.Char, "BGRA")
                }))
                {
                    img.Write(Response.OutputStream, MagickFormat.Png);
                }

                Response.OutputStream.Close();
            }
        }
        public static string ToMediaType(this string imageUrl)
        {
            var fileExtension = ToFileExtension(imageUrl);

            return(MimeTypeMap.GetMimeType(fileExtension));
        }
 public bool TryGetMimeType(string str, out string mimeType)
 => MimeTypeMap.TryGetMimeType(str, out mimeType);
Ejemplo n.º 22
0
 /// <summary>
 /// Uploads data to the bucket (the mimetype is inferred).
 /// </summary>
 /// <param name="fileName">Filename to save as in bucket</param>
 /// <param name="data">The byte array to read from</param>
 /// <param name="permissionLevel">The permission level to set</param>
 public Bucket UploadData(string fileName, byte[] data, Permissions permissionLevel = Permissions.OwnerOnly)
 {
     return(UploadData(fileName, data, MimeTypeMap.GetMimeType(Path.GetExtension(fileName)), permissionLevel));
 }
 public string GetExtension(string mimeType, bool throwErrorIfNotFound = true)
 => MimeTypeMap.GetExtension(mimeType, throwErrorIfNotFound);
Ejemplo n.º 24
0
 /// <summary>
 /// Uploads a file to the bucket. Mimetype is inferred.
 /// </summary>
 /// <param name="fileNameInBucket">The filename to save as in the bucket</param>
 /// <param name="pathToFile">Path to the file (relative or absolute)</param>
 /// <param name="permissionLevel">Permission level to set</param>
 public Bucket UploadFile(string fileNameInBucket, string pathToFile, Permissions permissionLevel = Permissions.OwnerOnly)
 {
     return(UploadFile(fileNameInBucket, pathToFile, MimeTypeMap.GetMimeType(Path.GetExtension(fileNameInBucket)), permissionLevel));
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Streams a file contents to the response as a HTTP response message
        /// </summary>
        /// <param name="controller">The controller reference</param>
        /// <param name="fileContents">The file contents to stream</param>
        /// <param name="contentType">The file content type</param>
        /// <param name="fileName">The file name to display (optional)</param>
        /// <param name="dispositionType">The content disposition type (optional)</param>
        /// <returns>An action result with the streamed file data</returns>
        public static HttpResponseMessage StreamFile
        (
            this ApiController controller,
            byte[] fileContents,
            string contentType,
            string fileName        = null,
            string dispositionType = "inline"
        )
        {
            if (fileContents == null || fileContents.Length == 0)
            {
                throw new ArgumentException
                      (
                          "An empty file cannot be streamed."
                      );
            }

            if (String.IsNullOrEmpty(fileName))
            {
                var fileExtension = MimeTypeMap.GetExtension
                                    (
                    contentType
                                    );

                fileName = $"Attachment.{fileExtension}";
            }

            // Remove commas from the file name as they are not supported
            fileName = fileName.Replace
                       (
                ",",
                String.Empty
                       );

            var result = new HttpResponseMessage
                         (
                HttpStatusCode.OK
                         );

            var contentTypeHeader = new MediaTypeHeaderValue
                                    (
                contentType
                                    );

            var dispositionHeader = new ContentDispositionHeaderValue
                                    (
                dispositionType
                                    )
            {
                FileName = fileName
            };

            result.Content = new ByteArrayContent
                             (
                fileContents
                             );

            result.Content.Headers.ContentType        = contentTypeHeader;
            result.Content.Headers.ContentLength      = fileContents.Length;
            result.Content.Headers.ContentDisposition = dispositionHeader;

            return(result);
        }
        public virtual FileResult DownloadReportByLonNumber(
            string operationNumber,
            string loanNumber,
            string fundCode,
            string loanTcdNum,
            string loanProjectNumber,
            string loanCurrencyCode,
            string format = "",
            string group  = DisbursementValues.SELECTED)
        {
            if ((format == DisbursementValues.PDF) || (format == DisbursementValues.EXCEL))
            {
                string pcMail = IDBContext.Current.UserName;

                OperationLevelProjectionsViewModel model;
                var projectionMatrix = _disbursementService.GetProjectionMatrixWithCache(
                    null,
                    operationNumber,
                    pcMail,
                    loanNumber,
                    fundCode,
                    loanTcdNum,
                    loanProjectNumber,
                    loanCurrencyCode);

                var oldProjection = _disbursementService.GetMonthlyProyections(
                    operationNumber,
                    projectionMatrix.CurrentProjectionMonth,
                    false,
                    projectionMatrix.IsExecution,
                    new string[] { loanNumber });

                model =
                    new OperationLevelProjectionsViewModel
                {
                    ProjectedMonths        = projectionMatrix.ProjectedMonths,
                    ProjectedYears         = projectionMatrix.ProjectedYears,
                    OldProjection          = oldProjection,
                    CurrentProjectionMonth = projectionMatrix.CurrentProjectionMonth,
                    Balance = projectionMatrix.Balance
                };

                var exportModel = _disbursementService.FormatOperationLevelModelToExport(model);

                try
                {
                    DownloadDisbursementReportResponse response = _disbursementService
                                                                  .DownloadDisbursementProjectionsReport(exportModel, format);
                    if (!response.IsValid)
                    {
                        throw new Exception(DisbursementValues.MSJ_ERROR_EXPORT
                                            + DisbursementValues.UNDERLINE_STRING + response.ErrorMessage);
                    }

                    string fileName = IDBContext.Current.Operation
                                      + DisbursementValues.UNDERLINE_STRING
                                      + Localization.GetText(DisbursementValues.DISBURSEMENT_PROJECTIONS)
                                      + Localization.GetText(DisbursementValues.LOAN_LEVEL);
                    string application;
                    switch (format)
                    {
                    case DisbursementValues.EXCEL:
                        application = MimeTypeMap.GetMimeType(DisbursementValues.EXCEL);
                        fileName    = fileName + DisbursementValues.DOT_STRING +
                                      DisbursementValues.EXCEL;
                        break;

                    default:
                        application = MimeTypeMap.GetMimeType(DisbursementValues.PDF);
                        fileName    = fileName + DisbursementValues.DOT_STRING +
                                      DisbursementValues.PDF;
                        break;
                    }

                    return(File(response.File, application, fileName));
                }
                catch (Exception)
                {
                    MessageHandler.SetMessage(
                        Localization.GetText(DisbursementValues.WARNING_UNHANDLED_ERROR),
                        DisbursementValues.ERROR);
                }
            }

            return(null);
        }
Ejemplo n.º 27
0
        public virtual FileResult DownloadReport(
            string operationNumber,
            string format = "",
            string group  = DisbursementValues.SELECTED)
        {
            string pcMail = IDBContext.Current.UserName;

            OperationLevelProjectionsViewModel model;

            string cacheName = string.Format(
                DisbursementValues.DISBURSEMENT_CACHE_SKELETON,
                pcMail,
                operationNumber,
                group);

            var isInExecution = _disbursementService.IsInExecution(operationNumber);

            model = _disbursementService.GetProjectionMatrixWithCache(
                null,
                pcMail,
                operationNumber,
                group,
                isInExecution.IsValid);

            var oldProjection = _disbursementService.GetMonthlyProyections(
                operationNumber,
                model.CurrentProjectionMonth,
                true,
                model.IsExecution,
                model.LoanNumbers,
                model.ExchangeRates);

            model.OldProjection = oldProjection != null
                ? oldProjection : new List <ActualsFromEdwViewModel>();

            var exportModel = _disbursementService.FormatOperationLevelModelToExport(model);

            try
            {
                DownloadDisbursementReportResponse response =
                    _disbursementService.DownloadDisbursementProjectionsReport(exportModel, format);
                if (!response.IsValid)
                {
                    throw new Exception(DisbursementValues.MSJ_ERROR_EXPORT
                                        + DisbursementValues.UNDERLINE_STRING + response.ErrorMessage);
                }

                string fileName = IDBContext.Current.Operation
                                  + DisbursementValues.UNDERLINE_STRING
                                  + Localization.GetText(DisbursementValues.DISBURSEMENT_PROJECTIONS)
                                  + Localization.GetText(DisbursementValues.LOAN_LEVEL);
                string application;
                switch (format)
                {
                case DisbursementValues.EXCEL:
                    application = MimeTypeMap.GetMimeType(DisbursementValues.EXCEL);
                    fileName    = fileName + DisbursementValues.DOT_STRING +
                                  DisbursementValues.EXCEL;
                    break;

                default:
                    application = MimeTypeMap.GetMimeType(DisbursementValues.PDF);
                    fileName    = fileName + DisbursementValues.DOT_STRING +
                                  DisbursementValues.PDF;
                    break;
                }

                return(File(response.File, application, fileName));
            }
            catch (Exception)
            {
                MessageHandler.SetMessage(
                    Localization.GetText(DisbursementValues.WARNING_UNHANDLED_ERROR),
                    DisbursementValues.ERROR);
            }

            return(null);
        }
Ejemplo n.º 28
0
        public async Task UploadAsync(string containerName, string fileName, Stream stream, string contentType = null, bool reportProgress = false)
        {
            var container = await CreateIfNotExistsAsync(containerName);

            var blockBlobClient = container.GetBlockBlobClient(fileName);

            BlobClient blobProgress = null;

            const int blockSize = 1 * 1024 * 1024; //1 MB Block
            const int offset    = 0;
            var       counter   = 0;
            var       blockIds  = new List <string>();

            var bytesRemaining = stream.Length;

            do
            {
                if (reportProgress)
                {
                    if (blobProgress == null)
                    {
                        blobProgress = container.GetBlobClient($"{fileName}.progress");
                    }

                    var p = (double)(stream.Length - bytesRemaining) / stream.Length * 100;
                    await blobProgress.UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes(p.ToString(CultureInfo.InvariantCulture))), true);
                }

                var dataToRead = Math.Min(bytesRemaining, blockSize);
                var data       = new byte[dataToRead];
                var dataRead   = await stream.ReadAsync(data.AsMemory(offset, (int)dataToRead));

                bytesRemaining -= dataRead;

                if (dataRead > 0)
                {
                    var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(counter.ToString("d6")));
                    await blockBlobClient.StageBlockAsync(blockId, new MemoryStream(data));

                    blockIds.Add(blockId);
                    counter++;
                }
            }while (bytesRemaining > 0);

            await blockBlobClient.CommitBlockListAsync(blockIds);

            if (string.IsNullOrEmpty(contentType))
            {
                await blockBlobClient.SetHttpHeadersAsync(new BlobHttpHeaders
                                                          { ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(fileName)) });
            }
            else
            {
                await blockBlobClient.SetHttpHeadersAsync(new BlobHttpHeaders
                                                          { ContentType = contentType });
            }

            if (blobProgress != null)
            {
                await blobProgress.DeleteIfExistsAsync();
            }
        }
Ejemplo n.º 29
0
 private void PreviewHandler(string file)
 {
     if (File.Exists(file))
     {
         Uri uri = new Uri(file);
         if (MimeTypeMap.GetMimeType(uri.ToString()).Contains("image"))
         {
             HidePreview();
             BitmapImage image = new BitmapImage();
             image.BeginInit();
             image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
             image.CacheOption   = BitmapCacheOption.OnLoad;
             image.UriSource     = uri;
             image.EndInit();
             if (MimeTypeMap.GetMimeType(uri.ToString()).Contains("gif"))
             {
                 gifPreview.Visibility = Visibility.Visible;
                 ImageBehavior.SetAnimatedSource(gifPreview, image);
             }
             else
             {
                 imgPreview.Visibility = Visibility.Visible;
                 imgPreview.Source     = image;
             }
         }
         else if (MimeTypeMap.GetMimeType(uri.ToString()).Contains("video") || MimeTypeMap.GetMimeType(uri.ToString()).Contains("audio"))
         {
             HidePreview();
             previewGrid.Visibility = Visibility.Visible;
             previewGrid.BringIntoView();
             time.Start();
             media.Play(new Media(lib, uri));
             media.Volume = 100;
         }
         else if (MimeTypeMap.GetMimeType(uri.ToString()).Contains("text"))
         {
             HidePreview();
             try
             {
                 string contents = File.ReadAllText(file);
                 txtPreviewScroller.Visibility = Visibility.Visible;
                 txtPreview.Visibility         = Visibility.Visible;
                 txtPreview.Text = contents;
             }
             catch (Exception exc)
             {
                 nullPreview.Visibility = Visibility.Visible;
             }
         }
         else
         {
             HidePreview();
             nullPreview.Visibility = Visibility.Visible;
         }
     }
 }
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            var url = EwfApp.GetRequestAppRelativeUrl(context.Request);

            var queryIndex = url.IndexOf("?", StringComparison.Ordinal);

            if (queryIndex >= 0)
            {
                url = url.Remove(queryIndex);
            }

            var extensionIndex = url.LastIndexOf(".", StringComparison.Ordinal);

            var versionStringOrFileExtensionIndex = extensionIndex;
            var urlVersionString = "";

            if (url.StartsWith(VersionedFilesFolderName + "/") || url.StartsWith(EwfFolderName + "/" + VersionedFilesFolderName + "/"))
            {
                urlVersionString = "invariant";
            }
            else
            {
                // We assume that all URL version strings will have the same length as the format string.
                var prefixedVersionStringIndex = extensionIndex - (urlVersionStringPrefix.Length + EwfSafeResponseWriter.UrlVersionStringFormat.Length);

                if (prefixedVersionStringIndex >= 0)
                {
                    DateTimeOffset dateAndTime;
                    var            versionString = url.Substring(prefixedVersionStringIndex + urlVersionStringPrefix.Length, EwfSafeResponseWriter.UrlVersionStringFormat.Length);
                    if (DateTimeOffset.TryParseExact(
                            versionString,
                            EwfSafeResponseWriter.UrlVersionStringFormat,
                            DateTimeFormatInfo.InvariantInfo,
                            DateTimeStyles.None,
                            out dateAndTime))
                    {
                        versionStringOrFileExtensionIndex = prefixedVersionStringIndex;
                        urlVersionString = versionString;
                    }
                }
            }

            if (versionStringOrFileExtensionIndex < 0)
            {
                throw new ResourceNotAvailableException("Failed to find the extension in the URL.", null);
            }
            var extension      = url.Substring(extensionIndex);
            var staticFileInfo = EwfApp.GlobalType.Assembly.CreateInstance(
                CombineNamespacesAndProcessEwfIfNecessary(
                    EwfApp.GlobalType.Namespace,
                    (url.Remove(versionStringOrFileExtensionIndex) + extension.CapitalizeString()).Separate("/", false)
                    .Select(i => EwlStatics.GetCSharpIdentifier(i.CapitalizeString()))
                    .Aggregate((a, b) => a + "." + b) + "+Info")) as StaticFileInfo;

            if (staticFileInfo == null)
            {
                throw new ResourceNotAvailableException("Failed to create an Info object for the request.", null);
            }

            var mediaTypeOverride = EwfApp.Instance.GetMediaTypeOverrides().SingleOrDefault(i => i.FileExtension == extension);
            var contentType       = mediaTypeOverride != null ? mediaTypeOverride.MediaType : MimeTypeMap.GetMimeType(extension);

            Func <string>         cacheKeyGetter = () => staticFileInfo.GetUrl(false, false, false);
            EwfSafeResponseWriter responseWriter;

            if (contentType == TewlContrib.ContentTypes.Css)
            {
                Func <string> cssGetter = () => File.ReadAllText(staticFileInfo.FilePath);
                responseWriter = urlVersionString.Any()
                                                         ? new EwfSafeResponseWriter(
                    cssGetter,
                    urlVersionString,
                    () => new ResponseMemoryCachingSetup(cacheKeyGetter(), staticFileInfo.GetResourceLastModificationDateAndTime()))
                                                         : new EwfSafeResponseWriter(
                    () => EwfResponse.Create(
                        TewlContrib.ContentTypes.Css,
                        new EwfResponseBodyCreator(() => CssPreprocessor.TransformCssFile(cssGetter()))),
                    staticFileInfo.GetResourceLastModificationDateAndTime(),
                    memoryCacheKeyGetter: cacheKeyGetter);
            }
            else
            {
                Func <EwfResponse> responseCreator = () => EwfResponse.Create(
                    contentType,
                    new EwfResponseBodyCreator(
                        responseStream => {
                    using (var fileStream = File.OpenRead(staticFileInfo.FilePath))
                        fileStream.CopyTo(responseStream);
                }));
                responseWriter = urlVersionString.Any()
                                                         ? new EwfSafeResponseWriter(
                    responseCreator,
                    urlVersionString,
                    memoryCachingSetupGetter: () => new ResponseMemoryCachingSetup(
                        cacheKeyGetter(),
                        staticFileInfo.GetResourceLastModificationDateAndTime()))
                                                         : new EwfSafeResponseWriter(
                    responseCreator,
                    staticFileInfo.GetResourceLastModificationDateAndTime(),
                    memoryCacheKeyGetter: cacheKeyGetter);
            }
            responseWriter.WriteResponse();
        }