Example #1
0
        public void TestIOMonadBindingFluent()
        {
            string data = "Testing 123";

            var result = GetTempFileName()
                         .Then(tmpFileName => { WriteFile(tmpFileName, data)(); return(tmpFileName); })
                         .Then(tmpFileName => { return(new { tmpFileName, data = ReadFile(tmpFileName)() }); })
                         .Then(context => { DeleteFile(context.tmpFileName)(); return(context.data); });

            Assert.True(result.Invoke() == "Testing 123");
        }
Example #2
0
        public ActionResult DeleteFile(int fileId, int groupId)
        {
            var action = new DeleteFile(_db, groupId, Requester(), fileId);

            action.Execute();
            return(RedirectToAction("Files", new { id = groupId }));
        }
Example #3
0
        private async void BtnDeleteAllFiles_Click(object sender, EventArgs e)
        {
            DialogResult dr = OpenFoldDialog();

            if ((dr == DialogResult.Yes) || (dr == DialogResult.OK))
            {
                // await DeleteAllfiles(openFold.SelectedPath);
                try
                {
                    this.SetFolderButtonStatus(false);
                    StartNewTask();
                    DeleteFileParameter param = new DeleteFileParameter();
                    param.OutoutDirectoy = openFold.SelectedPath.Trim();
                    DeleteFile deleteThreading = new DeleteFile(this.log, this.tokenSource, param);
                    task = deleteThreading.Run();
                    await task;
                    //
                }
                catch (Exception ex)
                {
                    log.RecordError(ex.Message);
                    //this.SetFolderButtonStatus(true);
                }
                finally
                {
                    this.SetFolderButtonStatus(true);
                }
            }
        }
Example #4
0
        private void DeleteFileAndSend(Session session, FileDeleteRequest request)
        {
            var deleteFileEventArgs = new DeleteFileEventArgs(request.Key);

            var response = new FileDeleteResponse()
            {
                MessageId    = request.MessageId,
                ResponseType = ResponseType.OK
            };

            try
            {
                DeleteFile?.Invoke(
                    this,
                    deleteFileEventArgs);
            }
            catch (Exception ex)
            {
                OnException(session, ex, disconnect: false);
                response.ResponseType = ResponseType.Exception;
                response.Exception    = ex.Message;
            }

            SendData(
                session,
                SerializeManager.Current.Serialize(response));
        }
Example #5
0
        protected override async Task <int> ExecuteOnExtractedPackage(string directoryPath)
        {
            var action = new DeleteFile
            {
                FilePath = this.Verb.FilePath
            };

            var executor = new DeleteFileExecutor(directoryPath);

            try
            {
                executor.OnFileRemoved += (_, filePath) =>
                {
                    this.Console.WriteSuccess($"File '{filePath}' has been removed.").GetAwaiter().GetResult();
                };

                await executor.Execute(action).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                await this.Console.WriteError($"File '{this.Verb.FilePath}' could not be removed.").ConfigureAwait(false);

                await this.Console.WriteError(e.Message).ConfigureAwait(false);

                return(StandardExitCodes.ErrorGeneric);
            }

            return(StandardExitCodes.ErrorSuccess);
        }
 public WorkspaceEditDocumentChange(DeleteFile deleteFile)
 {
     TextDocumentEdit = null;
     CreateFile       = null;
     RenameFile       = null;
     DeleteFile       = deleteFile;
 }
Example #7
0
 public static void Init(SaveFile getSaveFile, DeleteFile getDeleteFile, Func <ICrud> getCrud, Func <ISecretService> getSecretService)
 {
     GetSaveFile      = getSaveFile;
     GetDeleteFile    = getDeleteFile;
     GetCrud          = getCrud;
     GetSecretService = getSecretService;
 }
Example #8
0
		public static void addFileView(Context context, List<BookingDocumentDto> documents, bool isInConference, OnAddFileToView addFiles, DeleteFile deleteFile, LinearLayout llFileAttachment){
			if (addFiles == null) {
				addFiles = new OnAddFileToView (context, deleteFile, isInConference);
			}
			addFiles.InitView (documents);
			llFileAttachment.RemoveAllViews ();
			llFileAttachment.AddView (addFiles);
		}
