Пример #1
0
            public void setup()
            {
                fileName = Path.Combine(cacheDir, cacheFileName);

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                using (var f = File.Create(fileName)) { f.Close(); }

                _provider = new FileProvider(cacheDir, cacheFileName);
            }
Пример #2
0
        /// <summary>
        /// Creates an instance of the <see cref="GameMode"/> class and loads the data model.
        /// </summary>
        internal GameMode(GameModeInfo gameModeInfo, GameContext gameContext, FileProvider fileLoader) : base(gameContext)
        {
            GameModeInfo = gameModeInfo;
            FileLoader = fileLoader;

            // only continue if the game mode config file loaded correctly.
            if (GameModeInfo.IsValid)
            {
                MapFragmentManager = new MapFragmentManager(this);
                PokemonFactory = new PokemonFactory(this);
            }

            IsValid = true;
        }
Пример #3
0
        public void Step(string name, Action action)
        {
            var caseId = TestExecutionContext.CurrentContext.CurrentTest.Id;
            var uuid   = Guid.NewGuid().ToString("N");

            Allure.StartStep(caseId, uuid, new StepResult()
            {
                name = name
            });

            int       logLength     = TestExecutionContext.CurrentContext.CurrentResult.Output.Length;
            Exception stepException = null;

            try
            {
                action();
            }
            catch (Exception e)
            {
                stepException = e;
                AllureHelper.AttachPng("FailedElement", File.ReadAllBytes(new DirectoryInfo(FileProvider.GetFailedScreensDirectory())
                                                                          .GetFiles().OrderByDescending(file => file.LastWriteTime).First().FullName));
                AllureHelper.AttachPng("Screenshot",
                                       File.ReadAllBytes(ScreenshotProvider.PublishScreenshot($"Screenshot_{DateTime.Now.ToFileTime()}")));
                throw;
            }
            finally
            {
                Allure.UpdateStep(uuid, x =>
                {
                    x.status        = GetStatusFromException(stepException);
                    x.statusDetails = new StatusDetails
                    {
                        message = stepException?.Message,
                        trace   = stepException?.StackTrace
                    };
                    x.attachments.AddRange(AllureHelper.GetAttaches());
                });
                Allure.StopStep(uuid);
            }
        }
Пример #4
0
 public override async Task <bool> Exists(TId id, CancellationToken cancellationToken = default)
 {
     return(await(await FileProvider.GetFileInfo(GetPath(id)).ConfigureAwait(false)).Exists());
 }
Пример #5
0
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);

                var bundle = savedInstanceState ?? Intent.Extras;

                RequestId       = bundle.GetInt("id");
                Action          = bundle.GetString("action");
                AllowMultiple   = bundle.GetBoolean(Intent.ExtraAllowMultiple);
                PurgeCameraRoll = bundle.GetBoolean("purge-camera-roll");
                Type            = bundle.GetString("type");
                FrontCamera     = bundle.GetBoolean("front");
                if (Type == "video/*")
                {
                    IsVideo = true;
                }

                using (var intent = new Intent(Action))
                {
                    try
                    {
                        if (Action == Intent.ActionPick)
                        {
                            intent.SetType(Type);
                            intent.PutExtra(Intent.ExtraAllowMultiple, AllowMultiple);
                        }
                        else
                        {
                            if (IsVideo)
                            {
                                MaxSeconds = bundle.GetInt(MediaStore.ExtraDurationLimit, 0);
                                if (MaxSeconds != 0)
                                {
                                    intent.PutExtra(MediaStore.ExtraDurationLimit, MaxSeconds);
                                }

                                VideoQuality = (VideoQuality)bundle.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High);
                                intent.PutExtra(MediaStore.ExtraVideoQuality, VideoQuality == VideoQuality.Low ? 0 : 1);
                            }

                            if (FrontCamera)
                            {
                                intent.PutExtra("android.intent.extras.CAMERA_FACING", 1);
                            }

                            var file = new Java.IO.File(PrepareTempStorageFile().FullName);
                            Uri path;
                            var packageName = UIRuntime.CurrentActivity.PackageName;
                            if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
                            {
                                path = FileProvider.GetUriForFile(Application.Context, $"{packageName}.fileprovider", file);
                            }
                            else
                            {
                                path = Uri.FromFile(file);
                            }

                            intent.PutExtra(MediaStore.ExtraOutput, path);
                            FileUrlPath      = path;
                            FileAbsolotePath = file.AbsolutePath;
                        }


                        // if (intent.ResolveActivity(PackageManager) != null)
                        // Removed due to Android 11 changes.
                        // https://cketti.de/2020/09/03/avoid-intent-resolveactivity/
                        // https://stackoverflow.com/questions/62535856/intent-resolveactivity-returns-null-in-api-30
                        StartActivityForResult(intent, RequestId, savedInstanceState);
                    }
                    catch (Exception ex)
                    {
                        Log.For(this).Error(ex);
                        Picked.RaiseOn(Thread.Pool, new MediaPickedEventArgs(RequestId, ex));
                        Finish();
                    }
                }
            }