Example #9
0
        public void MergeTemporaryFilesOne_Path_CountDeleteFile() //Stab
        {
            DeleteFile  deleteFile  = new DeleteFile();
            FileService fileService = new FileService();

            fileService.MergeTemporaryFilesOne(@"D:\Laboratory_works\Тестирование\File_test\");
            Assert.That(fileService.Get_int(), Is.EqualTo(5));
        }
Example #10
0
		public OnAddFileToView (Context context, DeleteFile deleteFile, bool isInConference) : base(context)
		{
			this._context = context;
			this._deleteFile = deleteFile;
			this._isInConference = isInConference;

			this.Orientation = Orientation.Vertical;
			this.SetVerticalGravity (GravityFlags.CenterVertical);
		}
Example #11
0
 private void btnDelete_Click(object sender, EventArgs e)
 {
     if (MessageBox.Show(this, "Delete the file " + FilePath + "?", "Delete File", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
     {
         DeleteFile.Invoke(this, new FileViewerEventArgs()
         {
             FilePath = FilePath
         });
     }
 }
Example #12
0
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="groupName">组名</param>
        /// <param name="fileId">文件名</param>
        /// <param name="clusterName">集群名称</param>
        /// <returns>是否删除成功</returns>

        public async ValueTask <bool> RemoveFileAsync(string groupName, string fileId, string clusterName = "")
        {
            var queryUpdateRequest  = new QueryUpdate(groupName, fileId);
            var queryUpdateResponse = await _executer.Execute(queryUpdateRequest, clusterName);

            var storageNode = new StorageNode(queryUpdateResponse.GroupName, queryUpdateResponse.IPAddress, queryUpdateResponse.Port, 0);

            var request  = new DeleteFile(groupName, fileId);
            var response = await _executer.Execute(request, clusterName, storageNode.ConnectionAddress);

            return(response.Success);
        }
Example #13
0
        public async Task <IActionResult> DeleteCourse(Course course)
        {
            ResultState resultState = CheckCookie();

            if (resultState.Code == 2)
            {
                if (CourseExists(course.CourseID))
                {
                    var url = _context.Courses.AsNoTracking().Where(f => f.CourseID == course.CourseID).Select(f => f.url).FirstOrDefault();

                    if (url != null)
                    {
                        var           urls    = url.Split("|");
                        var           delPath = urls[0];
                        DirectoryInfo di      = new DirectoryInfo(delPath);
                        delPath           = di.Parent.ToString();
                        resultState.value = delPath + "         " + urls;
                        string message = DeleteFile.deleteFileByPath(delPath);
                        resultState.Message = message;
                        if (message == "删除成功")
                        {
                            _context.Courses.Remove(course);
                            await _context.SaveChangesAsync();

                            resultState.Message = "删除课程信息成功";
                            resultState.Success = true;
                            return(new JsonResult(resultState));
                        }
                        else
                        {
                            resultState.Success = false;
                            return(new JsonResult(resultState));
                        }
                    }
                    else
                    {
                        _context.Courses.Remove(course);
                        await _context.SaveChangesAsync();

                        resultState.Message = "删除课程信息成功,此课程无文件";
                        resultState.Success = true;
                        return(new JsonResult(resultState));
                    }
                }
                else
                {
                    resultState.Message = "删除课程失败";
                    resultState.Success = false;
                }
            }
            return(new JsonResult(resultState));
        }
Example #14
0
 public static void Setup <BaseIContentType>(
     Func <ICrud> getCrud, Func <ISecretService> getSecretService,
     Func <string> getContentViewPath, Func <string> getContentPageUrl,
     SaveFile getSaveFile, DeleteFile getDeleteFile,
     Func <SystemConfig> config, Func <IModelService> modelService)
     where BaseIContentType : class, IContentModel
 {
     ContentPostViewModel.Init(getContentViewPath, getContentPageUrl);
     MyReflectExtends.Init(getCrud);
     AbstractBaseContent.Init <BaseIContentType>(getCrud);
     PassModeConvert.Init(getSaveFile, getDeleteFile, getCrud, getSecretService);
     TypeExtends.Init <BaseIContentType>(config, modelService);
 }
Example #15
0
        public void Reply(DeleteFile message, IPEndPoint endpoint)
        {
            const byte DeleteFile = 0x02;

            byte[] command = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(message));

            var bytesToSend = new byte[1 + command.Length];

            bytesToSend[0] = DeleteFile;
            command.CopyTo(bytesToSend, 1);

            Client.Send(bytesToSend, bytesToSend.Length, endpoint);
        }
Example #16
0
 public HttpResponseMessage DeleteFile(DeleteFile model)
 {
     try
     {
         string path = "C:/repos/github/WebApiApp/WebApiApp.Web/images/" + model.SystemFileName;
         filesvc.DeleteFile(path, model.FileId);
         SuccessResponse resp = new SuccessResponse();
         return(Request.CreateResponse(HttpStatusCode.OK, resp));
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
     }
 }
        public void SerializeTo(string key, IClientSideObjectWriter writer, IEditorUrlBuilder urlBuilder)
        {
            Func <string, string> encoder = url => owner.IsSelfInitialized ? HttpUtility.UrlDecode(url) : url;
            var json = new Dictionary <string, string>();

            if (Select.HasValue())
            {
                json["selectUrl"] = encoder(urlBuilder.PrepareUrl(Select));
            }

            if (Thumbnail.HasValue())
            {
                json["thumbUrl"] = encoder(urlBuilder.PrepareUrl(Thumbnail));
            }

            if (Image.HasValue())
            {
                json["imageUrl"] = encoder(urlBuilder.PrepareUrl(Image));
            }

            if (Upload.HasValue())
            {
                json["uploadUrl"] = encoder(urlBuilder.PrepareUrl(Upload));
            }

            if (DeleteFile.HasValue())
            {
                json["deleteFileUrl"] = encoder(urlBuilder.PrepareUrl(DeleteFile));
            }

            if (DeleteDirectory.HasValue())
            {
                json["deleteDirectoryUrl"] = encoder(urlBuilder.PrepareUrl(DeleteDirectory));
            }

            if (CreateDirectory.HasValue())
            {
                json["createDirectoryUrl"] = encoder(urlBuilder.PrepareUrl(CreateDirectory));
            }

            if (Filter.HasValue() && Filter != DefaultFilter)
            {
                json["filter"] = Filter;
            }

            writer.AppendObject(key, json);
        }
Example #18
0
        private void RestoreDefaultCategories()
        {
            DeleteFile.Delete(ITEMSPATH);

            for (int i = _objects.Count - 1; i >= 0; i--)
            {
                _objects.RemoveAt(i);
            }

            DefaultCategories defaultCategories = new DefaultCategories();
            IList <string[]>  defaultCats       = defaultCategories.DefaultCategoryList;
            WriteListToFile   set = new WriteListToFile(defaultCats, CATEGORIESPATH);

            foreach (string[] category in defaultCats)
            {
                _objects.Add(new ShoppingListObject(category[0]));
            }
        }
Example #19
0
        public void TestExecute()
        {
            string tempFile = TestUtility.TempDir + @"testfile" + new Random().Next(100000000);

            File.Delete(tempFile);

            DeleteFile df = new DeleteFile();

            df.Path = tempFile;

            TestUtility.CreateFile(tempFile);

            df.Execute();

            Assert.IsFalse(File.Exists(tempFile));


            //cleanup
            File.Delete(tempFile);
        }
Example #20
0
        public virtual IEnumerator <ITask> DeleteFileHandler(DeleteFile deleteFile)
        {
            nxtcmd.LegoDelete cmd = new nxtcmd.LegoDelete(deleteFile.Body.FileName);
            yield return(Arbiter.Choice(_legoBrickPort.SendNxtCommand(cmd),
                                        delegate(nxtcmd.LegoResponse ok)
            {
                if (ok.Success || ok.ErrorCode == LegoErrorCode.FileNotFound)
                {
                    deleteFile.ResponsePort.Post(DefaultSubmitResponseType.Instance);
                }
                else
                {
                    deleteFile.ResponsePort.Post(Fault.FromException(new System.IO.IOException(ok.ErrorCode.ToString())));
                }
            },
                                        delegate(Fault fault)
            {
                deleteFile.ResponsePort.Post(fault);
            }));

            yield break;
        }
Example #21
0
        internal override ICommand Parse(string userInput)
        {
            string[]      inputArguments = SplitInputArguments(userInput);
            string        commandName    = $"{inputArguments[0]} {inputArguments[1]}".ToLower();
            List <string> commandOptions = ParseCommandOptions(inputArguments);
            ICommand      parsedCommand;

            switch (commandName)
            {
            case SupportedCommandConstants.FileDelete:
                parsedCommand = new DeleteFile(_fileService, commandOptions);
                break;

            case SupportedCommandConstants.FileDownload:
                parsedCommand = new DownloadFile(_fileService, commandOptions);
                break;

            case SupportedCommandConstants.FileInfo:
                parsedCommand = new InfoFile(_fileService, commandOptions);
                break;

            case SupportedCommandConstants.FileMove:
                parsedCommand = new MoveFile(_fileService, commandOptions);
                break;

            case SupportedCommandConstants.FileUpload:
                parsedCommand = new UploadFile(_fileService, commandOptions);
                break;

            case SupportedCommandConstants.UserInfo:
                parsedCommand = new InfoUser(_fileService);
                break;

            default: throw new Exception("Non-existent command!");
            }

            return(parsedCommand);
        }
Example #22
0
        public async Task <IActionResult> DeleteFilesByCourseID(int courseId)
        {
            ResultState resultState = CheckCookie();

            if (resultState.Code == 2)
            {
                //var urls = _context.Courses.Where(f => f.CourseID == courseId).Select(f => f.url).FirstOrDefault().Split("|");
                var cousurlInD = await _context.Courses.FirstOrDefaultAsync(x => x.CourseID == courseId);

                var           url     = cousurlInD.url;
                var           urls    = url.Split("|");
                var           delPath = urls[0];
                DirectoryInfo di      = new DirectoryInfo(delPath);
                delPath           = di.Parent.ToString();
                resultState.value = delPath + "         " + url;
                string message = DeleteFile.deleteFileByPath(delPath);
                resultState.Message = message;
                if (message == "删除成功")
                {
                    resultState.Success = true;

                    cousurlInD.url = null;
                    await _context.SaveChangesAsync();

                    return(new JsonResult(resultState));
                }
                else
                {
                    resultState.Success = false;
                    return(new JsonResult(resultState));
                }
            }
            resultState.Success = false;
            resultState.Message = "权限不够";
            return(new JsonResult(resultState));
        }
Example #23
0
            /// <summary>
            /// Stores file in its own virtual drive rho\apps\app
            /// </summary>
            /// <param name="file">Stream of file that needs to be saved in the Location.</param>
            /// <param name="fileName">Name i n which the file needs to be saved</param>
            /// <param name="StorechoosePictureResult">Callback event</param>
            /// <param name="choosePicture_output">The path of the image needs to be stored</param>
            /// <returns>Successll or error</returns>
            public async Task SaveToLocalFolderAsync(Stream file, string fileName, IMethodResult StoreTakePictureResult, Dictionary <string, string> TakePicture_output)
            {
                string        FileNameSuffix = "__DTF__";
                StorageFolder localFolder    = ApplicationData.Current.LocalFolder;

                string strLocalFolder = CRhoRuntime.getInstance().getRootPath(ApplicationData.Current.LocalFolder.Path.ToString());

                string[] strFolders = strLocalFolder.Split(new string[] { ApplicationData.Current.LocalFolder.Path.ToString() }, StringSplitOptions.None);
                Dictionary <bool, bool> Rho_SubFolder_Pass = new Dictionary <bool, bool>();

                Rho_SubFolder_Pass.Add(true, true);
                try
                {
                    //bool FIleExists= Rho_SubFolder_Pass[strFolders[1].Contains(localFolder.Path.ToString())];
                    string[] StrSubFolders = strFolders[0].Split('/');

                    foreach (string Path in StrSubFolders)
                    {
                        try
                        {
                            bool BlankFolder = Rho_SubFolder_Pass[!string.IsNullOrEmpty(Path)];
                            var  subfolders  = await localFolder.GetFoldersAsync();

                            foreach (StorageFolder appFolder in subfolders)
                            {
                                try
                                {
                                    bool status = Rho_SubFolder_Pass[appFolder.Name.Contains(Path)];
                                    localFolder = appFolder;
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                }

                string[] picList = Directory.GetFiles(localFolder.Path);
                try
                {
                    bool image = Rho_SubFolder_Pass[fileName.Contains(".jpg")];
                    fileName = fileName.Replace(".jpg", FileNameSuffix + ".jpg");
                }
                catch (Exception ex)
                {
                    fileName = fileName + FileNameSuffix;
                }

                foreach (string DeleteFile in picList)
                {
                    try
                    {
                        bool fileexist = Rho_SubFolder_Pass[DeleteFile.Contains(FileNameSuffix)];

                        File.Delete(DeleteFile);
                    }
                    catch (Exception ex)
                    {
                    }
                }


                StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                Task <Stream> outputStreamTask = storageFile.OpenStreamForWriteAsync();
                Stream        outputStream     = outputStreamTask.Result;
                var           bitmap           = new BitmapImage();

                /*bitmap.SetSource(file);
                 * var wb = new WriteableBitmap(bitmap);
                 * wb.SaveJpeg(outputStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                 * outputStream.Close();*/

                TakePicture_output["imageUri"]  = "\\" + storageFile.Name;
                TakePicture_output["image_uri"] = "\\" + storageFile.Name;

                StoreTakePictureResult.set(TakePicture_output);
            }
Example #24
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			RequestWindowFeature (WindowFeatures.ActionBar);
			SetContentView (Resource.Layout.popup_confirm_bookings);

			ActionBar.NavigationMode = ActionBarNavigationMode.Standard;
			ActionBar.Title = GetString(Resource.String.consultation_titile) + constants.bookingInfo.ReferenceNo;
			ActionBar.SetDisplayShowTitleEnabled (false);
			ActionBar.SetDisplayHomeAsUpEnabled(true);
			ActionBar.SetDisplayShowHomeEnabled (true);

			setHeadingTitle (GetString(Resource.String.consultation_titile) + constants.bookingInfo.ReferenceNo);

			llProgress = FindViewById<LinearLayout> (Resource.Id.llProgressBar);
			llProgress.Visibility = ViewStates.Gone;

			popupNotice = new PopupNoticeInfomation(this);
			popupNotice.noticeDelegate = this;

			deleteFile = new DeleteFile (this);
			deleteFile.deleteFileAction = this;

			var avatar = FindViewById<ImageView> (Resource.Id.avatar_popup_booking);
			var tvName = FindViewById<TextView> (Resource.Id.tv_name_popup_booking);
			var tvTitleTime = FindViewById<TextView> (Resource.Id.tv_title_proposed_time);
			var tvConfirmedTime = FindViewById<TextView> (Resource.Id.tv_time_popup_booking);
			var tvFee = FindViewById<TextView> (Resource.Id.tv_fee_popup_booking);
			var btnAddfile = FindViewById<Button> (Resource.Id.btn_addfile_confirm_booking);
			var btnTalkNowRequest = FindViewById<Button> (Resource.Id.btn_request_talknow_booking);
			var btnDecline = FindViewById<Button> (Resource.Id.btn_decline_confirm_booking);
			llFileAttachment = FindViewById<LinearLayout> (Resource.Id.llFileAttachConfirmed);
			var tvEnquiry = FindViewById<TextView> (Resource.Id.tv_enquiry_booking);
			var tvFeeTitle = FindViewById<TextView> (Resource.Id.tv_title_cost_confirm);

			btnTalkNowRequest.SetText(Resource.String.talkNow_title_button);
			btnAddfile.SetText(Resource.String.add_file_btn);
			tvTitleTime.SetText(Resource.String.confirmed_time_title);

			btnTalkNowRequest.Visibility = ViewStates.Gone;
			if (MApplication.getInstance ().isConsultant) {
				if (Utils.isShowTalkNowRequest (DateTime.Parse (constants.bookingInfo.StartTime), DateTime.Parse (constants.bookingInfo.EndTime), MApplication.getInstance ().timezoneName)){
					btnTalkNowRequest.Visibility = ViewStates.Visible;
				}
			}
			tvEnquiry.Text = constants.bookingInfo.Enquiry;
			datetimeStart = DateTime.Parse (constants.bookingInfo.StartTime);
			datetimeEnd = DateTime.Parse (constants.bookingInfo.EndTime);
			if (datetimeStart.Date == datetimeEnd.Date) {
				tvConfirmedTime.Text = datetimeStart.ToString (constants.sDateFormat) + " " + datetimeStart.ToString (constants.sTimeFormat, new CultureInfo("en-us")).ToUpper () + " - " + datetimeEnd.ToString (constants.sTimeFormat, new CultureInfo("en-us")).ToUpper ();
			} else {
				tvConfirmedTime.Text = datetimeStart.ToString (constants.sDateFormat) + " " + datetimeStart.ToString (constants.sTimeFormat, new CultureInfo("en-us")).ToUpper () + " - " + datetimeEnd.ToString (constants.sDateFormat) + " " + datetimeEnd.ToString (constants.sTimeFormat, new CultureInfo("en-us")).ToUpper ();
			}

			string fee = "";
			if (MApplication.getInstance ().isConsultant) {
				fee = "$" + Utils.getCost (constants.bookingInfo.RatePerMinute) + " " + GetString (Resource.String.price_per_minute);
			} else {
				fee = "$" + Utils.getCost (constants.bookingInfo.CostPerMinute) + " " + GetString (Resource.String.price_per_minute);
			}
			if (!MApplication.getInstance ().isConsultant) {
				fee += " ($" + Utils.getCost(constants.bookingInfo.CustomerMinCharge) + " minimum)";
			} else if(!constants.bookingInfo.IsApplyNoMinimumCharge){
				fee += " ($" + Utils.getCost (constants.bookingInfo.SpecialistMinCharge) + " minimum)";
			}
			tvFee.Text = fee;

			if (MApplication.getInstance().isConsultant) {
				UrlImageViewHelper.UrlImageViewHelper.SetUrlDrawable(avatar, HttpConstants.BASE_URL + constants.bookingInfo.CustomerAvatar, Resource.Drawable.special_home, constants.iTimeLoading, this);
				tvName.Text = constants.bookingInfo.CustomerName;
				tvFeeTitle.Text = "CONSULTATION FEE";
			} else {
				UrlImageViewHelper.UrlImageViewHelper.SetUrlDrawable(avatar, HttpConstants.BASE_URL + constants.bookingInfo.SpecialistAvatar, Resource.Drawable.special_home, constants.iTimeLoading, this);
				tvName.Text = constants.bookingInfo.SpecialistName;
				tvFeeTitle.Text = "APPLICABLE COST";
			}

			btnTalkNowRequest.Click += (sender, e) => {
				if (Utils.isShowTalkNowRequest (DateTime.Parse (constants.bookingInfo.StartTime), DateTime.Parse (constants.bookingInfo.EndTime), MApplication.getInstance ().timezoneName)){
					MApplication.getInstance().customerID = constants.bookingInfo.CustomerId;
					if(talkNowUI == null){
						talkNowUI = new TalkNowUI(this);
						talkNowUI.actionTalknowDelegate = this;
					}
					talkNowUI.talknowRequest(false, constants.bookingInfo.Id);
				} else {
					showExpiredNotice();
				}
			};
			uploadPhoto = new UploadPhoto(this);
			uploadPhoto.actionUploadPhotoDelegate = this;

			btnAddfile.Click += (sender, e) => {
				if (!utilsAndroid.checkIsExpired(DateTime.Parse (constants.bookingInfo.EndTime))){
					if(uploadPhoto == null){
						uploadPhoto = new UploadPhoto(this);
						uploadPhoto.actionUploadPhotoDelegate = this;
					}
					uploadPhoto.selectActionUpload();
				} else {
					showExpiredNotice();
				}
			};

			btnDecline.Text = GetString (Resource.String.cancel_consultation);
			btnDecline.Click += (sender, e) => {
				if (!utilsAndroid.checkIsExpired(DateTime.Parse (constants.bookingInfo.EndTime))){
					if(updateBookingStatus == null){
						updateBookingStatus = new UpdateBookingStatus(this);
						updateBookingStatus.actionUpdateBookingStatus = this;
					}
					updateBookingStatus.showDeclineBookingConfirm();
				} else {
					showExpiredNotice();
				}
			};	

			if (constants.bookingInfo.BookingDocuments != null && constants.bookingInfo.BookingDocuments.Count > 0) {
				int isize = constants.bookingInfo.BookingDocuments.Count;
				for (int i = 0; i < isize; i++) {
					bookingDocs.Add(constants.bookingInfo.BookingDocuments[i]);
				}
				utilsAndroid.addFileView (this, bookingDocs, true, addFiles, deleteFile, llFileAttachment);
			}

			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostUploadFileSuccess, new TCSelector (onUploadFileSuccess));
			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostDeleteFileSuccess, new TCSelector (onDeleteFileSuccess));
		}
Example #25
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			RequestWindowFeature (WindowFeatures.ActionBar);
			SetContentView (Resource.Layout.pastbooking_detail);

			ActionBar.NavigationMode = ActionBarNavigationMode.Standard;
			ActionBar.Title = GetString(Resource.String.consultation_titile) + constants.bookingInfo.ReferenceNo;
			ActionBar.SetDisplayShowTitleEnabled (false);
			ActionBar.SetDisplayHomeAsUpEnabled(true);
			ActionBar.SetDisplayShowHomeEnabled (true);

			setHeadingTitle (GetString(Resource.String.consultation_titile) + constants.bookingInfo.ReferenceNo);

			var tvName = FindViewById<TextView> (Resource.Id.tv_name_past_detail);
			var avatar = FindViewById<ImageView> (Resource.Id.avatar_past_detail);
			numRating = FindViewById<ImageView> (Resource.Id.img_num_rating_pass);
			imgFavorite = FindViewById<ImageView> (Resource.Id.img_add_favorite_pass);
			imgEmailProfile = FindViewById<ImageView> (Resource.Id.img_email_profile_pass);
			imgRating = FindViewById<ImageView> (Resource.Id.img_rating_pass);

			tvExpiredNotice = FindViewById<TextView> (Resource.Id.tv_expired_notice);
			//llSoonest = FindViewById<LinearLayout> (Resource.Id.llSoonestDetail);
			//llStandard = FindViewById<LinearLayout> (Resource.Id.llStandardDetail);
			//llAnother = FindViewById<LinearLayout> (Resource.Id.llAnotherTimeDetail);
			llTalknow = FindViewById<LinearLayout> (Resource.Id.llTalkNowDetail);
			llActionBooking = FindViewById<LinearLayout> (Resource.Id.llActionBooking);

			tvDateStartCall = FindViewById<TextView> (Resource.Id.tv_start_date_past);
			tvTimeStartCall = FindViewById<TextView> (Resource.Id.tv_start_time_past);
			tvDateEndCall = FindViewById<TextView> (Resource.Id.tv_end_date_past);
			tvTimeEndCall = FindViewById<TextView> (Resource.Id.tv_end_time_past);
			tvDuration = FindViewById<TextView> (Resource.Id.tv_total_time_past);
			tvCost = FindViewById<TextView> (Resource.Id.tv_total_cost_past);
			tvFee = FindViewById<TextView> (Resource.Id.tv_total_fee_past);
			llFileAttachment = FindViewById<LinearLayout> (Resource.Id.llFileAtachment);
			llGroupFee = FindViewById<LinearLayout> (Resource.Id.llGroupFeePass);
			tvNoticeWaivedFee = FindViewById<TextView> (Resource.Id.tv_notice_waived_pass);
			tvStandardCost = FindViewById<TextView> (Resource.Id.tvDolarStandard);
			//tvAnotherCost = FindViewById<TextView> (Resource.Id.tvDolarAnotherTime);
			tvTalkNowCost = FindViewById<TextView> (Resource.Id.tvDolarTalkNow);
			llStatusPass = FindViewById<LinearLayout> (Resource.Id.llGroupStatus);
			llDetailPass = FindViewById<LinearLayout> (Resource.Id.llContentPass);
			imgIconStep2 = FindViewById<ImageView> (Resource.Id.imgIconCallingStep2);
			tvDeferInfo = FindViewById<TextView> (Resource.Id.tv_sub_waiting_call_1);
			tvDialStep2 = FindViewById<TextView> (Resource.Id.tvDialStep2);

			pastDetailActivity = this;

			popupNotice = new PopupNoticeInfomation(this);
			popupNotice.noticeDelegate = this;

			deleteFile = new DeleteFile (this);
			deleteFile.deleteFileAction = this;

			uploadPhoto = new UploadPhoto(this);
			uploadPhoto.actionUploadPhotoDelegate = this;

			transcribe = new TranscribeRequest (this);
			transcribe.transcribeDelegate = this;

			tvDeferInfo.Visibility = ViewStates.Gone;
			llStatusPass.Visibility = ViewStates.Gone;
			tvExpiredNotice.Visibility = ViewStates.Gone;

			numRating.SetImageResource(utilsAndroid.getIconRatingResource(0));
			if (MApplication.getInstance ().isConsultant) {
				progressDialogParent.Show ();
				GetBookingInfo getBookingInfo = new GetBookingInfo (this);
				getBookingInfo.actionDelegate = this;
				getBookingInfo.getBookingInfo (constants.bookingInfo.Id);
			} else {
				llActionBooking.Visibility = ViewStates.Gone;
				progressDialogParent.Show ();
				GetSpecialistProfile getSpecInfo = new GetSpecialistProfile (this);
				getSpecInfo.actionDelegate = this;
				getSpecInfo.getSpecProfile (MApplication.getInstance ().specialistID);
			}

			tvNoticeWaivedFee.Visibility = ViewStates.Gone;

			if (constants.bookingInfo.BookingDocuments != null && constants.bookingInfo.BookingDocuments.Count > 0) {
				int isize = constants.bookingInfo.BookingDocuments.Count;
				for (int i = 0; i < isize; i++) {
					bookingDocs.Add(constants.bookingInfo.BookingDocuments[i]);
				}
				utilsAndroid.addFileView (this, bookingDocs, true, addFiles, deleteFile, llFileAttachment);
			}

			if (MApplication.getInstance ().isConsultant) {
				tvName.Text = constants.bookingInfo.CustomerName;
				UrlImageViewHelper.UrlImageViewHelper.SetUrlDrawable(avatar, HttpConstants.BASE_URL + constants.bookingInfo.CustomerAvatar, Resource.Drawable.special_home, constants.iTimeLoading, this);

				imgFavorite.Visibility = ViewStates.Gone;
				imgEmailProfile.Visibility = ViewStates.Gone;
				llSoonest.Visibility = ViewStates.Gone;
				llStandard.Visibility = ViewStates.Gone;
				llAnother.Visibility = ViewStates.Gone;
				llTalknow.Visibility = ViewStates.Gone;
			} else {
				tvName.Text = constants.bookingInfo.SpecialistName;
				UrlImageViewHelper.UrlImageViewHelper.SetUrlDrawable(avatar, HttpConstants.BASE_URL + constants.bookingInfo.SpecialistAvatar, Resource.Drawable.special_home, constants.iTimeLoading, this);

				llGroupFee.Visibility = ViewStates.Gone;
			}

			tvDateStartCall.Text = Utils.getDateTimeNow (MApplication.getInstance ().timezoneName).ToString (constants.sDateFormat);
			tvTimeStartCall.Text = Utils.getDateTimeNow (MApplication.getInstance ().timezoneName).ToString (constants.sTimeFormat, new CultureInfo("en-us")).ToUpper();
			tvDateEndCall.Text = Utils.getDateTimeNow (MApplication.getInstance ().timezoneName).ToString (constants.sDateFormat);
			tvTimeEndCall.Text = Utils.getDateTimeNow (MApplication.getInstance ().timezoneName).ToString (constants.sTimeFormat, new CultureInfo("en-us")).ToUpper();

			setDataPastBookingToView ();

			setActionToView ();

			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostUploadFileSuccess, new TCSelector (onUploadFileSuccess));
			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostDeleteFileSuccess, new TCSelector (onDeleteFileSuccess));
		}
        public virtual IEnumerator<ITask> DeleteFileHandler(DeleteFile deleteFile)
        {
            nxtcmd.LegoDelete cmd = new nxtcmd.LegoDelete(deleteFile.Body.FileName);
            yield return Arbiter.Choice(_legoBrickPort.SendNxtCommand(cmd),
                delegate(nxtcmd.LegoResponse ok)
                {
                    if (ok.Success || ok.ErrorCode == LegoErrorCode.FileNotFound)
                    {
                        deleteFile.ResponsePort.Post(DefaultSubmitResponseType.Instance);
                    }
                    else
                    {
                        deleteFile.ResponsePort.Post(Fault.FromException(new System.IO.IOException(ok.ErrorCode.ToString())));
                    }
                },
                delegate(Fault fault)
                {
                    deleteFile.ResponsePort.Post(fault);
                });

            yield break;
        }
Example #27
0
 public async Task <Unit> DeleteFileAsync([FromBody] DeleteFile deleteFile)
 {
     return(await _mediator.Send(deleteFile));
 }
Example #28
0
 public void DeleteFile(string filename)
 {
     CheckDisposed();
     (_DeleteFile ?? (_DeleteFile = (_callback.Resolve <DeleteFile>() ?? ((pfilename) => { }))))(filename);
 }
        // NOTE: The specific task data (ExecuteDeviceCommandAsyncTaskData.Data) must be a Tuple<MenuLayout, bool, bool>.
        // The first Boolean value indicates whether the operation should attempt to force the removal of menu position data.
        // The second Boolean value indicates whether the operation should update the root file's names (device name, owner).
        private static void SyncHostToDevice(AsyncTaskData taskData)
        {
            var data   = (ExecuteDeviceCommandAsyncTaskData)taskData;
            var device = data.Device;

            data.Task.UpdateTaskProgress(0, Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ComputingChangesProgress);
            var currentDirtyFlags = GetDirtyFlags.Instance.Execute <LfsDirtyFlags>(device.Port, data);
            var deviceFileSystem  = DownloadFileSystemTables.Instance.Execute <FileSystem>(device.Port, data);

            deviceFileSystem.Status = currentDirtyFlags;
            if (data.AcceptCancelIfRequested())
            {
                return;
            }

            var hostData              = (Tuple <MenuLayout, bool, bool>)data.Data;
            var hostFileSystem        = hostData.Item1.FileSystem;
            var resetSaveMenuPosition = hostData.Item2;

            if (resetSaveMenuPosition)
            {
                hostFileSystem.ForceRemovalOfMenuPositionData(deviceFileSystem);
            }
            hostFileSystem.SuppressRootFileNameDifferences(device);
            hostFileSystem.PopulateSaveDataForksFromDevice(deviceFileSystem);

            // The first pass gathers all differences, including errors.
            var allDifferencesWithErrors = hostFileSystem.CompareTo(deviceFileSystem, device, true);

#if USE_SMART_COPY
            // Now, use a clone of the original file system to compute the actual work to do, and use the failures for a post-op error report.
            var hostFileSystemWorkingCopy = hostFileSystem.Clone();

            var ignoreRootFileNames = !hostData.Item3;
            if (ignoreRootFileNames)
            {
                hostFileSystemWorkingCopy.Files[GlobalFileTable.RootDirectoryFileNumber].ShortName = deviceFileSystem.Files[GlobalFileTable.RootDirectoryFileNumber].ShortName;
                hostFileSystemWorkingCopy.Files[GlobalFileTable.RootDirectoryFileNumber].LongName  = deviceFileSystem.Files[GlobalFileTable.RootDirectoryFileNumber].LongName;
            }

            var partialErrors  = hostFileSystemWorkingCopy.CleanUpInvalidEntries(deviceFileSystem, allDifferencesWithErrors, FileSystemHelpers.ShouldRemoveInvalidEntry, ShouldIncludeError);
            var allDifferences = hostFileSystemWorkingCopy.CompareTo(deviceFileSystem, device, true);
#else
            // This will try to copy all ROMs, even incompatible ones, and should eventually be removed.
            var hostFileSystemWorkingCopy = hostFileSystem;
            var partialErrors             = allDifferencesWithErrors.GetAllFailures(ShouldIncludeError);
            var allDifferences            = allDifferencesWithErrors;
#endif // USE_SMART_COPY

            var succeeded    = true;
            var phaseNumber  = 0;
            var updateString = string.Empty;

            // Run any delete operations...
            var total       = allDifferences.DirectoryDifferences.ToDelete.Count + allDifferences.FileDifferences.ToDelete.Count + allDifferences.ForkDifferences.ToDelete.Count + allDifferences.ForkDifferences.ToUpdate.Count;
            var numComplete = 0;
            if (data.AcceptCancelIfRequested())
            {
                return;
            }
            if (total > 0)
            {
                ++phaseNumber;

                if (!data.CancelRequsted && succeeded && allDifferences.DirectoryDifferences.ToDelete.Any())
                {
                    var deleteOpData = new DeleteOperationData(data, LfsEntityType.Directory)
                    {
                        Factory              = (gdn) => DeleteFolder.Create((byte)(uint)gdn[0]),
                        UpdateTitleFormat    = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ProgressTitleFormat,
                        UpdateTitleInfo      = Resources.Strings.LfsOperation_Remove,
                        UpdateProgressFormat = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_DeletingItemProgressFormat,
                        UpdateProgressInfo   = Resources.Strings.DirectoriesInSentence,
                        Phase = phaseNumber, Total = total, Current = numComplete
                    };
                    currentDirtyFlags |= DeleteEntries(allDifferences.DirectoryDifferences.ToDelete, deleteOpData, currentDirtyFlags, deviceFileSystem);
                    numComplete        = deleteOpData.Current;
                    succeeded          = data.Succeeded;
                }

                if (!data.CancelRequsted && succeeded && allDifferences.FileDifferences.ToDelete.Any())
                {
                    var deleteOpData = new DeleteOperationData(data, LfsEntityType.File)
                    {
                        Factory              = (gfn) => DeleteFile.Create((ushort)(uint)gfn[0]),
                        UpdateTitleFormat    = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ProgressTitleFormat,
                        UpdateTitleInfo      = Resources.Strings.LfsOperation_Remove,
                        UpdateProgressFormat = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_DeletingItemProgressFormat,
                        UpdateProgressInfo   = Resources.Strings.FilesInSentence,
                        Phase = phaseNumber, Total = total, Current = numComplete
                    };
                    currentDirtyFlags |= DeleteEntries(allDifferences.FileDifferences.ToDelete, deleteOpData, currentDirtyFlags, deviceFileSystem);
                    numComplete        = deleteOpData.Current;
                    succeeded          = data.Succeeded;
                }

                if (!data.CancelRequsted && succeeded && (allDifferences.ForkDifferences.ToDelete.Any() || allDifferences.ForkDifferences.ToUpdate.Any()))
                {
                    var deleteOpData = new DeleteOperationData(data, LfsEntityType.Fork)
                    {
                        Factory              = (gkn) => DeleteFork.Create((ushort)(uint)gkn[0]),
                        UpdateTitleFormat    = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ProgressTitleFormat,
                        UpdateTitleInfo      = Resources.Strings.LfsOperation_Remove,
                        UpdateProgressFormat = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_DeletingItemProgressFormat,
                        UpdateProgressInfo   = Resources.Strings.DeviceMultistageCommand_RemovingFileContents,
                        Phase = phaseNumber, Total = total, Current = numComplete
                    };
                    var forks = allDifferences.ForkDifferences.ToDelete.ToList();
                    var updatedForksToTreatAsDeletions = allDifferences.ForkDifferences.ToUpdate.Select(f => (uint)f.GlobalForkNumber).Where(f => !allDifferences.ForkDifferences.FailedOperations.Any(o => (o.Value.GlobalFileSystemNumber == f) && FileSystemHelpers.IsMissingForkError(o.Value)));
                    forks.AddRange(updatedForksToTreatAsDeletions);
                    currentDirtyFlags |= DeleteEntries(forks, deleteOpData, currentDirtyFlags, deviceFileSystem);
                    numComplete        = deleteOpData.Current;
                    succeeded          = data.Succeeded;
                }
            }

            if (data.AcceptCancelIfRequested())
            {
                return;
            }

            data.CurrentlyExecutingCommand = ProtocolCommandId.UnknownCommand;
            data.FailureMessage            = Resources.Strings.SyncHostToDeviceCommand_GatherUpdatesFailedMessage;
            var updateOperations = hostFileSystemWorkingCopy.GatherAllUpdates(allDifferences, device.UniqueId);
            if (updateOperations.Any())
            {
                do
                {
                    if (data.AcceptCancelIfRequested())
                    {
                        break;
                    }
                    LfsUpdateOperation operation = null;
                    data.FailureMessage = Resources.Strings.SyncHostToDevice_FetchUpdateOperationFailedMessage;
                    updateOperations    = updateOperations.FetchUpdateOperation(out operation);
                    if (data.AcceptCancelIfRequested())
                    {
                        break;
                    }

                    ++phaseNumber;
                    numComplete = 0;
                    total       = operation.Forks.Count + operation.Files.Count + operation.Directories.Count;
                    foreach (var failure in operation.Failures)
                    {
                        partialErrors[failure.Description] = failure.Exception;
                    }

                    // Load forks.
                    var address = 0u;
                    if (!data.CancelRequsted && succeeded && operation.Forks.Any())
                    {
                        data.FailureMessage = null;
                        var uploadOpData = new UploadDataOperationData(data, address)
                        {
                            TargetType           = LfsEntityType.Fork,
                            Factory              = (upl) => UploadDataBlockToRam.Create((uint)upl[0], (ByteSerializer)upl[1], (uint)upl[2]),
                            GetSerializer        = FileSystemHelpers.ToForkByteSerializer,
                            ShouldUpdateProgress = (k) => true,
                            UpdateTitleFormat    = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ProgressTitleFormat,
                            UpdateTitleInfo      = operation.ProgressTitle,
                            UpdateProgressFormat = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_TransferToRamProgressFormat,
                            Phase = phaseNumber, Total = total, Current = numComplete
                        };
                        address     = UploadEntries(operation.FileSystem.Forks, operation.Forks, uploadOpData);
                        numComplete = uploadOpData.Current;
                        succeeded   = data.Succeeded;
                    }

                    // Load GFT update.
                    if (!data.CancelRequsted && succeeded && operation.Files.Any())
                    {
                        data.FailureMessage = null;
                        var fileRange = operation.GfnRange;
                        var files     = Enumerable.Range(fileRange.Minimum, (fileRange.Maximum - fileRange.Minimum) + 1); // slower than a loop, but who cares?

                        var uploadOpData = new UploadDataOperationData(data, address)
                        {
                            TargetType           = LfsEntityType.File,
                            Factory              = (upl) => UploadDataBlockToRam.Create((uint)upl[0], (ByteSerializer)upl[1], (uint)upl[2]),
                            GetSerializer        = FileSystemHelpers.ToFileByteSerializer,
                            ShouldUpdateProgress = (f) => (f != null) && operation.Files.Contains(((ILfsFileInfo)f).GlobalFileNumber),
                            UpdateTitleFormat    = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ProgressTitleFormat,
                            UpdateTitleInfo      = operation.ProgressTitle,
                            UpdateProgressFormat = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_TransferToRamProgressFormat,
                            Phase   = phaseNumber,
                            Total   = total,
                            Current = numComplete
                        };

                        // THIS COULD BE DONE WITH ONE LARGE BLOCK INSTEAD OF MANY SMALLER ONES
                        address     = UploadEntries(operation.FileSystem.Files, files, uploadOpData);
                        numComplete = uploadOpData.Current;
                        succeeded   = data.Succeeded;
                    }

                    // Load GDT update.
                    if (!data.CancelRequsted && succeeded && operation.Directories.Any())
                    {
                        data.FailureMessage = null;
                        var directoryRange = operation.GdnRange;
                        var directories    = Enumerable.Range(directoryRange.Minimum, (directoryRange.Maximum - directoryRange.Minimum) + 1); // slower than a loop, but who cares?

                        var uploadOpData = new UploadDataOperationData(data, address)
                        {
                            TargetType           = LfsEntityType.Directory,
                            Factory              = (upl) => UploadDataBlockToRam.Create((uint)upl[0], (ByteSerializer)upl[1], (uint)upl[2]),
                            GetSerializer        = FileSystemHelpers.ToDirectoryByteSerializer,
                            ShouldUpdateProgress = (d) => (d != null) && operation.Files.Contains(((IDirectory)d).GlobalDirectoryNumber),
                            UpdateTitleFormat    = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ProgressTitleFormat,
                            UpdateTitleInfo      = operation.ProgressTitle,
                            UpdateProgressFormat = Resources.Strings.DeviceMultistageCommand_UpdatingFiles_TransferToRamProgressFormat,
                            Phase   = phaseNumber,
                            Total   = total,
                            Current = numComplete
                        };

                        // THIS COULD BE DONE WITH ONE LARGE BLOCK INSTEAD OF MANY SMALLER ONES
                        address     = UploadEntries(operation.FileSystem.Directories, directories, uploadOpData);
                        numComplete = uploadOpData.Current;
                        succeeded   = data.Succeeded;
                    }
                    if (data.AcceptCancelIfRequested())
                    {
                        break;
                    }

                    // Everything is in RAM now, so execute commands.
                    address     = 0; // All the data was initially loaded at location zero.
                    numComplete = 0;
                    total       = operation.Forks.Count;
                    if (operation.Files.Count > 0)
                    {
                        ++total;
                    }
                    if (operation.Directories.Count > 0)
                    {
                        ++total;
                    }

                    // Create forks.
                    if (!data.CancelRequsted && succeeded && operation.Forks.Any())
                    {
                        data.FailureMessage = null;
                        var numCreated  = 0;
                        var numToCreate = operation.Forks.Count;
                        foreach (var gkn in operation.Forks)
                        {
                            if (data.AcceptCancelIfRequested())
                            {
                                break;
                            }
                            address = address.Align();
                            var fork = operation.FileSystem.Forks[gkn];
                            updateString = string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.Strings.DeviceMultistageCommand_UpdatingFiles_ProgressTitleFormat, operation.ProgressTitle, ++numComplete, total, phaseNumber);
                            data.Task.UpdateTaskTitle(updateString);
                            updateString = string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.Strings.DeviceMultistageCommand_UpdatingFiles_CreatingItemProgressFormat, fork.Name, ++numCreated, numToCreate);
                            data.Task.UpdateTaskProgress((double)numCreated / numToCreate, updateString);
                            currentDirtyFlags |= currentDirtyFlags.UpdateFileSystemDirtyState(deviceFileSystem, data, gkn, LfsOperations.Add, LfsEntityType.Fork);
                            CreateForkFromRam.Create(address, fork).Execute(device.Port, data, out succeeded);
                            address += (uint)fork.SerializeByteCount;
                        }
                        address = address.Align();
                    }

                    // Update GFT.
                    if (!data.CancelRequsted && succeeded && operation.Files.Any())
                    {
                        data.FailureMessage = null;
                        if (data.AcceptCancelIfRequested())
                        {
                            break;
                        }
                        var gftRange = operation.GfnRange;
                        if (operation.Files.Count == 1)
                        {
                            updateString = string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.Strings.DeviceMultistageCommand_UpdatingFileSystemTablesOneEntry_ProgressTitleFormat, Resources.Strings.File, gftRange.Minimum, phaseNumber);
                        }
                        else
                        {
                            updateString = string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.Strings.DeviceMultistageCommand_UpdatingFileSystemTables_ProgressTitleFormat, Resources.Strings.File, gftRange.Minimum, gftRange.Maximum, phaseNumber);
                        }
                        data.Task.UpdateTaskTitle(updateString);
                        data.Task.UpdateTaskProgress((double)(++numComplete) / total, Resources.Strings.DeviceMultistageCommand_UpdatingGlobalFilesTable);
                        currentDirtyFlags |= currentDirtyFlags.UpdateFileSystemDirtyState(deviceFileSystem, data, gftRange.Minimum, LfsOperations.Update, LfsEntityType.File);
                        UpdateGlobalFileTable.Create(address, gftRange).Execute(device.Port, data, out succeeded);
                        address += (uint)(gftRange.Maximum - gftRange.Minimum + 1) * LfsFileInfo.FlatSizeInBytes;
                    }

                    // Update GDT.
                    if (!data.CancelRequsted && succeeded && operation.Directories.Any())
                    {
                        data.FailureMessage = null;
                        if (data.AcceptCancelIfRequested())
                        {
                            break;
                        }
                        var gdtRange = operation.GdnRange;
                        if (operation.Directories.Count == 1)
                        {
                            updateString = string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.Strings.DeviceMultistageCommand_UpdatingFileSystemTablesOneEntry_ProgressTitleFormat, Resources.Strings.Directory, gdtRange.Minimum, phaseNumber);
                        }
                        else
                        {
                            updateString = string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.Strings.DeviceMultistageCommand_UpdatingFileSystemTables_ProgressTitleFormat, Resources.Strings.Directory, gdtRange.Minimum, gdtRange.Maximum, phaseNumber);
                        }
                        data.Task.UpdateTaskTitle(updateString);
                        data.Task.UpdateTaskProgress((double)(++numComplete) / total, Resources.Strings.DeviceMultistageCommand_UpdatingGlobalDirectoriesTable);
                        currentDirtyFlags |= currentDirtyFlags.UpdateFileSystemDirtyState(deviceFileSystem, data, gdtRange.Minimum, LfsOperations.Update, LfsEntityType.Directory);
                        UpdateGlobalDirectoryTable.Create(address, gdtRange).Execute(device.Port, data, out succeeded);
                        address += (uint)(gdtRange.Maximum - gdtRange.Minimum + 1) * Directory.FlatSizeInBytes;
                    }
                }while (!data.CancelRequsted && succeeded && updateOperations.Any());
            }

            if (!data.CancelRequsted && data.Succeeded)
            {
                SetDirtyFlags.Create(LfsDirtyFlags.None).Execute(device.Port, data, out succeeded);
                deviceFileSystem.Status = LfsDirtyFlags.None;
            }

            if (!data.CancelRequsted && data.Succeeded)
            {
                var updatedFileSystem = DownloadFileSystemTables.Instance.Execute(device.Port, data, out succeeded) as FileSystem;
#if USE_SMART_COPY
                partialErrors = allDifferences.CombineAllFailures(partialErrors, ShouldIncludeError);
#endif // USE_SMART_COPY
                data.Result = new Tuple <FileSystem, IDictionary <string, FailedOperationException> >(updatedFileSystem, partialErrors);
            }
        }