Пример #6
0
            public override void OnResourceReady(Object resource, ITransition transition)
            {
                try
                {
                    switch (MAdapter.AttachmentList?.Count)
                    {
                    case > 0:
                    {
                        var item = MAdapter.AttachmentList[Position];
                        if (item != null && string.IsNullOrEmpty(item.Thumb?.FileUrl))
                        {
                            var fileName = item.FileUrl.Split('/').Last();
                            var fileNameWithoutExtension = fileName.Split('.').First();

                            var pathImage = Methods.Path.FolderDcimImage + "/" + fileNameWithoutExtension + ".png";

                            var videoImage = Methods.MultiMedia.GetMediaFrom_Gallery(Methods.Path.FolderDcimImage, fileNameWithoutExtension + ".png");
                            switch (videoImage)
                            {
                            case "File Dont Exists":
                            {
                                switch (resource)
                                {
                                case Bitmap bitmap:
                                {
                                    Methods.MultiMedia.Export_Bitmap_As_Image(bitmap, fileNameWithoutExtension, Methods.Path.FolderDcimImage);

                                    File file2    = new File(pathImage);
                                    var  photoUri = FileProvider.GetUriForFile(MAdapter.ActivityContext, MAdapter.ActivityContext.PackageName + ".fileprovider", file2);

                                    Glide.With(MAdapter.ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(ViewHolder.Image);

                                    item.Thumb = new Attachments.VideoThumb
                                    {
                                        FileUrl = photoUri.ToString()
                                    };
                                    break;
                                }
                                }

                                break;
                            }

                            default:
                            {
                                File file2    = new File(pathImage);
                                var  photoUri = FileProvider.GetUriForFile(MAdapter.ActivityContext, MAdapter.ActivityContext.PackageName + ".fileprovider", file2);

                                Glide.With(MAdapter.ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(ViewHolder.Image);

                                item.Thumb = new Attachments.VideoThumb
                                {
                                    FileUrl = photoUri.ToString()
                                };
                                break;
                            }
                            }
                        }

                        break;
                    }
                    }
                }
                catch (Exception e)
                {
                    Methods.DisplayReportResultTrack(e);
                }
            }
        // Function Update Image Group : Avatar && Cover
        private async void UpdateImageGroup_Api(string type, string path)
        {
            try
            {
                if (!Methods.CheckConnectivity())
                {
                    Toast.MakeText(this, GetString(Resource.String.Lbl_CheckYourInternetConnection), ToastLength.Short).Show();
                }
                else
                {
                    if (type == "Avatar")
                    {
                        var(apiStatus, respond) = await RequestsAsync.Group.Update_Group_Avatar(GroupId, path);

                        if (apiStatus == 200)
                        {
                            if (respond is MessageObject result)
                            {
                                Toast.MakeText(this, result.Message, ToastLength.Short).Show();

                                //Set image
                                File file2    = new File(path);
                                var  photoUri = FileProvider.GetUriForFile(this, PackageName + ".fileprovider", file2);
                                Glide.With(this).Load(photoUri).Apply(new RequestOptions()).Into(UserProfileImage);

                                //GlideImageLoader.LoadImage(this, file.Path, UserProfileImage, ImageStyle.RoundedCrop, ImagePlaceholders.Color);
                            }
                        }
                        else
                        {
                            Methods.DisplayReportResult(this, respond);
                        }
                    }
                    else if (type == "Cover")
                    {
                        var(apiStatus, respond) = await RequestsAsync.Group.Update_Group_Cover(GroupId, path);

                        if (apiStatus == 200)
                        {
                            if (!(respond is MessageObject result))
                            {
                                return;
                            }

                            Toast.MakeText(this, result.Message, ToastLength.Short).Show();

                            //Set image
                            File file2    = new File(path);
                            var  photoUri = FileProvider.GetUriForFile(this, PackageName + ".fileprovider", file2);
                            Glide.With(this).Load(photoUri).Apply(new RequestOptions()).Into(CoverImage);


                            //GlideImageLoader.LoadImage(this, file.Path, CoverImage, ImageStyle.CenterCrop, ImagePlaceholders.Color);
                        }
                        else
                        {
                            Methods.DisplayReportResult(this, respond);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #8
0
        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
        {
            try
            {
                if (viewHolder is JobsAdapterViewHolder holder)
                {
                    var item = JobList[position];
                    if (item != null)
                    {
                        if (item.Image.Contains("http"))
                        {
                            var image = item.Image.Replace(Client.WebsiteUrl + "/", "");
                            if (!image.Contains("http"))
                            {
                                item.Image = Client.WebsiteUrl + "/" + image;
                            }
                            else
                            {
                                item.Image = image;
                            }

                            GlideImageLoader.LoadImage(ActivityContext, item.Image, holder.Image, ImageStyle.FitCenter, ImagePlaceholders.Drawable);
                        }
                        else
                        {
                            File file2    = new File(item.Image);
                            var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                            Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.Image);
                        }

                        holder.Title.Text = Methods.FunString.DecodeString(item.Title);

                        var(currency, currencyIcon) = WoWonderTools.GetCurrency(item.Currency);
                        var categoryName = CategoriesController.ListCategoriesJob.FirstOrDefault(categories => categories.CategoriesId == item.Category)?.CategoriesName;
                        Console.WriteLine(currency);
                        if (string.IsNullOrEmpty(categoryName))
                        {
                            categoryName = Application.Context.GetText(Resource.String.Lbl_Unknown);
                        }

                        holder.Salary.Text = currencyIcon + " " + item.Minimum + " - " + currencyIcon + " " + item.Maximum + " . " + categoryName;

                        holder.Description.Text = Methods.FunString.SubStringCutOf(Methods.FunString.DecodeString(item.Description), 100);

                        if (item.IsOwner != null && item.IsOwner.Value)
                        {
                            holder.IconMore.Visibility = ViewStates.Visible;
                            holder.Button.Text         = ActivityContext.GetString(Resource.String.Lbl_show_applies) + " (" + item.ApplyCount + ")";
                            holder.Button.Tag          = "ShowApply";
                        }
                        else
                        {
                            holder.IconMore.Visibility = ViewStates.Gone;
                        }

                        //Set Button if its applied
                        if (item.Apply == "true")
                        {
                            holder.Button.Text    = ActivityContext.GetString(Resource.String.Lbl_already_applied);
                            holder.Button.Enabled = false;
                        }
                        else if (item.Apply != "true" && item.Page.IsPageOnwer != null && !item.Page.IsPageOnwer.Value)
                        {
                            holder.Button.Text = ActivityContext.GetString(Resource.String.Lbl_apply_now);
                            holder.Button.Tag  = "Apply";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Methods.DisplayReportResultTrack(exception);
            }
        }
        public void OpenImageLightBox(CommentObjectExtra item)
        {
            try
            {
                if (item == null)
                {
                    return;
                }

                var imageUrl = !string.IsNullOrEmpty(item.CFile) && (item.CFile.Contains("file://") || item.CFile.Contains("content://") || item.CFile.Contains("storage")) ? item.CFile : Client.WebsiteUrl + "/" + item.CFile;

                MainContext.RunOnUiThread(() =>
                {
                    var fileName = imageUrl.Split('/').Last();

                    var getImage = Methods.MultiMedia.GetMediaFrom_Gallery(Methods.Path.FolderDcimImage, fileName);
                    if (getImage != "File Dont Exists")
                    {
                        Java.IO.File file2 = new Java.IO.File(getImage);
                        var photoUri       = FileProvider.GetUriForFile(MainContext, MainContext.PackageName + ".fileprovider", file2);

                        Intent intent = new Intent(Intent.ActionPick);
                        intent.SetAction(Intent.ActionView);
                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                        intent.SetDataAndType(photoUri, "image/*");
                        MainContext.StartActivity(intent);
                    }
                    else
                    {
                        string filename  = imageUrl.Split('/').Last();
                        string filePath  = Path.Combine(Methods.Path.FolderDcimImage);
                        string mediaFile = filePath + "/" + filename;

                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }

                        if (!File.Exists(mediaFile))
                        {
                            WebClient webClient = new WebClient();
                            AndHUD.Shared.Show(MainContext, MainContext.GetText(Resource.String.Lbl_Loading));

                            webClient.DownloadDataAsync(new Uri(imageUrl));
                            webClient.DownloadProgressChanged += (sender, args) =>
                            {
                                //var progress = args.ProgressPercentage;
                                // holder.loadingProgressview.Progress = progress;
                                //Show a progress
                                AndHUD.Shared.Show(MainContext, MainContext.GetText(Resource.String.Lbl_Loading));
                            };
                            webClient.DownloadDataCompleted += (s, e) =>
                            {
                                try
                                {
                                    File.WriteAllBytes(mediaFile, e.Result);

                                    getImage = Methods.MultiMedia.GetMediaFrom_Gallery(Methods.Path.FolderDcimImage, fileName);
                                    if (getImage != "File Dont Exists")
                                    {
                                        Java.IO.File file2 = new Java.IO.File(getImage);

                                        Android.Net.Uri photoUri = FileProvider.GetUriForFile(MainContext, MainContext.PackageName + ".fileprovider", file2);

                                        Intent intent = new Intent(Intent.ActionPick);
                                        intent.SetAction(Intent.ActionView);
                                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                                        intent.SetDataAndType(photoUri, "image/*");
                                        MainContext.StartActivity(intent);
                                    }
                                    else
                                    {
                                        Toast.MakeText(MainContext, MainContext.GetText(Resource.String.Lbl_something_went_wrong), ToastLength.Long).Show();
                                    }
                                }
                                catch (Exception exception)
                                {
                                    Console.WriteLine(exception);
                                }

                                //var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                                //mediaScanIntent.SetData(Uri.FromFile(new File(mediaFile)));
                                //Application.Context.SendBroadcast(mediaScanIntent);

                                // Tell the media scanner about the new file so that it is
                                // immediately available to the user.
                                MediaScannerConnection.ScanFile(Application.Context, new[] { mediaFile }, null, null);

                                AndHUD.Shared.Dismiss(MainContext);
                            };
                        }
                    }
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #10
0
        public void LoadCommentData(CommentObjectExtra item, CommentAdapterViewHolder holder, int position = 0, bool hasClickEvents = true)
        {
            try
            {
                if (!string.IsNullOrEmpty(item.Text) || !string.IsNullOrWhiteSpace(item.Text))
                {
                    var changer = new TextSanitizer(holder.CommentText, ActivityContext);
                    changer.Load(Methods.FunString.DecodeString(item.Text));
                }
                else
                {
                    holder.CommentText.Visibility = ViewStates.Gone;
                }

                holder.TimeTextView.Text = Methods.Time.TimeAgo(int.Parse(item.Time));
                holder.UserName.Text     = item.Publisher.Name;

                GlideImageLoader.LoadImage(ActivityContext, item.Publisher.Avatar, holder.Image, ImageStyle.CircleCrop, ImagePlaceholders.Drawable);

                var textHighLighter = item.Publisher.Name;
                var textIsPro       = string.Empty;

                if (item.Publisher.Verified == "1")
                {
                    textHighLighter += " " + IonIconsFonts.CheckmarkCircled;
                }

                if (item.Publisher.IsPro == "1")
                {
                    textIsPro        = " " + IonIconsFonts.Flash;
                    textHighLighter += textIsPro;
                }

                var decorator = TextDecorator.Decorate(holder.UserName, textHighLighter).SetTextStyle((int)TypefaceStyle.Bold, 0, item.Publisher.Name.Length);

                if (item.Publisher.Verified == "1")
                {
                    decorator.SetTextColor(Resource.Color.Post_IsVerified, IonIconsFonts.CheckmarkCircled);
                }

                if (item.Publisher.IsPro == "1")
                {
                    decorator.SetTextColor(Resource.Color.text_color_in_between, textIsPro);
                }

                decorator.Build();

                //Image
                if (holder.ItemViewType == 1 || holder.CommentImage != null)
                {
                    if (!string.IsNullOrEmpty(item.CFile) && (item.CFile.Contains("file://") || item.CFile.Contains("content://") || item.CFile.Contains("storage") || item.CFile.Contains("/data/user/0/")))
                    {
                        File file2    = new File(item.CFile);
                        var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                        Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.CommentImage);

                        //GlideImageLoader.LoadImage(ActivityContext,item.CFile, holder.CommentImage, ImageStyle.CenterCrop, ImagePlaceholders.Color);
                    }
                    else
                    {
                        if (!item.CFile.Contains(Client.WebsiteUrl))
                        {
                            item.CFile = WoWonderTools.GetTheFinalLink(item.CFile);
                        }

                        GlideImageLoader.LoadImage(ActivityContext, item.CFile, holder.CommentImage, ImageStyle.CenterCrop, ImagePlaceholders.Color);
                    }
                }

                //Voice
                if (holder.VoiceLayout != null && !string.IsNullOrEmpty(item.Record))
                {
                    LoadAudioItem(holder, position, item);
                }

                if (item.Replies != "0" && item.Replies != null)
                {
                    holder.ReplyTextView.Text = ActivityContext.GetText(Resource.String.Lbl_Reply) + " " + "(" + item.Replies + ")";
                }

                if (AppSettings.PostButton == PostButtonSystem.ReactionDefault || AppSettings.PostButton == PostButtonSystem.ReactionSubShine)
                {
                    item.Reaction ??= new WoWonderClient.Classes.Posts.Reaction();

                    if ((bool)(item.Reaction != null & item.Reaction?.IsReacted))
                    {
                        if (!string.IsNullOrEmpty(item.Reaction.Type))
                        {
                            switch (item.Reaction.Type)
                            {
                            case "1":
                            case "Like":
                                ReactionComment.SetReactionPack(holder, ReactConstants.Like);
                                holder.LikeTextView.Tag = "Liked";
                                break;

                            case "2":
                            case "Love":
                                ReactionComment.SetReactionPack(holder, ReactConstants.Love);
                                holder.LikeTextView.Tag = "Liked";
                                break;

                            case "3":
                            case "HaHa":
                                ReactionComment.SetReactionPack(holder, ReactConstants.HaHa);
                                holder.LikeTextView.Tag = "Liked";
                                break;

                            case "4":
                            case "Wow":
                                ReactionComment.SetReactionPack(holder, ReactConstants.Wow);
                                holder.LikeTextView.Tag = "Liked";
                                break;

                            case "5":
                            case "Sad":
                                ReactionComment.SetReactionPack(holder, ReactConstants.Sad);
                                holder.LikeTextView.Tag = "Liked";
                                break;

                            case "6":
                            case "Angry":
                                ReactionComment.SetReactionPack(holder, ReactConstants.Angry);
                                holder.LikeTextView.Tag = "Liked";
                                break;

                            default:
                                holder.LikeTextView.Text = ActivityContext.GetText(Resource.String.Btn_Like);
                                holder.LikeTextView.SetTextColor(AppSettings.SetTabDarkTheme ? Color.White : Color.Black);
                                holder.LikeTextView.Tag = "Like";
                                break;
                            }
                        }
                    }
                    else
                    {
                        holder.LikeTextView.Text = ActivityContext.GetText(Resource.String.Btn_Like);
                        holder.LikeTextView.SetTextColor(AppSettings.SetTabDarkTheme ? Color.White : Color.Black);
                        holder.LikeTextView.Tag = "Like";
                    }
                }
                else if (AppSettings.PostButton == PostButtonSystem.Wonder || AppSettings.PostButton == PostButtonSystem.DisLike)
                {
                    if ((bool)(item.Reaction != null & !item.Reaction?.IsReacted))
                    {
                        ReactionComment.SetReactionPack(holder, ReactConstants.Default);
                    }

                    if (item.IsCommentLiked)
                    {
                        holder.LikeTextView.Text = ActivityContext.GetText(Resource.String.Btn_Liked);
                        holder.LikeTextView.SetTextColor(Color.ParseColor(AppSettings.MainColor));
                        holder.LikeTextView.Tag = "Liked";
                    }

                    switch (AppSettings.PostButton)
                    {
                    case PostButtonSystem.Wonder when item.IsCommentWondered:
                    {
                        holder.DislikeTextView.Text = ActivityContext.GetString(Resource.String.Lbl_wondered);
                        holder.DislikeTextView.SetTextColor(Color.ParseColor(AppSettings.MainColor));
                        holder.DislikeTextView.Tag = "Disliked";
                        break;
                    }

                    case PostButtonSystem.Wonder:
                    {
                        holder.DislikeTextView.Text = ActivityContext.GetString(Resource.String.Btn_Wonder);
                        holder.DislikeTextView.SetTextColor(AppSettings.SetTabDarkTheme ? Color.White : Color.Black);
                        holder.DislikeTextView.Tag = "Dislike";
                        break;
                    }

                    case PostButtonSystem.DisLike when item.IsCommentWondered:
                    {
                        holder.DislikeTextView.Text = ActivityContext.GetString(Resource.String.Lbl_disliked);
                        holder.DislikeTextView.SetTextColor(Color.ParseColor("#f89823"));
                        holder.DislikeTextView.Tag = "Disliked";
                        break;
                    }

                    case PostButtonSystem.DisLike:
                    {
                        holder.DislikeTextView.Text = ActivityContext.GetString(Resource.String.Btn_Dislike);
                        holder.DislikeTextView.SetTextColor(AppSettings.SetTabDarkTheme ? Color.White : Color.Black);
                        holder.DislikeTextView.Tag = "Dislike";
                        break;
                    }
                    }
                }
                else
                {
                    if (item.IsCommentLiked)
                    {
                        holder.LikeTextView.Text = ActivityContext.GetText(Resource.String.Btn_Liked);
                        holder.LikeTextView.SetTextColor(Color.ParseColor(AppSettings.MainColor));
                        holder.LikeTextView.Tag = "Liked";
                    }
                    else
                    {
                        holder.LikeTextView.Text = ActivityContext.GetText(Resource.String.Btn_Like);
                        holder.LikeTextView.SetTextColor(AppSettings.SetTabDarkTheme ? Color.White : Color.Black);
                        holder.LikeTextView.Tag = "Like";
                    }
                }

                holder.TimeTextView.Tag = "true";
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #11
0
        private void OnFileBoundServiceResult(string action)
        {
            //http://stackoverflow.com/questions/2197741/how-can-i-send-emails-from-my-android-application

            try
            {
                if (!_isBound)
                {
                    return;
                }

                var service = _binder.Service as FileBoundService;
                if (service == null)
                {
                    return;
                }

                if (service.ServiceExceptions != null && service.ServiceExceptions.ContainsKey(action))
                {
                    var exception = service.ServiceExceptions[action];
                    if (exception != null)
                    {
                        ShowError(exception, Resource.String.InternalError);
                        return;
                    }
                }

                if (service.Result != Result.Ok)
                {
                    return;
                }

                Intent activityIntent;
                var    requestCode = 0;

                switch (action)
                {
                case FileBoundService.ActionFeedback:
                    var emailIntent = new Intent(Intent.ActionSend);
                    //emailIntent.SetData(Uri.Parse("mailto:" + GetString(Resource.String.FeedbackMail)));
                    emailIntent.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.FeedbackMail) });
                    var applicationName = GetString(Resource.String.ApplicationName);
                    emailIntent.PutExtra(Intent.ExtraSubject,
                                         string.Format("{0} ver. {1}", applicationName, _version));
                    var bodytext = string.Format("Model: {0}{1}OS: {2}{1}Application: {3}", AndroidUtil.GetDeviceName(),
                                                 System.Environment.NewLine, AndroidUtil.GetAndroidVersion(),
                                                 string.Format("{0} ver. {1}", applicationName, _versionFull));

                    var intentType = "text/plain; charset=UTF-8;";

                    var zipFile = new Java.IO.File(_compressFileName);
                    if (zipFile.Exists())
                    {
                        //emailIntent.SetType("application/zip");
                        intentType += " " + MimeTypeZip;
                        var uri = FileProvider.GetUriForFile(this,
                                                             Application.Context.PackageName + ".FileProvider", zipFile);
                        //emailIntent.PutExtra(Intent.ExtraStream, Uri.Parse("file://" + _compressFileName));
                        emailIntent.PutExtra(Intent.ExtraStream, uri);
                    }
                    else
                    {
                        //throw new FileNotFoundException(string.Format("File '{0}' not found.", _compressFileName));
                        bodytext += string.Format("{0}No log-file (logToFile: {1})", System.Environment.NewLine,
                                                  AppSettings.Default.LoggingUseFile);
                    }

                    emailIntent.SetType(intentType);
                    emailIntent.PutExtra(Intent.ExtraText, bodytext);

                    activityIntent =
                        Intent.CreateChooser(emailIntent, GetString(Resource.String.EmailChooserTitle));
                    break;

                case FileBoundService.ActionZipLogFiles:
                    activityIntent = new Intent(Intent.ActionCreateDocument);
                    activityIntent.AddCategory(Intent.CategoryOpenable);
                    activityIntent.SetType(MimeTypeZip);
                    var title = Path.GetFileName(_compressFileName)?.ToLower();
                    if (!string.IsNullOrEmpty(title))
                    {
                        activityIntent.PutExtra(Intent.ExtraTitle, title);
                    }
                    requestCode = RequestCodeExportLog;
                    break;

                case FileBoundService.ActionExportLog:
                    return;

                default:
                    throw new NotImplementedException(action);
                }

                if (activityIntent != null)
                {
                    StartActivityForResult(activityIntent, requestCode);
                }
            }
            catch (ActivityNotFoundException ex)
            {
                ShowError(ex, Resource.String.NoEmailClientsInstalled);
            }
            catch (Exception ex)
            {
                ShowError(ex, Resource.String.InternalError);
            }
            finally
            {
                ShowProgressbar(false);
            }
        }
Пример #12
0
        //Result
        public override async void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            try
            {
                base.OnActivityResult(requestCode, resultCode, data);
                if (requestCode == 108 || requestCode == CropImage.CropImageActivityRequestCode)
                {
                    if (Methods.CheckConnectivity())
                    {
                        var result = CropImage.GetActivityResult(data);

                        if (result.IsSuccessful)
                        {
                            var resultPathImage = result.Uri.Path;

                            if (!string.IsNullOrEmpty(resultPathImage))
                            {
                                Java.IO.File file2    = new Java.IO.File(resultPathImage);
                                var          photoUri = FileProvider.GetUriForFile(Activity, Activity.PackageName + ".fileprovider", file2);

                                GlideImageLoader.LoadImage(Activity, photoUri.Path, UserProfileImage, ImageStyle.CircleCrop, ImagePlaceholders.Drawable);

                                var dataUser = ListUtils.MyProfileList.FirstOrDefault();
                                if (dataUser != null)
                                {
                                    dataUser.Avatar    = resultPathImage;
                                    UserDetails.Avatar = resultPathImage;

                                    SqLiteDatabase dbDatabase = new SqLiteDatabase();
                                    dbDatabase.InsertOrUpdateToMyProfileTable(dataUser);
                                    dbDatabase.Dispose();
                                }

                                var dataStory = GlobalContext.NewsFeedFragment.StoryAdapter?.StoryList?.FirstOrDefault(a => a.Type == "Your");
                                if (dataStory != null)
                                {
                                    dataStory.Avatar = resultPathImage;
                                    GlobalContext.NewsFeedFragment.StoryAdapter.NotifyItemChanged(0);
                                }

                                await Task.Run(async() =>
                                {
                                    (int apiStatus, var respond) = await RequestsAsync.User.SaveImageUser(resultPathImage).ConfigureAwait(false);
                                });
                            }
                            else
                            {
                                Toast.MakeText(Activity, Activity.GetText(Resource.String.Lbl_something_went_wrong), ToastLength.Long).Show();
                            }
                        }
                        else
                        {
                            Toast.MakeText(Activity, Activity.GetText(Resource.String.Lbl_something_went_wrong), ToastLength.Long).Show();
                        }
                    }
                    else
                    {
                        Toast.MakeText(Activity, Activity.GetText(Resource.String.Lbl_CheckYourInternetConnection), ToastLength.Long).Show();
                    }
                }
                else if (requestCode == 3000)
                {
                    LoadProfile();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #13
0
        private void LoadAudioItem(CommentAdapterViewHolder soundViewHolder, int position, CommentObjectExtra item)
        {
            try
            {
                item.SoundViewHolder ??= soundViewHolder;

                soundViewHolder.VoiceLayout.Visibility = ViewStates.Visible;

                var fileName = item.Record.Split('/').Last();

                var mediaFile = WoWonderTools.GetFile(item.PostId, Methods.Path.FolderDcimSound, fileName, item.Record);
                soundViewHolder.DurationVoice.Text = string.IsNullOrEmpty(item.MediaDuration)
                    ? Methods.AudioRecorderAndPlayer.GetTimeString(Methods.AudioRecorderAndPlayer.Get_MediaFileDuration(mediaFile))
                    : item.MediaDuration;

                soundViewHolder.PlayButton.Visibility = ViewStates.Visible;

                if (!soundViewHolder.PlayButton.HasOnClickListeners)
                {
                    soundViewHolder.PlayButton.Click += (o, args) =>
                    {
                        try
                        {
                            if (PositionSound != position)
                            {
                                var list = CommentList.Where(a => a.MediaPlayer != null).ToList();
                                if (list.Count > 0)
                                {
                                    foreach (var extra in list)
                                    {
                                        if (extra.MediaPlayer != null)
                                        {
                                            extra.MediaPlayer.Stop();
                                            extra.MediaPlayer.Reset();
                                        }
                                        extra.MediaPlayer = null;
                                        extra.MediaTimer  = null;

                                        extra.MediaPlayer?.Release();
                                        extra.MediaPlayer = null;
                                    }
                                }
                            }

                            if (mediaFile.Contains("http"))
                            {
                                mediaFile = WoWonderTools.GetFile(item.PostId, Methods.Path.FolderDcimSound, fileName, item.Record);
                            }

                            if (item.MediaPlayer == null)
                            {
                                PositionSound    = position;
                                item.MediaPlayer = new Android.Media.MediaPlayer();
                                item.MediaPlayer.SetAudioAttributes(new AudioAttributes.Builder().SetUsage(AudioUsageKind.Media).SetContentType(AudioContentType.Music).Build());

                                item.MediaPlayer.Completion += (sender, e) =>
                                {
                                    try
                                    {
                                        soundViewHolder.PlayButton.Tag = "Play";
                                        //soundViewHolder.PlayButton.SetImageResource(item.ModelType == MessageModelType.LeftAudio ? Resource.Drawable.ic_play_dark_arrow : Resource.Drawable.ic_play_arrow);
                                        soundViewHolder.PlayButton.SetImageResource(Resource.Drawable.ic_play_dark_arrow);

                                        item.MediaIsPlaying = false;

                                        item.MediaPlayer.Stop();
                                        item.MediaPlayer.Reset();
                                        item.MediaPlayer = null;

                                        item.MediaTimer.Enabled = false;
                                        item.MediaTimer.Stop();
                                        item.MediaTimer = null;
                                    }
                                    catch (Exception exception)
                                    {
                                        Console.WriteLine(exception);
                                    }
                                };

                                item.MediaPlayer.Prepared += (s, ee) =>
                                {
                                    try
                                    {
                                        item.MediaIsPlaying            = true;
                                        soundViewHolder.PlayButton.Tag = "Pause";
                                        soundViewHolder.PlayButton.SetImageResource(AppSettings.SetTabDarkTheme ? Resource.Drawable.ic_media_pause_light : Resource.Drawable.ic_media_pause_dark);

                                        if (item.MediaTimer == null)
                                        {
                                            item.MediaTimer = new Timer {
                                                Interval = 1000
                                            }
                                        }
                                        ;

                                        item.MediaPlayer.Start();

                                        //var durationOfSound = item.MediaPlayer.Duration;

                                        item.MediaTimer.Elapsed += (sender, eventArgs) =>
                                        {
                                            ActivityContext.RunOnUiThread(() =>
                                            {
                                                try
                                                {
                                                    if (item.MediaTimer.Enabled)
                                                    {
                                                        if (item.MediaPlayer.CurrentPosition <= item.MediaPlayer.Duration)
                                                        {
                                                            soundViewHolder.DurationVoice.Text = Methods.AudioRecorderAndPlayer.GetTimeString(item.MediaPlayer.CurrentPosition);
                                                        }
                                                        else
                                                        {
                                                            soundViewHolder.DurationVoice.Text = Methods.AudioRecorderAndPlayer.GetTimeString(item.MediaPlayer.Duration);

                                                            soundViewHolder.PlayButton.Tag = "Play";
                                                            //soundViewHolder.PlayButton.SetImageResource(item.ModelType == MessageModelType.LeftAudio ? Resource.Drawable.ic_play_dark_arrow : Resource.Drawable.ic_play_arrow);
                                                            soundViewHolder.PlayButton.SetImageResource(Resource.Drawable.ic_play_dark_arrow);
                                                        }
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    Console.WriteLine(e);
                                                    soundViewHolder.PlayButton.Tag = "Play";
                                                }
                                            });
                                        };
                                        item.MediaTimer.Start();
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine(e);
                                    }
                                };

                                if (mediaFile.Contains("http"))
                                {
                                    item.MediaPlayer.SetDataSource(ActivityContext, Uri.Parse(mediaFile));
                                    item.MediaPlayer.PrepareAsync();
                                }
                                else
                                {
                                    File file2    = new File(mediaFile);
                                    var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);

                                    item.MediaPlayer.SetDataSource(ActivityContext, photoUri);
                                    item.MediaPlayer.Prepare();
                                }

                                item.SoundViewHolder = soundViewHolder;
                            }
                            else
                            {
                                if (soundViewHolder.PlayButton.Tag.ToString() == "Play")
                                {
                                    soundViewHolder.PlayButton.Tag = "Pause";
                                    soundViewHolder.PlayButton.SetImageResource(AppSettings.SetTabDarkTheme ? Resource.Drawable.ic_media_pause_light : Resource.Drawable.ic_media_pause_dark);

                                    item.MediaIsPlaying = true;
                                    item.MediaPlayer?.Start();

                                    if (item.MediaTimer != null)
                                    {
                                        item.MediaTimer.Enabled = true;
                                        item.MediaTimer.Start();
                                    }
                                }
                                else if (soundViewHolder.PlayButton.Tag.ToString() == "Pause")
                                {
                                    soundViewHolder.PlayButton.Tag = "Play";
                                    //soundViewHolder.PlayButton.SetImageResource(item.ModelType == MessageModelType.LeftAudio ? Resource.Drawable.ic_play_dark_arrow : Resource.Drawable.ic_play_arrow);
                                    soundViewHolder.PlayButton.SetImageResource(Resource.Drawable.ic_play_dark_arrow);

                                    item.MediaIsPlaying = false;
                                    item.MediaPlayer?.Pause();

                                    if (item.MediaTimer != null)
                                    {
                                        item.MediaTimer.Enabled = false;
                                        item.MediaTimer.Stop();
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    };
                }

                item.SoundViewHolder ??= soundViewHolder;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #14
0
 public FileIO(FileProvider fileProvider)
 {
     FileProvider = fileProvider;
 }
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FileSystem"/> class.
 /// </summary>
 public FileSystem()
 {
     File      = new FileProvider();
     Directory = new DirectoryProvider();
 }
Пример #16
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Context = new LiteIDContext();

            Uri PackedDocURI;

            if (Intent.HasExtra("PackedDocURI"))
            {
                PackedDocURI = (Uri)Intent.GetParcelableExtra("PackedDocURI");
            }
            else if (Intent.Data != null)
            {
                PackedDocURI = Intent.Data;
            }
            else
            {
                Android.Util.Log.Error("liteid-import", "No valid URI in intent!");
                Finish();
                return;
            }

            Stream PackedDocStream = ContentResolver.OpenInputStream(PackedDocURI);

            CurrentDoc = Document.ImportDocument(PackedDocStream);


            SetContentView(Resource.Layout.ImportDoc);
            TextView docTitle = FindViewById <TextView>(Resource.Id.docTitle);

            docTitle.Text = CurrentDoc.Name;
            TextView docDate = FindViewById <TextView>(Resource.Id.docDate);

            docDate.Text = "Added to blockchain on: " + CurrentDoc.IngestionTime.ToLongDateString();

            if (CurrentDoc.TextDoc)
            {
                LinearLayout modeText = FindViewById <LinearLayout>(Resource.Id.modeText);
                modeText.Visibility = ViewStates.Visible;
                TextView docContent = FindViewById <TextView>(Resource.Id.docContent);
                docContent.Text = CurrentDoc.GetTextContent();
            }
            else
            {
                LinearLayout modeFile = FindViewById <LinearLayout>(Resource.Id.modeFile);
                modeFile.Visibility = ViewStates.Visible;
                TextView docType = FindViewById <TextView>(Resource.Id.docType);
                docType.Text = "Type: " + CurrentDoc.MimeType;
                Button buttonOpen = FindViewById <Button>(Resource.Id.buttonOpen);

                buttonOpen.Click += delegate
                {
                    string       path       = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    string       filename   = Path.Combine(path, "import/" + CurrentDoc.ID);
                    Java.IO.File outfile    = new Java.IO.File(filename);
                    Uri          extURI     = FileProvider.GetUriForFile(ApplicationContext, "org.LiteID.fileprovider", outfile);
                    Intent       viewIntent = new Intent(Intent.ActionView);
                    viewIntent.SetDataAndType(extURI, CurrentDoc.MimeType);
                    viewIntent.AddFlags(ActivityFlags.NewTask);
                    viewIntent.SetFlags(ActivityFlags.GrantReadUriPermission);

                    if (viewIntent.ResolveActivity(ApplicationContext.PackageManager) != null)
                    {
                        StartActivity(viewIntent);
                    }
                    else
                    {
                        Toast.MakeText(this.ApplicationContext, "You don't have any apps that can open this.", ToastLength.Long).Show();
                    }
                };
            }

            TextView textOriginID = FindViewById <TextView>(Resource.Id.textOriginID);

            if (CurrentDoc.OriginID == Context.Config.BlockchainID)
            {
                textOriginID.Text = "0x" + LiteIDContext.BytesToHex(CurrentDoc.OriginID) + " (You)";
            }
            else
            {
                textOriginID.Text = "0x" + LiteIDContext.BytesToHex(CurrentDoc.OriginID);
            }

            Button buttonVerify  = FindViewById <Button>(Resource.Id.buttonVerify);
            Button buttonSave    = FindViewById <Button>(Resource.Id.buttonSave);
            Button buttonDiscard = FindViewById <Button>(Resource.Id.buttonDiscard);

            buttonVerify.Click += delegate
            {
                //TODO: Implement this
                Toast.MakeText(this.ApplicationContext, "Verified", ToastLength.Long).Show();
            };

            buttonSave.Click += delegate
            {
                string path        = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                string docImported = Path.Combine(path, "import/" + CurrentDoc.ID);
                string docFinal    = Path.Combine(path, CurrentDoc.ID);
                if (File.Exists(docFinal))
                {
                    Toast.MakeText(this.ApplicationContext, "You already have this document.", ToastLength.Long).Show();
                }
                else
                {
                    File.Move(docImported, docFinal);
                    Context.DocStore.Documents.Add(CurrentDoc);
                    Context.DocStore.SaveList(Context.DocStoreFile);
                }
                Finish();
            };

            buttonDiscard.Click += delegate
            {
                new AlertDialog.Builder(this)
                .SetIcon(Android.Resource.Drawable.IcDialogAlert)
                .SetTitle("Delete File")
                .SetMessage("Are you sure you want to discard this document? You can import it again later.")
                .SetPositiveButton("Yes", delegate
                {
                    string path     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    string filename = Path.Combine(path, "import/" + CurrentDoc.ID);
                    File.Delete(filename);
                    Finish();
                })
                .SetNegativeButton("No", delegate { })
                .Show();
            };
        }
Пример #17
0
        private void SerializeObject(Queue <SerializeOperation> serializeOperations, string url, object obj, bool publicReference)
        {
            // Don't create context in case we don't want to serialize referenced objects
            //if (!SerializeReferencedObjects && obj != RootObject)
            //    return null;

            // Already saved?
            // TODO: Ref counting? Should we change it on save? Probably depends if we cache or not.
            if (LoadedAssetReferences.ContainsKey(obj))
            {
                return;
            }

            var serializer = Serializer.GetSerializer(null, obj.GetType());

            if (serializer == null)
            {
                throw new InvalidOperationException(string.Format("Content serializer for {0} could not be found.", obj.GetType()));
            }

            var contentSerializerContext = new ContentSerializerContext(url, ArchiveMode.Serialize, this);

            using (var stream = FileProvider.OpenStream(url, VirtualFileMode.Create, VirtualFileAccess.Write))
            {
                var streamWriter = new BinarySerializationWriter(stream);
                PrepareSerializerContext(contentSerializerContext, streamWriter.Context);

                ChunkHeader header = null;

                // Allocate space in the stream, and also include header version in the hash computation, which is better
                // If serialization type is null, it means there should be no header.
                var serializationType = serializer.SerializationType;
                if (serializationType != null)
                {
                    header      = new ChunkHeader();
                    header.Type = serializer.SerializationType.AssemblyQualifiedName;
                    header.Write(streamWriter);
                    header.OffsetToObject = (int)streamWriter.NativeStream.Position;
                }

                contentSerializerContext.SerializeContent(streamWriter, serializer, obj);

                // Write references and updated header
                if (header != null)
                {
                    header.OffsetToReferences = (int)streamWriter.NativeStream.Position;
                    contentSerializerContext.SerializeReferences(streamWriter);

                    // Move back to the pre-allocated header position in the steam
                    stream.Seek(0, SeekOrigin.Begin);

                    // Write actual header.
                    header.Write(new BinarySerializationWriter(stream));
                }
            }

            var assetReference = new AssetReference(url, publicReference);

            contentSerializerContext.AssetReference = assetReference;
            SetAssetObject(assetReference, obj);

            // Process content references
            // TODO: Should we work at ChunkReference level?
            foreach (var contentReference in contentSerializerContext.ContentReferences)
            {
                if (contentReference.ObjectValue != null)
                {
                    var attachedReference = AttachedReferenceManager.GetAttachedReference(contentReference.ObjectValue);
                    if (attachedReference == null || attachedReference.IsProxy)
                    {
                        continue;
                    }

                    serializeOperations.Enqueue(new SerializeOperation(contentReference.Location, contentReference.ObjectValue, false));
                }
            }
        }
 bool IEquatable <NormalizedPath> .Equals(NormalizedPath other) =>
 other != null &&
 FileProvider?.ToString() == other.FileProvider?.ToString() &&
 FullPath == other.FullPath;
        private void MAdapterOnItemClick(object sender, Holders.MesClickEventArgs e)
        {
            try
            {
                if (e.Position <= -1)
                {
                    return;
                }
                var item = MAdapter.GetItem(e.Position);
                if (item != null)
                {
                    switch (e.Type)
                    {
                    case Holders.TypeClick.Text:
                    case Holders.TypeClick.Contact:
                        item.MesData.ShowTimeText = !item.MesData.ShowTimeText;
                        MAdapter.NotifyItemChanged(MAdapter.DifferList.IndexOf(item));
                        break;

                    case Holders.TypeClick.File:
                    {
                        var    fileName  = item.MesData.Media.Split('/').Last();
                        string imageFile = Methods.MultiMedia.CheckFileIfExits(item.MesData.Media);
                        if (imageFile != "File Dont Exists")
                        {
                            try
                            {
                                var    extension = fileName.Split('.').Last();
                                string mimeType  = MimeTypeMap.GetMimeType(extension);

                                Intent openFile = new Intent();
                                openFile.SetFlags(ActivityFlags.NewTask);
                                openFile.SetFlags(ActivityFlags.GrantReadUriPermission);
                                openFile.SetAction(Intent.ActionView);
                                openFile.SetDataAndType(Uri.Parse(imageFile), mimeType);
                                StartActivity(openFile);
                            }
                            catch (Exception exception)
                            {
                                Methods.DisplayReportResultTrack(exception);
                            }
                        }
                        else
                        {
                            var    extension = fileName.Split('.').Last();
                            string mimeType  = MimeTypeMap.GetMimeType(extension);

                            Intent i = new Intent(Intent.ActionView);
                            i.SetData(Uri.Parse(item.MesData.Media));
                            i.SetType(mimeType);
                            StartActivity(i);
                            // Toast.MakeText(MainActivity, MainActivity.GetText(Resource.String.Lbl_something_went_wrong), ToastLength.Long)?.Show();
                        }

                        break;
                    }

                    case Holders.TypeClick.Video:
                    {
                        var fileName  = item.MesData.Media.Split('/').Last();
                        var mediaFile = WoWonderTools.GetFile(UserId, Methods.Path.FolderDcimVideo, fileName, item.MesData.Media);

                        string imageFile = Methods.MultiMedia.CheckFileIfExits(mediaFile);
                        if (imageFile != "File Dont Exists")
                        {
                            File file2    = new File(mediaFile);
                            var  mediaUri = FileProvider.GetUriForFile(this, PackageName + ".fileprovider", file2);

                            if (AppSettings.OpenVideoFromApp)
                            {
                                Intent intent = new Intent(this, typeof(VideoFullScreenActivity));
                                intent.PutExtra("videoUrl", mediaUri.ToString());
                                StartActivity(intent);
                            }
                            else
                            {
                                Intent intent = new Intent();
                                intent.SetAction(Intent.ActionView);
                                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                                intent.SetDataAndType(mediaUri, "video/*");
                                StartActivity(intent);
                            }
                        }
                        else
                        {
                            if (AppSettings.OpenVideoFromApp)
                            {
                                Intent intent = new Intent(this, typeof(VideoFullScreenActivity));
                                intent.PutExtra("videoUrl", item.MesData.Media);
                                StartActivity(intent);
                            }
                            else
                            {
                                Intent intent = new Intent(Intent.ActionView, Uri.Parse(item.MesData.Media));
                                StartActivity(intent);
                            }
                        }

                        break;
                    }

                    case Holders.TypeClick.Image:
                    {
                        if (AppSettings.OpenImageFromApp)
                        {
                            Intent intent = new Intent(this, typeof(ImageViewerActivity));
                            intent.PutExtra("Id", UserId);
                            intent.PutExtra("SelectedItem", JsonConvert.SerializeObject(item.MesData));
                            StartActivity(intent);
                        }
                        else
                        {
                            var fileName  = item.MesData.Media.Split('/').Last();
                            var mediaFile = WoWonderTools.GetFile(UserId, Methods.Path.FolderDcimImage, fileName, item.MesData.Media);

                            string imageFile = Methods.MultiMedia.CheckFileIfExits(mediaFile);
                            if (imageFile != "File Dont Exists")
                            {
                                File file2    = new File(mediaFile);
                                var  photoUri = FileProvider.GetUriForFile(this, PackageName + ".fileprovider", file2);

                                Intent intent = new Intent();
                                intent.SetAction(Intent.ActionView);
                                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                                intent.SetDataAndType(photoUri, "image/*");
                                StartActivity(intent);
                            }
                            else
                            {
                                Intent intent = new Intent(Intent.ActionView, Uri.Parse(mediaFile));
                                StartActivity(intent);
                            }
                        }

                        break;
                    }

                    case Holders.TypeClick.Map:
                    {
                        // Create a Uri from an intent string. Use the result to create an Intent.
                        var uri    = Uri.Parse("geo:" + item.MesData.Lat + "," + item.MesData.Lng);
                        var intent = new Intent(Intent.ActionView, uri);
                        intent.SetPackage("com.google.android.apps.maps");
                        intent.AddFlags(ActivityFlags.NewTask);
                        StartActivity(intent);
                        break;
                    }
                    }
                }
            }
            catch (Exception exception)
            {
                Methods.DisplayReportResultTrack(exception);
            }
        }
Пример #20
0
            public void setup()
            {
                fileName = Path.Combine(cacheDir, cacheFileName);

                if (File.Exists(fileName))
                    File.Delete(fileName);

                _provider = new FileProvider(cacheDir, cacheFileName);
            }
        public static void LoadImage(Activity activity, string imageUri, ImageView image, ImageStyle style, ImagePlaceholders imagePlaceholders, bool compress = false, RequestOptions options = null)
        {
            try
            {
                if (string.IsNullOrEmpty(imageUri) || string.IsNullOrWhiteSpace(imageUri) || image == null || activity?.IsDestroyed != false)
                {
                    return;
                }

                imageUri = imageUri.Replace(" ", "");

                var newImage = Glide.With(activity);

                options ??= GetOptions(style, imagePlaceholders);

                switch (compress)
                {
                case true when style != ImageStyle.RoundedCrop:
                {
                    if (imageUri.Contains("avatar") || imageUri.Contains("Avatar"))
                    {
                        options.Override(AppSettings.AvatarPostSize);
                    }
                    else if (imageUri.Contains("gif"))
                    {
                        options.Override(AppSettings.ImagePostSize);
                    }
                    else
                    {
                        options.Override(AppSettings.ImagePostSize);
                    }
                    break;
                }
                }

                switch (compress)
                {
                case true:
                    options.Override(AppSettings.ImagePostSize);
                    break;
                }

                if (imageUri.Contains("no_profile_image") || imageUri.Contains("blackdefault") || imageUri.Contains("no_profile_image_circle") ||
                    imageUri.Contains("ImagePlacholder") || imageUri.Contains("ImagePlacholder_circle") || imageUri.Contains("Grey_Offline") ||
                    imageUri.Contains("Image_File") || imageUri.Contains("Audio_File") || imageUri.Contains("addImage") || imageUri.Contains("d-group") ||
                    imageUri.Contains("d-cover") || imageUri.Contains("d-avatar") || imageUri.Contains("user_anonymous"))
                {
                    if (imageUri.Contains("no_profile_image_circle"))
                    {
                        newImage.Load(Resource.Drawable.no_profile_image_circle).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("no_profile_image") || imageUri.Contains("d-avatar"))
                    {
                        newImage.Load(Resource.Drawable.no_profile_image).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("ImagePlacholder"))
                    {
                        newImage.Load(Resource.Drawable.ImagePlacholder).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("ImagePlacholder_circle"))
                    {
                        newImage.Load(Resource.Drawable.ImagePlacholder_circle).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("blackdefault"))
                    {
                        newImage.Load(Resource.Drawable.blackdefault).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("Grey_Offline"))
                    {
                        newImage.Load(Resource.Drawable.Grey_Offline).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("Image_File"))
                    {
                        newImage.Load(Resource.Drawable.Image_File).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("Audio_File"))
                    {
                        newImage.Load(Resource.Drawable.Audio_File).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("addImage"))
                    {
                        newImage.Load(Resource.Drawable.addImage).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("d-group"))
                    {
                        newImage.Load(Resource.Drawable.default_group).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("d-page"))
                    {
                        newImage.Load(Resource.Drawable.default_page).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("d-cover"))
                    {
                        newImage.Load(Resource.Drawable.Cover_image).Apply(options).Into(image);
                    }
                    else if (imageUri.Contains("user_anonymous"))
                    {
                        newImage.Load(Resource.Drawable.user_anonymous).Apply(options).Into(image);
                    }
                }
                else
                {
                    switch (string.IsNullOrEmpty(imageUri))
                    {
                    case false when imageUri.Contains("http"):
                        newImage.Load(imageUri).Apply(options).Into(image);

                        break;

                    case false when imageUri.Contains("file://") || imageUri.Contains("content://") || imageUri.Contains("storage") || imageUri.Contains("/data/user/0/"):
                    {
                        File           file2    = new File(imageUri);
                        var            photoUri = FileProvider.GetUriForFile(activity, activity.PackageName + ".fileprovider", file2);
                        RequestOptions option   = style == ImageStyle.CircleCrop ? new RequestOptions().CircleCrop() : new RequestOptions();
                        Glide.With(activity).Load(photoUri).Apply(option).Into(image);
                        break;
                    }

                    default:
                        newImage.Load(Resource.Drawable.no_profile_image).Apply(options).Into(image);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
Пример #22
0
        /// <summary>
        /// Builds an entire solution.
        /// When more than one project in a solution, all projects gets build into the same WSP package.
        /// </summary>
        public void BuildSolution()
        {
            Dictionary <string, AssemblyInfo> assembliesFound = new Dictionary <string, AssemblyInfo>(StringComparer.InvariantCultureIgnoreCase);

            if (!Config.Current.BuildSolution)
            {
                // Set the Project path to the solution path
                //Config.Current.ProjectPath = Config.Current.SolutionPath;
                BuildProject(assembliesFound);
            }
            else
            {
                DirectoryInfo solutionDir = new DirectoryInfo(Config.Current.SolutionPath);
                foreach (DirectoryInfo dir in FileProvider.GetDirectories(solutionDir))
                {
                    // Reinitialize the Config object to ensure that its clean.
                    //Config.Current.ReInitialize();
                    Config.Current.ProjectPath = dir.FullName;

                    BuildProject(assembliesFound);
                }
                Config.Current.ProjectPath = Config.Current.SolutionPath;
            }

            SetWSS40SolutionProperties(this.Solution);

            // Create AssemblyFileReferences, add CodeGroups and CodeAccessSecurity
            this.Solution.Assemblies = BuildAssemblyFileReference(assembliesFound);

            // Add the CAS policy, if enabled
            if (Config.Current.BuildCAS)
            {
                this.Solution.CodeAccessSecurity = AppendArray <PolicyItemDefinition>(this.Solution.CodeAccessSecurity, BuildPolicyItemDefinition());
            }


            string compatibilityNote = null;

            if (this.IsWSS40)
            {
                compatibilityNote = "Solution compatibility: SharePoint 2010";
            }
            else
            {
                compatibilityNote = "Solution compatibility: SharePoint 2007 and SharePoint 2010";
            }

            // Create the wsp manifest file
            this.ManifestContent = Serializer.ObjectToXML(this.Solution, this.IsWSS40);

            // Add a note
            int index = this.ManifestContent.IndexOf("\r\n");

            if (index > 0)
            {
                this.ManifestContent = this.ManifestContent.Insert(index, "<!-- Solution created by WSPBuilder. " + DateTime.Now.ToString() + " * " + compatibilityNote + " -->");
            }

            if (Config.Current.BuildCAS)
            {
                // Apply the permissions to the PolicyItemDefinitions
                // This happens here after the serialization, because the wsp shema definition
                // do not implement the IPermission object in a useful way.
                // This is the last solution to the problem I wanted to implement, but the only
                // one I was able to get to work properly.
                this.ManifestContent = ApplyPolicyPermissions(this.ManifestContent);
            }

            // Replace tokens in files with the Replacement Parameters.
            CreateFilesWithReplacementParameters();

            Log.Information(compatibilityNote);
        }
Пример #23
0
 public override async Task <bool> Exists(string id, CancellationToken cancellationToken = default)
 {
     return(await(await FileProvider.GetFileInfo(GetPath(id))).Exists());
 }
 public static ParsingState TryParse(FileProvider fileProvider, out LocalStorage localStorage, bool minimizeFileIo = false)
 => TryParse(fileProvider, null, out localStorage, minimizeFileIo);
Пример #25
0
        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
        {
            try
            {
                if (viewHolder is HSharedFilesAdapterViewHolder holder)
                {
                    var item = SharedFilesList[position];
                    if (item == null)
                    {
                        return;
                    }
                    switch (item.FileType)
                    {
                    case "Video":
                    {
                        var fileName = item.FilePath.Split('/').Last();
                        var fileNameWithoutExtension = fileName.Split('.').First();

                        FontUtils.SetTextViewIcon(FontsIconFrameWork.IonIcons, holder.PlayIcon, IonIconsFonts.Play);
                        holder.PlayIcon.Visibility = ViewStates.Visible;

                        FontUtils.SetTextViewIcon(FontsIconFrameWork.IonIcons, holder.TypeIcon, IonIconsFonts.Videocamera);
                        holder.TypeIcon.Visibility = ViewStates.Visible;

                        var videoPlaceHolderImage = Methods.MultiMedia.GetMediaFrom_Gallery(Methods.Path.FolderDcimVideo + "/" + UserId, fileNameWithoutExtension + ".png");
                        if (videoPlaceHolderImage == "File Dont Exists")
                        {
                            var bitmapImage = Methods.MultiMedia.Retrieve_VideoFrame_AsBitmap(ActivityContext, item.FilePath);
                            Methods.MultiMedia.Export_Bitmap_As_Image(bitmapImage, fileNameWithoutExtension, Methods.Path.FolderDcimVideo + "/" + UserId);

                            var imageVideo = Methods.Path.FolderDcimVideo + "/" + UserId + "/" + fileNameWithoutExtension + ".png";

                            File file2    = new File(imageVideo);
                            var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                            Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.Image);
                        }
                        else
                        {
                            File file2    = new File(videoPlaceHolderImage);
                            var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                            Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.Image);
                        }

                        break;
                    }

                    case "Gif":
                    {
                        holder.TypeIcon.Text = ActivityContext.GetText(Resource.String.Lbl_Gif);
                        FontUtils.SetFont(holder.TypeIcon, Fonts.SfSemibold);

                        holder.PlayIcon.Visibility = ViewStates.Gone;
                        holder.TypeIcon.Visibility = ViewStates.Visible;

                        File file2    = new File(item.FilePath);
                        var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                        Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.Image);
                        break;
                    }

                    case "Sticker":
                    {
                        holder.PlayIcon.Visibility = ViewStates.Gone;
                        holder.TypeIcon.Visibility = ViewStates.Gone;

                        File file2    = new File(item.FilePath);
                        var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                        Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.Image);
                        break;
                    }

                    case "Image":
                    {
                        holder.PlayIcon.Visibility = ViewStates.Gone;
                        holder.TypeIcon.Visibility = ViewStates.Gone;

                        File file2    = new File(item.FilePath);
                        var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                        Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.Image);
                        break;
                    }

                    case "Sounds":
                        holder.PlayIcon.Visibility = ViewStates.Gone;
                        holder.TypeIcon.Visibility = ViewStates.Gone;

                        Glide.With(ActivityContext).Load(ActivityContext.GetDrawable(Resource.Drawable.Audio_File)).Apply(new RequestOptions()).Into(holder.Image);
                        break;

                    case "File":
                        holder.PlayIcon.Visibility = ViewStates.Gone;
                        holder.TypeIcon.Visibility = ViewStates.Gone;

                        Glide.With(ActivityContext).Load(ActivityContext.GetDrawable(Resource.Drawable.Image_File)).Apply(new RequestOptions()).Into(holder.Image);
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Пример #26
0
        /// <summary>
        /// OnCreate
        /// </summary>
        /// <param name="savedInstanceState"></param>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Bundle b = (savedInstanceState ?? Intent.Extras);

            bool ran = b.GetBoolean("ran", defaultValue: false);

            this.title       = b.GetString(MediaStore.MediaColumns.Title);
            this.description = b.GetString(MediaStore.Images.ImageColumns.Description);

            this.tasked = b.GetBoolean(ExtraTasked);
            this.id     = b.GetInt(ExtraId, 0);
            this.type   = b.GetString(ExtraType);
            this.front  = b.GetInt(ExtraFront);
            if (this.type == "image/*")
            {
                this.isPhoto = true;
            }

            this.action = b.GetString(ExtraAction);
            Intent pickIntent = null;

            try
            {
                pickIntent = new Intent(this.action);
                if (this.action == Intent.ActionPick)
                {
                    pickIntent.SetType(type);
                }
                else
                {
                    if (!this.isPhoto)
                    {
                        this.seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0);
                        if (this.seconds != 0)
                        {
                            pickIntent.PutExtra(MediaStore.ExtraDurationLimit, seconds);
                        }
                    }

                    this.saveToAlbum = b.GetBoolean(ExtraSaveToAlbum);
                    pickIntent.PutExtra(ExtraSaveToAlbum, this.saveToAlbum);

                    this.quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High);
                    pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(this.quality));

                    if (front != 0)
                    {
                        pickIntent.PutExtra(ExtraFront, (int)Android.Hardware.CameraFacing.Front);
                    }

                    if (!ran)
                    {
                        this.path = GetOutputMediaFile(this, b.GetString(ExtraPath), this.title, this.isPhoto, false);

                        Touch();

                        var targetsNOrNewer = false;

                        try
                        {
                            targetsNOrNewer = (int)Application.Context.ApplicationInfo.TargetSdkVersion >= 24;
                        }
                        catch (Exception appInfoEx)
                        {
                            System.Diagnostics.Debug.WriteLine("Unable to get application info for targetSDK, trying to get from package manager: " + appInfoEx);
                            targetsNOrNewer = false;

                            var appInfo = PackageManager.GetApplicationInfo(Application.Context.PackageName, 0);
                            if (appInfo != null)
                            {
                                targetsNOrNewer = (int)appInfo.TargetSdkVersion >= 24;
                            }
                        }

                        if (targetsNOrNewer && this.path.Scheme == "file")
                        {
                            var photoURI = FileProvider.GetUriForFile(this,
                                                                      Application.Context.PackageName + ".fileprovider",
                                                                      new Java.IO.File(this.path.Path));

                            GrantUriPermissionsForIntent(pickIntent, photoURI);
                            pickIntent.PutExtra(MediaStore.ExtraOutput, photoURI);
                        }
                        else
                        {
                            pickIntent.PutExtra(MediaStore.ExtraOutput, this.path);
                        }
                    }
                    else
                    {
                        this.path = Uri.Parse(b.GetString(ExtraPath));
                    }
                }



                if (!ran)
                {
                    StartActivityForResult(pickIntent, this.id);
                }
            }
            catch (Exception ex)
            {
                OnMediaPicked(new MediaPickedEventArgs(this.id, ex));
                //must finish here because an exception has occured else blank screen
                Finish();
            }
            finally
            {
                if (pickIntent != null)
                {
                    pickIntent.Dispose();
                }
            }
        }
Пример #27
0
 /// <summary>
 /// Creates a File list text file, that can be used to include or exclude files from the WSP package.
 /// </summary>
 public void CreateFileList()
 {
     Log.Information("Creating a WSP File list");
     FileProvider.CreateFileList(Config.Current.CreateWSPFileList, this.CabFiles);
 }
Пример #28
0
        /// <summary>
        /// OnCreate
        /// </summary>
        /// <param name="savedInstanceState"></param>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            MediaImplementation.CancelRequested += CancellationRequested;

            var b = (savedInstanceState ?? Intent.Extras);

            var ran = b.GetBoolean("ran", defaultValue: false);

            title       = b.GetString(MediaStore.MediaColumns.Title);
            description = b.GetString(MediaStore.Images.ImageColumns.Description);

            tasked = b.GetBoolean(ExtraTasked);
            id     = b.GetInt(ExtraId, 0);
            type   = b.GetString(ExtraType);
            front  = b.GetInt(ExtraFront);
            if (type == "image/*")
            {
                isPhoto = true;
            }

            action = b.GetString(ExtraAction);
            Intent pickIntent = null;

            try
            {
                pickIntent = new Intent(action);
                if (action == Intent.ActionPick)
                {
                    pickIntent.SetType(type);
                }
                else
                {
                    if (!isPhoto)
                    {
                        var isPixel = false;
                        try
                        {
                            var name = Settings.System.GetString(Application.Context.ContentResolver, "device_name");
                            isPixel = name.Contains("Pixel") || name.Contains("pixel");
                        }
                        catch (Exception)
                        {
                        }

                        seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0);
                        if (seconds != 0 && !isPixel)
                        {
                            pickIntent.PutExtra(MediaStore.ExtraDurationLimit, seconds);
                        }

                        size = b.GetLong(MediaStore.ExtraSizeLimit, 0);
                        if (size != 0)
                        {
                            pickIntent.PutExtra(MediaStore.ExtraSizeLimit, size);
                        }
                    }

                    saveToAlbum = b.GetBoolean(ExtraSaveToAlbum);
                    pickIntent.PutExtra(ExtraSaveToAlbum, saveToAlbum);

                    quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High);
                    pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(quality));

                    if (front != 0)
                    {
                        pickIntent.UseFrontCamera();
                    }
                    else
                    {
                        pickIntent.UseBackCamera();
                    }

                    if (!ran)
                    {
                        path = GetOutputMediaFile(this, b.GetString(ExtraPath), title, isPhoto, false);

                        Touch();


                        if (path.Scheme == "file")
                        {
                            try
                            {
                                var photoURI = FileProvider.GetUriForFile(this,
                                                                          Application.Context.PackageName + ".fileprovider",
                                                                          new Java.IO.File(path.Path));

                                GrantUriPermissionsForIntent(pickIntent, photoURI);
                                pickIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
                                pickIntent.AddFlags(ActivityFlags.GrantWriteUriPermission);
                                pickIntent.PutExtra(MediaStore.ExtraOutput, photoURI);
                            }
                            catch (Java.Lang.IllegalArgumentException iae)
                            {
                                //Using a Huawei device on pre-N. Increased likelihood of failure...
                                if (HuaweiManufacturer.Equals(Build.Manufacturer, StringComparison.CurrentCultureIgnoreCase) && (int)Build.VERSION.SdkInt < 24)
                                {
                                    pickIntent.PutExtra(MediaStore.ExtraOutput, path);
                                }
                                else
                                {
                                    System.Diagnostics.Debug.WriteLine($"Unable to get file location, check and set manifest with file provider. Exception: {iae}");

                                    throw new ArgumentException("Unable to get file location. This most likely means that the file provider information is not set in your Android Manifest file. Please check documentation on how to set this up in your project.", iae);
                                }
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine($"Unable to get file location, check and set manifest with file provider. Exception: {ex}");

                                throw new ArgumentException("Unable to get file location. This most likely means that the file provider information is not set in your Android Manifest file. Please check documentation on how to set this up in your project.", ex);
                            }
                        }
                        else
                        {
                            pickIntent.PutExtra(MediaStore.ExtraOutput, path);
                        }
                    }
                    else
                    {
                        path = Uri.Parse(b.GetString(ExtraPath));
                    }
                }



                if (!ran)
                {
                    StartActivityForResult(pickIntent, id);
                }
            }
            catch (Exception ex)
            {
                OnMediaPicked(new MediaPickedEventArgs(id, ex));
                //must finish here because an exception has occured else blank screen
                Finish();
            }
            finally
            {
                if (pickIntent != null)
                {
                    pickIntent.Dispose();
                }
            }
        }
Пример #29
0
        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
        {
            try
            {
                if (viewHolder is JobsAdapterViewHolder holder)
                {
                    var item = JobList[position];
                    if (item != null)
                    {
                        if (item.Image.Contains("http"))
                        {
                            var image = item.Image.Replace(Client.WebsiteUrl + "/", "");
                            if (!image.Contains("http"))
                            {
                                item.Image = Client.WebsiteUrl + "/" + image;
                            }
                            else
                            {
                                item.Image = image;
                            }

                            GlideImageLoader.LoadImage(ActivityContext, item.Image, holder.Image, ImageStyle.FitCenter, ImagePlaceholders.Drawable);
                        }
                        else
                        {
                            File file2    = new File(item.Image);
                            var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);
                            Glide.With(ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(holder.Image);
                        }

                        holder.Title.Text = Methods.FunString.DecodeString(item.Title);

                        var(currency, currencyIcon) = ObeeNetworkTools.GetCurrency(item.Currency);
                        var categoryName = CategoriesController.ListCategoriesJob.FirstOrDefault(categories => categories.CategoriesId == item.Category)?.CategoriesName;
                        Console.WriteLine(currency);
                        if (string.IsNullOrEmpty(categoryName))
                        {
                            categoryName = Application.Context.GetText(Resource.String.Lbl_Unknown);
                        }

                        holder.Salary.Text = currencyIcon + " " + item.Minimum + " - " + currencyIcon + " " + item.Maximum + " . " + categoryName;

                        holder.Description.Text = Methods.FunString.SubStringCutOf(Methods.FunString.DecodeString(item.Description), 100);

                        if (item.IsOwner)
                        {
                            holder.IconMore.Visibility = ViewStates.Visible;
                            holder.Button.Text         = ActivityContext.GetString(Resource.String.Lbl_show_applies) + " (" + item.ApplyCount + ")";
                            holder.Button.Tag          = "ShowApply";
                        }
                        else
                        {
                            holder.IconMore.Visibility = ViewStates.Gone;
                        }

                        //Set Button if its applied
                        if (item.Apply == "true")
                        {
                            holder.Button.Text    = ActivityContext.GetString(Resource.String.Lbl_already_applied);
                            holder.Button.Enabled = false;
                        }

                        if (!holder.Button.HasOnClickListeners)
                        {
                            holder.Button.Click += (sender, args) =>
                            {
                                try
                                {
                                    switch (holder.Button.Tag.ToString())
                                    {
                                    // Open Apply Job Activity
                                    case "ShowApply":
                                    {
                                        if (item.ApplyCount == "0")
                                        {
                                            Toast.MakeText(ActivityContext, ActivityContext.GetString(Resource.String.Lbl_ThereAreNoRequests), ToastLength.Short).Show();
                                            return;
                                        }

                                        var intent = new Intent(ActivityContext, typeof(ShowApplyJobActivity));
                                        intent.PutExtra("JobsObject", JsonConvert.SerializeObject(item));
                                        ActivityContext.StartActivity(intent);
                                        break;
                                    }

                                    case "Apply":
                                    {
                                        var intent = new Intent(ActivityContext, typeof(ApplyJobActivity));
                                        intent.PutExtra("JobsObject", JsonConvert.SerializeObject(item));
                                        ActivityContext.StartActivity(intent);
                                        break;
                                    }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                }
                            };

                            holder.IconMore.Click += (sender, args) =>
                            {
                                try
                                {
                                    DialogType     = "More";
                                    DataInfoObject = item;

                                    var arrayAdapter = new List <string>();
                                    var dialogList   = new MaterialDialog.Builder(ActivityContext).Theme(AppSettings.SetTabDarkTheme ? Theme.Dark : Theme.Light);

                                    arrayAdapter.Add(ActivityContext.GetText(Resource.String.Lbl_Edit));
                                    arrayAdapter.Add(ActivityContext.GetText(Resource.String.Lbl_Delete));

                                    dialogList.Title(ActivityContext.GetText(Resource.String.Lbl_More));
                                    dialogList.Items(arrayAdapter);
                                    dialogList.NegativeText(ActivityContext.GetText(Resource.String.Lbl_Close)).OnNegative(this);
                                    dialogList.AlwaysCallSingleChoiceCallback();
                                    dialogList.ItemsCallback(this).Build().Show();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                }
                            };
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Пример #30
0
        public void OpenImageLihtBox(string imageurl)
        {
            try
            {
                if (string.IsNullOrEmpty(imageurl))
                {
                    return;
                }

                ApplicationContext.RunOnUiThread(() =>
                {
                    var fileName = imageurl.Split('/').Last();

                    var getImage = IMethods.MultiMedia.GetMediaFrom_Gallery(IMethods.IPath.FolderDcimPost, fileName);
                    if (getImage != "File Dont Exists")
                    {
                        Java.IO.File file2 = new Java.IO.File(getImage);
                        var photoURI       = FileProvider.GetUriForFile(ApplicationContext, ApplicationContext.PackageName + ".fileprovider", file2);

                        Intent intent = new Intent(Intent.ActionPick);
                        intent.SetAction(Intent.ActionView);
                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                        intent.SetDataAndType(photoURI, "image/*");
                        ApplicationContext.StartActivity(intent);
                    }
                    else
                    {
                        string Filename  = imageurl.Split('/').Last();
                        string filePath  = Path.Combine(IMethods.IPath.FolderDcimPost);
                        string MediaFile = filePath + "/" + Filename;

                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }

                        if (!File.Exists(MediaFile))
                        {
                            WebClient WebClient = new WebClient();
                            AndHUD.Shared.Show(ApplicationContext, ApplicationContext.GetText(Resource.String.Lbl_Loading));

                            WebClient.DownloadDataAsync(new System.Uri(imageurl));
                            WebClient.DownloadProgressChanged += (sender, args) =>
                            {
                                var progress = args.ProgressPercentage;
                                // holder.loadingProgressview.Progress = progress;
                                //Show a progress
                                AndHUD.Shared.Show(ApplicationContext, ApplicationContext.GetText(Resource.String.Lbl_Loading));
                            };
                            WebClient.DownloadDataCompleted += (s, e) =>
                            {
                                try
                                {
                                    File.WriteAllBytes(MediaFile, e.Result);

                                    var get_Image = IMethods.MultiMedia.GetMediaFrom_Gallery(IMethods.IPath.FolderDcimPost, fileName);
                                    if (get_Image != "File Dont Exists")
                                    {
                                        Java.IO.File file2 = new Java.IO.File(get_Image);

                                        Android.Net.Uri photoURI = FileProvider.GetUriForFile(ApplicationContext, ApplicationContext.PackageName + ".fileprovider", file2);

                                        Intent intent = new Intent(Intent.ActionPick);
                                        intent.SetAction(Intent.ActionView);
                                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                                        intent.SetDataAndType(photoURI, "image/*");
                                        ApplicationContext.StartActivity(intent);
                                    }
                                    else
                                    {
                                        Toast.MakeText(ApplicationContext, ApplicationContext.GetText(Resource.String.Lbl_something_went_wrong), ToastLength.Long).Show();
                                    }
                                }
                                catch (Exception exception)
                                {
                                    Crashes.TrackError(exception);
                                }

                                var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                                mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(MediaFile)));
                                ApplicationContext.SendBroadcast(mediaScanIntent);


                                AndHUD.Shared.Dismiss(ApplicationContext);
                            };
                        }
                    }
                });
            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
            }
        }
Пример #31
0
        public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
        {
            try
            {
                if (viewHolder is AttachmentsAdapterViewHolder holder)
                {
                    var item = AttachmentList[position];
                    if (item != null)
                    {
                        if (item.TypeAttachment == "Default")
                        {
                            Glide.With(ActivityContext).Load(Resource.Drawable.addImage).Apply(new RequestOptions().Placeholder(Resource.Drawable.ImagePlacholder)).Into(holder.Image);
                        }
                        else
                        {
                            if (item.FileSimple.Contains("http") || item.FileSimple == "Image_File" || item.FileSimple == "Audio_File")
                            {
                                GlideImageLoader.LoadImage(ActivityContext, item.FileSimple, holder.Image, ImageStyle.CenterCrop, ImagePlaceholders.Drawable);
                            }
                            else
                            {
                                if (item.TypeAttachment == "postVideo" && string.IsNullOrEmpty(item.FileSimple) && !new File(item.FileSimple).Exists())
                                {
                                    File file2    = new File(item.FileUrl);
                                    var  photoUri = FileProvider.GetUriForFile(ActivityContext, ActivityContext.PackageName + ".fileprovider", file2);

                                    Glide.With(ActivityContext)
                                    .AsBitmap()
                                    .Placeholder(Resource.Drawable.blackdefault)
                                    .Error(Resource.Drawable.blackdefault)
                                    .Load(photoUri)                                    // or URI/path
                                    .Into(new MySimpleTarget(this, holder, position)); //image view to set thumbnail to
                                }
                                else
                                {
                                    Glide.With(ActivityContext).Load(new File(item.FileUrl)).Apply(new RequestOptions().Placeholder(Resource.Drawable.Blue_Color).Error(Resource.Drawable.Blue_Color)).Into(holder.Image);
                                }
                            }
                        }

                        switch (item.TypeAttachment)
                        {
                        case "postVideo":
                            holder.AttachType.Visibility = ViewStates.Visible;
                            break;

                        case "postPhotos":
                        case "postMusic":
                        case "postFile":
                            holder.AttachType.Visibility = ViewStates.Gone;
                            break;

                        case "Default":
                            holder.ImageDelete.Visibility = ViewStates.Invisible;
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Пример #32
0
 public Stream OpenAsStream(string url, StreamFlags streamFlags)
 {
     return(FileProvider.OpenStream(url, VirtualFileMode.Open, VirtualFileAccess.Read, streamFlags: streamFlags));
 }
Пример #33
0
		public SearchResult (FileProvider fileProvider, int offset, int length)
		{
			FileProvider = fileProvider;
			Offset = offset;
			Length = length;
		}
Пример #34
0
        private object DeserializeObject(Queue <DeserializeOperation> serializeOperations, AssetReference parentAssetReference, string url, Type objType, object obj, AssetManagerLoaderSettings settings)
        {
            // Try to find already loaded object
            AssetReference assetReference = FindDeserializedObject(url, objType);

            if (assetReference != null && assetReference.Deserialized)
            {
                // Add reference
                bool isRoot = parentAssetReference == null;
                if (isRoot || parentAssetReference.References.Add(assetReference))
                {
                    IncrementReference(assetReference, isRoot);
                }

                return(assetReference.Object);
            }

            if (!FileProvider.FileExists(url))
            {
                HandleAssetNotFound(url);
                return(null);
            }

            ContentSerializerContext contentSerializerContext;
            object result;

            // Open asset binary stream
            using (var stream = FileProvider.OpenStream(url, VirtualFileMode.Open, VirtualFileAccess.Read))
            {
                // File does not exist
                // TODO/Benlitz: Add a log entry for that, it's not expected to happen
                if (stream == null)
                {
                    return(null);
                }

                Type headerObjType = null;

                // Read header
                var streamReader = new BinarySerializationReader(stream);
                var chunkHeader  = ChunkHeader.Read(streamReader);
                if (chunkHeader != null)
                {
                    headerObjType = Type.GetType(chunkHeader.Type);
                }

                // Find serializer
                var serializer = Serializer.GetSerializer(headerObjType, objType);
                if (serializer == null)
                {
                    throw new InvalidOperationException(string.Format("Content serializer for {0}/{1} could not be found.", headerObjType, objType));
                }
                contentSerializerContext = new ContentSerializerContext(url, ArchiveMode.Deserialize, this)
                {
                    LoadContentReferences = settings.LoadContentReferences
                };

                // Read chunk references
                if (chunkHeader != null && chunkHeader.OffsetToReferences != -1)
                {
                    // Seek to where references are stored and deserialize them
                    streamReader.NativeStream.Seek(chunkHeader.OffsetToReferences, SeekOrigin.Begin);
                    contentSerializerContext.SerializeReferences(streamReader);
                    streamReader.NativeStream.Seek(chunkHeader.OffsetToObject, SeekOrigin.Begin);
                }

                if (assetReference == null)
                {
                    // Create AssetReference
                    assetReference = new AssetReference(url, parentAssetReference == null);
                    contentSerializerContext.AssetReference = assetReference;
                    result = obj ?? serializer.Construct(contentSerializerContext);
                    SetAssetObject(assetReference, result);
                }
                else
                {
                    result = assetReference.Object;
                    contentSerializerContext.AssetReference = assetReference;
                }

                assetReference.Deserialized = true;

                PrepareSerializerContext(contentSerializerContext, streamReader.Context);

                contentSerializerContext.SerializeContent(streamReader, serializer, result);

                // Add reference
                if (parentAssetReference != null)
                {
                    parentAssetReference.References.Add(assetReference);
                }
            }

            if (settings.LoadContentReferences)
            {
                // Process content references
                // TODO: Should we work at ChunkReference level?
                foreach (var contentReference in contentSerializerContext.ContentReferences)
                {
                    bool shouldBeLoaded = true;

                    //AssetReference childReference;

                    if (settings.ContentFilter != null)
                    {
                        settings.ContentFilter(contentReference, ref shouldBeLoaded);
                    }

                    if (shouldBeLoaded)
                    {
                        serializeOperations.Enqueue(new DeserializeOperation(assetReference, contentReference.Location, contentReference.Type, contentReference.ObjectValue));
                    }
                }
            }

            return(result);
        }