Example #30
0
        private ActionBase ParseObjectAction(JProperty node, ActionType action_type)
        {
            switch (action_type)
            {
            case ActionType.Execute:

                string filename = mroot.substitue_enviro_vars(node.Value.ToString());

                ExecuteProcess executeAction = new ExecuteProcess();
                executeAction.FileName         = filename;
                executeAction.Params           = "";
                executeAction.OnlyIfNotRunning = true;

                return(executeAction);

            case ActionType.Wait:
                int waittime = Convert.ToInt32((node.Value.ToString()));

                WaitAction wait = new WaitAction();
                wait.Milliseconds = waittime;
                return(wait);

            case ActionType.ShowDialog:

                ShowDialog showDialog = new ShowDialog();
                showDialog.Message = mroot.substitue_enviro_vars(node.Value.ToString());
                return(showDialog);

            case ActionType.CopyFolder:

                throw new NotSupportedException("Simple CopyFolder is not allowed");

            case ActionType.CopyFile:

                throw new NotSupportedException("Simple CopyFile is not allowed");

            case ActionType.DeleteFile:
            {
                string sourceFile = mroot.substitue_enviro_vars(node.Value.ToString());

                DeleteFile delteFiles = new DeleteFile();
                delteFiles.SourceFile = sourceFile;
                return(delteFiles);
            }

            case ActionType.DeleteFiles:
            {
                string sourceFolder     = mroot.substitue_enviro_vars(node.Value.ToString());
                string delete_pattern   = "(.)";
                bool   recursive_delete = false;

                DeleteFiles delteFiles = new DeleteFiles();
                delteFiles.SourceFolder    = sourceFolder;
                delteFiles.DeletePattern   = delete_pattern;
                delteFiles.RecursiveDelete = recursive_delete;
                return(delteFiles);
            }

            case ActionType.DeleteFolder:
            {
                string dirPath = mroot.substitue_enviro_vars(node.Value.ToString());

                DeleteFolder deleteFolder = new DeleteFolder();
                deleteFolder.FolderPath = dirPath;
                return(deleteFolder);
            }

            case ActionType.DeleteFolders:
            {
                string sourceFolder   = mroot.substitue_enviro_vars(node.Value.ToString());
                string delete_pattern = "(.)";

                DeleteFolders deleteFolders = new DeleteFolders();
                deleteFolders.SourceFolder  = sourceFolder;
                deleteFolders.DeletePattern = delete_pattern;
                return(deleteFolders);
            }

            case ActionType.ZipFolder:

                throw new NotSupportedException("Simple ZipFolder is not allowed");
            }

            return(null);
        }
Example #31
0
        private ActionBase ParseObjectAction(JObject node, ActionType action_type)
        {
            switch (action_type)
            {
            case ActionType.ControlFlow:
                var condition = (node["condition"].ToString());

                if (condition.Equals("dialog"))
                {
                    return(ParseDialogControlFlow(node));
                }

                return(null);

            case ActionType.Execute:

                string filename         = mroot.substitue_enviro_vars(node["filename"].ToString());
                string paramxs          = node.ContainsKey("params") ? mroot.substitue_enviro_vars(node["params"].ToString()) : "";
                bool   onlyIfnotRunning = node.ContainsKey("onlyIfNotRunning") ? node["params"].Value <bool>() : true;

                ExecuteProcess executeAction = new ExecuteProcess();
                executeAction.FileName         = filename;
                executeAction.Params           = paramxs;
                executeAction.OnlyIfNotRunning = onlyIfnotRunning;

                return(executeAction);


            case ActionType.Wait:
                int waittime = (node["duration_ms"].Value <Int32>());

                WaitAction wait = new WaitAction();
                wait.Milliseconds = waittime;
                return(wait);

            case ActionType.ShowDialog:

                ShowDialog showDialog = new ShowDialog();
                showDialog.Message = mroot.substitue_enviro_vars(node["message"].ToString());
                if (node.ContainsKey("messagetype"))
                {
                    showDialog.MessageType = (ShowDialog.Type)Enum.Parse(typeof(ShowDialog.Type), node["messagetype"].ToString(), true);
                }
                return(showDialog);

            case ActionType.CopyFolder:

                string source       = mroot.substitue_enviro_vars(node["source"].ToString());
                string destination  = mroot.substitue_enviro_vars(node["destination"].ToString());
                string file_pattern = node.ContainsKey("desc") ? node["copy_filepattern"].ToString() : null;
                string dir_pattern  = node.ContainsKey("desc") ? node["copy_dirpattern"].ToString() : null;

                CopyFolder copyFolder = new CopyFolder();
                copyFolder.Source          = source ?? copyFolder.Source;
                copyFolder.Destination     = destination ?? copyFolder.Destination;
                copyFolder.CopyFilePattern = file_pattern ?? copyFolder.CopyFilePattern;
                copyFolder.CopyDirPattern  = dir_pattern ?? copyFolder.CopyDirPattern;

                return(copyFolder);

            case ActionType.CopyFile:

                source      = mroot.substitue_enviro_vars(node["source"].ToString());
                destination = mroot.substitue_enviro_vars(node["destination"].ToString());

                CopyFile copyFile = new CopyFile();
                copyFile.Source      = source;
                copyFile.Destination = destination;
                return(copyFile);

            case ActionType.DeleteFile:
            {
                string sourceFile = mroot.substitue_enviro_vars(node["source"].ToString());

                DeleteFile delteFiles = new DeleteFile();
                delteFiles.SourceFile = sourceFile;
                return(delteFiles);
            }

            case ActionType.DeleteFiles:
            {
                string sourceFolder     = mroot.substitue_enviro_vars(node["source"].ToString());
                string delete_pattern   = node.ContainsKey("pattern") ? node["pattern"].ToString() : "(.)";
                bool   recursive_delete = node.ContainsKey("recursive") ? node["recursive"].Value <bool>() : false;

                DeleteFiles delteFiles = new DeleteFiles();
                delteFiles.SourceFolder    = sourceFolder;
                delteFiles.DeletePattern   = delete_pattern;
                delteFiles.RecursiveDelete = recursive_delete;
                return(delteFiles);
            }

            case ActionType.DeleteFolder:
            {
                string dirPath = mroot.substitue_enviro_vars(node["source"].ToString());

                DeleteFolder deleteFolder = new DeleteFolder();
                deleteFolder.FolderPath = dirPath;
                return(deleteFolder);
            }

            case ActionType.DeleteFolders:
            {
                string sourceFolder   = mroot.substitue_enviro_vars(node["source"].ToString());
                string delete_pattern = node.ContainsKey("pattern") ? node["pattern"].ToString() : "(.)";

                DeleteFolders deleteFolders = new DeleteFolders();
                deleteFolders.SourceFolder  = sourceFolder;
                deleteFolders.DeletePattern = delete_pattern;
                return(deleteFolders);
            }

            case ActionType.ZipFolder:
            {
                string sourceFolder        = mroot.substitue_enviro_vars(node["source"].ToString());
                string zipfile_destination = mroot.substitue_enviro_vars(node["zipfile"].ToString());

                ZipFolder zipFolder = new ZipFolder();
                zipFolder.SourceFolder   = sourceFolder;
                zipFolder.DestinationZip = zipfile_destination;
                return(zipFolder);
            }
            }

            return(null);
        }
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			SetContentView (Resource.Layout.customer_calling_layout);

			bloaded = false;

			ActionBar.NavigationMode = ActionBarNavigationMode.Standard;
			ActionBar.SetTitle(Resource.String.calling_title);
			ActionBar.SetDisplayShowTitleEnabled (false);
			ActionBar.SetDisplayHomeAsUpEnabled(true);
			ActionBar.SetDisplayShowHomeEnabled (true);

			setHeadingTitle (Resource.String.calling_title);

			callingActivity = this;

			llProgress = FindViewById<LinearLayout> (Resource.Id.llProgressBar);
			llProgress.Visibility = ViewStates.Gone;

			tvName = FindViewById<TextView> (Resource.Id.tv_name_spec_calling);
			tvTimeDuration = FindViewById<TextView> (Resource.Id.tv_time_customer_calling);
			tvCostDuration = FindViewById<TextView> (Resource.Id.tv_cost_customer_calling);
			img_upfile = FindViewById<ImageView> (Resource.Id.img_upfile_calling);
			var avatar = FindViewById<ImageView> (Resource.Id.img_avatar_customer_calling);
			llFileAttach = FindViewById<LinearLayout> (Resource.Id.ll_file_attach_customer_calling);

			// Follow up action
			llGrFollowUpAction = FindViewById<LinearLayout> (Resource.Id.llGrFollowUpAction);
			imgRatingFollowUp = FindViewById<ImageView> (Resource.Id.imgRatingFolowUp);
			imgFavoriteFollowUp = FindViewById<ImageView> (Resource.Id.imgFavoriteFolowUp);
			imgEmailFollowUp = FindViewById<ImageView> (Resource.Id.imgEmailFollowUp);
			imgWaiveFeeFollowUp = FindViewById<ImageView> (Resource.Id.imgWaiveFeeFollowUp);
			imgTranscribeFollowUp = FindViewById<ImageView> (Resource.Id.imgTranscribeFollowUp);
			imgUpPhotoFollowUp = FindViewById<ImageView> (Resource.Id.imgUpPhotoFollowUp);
			imgReplayFollowUp = FindViewById<ImageView> (Resource.Id.imgReplayFollowUp);
			llRatingFollowUp = FindViewById<LinearLayout> (Resource.Id.llRatingFollowUp);
			llFavoriteFollowUp = FindViewById<LinearLayout> (Resource.Id.llFavoriteFollowUp);
			llEmailFollowUp = FindViewById<LinearLayout> (Resource.Id.llEmailFollowUp);
			llWaiveFollowUp = FindViewById<LinearLayout> (Resource.Id.llWaiveFeeFollowUp);
			llTransribeFollowUp = FindViewById<LinearLayout> (Resource.Id.llTranscribeFollowUp);
			llUpphotoFollowUp = FindViewById<LinearLayout> (Resource.Id.llUploadPhotoFollowUp);
			llReplayFollowUp = FindViewById<LinearLayout> (Resource.Id.llReplayFollowUp);
			tvWaiveFeeNotice = FindViewById<TextView> (Resource.Id.tv_notice_waived_calling);

			UrlImageViewHelper.UrlImageViewHelper.SetUrlDrawable (avatar, HttpConstants.BASE_URL + constants.durationInfo.AvatarPath, Resource.Drawable.special_home, constants.iTimeLoading, this);

			tvName.Text = constants.durationInfo.UserFullName;

			llGrFollowUpAction.Visibility = ViewStates.Gone;

			uploadPhoto = new UploadPhoto(this);
			uploadPhoto.actionUploadPhotoDelegate = this;

			deleteFile = new Teleconsult.Android.DeleteFile (this);
			deleteFile.deleteFileAction = this;

			// Action
			Background bgUpfile = new Background (this, Resource.Drawable.camera, Resource.Drawable.camera_pressed);
			img_upfile.SetBackgroundDrawable (bgUpfile);
			img_upfile.Click += (sender, e) => {
				if(uploadPhoto == null){
					uploadPhoto = new UploadPhoto(this);
					uploadPhoto.actionUploadPhotoDelegate = this;
				}
				uploadPhoto.selectActionUpload();
			};

			Background bgRating = new Background (this, Resource.Drawable.icon_feedback, Resource.Drawable.icon_feedback_pressed);
			imgRatingFollowUp.SetBackgroundDrawable (bgRating);
			imgRatingFollowUp.Click += (sender, e) => {
				if(isFeeback) {
					if(dialogFeedbackReview == null){
						dialogFeedbackReview = new RatingFeedbackReview(this);
					}
					dialogFeedbackReview.showFeedbackReview(iRatingNumber, sFeedBackContent);
				} else {
					if(dialogFeedback == null){
						dialogFeedback = new RatingFeedbackUI(this, callId);
						dialogFeedback.actionRatingDelegate = this;
					}
					dialogFeedback.showRatingFeedback();
				}
			};

			imgFavoriteFollowUp.Click += (sender, e) => {
				if (isFavorite) {
					if(dialogFavorite == null){
						dialogFavorite = new FavoriteUI(this);
						dialogFavorite.actionFavoriteDelegate = this;
					}
					dialogFavorite.removeFavoriteRequest(specId);
				} else {
					if(dialogFavorite == null){
						dialogFavorite = new FavoriteUI(this);
						dialogFavorite.actionFavoriteDelegate = this;
					}
					dialogFavorite.addToFavouriteRequest(specId);
				}
			};

			Background bgEmail = new Background (this, Resource.Drawable.ic_emailprofile, Resource.Drawable.ic_emailprofile_pressed);
			imgEmailFollowUp.SetBackgroundDrawable (bgEmail);
			imgEmailFollowUp.Click += (sender, e) => {
				SendEmailUI dialog = new SendEmailUI(this);
				dialog.actionDelegate = this;
				dialog.showEmailDialog(specId);
			};

			Background bgWaivefee = new Background (this, Resource.Drawable.ic_waive, Resource.Drawable.ic_waive_pressed);
			imgWaiveFeeFollowUp.SetBackgroundDrawable (bgWaivefee);
			imgWaiveFeeFollowUp.Click += (sender, e) => {
				if(dtEndWaiveFee != null && dtEndWaiveFee.AddMinutes (Constants.pTimeWaiveFee) >= Utils.getDateTimeNow (MApplication.getInstance ().timezoneName)){
					if (popupConfirm == null) {
						popupConfirm = new PopUpConfirm (this);
						popupConfirm.actionConfirmDelegate = this;
					}
					popupConfirm.showConfirmDialog (GetString(Resource.String.waive_fee_title), GetString(Resource.String.waive_fee_content), "Yes", "No");
				} else {
					popupNotice.showNoticeDialog(GetString(Resource.String.waive_fee_expired_title), GetString(Resource.String.waive_fee_expired));
					imgWaiveFeeFollowUp.Enabled = false;
					imgWaiveFeeFollowUp.SetBackgroundResource(Resource.Drawable.ic_waive_disable);
					imgWaiveFeeFollowUp.SetImageResource(Resource.Drawable.ic_waive_disable);
				}
			};

			Background bgTranscribe = new Background (this, Resource.Drawable.ic_transcribe, Resource.Drawable.ic_transcribe_pressed);
			imgTranscribeFollowUp.SetBackgroundDrawable (bgTranscribe);
			imgTranscribeFollowUp.Click += (sender, e) => {
				TranscribeRequest transcribe = new TranscribeRequest(this);
				transcribe.transcribeDelegate = this;
				transcribe.getTranscribe(callId, recordUrl);
			};

			Background bgUpphoto = new Background (this, Resource.Drawable.camera, Resource.Drawable.camera_pressed);
			imgUpPhotoFollowUp.SetBackgroundDrawable (bgUpphoto);
			imgUpPhotoFollowUp.Click += (sender, e) => {
				if(uploadPhoto == null){
					uploadPhoto = new UploadPhoto(this);
					uploadPhoto.actionUploadPhotoDelegate = this;
				}
				uploadPhoto.selectActionUpload();
			};

			Background bgReplay = new Background (this, Resource.Drawable.ic_replay, Resource.Drawable.ic_replay_pressed);
			imgReplayFollowUp.SetBackgroundDrawable (bgReplay);
			imgReplayFollowUp.Click += (sender, e) => {
				if(recordUrl != null){
					if(!recordUrl.Equals("")){
						Intent intent = new Intent(this, typeof(PlayAudioManager));
						intent.PutExtra(constants.pPathAudioFile, recordUrl);
						StartActivity(intent);
					} else {
						popupNotice.showNoticeDialog(GetString(Resource.String.title_notice), GetString(Resource.String.replay_not_exist_notice));
					}
				} else {
					popupNotice.showNoticeDialog(GetString(Resource.String.title_notice), GetString(Resource.String.replay_not_exist_notice));
				}
			};

			popupNotice = new PopupNoticeInfomation (this);
			popupNotice.noticeDelegate = this;

			updateCallStart (constants.durationInfo);
			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostStopCall, new TCSelector (updateCallStop));
			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostFolloUp, new TCSelector (onFollowUpAction));
			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostUploadFileSuccess, new TCSelector (onUploadFileSuccess));
			TCNotificationCenter.defaultCenter.addObserver (this, Constants.kPostDeleteFileSuccess, new TCSelector (onDeleteFileSuccess));
		}
Example #33
0
        public static string[] SplitedString; // The Splited String
        public static void ReadAsync(string Command)
        {
            SplitedString = Command.Split(' '); // The Splited String

            // Format the current Taiyou Line
            for (int i = 0; i < SplitedString.Length; i++)
            {
                // FORMATATION
                SplitedString[i] = SplitedString[i].Replace("%N", Environment.NewLine); // New Line

                for (int i2 = 0; i2 < GlobalVars_String_Names.Count; i2++)
                {
                    SplitedString[i] = SplitedString[i].Replace("$STRING_" + GlobalVars_String_Names[i2] + "$", GlobalVars_String_Content[i2].Replace(" ", ""));
                }
                for (int i2 = 0; i2 < GlobalVars_Bool_Names.Count; i2++)
                {
                    SplitedString[i] = SplitedString[i].Replace("$BOOL_" + GlobalVars_Bool_Names[i2] + "$", Convert.ToString(GlobalVars_Bool_Content[i2]));
                }
                for (int i2 = 0; i2 < GlobalVars_Int_Names.Count; i2++)
                {
                    SplitedString[i] = SplitedString[i].Replace("$INT_" + GlobalVars_Int_Names[i2] + "$", Convert.ToString(GlobalVars_Int_Content[i2]));
                }
                for (int i2 = 0; i2 < GlobalVars_Float_Names.Count; i2++)
                {
                    SplitedString[i] = SplitedString[i].Replace("$FLOAT_" + GlobalVars_Float_Names[i2] + "$", Convert.ToString(GlobalVars_Float_Content[i2]));
                }



                if (SplitedString[i].Contains("%RANDOM%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   Arg1             = SubSplitedString[2]; // Number 1
                    string   Arg2             = SubSplitedString[3]; // Number 2
                    Random   RND = new Random();

                    SplitedString[i] = SplitedString[i].Replace("%RANDOM%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(RND.Next(Convert.ToInt32(Arg1), Convert.ToInt32(Arg2))));
                }

                if (SplitedString[i].Contains("%ADD%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');

                    string Arg1       = SubSplitedString[2]; // Number 1
                    string Arg2       = SubSplitedString[3]; // Number 2
                    int    MathResult = Convert.ToInt32(Arg1) + Convert.ToInt32(Arg2);

                    SplitedString[i] = SplitedString[i].Replace("%ADD%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(MathResult));
                }

                if (SplitedString[i].Contains("%DECREASE%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   Arg1             = SubSplitedString[2]; // Number 1
                    string   Arg2             = SubSplitedString[3]; // Number 2
                    int      MathResult       = Convert.ToInt32(Arg1) - Convert.ToInt32(Arg2);

                    SplitedString[i] = SplitedString[i].Replace("%DECREASE%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(MathResult));
                }

                if (SplitedString[i].Contains("%MULTIPLY%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   Arg1             = SubSplitedString[2]; // Number 1
                    string   Arg2             = SubSplitedString[3]; // MultiplyTimes
                    int      MathResult       = Convert.ToInt32(Arg1) * Convert.ToInt32(Arg2);

                    SplitedString[i] = SplitedString[i].Replace("%MULTIPLY%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(MathResult));
                }

                if (SplitedString[i].Contains("%DIVIDE%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   Arg1             = SubSplitedString[2]; // Number 1
                    string   Arg2             = SubSplitedString[3]; // Number 2
                    int      MathResult       = Convert.ToInt32(Arg1) / Convert.ToInt32(Arg2);

                    SplitedString[i] = SplitedString[i].Replace("%DIVIDE%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(MathResult));
                }

                if (SplitedString[i].Contains("%DIFERENCE%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   Arg1             = SubSplitedString[2]; // Number 1
                    string   Arg2             = SubSplitedString[3]; // Number 2
                    int      MathResult       = Math.Abs(Convert.ToInt32(Arg1) - Convert.ToInt32(Arg2));


                    SplitedString[i] = SplitedString[i].Replace("%DIFERENCE%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(MathResult));
                }

                if (SplitedString[i].Contains("%PERCENTAGE%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   Arg1             = SubSplitedString[2]; // Number 1
                    string   Arg2             = SubSplitedString[3]; // Number 2
                    int      MathResult       = (int)Math.Round((double)(100 * Convert.ToInt32(Arg1)) / Convert.ToInt32(Arg2));


                    SplitedString[i] = SplitedString[i].Replace("%PERCENTAGE%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(MathResult));
                }

                if (SplitedString[i].Contains("%LOCATION_OF%"))
                {
                    string[]  SubSplitedString = SplitedString[i].Split('%');
                    string    Arg1             = SubSplitedString[2]; // Render Type
                    string    Arg2             = SubSplitedString[3]; // Render Name
                    string    Arg3             = SubSplitedString[4]; // Value Type
                    Rectangle RectObject       = GlobalVars_Rectangle_Content[RenderQuee.Main.RenderCommand_RectangleVar.IndexOf(Arg2)];

                    int RenderNameIndex = -1;
                    if (Arg1 == "SPRITE")
                    {
                        RenderNameIndex = RenderQuee.Main.RenderCommand_Name.IndexOf(Arg2);
                    }
                    ;
                    if (Arg1 == "TEXT")
                    {
                        RenderNameIndex = RenderQuee.Main.TextRenderCommand_Name.IndexOf(Arg2);
                    }
                    ;
                    int ValToReturn = 0;
                    if (Arg3 == "X" && Arg1 == "SPRITE")
                    {
                        ValToReturn = RectObject.X;
                    }
                    ;
                    if (Arg3 == "X" && Arg1 == "TEXT")
                    {
                        ValToReturn = RenderQuee.Main.TextRenderCommand_X[RenderNameIndex];
                    }

                    if (Arg3 == "Y" && Arg1 == "SPRITE")
                    {
                        ValToReturn = RectObject.Y;
                    }
                    ;
                    if (Arg3 == "Y" && Arg1 == "TEXT")
                    {
                        ValToReturn = RenderQuee.Main.TextRenderCommand_Y[RenderNameIndex];
                    }
                    ;

                    if (Arg3 == "W" && Arg1 == "SPRITE")
                    {
                        ValToReturn = RectObject.Width;
                    }
                    ;
                    if (Arg3 == "H" && Arg1 == "SPRITE")
                    {
                        ValToReturn = RectObject.Height;
                    }
                    ;


                    SplitedString[i] = SplitedString[i].Replace("%LOCATION_OF%" + Arg1 + "%" + Arg2 + "%" + Arg3 + "%", Convert.ToString(ValToReturn));
                }

                if (SplitedString[i].Contains("%COLOR_VALUE%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   Arg1             = SubSplitedString[2]; // ColorVarName
                    string   Arg2             = SubSplitedString[3]; // CodeName
                    int      ColorVarIndex    = GlobalVars_Color_Names.IndexOf(Arg1);
                    string   ValToReturn      = "0";
                    if (ColorVarIndex == -1)
                    {
                        throw new Exception("Color Variable [" + Arg1 + "] does not exist.");
                    }

                    if (Arg2.Equals("R"))
                    {
                        ValToReturn = Convert.ToString(GlobalVars_Color_Content[ColorVarIndex].R);
                    }
                    ;
                    if (Arg2.Equals("G"))
                    {
                        ValToReturn = Convert.ToString(GlobalVars_Color_Content[ColorVarIndex].G);
                    }
                    ;
                    if (Arg2.Equals("B"))
                    {
                        ValToReturn = Convert.ToString(GlobalVars_Color_Content[ColorVarIndex].B);
                    }
                    ;
                    if (Arg2.Equals("A"))
                    {
                        ValToReturn = Convert.ToString(GlobalVars_Color_Content[ColorVarIndex].A);
                    }
                    ;
                    if (Arg2.Equals("ALL"))
                    {
                        ValToReturn = GlobalVars_Color_Content[ColorVarIndex].R + "," + GlobalVars_Color_Content[ColorVarIndex].G + "," + GlobalVars_Color_Content[ColorVarIndex].B + "," + GlobalVars_Color_Content[ColorVarIndex].A;
                    }
                    ;


                    SplitedString[i] = SplitedString[i].Replace("%COLOR_VALUE%" + Arg1 + "%" + Arg2 + "%", Convert.ToString(ValToReturn));
                }


                if (SplitedString[i].Contains("%LIST_VALUE%"))
                {
                    string[] SubSplitedString = SplitedString[i].Split('%');
                    string   ValToReturn      = "null_or_incorrect";
                    string   Arg1             = SubSplitedString[2]; // ListType
                    string   Arg2             = SubSplitedString[3]; // ListName
                    string   Arg3             = SubSplitedString[4]; // Index

                    if (Arg1.Equals("STRING"))
                    {
                        int ListNameIndex = GlobalVars_StringList_Names.IndexOf(Arg2);
                        int Index         = Convert.ToInt32(Arg3);

                        ValToReturn = GlobalVars_StringList_Content[ListNameIndex][Index];
                    }

                    if (Arg1.Equals("INT"))
                    {
                        int ListNameIndex = GlobalVars_IntList_Names.IndexOf(Arg2);
                        int Index         = Convert.ToInt32(Arg3);

                        ValToReturn = Convert.ToString(GlobalVars_IntList_Content[ListNameIndex][Index]);
                    }

                    if (Arg1.Equals("COLOR"))
                    {
                        int ListNameIndex = GlobalVars_ColorList_Names.IndexOf(Arg2);
                        int Index         = Convert.ToInt32(Arg3);

                        Color  ColorGetted       = GlobalVars_ColorList_Content[ListNameIndex][Index];
                        string ColorCodeToReturn = ColorGetted.R + "," + ColorGetted.G + "," + ColorGetted.B + "," + ColorGetted.A;

                        ValToReturn = ColorCodeToReturn;
                    }

                    if (Arg1.Equals("FLOAT"))
                    {
                        int ListNameIndex = GlobalVars_FloatList_Names.IndexOf(Arg2);
                        int Index         = Convert.ToInt32(Arg3);

                        ValToReturn = Convert.ToString(GlobalVars_FloatList_Content[ListNameIndex][Index]);
                    }

                    if (Arg1.Equals("RECTANGLE"))
                    {
                        int ListNameIndex = GlobalVars_RectangleList_Names.IndexOf(Arg2);
                        int Index         = Convert.ToInt32(Arg3);

                        Rectangle RectGetted    = GlobalVars_RectangleList_Content[ListNameIndex][Index];
                        string    RectangleCode = RectGetted.X + "," + RectGetted.Y + "," + RectGetted.Width + "," + RectGetted.Height;

                        ValToReturn = Convert.ToString(RectangleCode);
                    }


                    SplitedString[i] = SplitedString[i].Replace("%LIST_VALUE%" + Arg1 + "%" + Arg2 + "%" + Arg3 + "%", Convert.ToString(ValToReturn));
                }
            }


            // Begin Command Interpretation
            if (SplitedString[0].Equals("0x0"))
            {
                Clear.Initialize();
            }
            if (SplitedString[0].Equals("0x1"))
            {
                Call.Initialize(SplitedString[1]);
            }
            if (SplitedString[0].Equals("0x2"))
            {
                Write.Initialize(SplitedString[1]);
            }
            if (SplitedString[0].Equals("0x3"))
            {
                WriteLine.Initialize(SplitedString[1]);
            }
            if (SplitedString[0].Equals("0x4"))
            {
                WriteFile.Initialize(SplitedString[1], SplitedString[2]);
            }
            if (SplitedString[0].Equals("0x5"))
            {
                TaiyouIF.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("0x6"))
            {
                Abort.Initialize();
            }
            if (SplitedString[0].Equals("0x7"))
            {
                Declare.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("0x8"))
            {
                WriteVar.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("0x9"))
            {
                MathOP.Intialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x0"))
            {
                Goto.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x1"))
            {
                FileExists.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x2"))
            {
                ReadFile.Intialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x3"))
            {
                DirectoryExists.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x4"))
            {
                DownloadServerString.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x5"))
            {
                CopyFile.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x6"))
            {
                MoveFile.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x7"))
            {
                DeleteFile.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x8"))
            {
                AddRenderQuee.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("1x9"))
            {
                AddEvent.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("2x0"))
            {
                CheckEvent.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("2x1"))
            {
                ChangeWindowPropertie.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("2x2"))
            {
                Colision.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("2x3"))
            {
                Reload.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("2x4"))
            {
                GetKeyPressed.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("2x5"))
            {
                AddRenderTextQuee.Initialize(SplitedString);
            }
            if (SplitedString[0].Equals("2x6"))
            {
                ChangeRenderProp.Initialize(SplitedString);
            }

            if (SplitedString[0].Equals("2x7"))
            {
                ChangeBackgroundColor.Initialize(SplitedString);
            }

            if (SplitedString[0].Equals("2x8"))
            {
                Undeclare.Initialize(SplitedString);
            }

            if (SplitedString[0].Equals("2x9"))
            {
                SendBGMCommand.Initialize(SplitedString);
            }

            if (SplitedString[0].Equals("3x0"))
            {
                MasterVolume.Initialize(SplitedString);
            }

            if (SplitedString[0].Equals("3x1"))
            {
                LanguageSystemManager.Initialize(SplitedString);
            }

            if (SplitedString[0].Equals("3x2"))
            {
                // FIXME Not Working
                //VarMath.Initialize(SplitedString);
            }



            if (Global.IsLowLevelDebugEnabled)
            {
                for (int i = 0; i < SplitedString.Length; i++)
                {
                    Console.Write(SplitedString[i] + " ");
                }
                Console.Write("\n");
            }
        }
Example #34
0
        public static SetupTask CreateFrom(XElement taskElement)
        {
            SetupTask result;

            switch (taskElement.Name.LocalName)
            {
            case "Group":
                result = new Composite(taskElement);
                break;

            case "ExtractArchive":
                result = new ExtractArchive(taskElement);
                break;

            case "TweakINI":
                result = new TweakINI(taskElement);
                break;

            case "CopyFile":
                result = new CopyFile(taskElement);
                break;

            case "Embedded":
                result = new Embedded(taskElement);
                break;

            case "Clean":
                result = new Clean(taskElement);
                break;

            case "CreateEmptyFolder":
                result = new CreateEmptyFolder(taskElement);
                break;

            case "RunProcess":
                result = new RunProcess(taskElement);
                break;

            case "DeleteFolder":
                result = new DeleteFolder(taskElement);
                break;

            case "DeleteFile":
                result = new DeleteFile(taskElement);
                break;

            case "MoveFolder":
                result = new MoveFolder(taskElement);
                break;

            case "EditFile":
                result = new EditFile(taskElement);
                break;

            case "Dummy":
                result = new Composite();
                break;

            default:
                throw new NotSupportedException("Task type " + taskElement.Name.LocalName + " is not supported.");
            }

            result.xml = taskElement.ToString();
            result.Id  = taskElement.Attribute("Id")?.Value ?? Guid.NewGuid().ToString();

            // this feels clunky, but that's fine I guess...
            result.WaitFor = result.WaitFor.Union(Program.Tokenize(taskElement.Attribute("WaitFor")?.Value)).ToImmutableArray();
            return(result);
        }
Example #35
0
        public void Dispose()
        {
            // Clearing all of these ensures that the transient APIs
            // can't be called outside of the appropriate scope.

            #region dispose-dispatcher service-apis
            _GetNuGetExePath             = null;
            _GetNuGetDllPath             = null;
            _DownloadFile                = null;
            _AddPinnedItemToTaskbar      = null;
            _RemovePinnedItemFromTaskbar = null;
            _CreateShortcutLink          = null;
            _UnzipFileIncremental        = null;
            _UnzipFile                 = null;
            _AddFileAssociation        = null;
            _RemoveFileAssociation     = null;
            _AddExplorerMenuItem       = null;
            _RemoveExplorerMenuItem    = null;
            _SetEnvironmentVariable    = null;
            _RemoveEnvironmentVariable = null;
            _AddFolderToPath           = null;
            _RemoveFolderFromPath      = null;
            _InstallMSI                = null;
            _RemoveMSI                 = null;
            _StartProcess              = null;
            _InstallVSIX               = null;
            _UninstallVSIX             = null;
            _InstallPowershellScript   = null;
            _UninstallPowershellScript = null;
            _SearchForExecutable       = null;
            _GetUserBinFolder          = null;
            _GetSystemBinFolder        = null;
            _CopyFile                = null;
            _CopyFolder              = null;
            _Delete                  = null;
            _DeleteFolder            = null;
            _CreateFolder            = null;
            _DeleteFile              = null;
            _BeginTransaction        = null;
            _AbortTransaction        = null;
            _EndTransaction          = null;
            _GenerateUninstallScript = null;
            _GetKnownFolder          = null;
            _IsElevated              = null;
            #endregion

            #region dispose-dispatcher core-apis
            _Warning          = null;
            _Message          = null;
            _Error            = null;
            _Debug            = null;
            _Verbose          = null;
            _ExceptionThrown  = null;
            _Progress         = null;
            _ProgressComplete = null;
            _GetHostDelegate  = null;
            _IsCancelled      = null;
            #endregion

            #region dispose-dispatcher request-apis
            _OkToContinue                       = null;
            _YieldPackage                       = null;
            _YieldPackageDetails                = null;
            _YieldPackageSwidtag                = null;
            _YieldSource                        = null;
            _YieldMetadataDefinition            = null;
            _YieldInstallationOptionsDefinition = null;
            #endregion

            #region dispose-dispatcher host-apis
            _GetMetadataKeys             = null;
            _GetMetadataValues           = null;
            _GetInstallationOptionKeys   = null;
            _GetInstallationOptionValues = null;
            _PackageSources   = null;
            _GetConfiguration = null;
            _ShouldContinueWithUntrustedPackageSource = null;
            _ShouldProcessPackageInstall                = null;
            _ShouldProcessPackageUninstall              = null;
            _ShouldContinueAfterPackageInstallFailure   = null;
            _ShouldContinueAfterPackageUninstallFailure = null;
            _ShouldContinueRunningInstallScript         = null;
            _ShouldContinueRunningUninstallScript       = null;
            _AskPermission = null;
            _WhatIf        = null;
            #endregion

            #region dispose-dispatcher protocol-apis
            _ProtocolGetNames        = null;
            _ProtocolIsValidSource   = null;
            _ProtocolGetItemMetadata = null;
            _ProtocolDownloadItem    = null;
            _ProtocolUnpackItem      = null;
            _InstallItem             = null;
            #endregion

            _callback = null;
        }
Example #36
0
 /// <summary>
 /// 引发 <see cref="DeleteFile" /> 事件
 /// </summary>
 protected virtual void OnDeleteFile(InstallFileEventArgs e)
 {
     DeleteFile?.Invoke(this, e);
 }