Inheritance: IDisposable
Ejemplo n.º 1
0
        /// <summary>
        ///   Fetch from the <see cref = "Remote" />.
        /// </summary>
        /// <param name="remote">The remote to fetch</param>
        /// <param name="tagFetchMode">Optional parameter indicating what tags to download.</param>
        /// <param name="onProgress">Progress callback. Corresponds to libgit2 progress callback.</param>
        /// <param name="onCompletion">Completion callback. Corresponds to libgit2 completion callback.</param>
        /// <param name="onUpdateTips">UpdateTips callback. Corresponds to libgit2 update_tips callback.</param>
        /// <param name="onTransferProgress">Callback method that transfer progress will be reported through.
        ///   Reports the client's state regarding the received and processed (bytes, objects) from the server.</param>
        /// <param name="credentials">Credentials to use for username/password authentication.</param>
        public virtual void Fetch(
            Remote remote,
            TagFetchMode tagFetchMode = TagFetchMode.Auto,
            ProgressHandler onProgress = null,
            CompletionHandler onCompletion = null,
            UpdateTipsHandler onUpdateTips = null,
            TransferProgressHandler onTransferProgress = null,
            Credentials credentials = null)
        {
            Ensure.ArgumentNotNull(remote, "remote");

            // We need to keep a reference to the git_cred_acquire_cb callback around
            // so it will not be garbage collected before we are done with it.
            // Note that we also have a GC.KeepAlive call at the end of the method.
            NativeMethods.git_cred_acquire_cb credentialCallback = null;

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true))
            {
                var callbacks = new RemoteCallbacks(onProgress, onCompletion, onUpdateTips);
                GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks();

                Proxy.git_remote_set_autotag(remoteHandle, tagFetchMode);

                if (credentials != null)
                {
                    credentialCallback = (out IntPtr cred, IntPtr url, IntPtr username_from_url, uint types, IntPtr payload) =>
                        NativeMethods.git_cred_userpass_plaintext_new(out cred, credentials.Username, credentials.Password);

                    Proxy.git_remote_set_cred_acquire_cb(
                        remoteHandle,
                        credentialCallback,
                        IntPtr.Zero);
                }

                // It is OK to pass the reference to the GitCallbacks directly here because libgit2 makes a copy of
                // the data in the git_remote_callbacks structure. If, in the future, libgit2 changes its implementation
                // to store a reference to the git_remote_callbacks structure this would introduce a subtle bug
                // where the managed layer could move the git_remote_callbacks to a different location in memory,
                // but libgit2 would still reference the old address.
                //
                // Also, if GitRemoteCallbacks were a class instead of a struct, we would need to guard against
                // GC occuring in between setting the remote callbacks and actual usage in one of the functions afterwords.
                Proxy.git_remote_set_callbacks(remoteHandle, ref gitCallbacks);

                try
                {
                    Proxy.git_remote_connect(remoteHandle, GitDirection.Fetch);
                    Proxy.git_remote_download(remoteHandle, onTransferProgress);
                    Proxy.git_remote_update_tips(remoteHandle);
                }
                finally
                {
                    Proxy.git_remote_disconnect(remoteHandle);
                }
            }

            // To be safe, make sure the credential callback is kept until
            // alive until at least this point.
            GC.KeepAlive(credentialCallback);
        }
Ejemplo n.º 2
0
        private ProgressBar progressBar; // Progress spinner to use for table operations

        // Called when the activity initially gets created
		protected override async void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Activity_To_Do);

            // Initialize the progress bar
			progressBar = FindViewById<ProgressBar>(Resource.Id.loadingProgressBar);
			progressBar.Visibility = ViewStates.Gone;

			// Create ProgressFilter to handle busy state
			var progressHandler = new ProgressHandler ();
			progressHandler.BusyStateChange += (busy) => {
				if (progressBar != null) 
					progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
			};

			try 
            {
                // PUSH NOTIFICATIONS: Register for push notifications
                System.Diagnostics.Debug.WriteLine("Registering...");
				// Initialize our Gcm Service Hub
				GcmService.Initialize(this);
				GcmService.Register(this);


				// MOBILE SERVICES: Setup azure mobile services - this is separate from push notifications
				CurrentPlatform.Init ();
				// Create the Mobile Service Client instance, using the provided
				// Mobile Service URL and key
				client = new MobileServiceClient(
					Constants.ApplicationURL,
					Constants.ApplicationKey, progressHandler);

				// Get the Mobile Service Table instance to use
				todoTable = client.GetTable<TodoItem>();


				// USER INTERFACE: setup the Android UI
				textNewTodo = FindViewById<EditText>(Resource.Id.textNewTodo);

				// Create an adapter to bind the items with the view
				adapter = new TodoItemAdapter(this, Resource.Layout.Row_List_To_Do);
				var listViewTodo = FindViewById<ListView>(Resource.Id.listViewTodo);
				listViewTodo.Adapter = adapter;

				// Load the items from the Mobile Service
				await RefreshItemsFromTableAsync();
			} 
            catch (Java.Net.MalformedURLException) 
            {
				CreateAndShowDialog(new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
			} 
            catch (Exception e) 
            {
				CreateAndShowDialog(e, "Error");
			}
		}
Ejemplo n.º 3
0
        private ProgressBar progressBar; // Progress spinner to use for table operations

        // Called when the activity initially gets created
		protected override async void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Activity_To_Do);

            // Initialize the progress bar
			progressBar = FindViewById<ProgressBar>(Resource.Id.loadingProgressBar);
			progressBar.Visibility = ViewStates.Gone;

			// Create ProgressFilter to handle busy state
			// Create ProgressFilter to handle busy state
			var progressHandler = new ProgressHandler ();
			progressHandler.BusyStateChange += (busy) => {
				if (progressBar != null) 
					progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
			};

			try 
            {
                // Check to ensure everything's setup right
                PushClient.CheckDevice(this);
                PushClient.CheckManifest(this);

                // Register for push notifications
                System.Diagnostics.Debug.WriteLine("Registering...");
                PushClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);

				CurrentPlatform.Init ();
				// Create the Mobile Service Client instance, using the provided
				// Mobile Service URL and key
				client = new MobileServiceClient(
					Constants.ApplicationURL,
					Constants.ApplicationKey, progressHandler);

				// Get the Mobile Service Table instance to use
				todoTable = client.GetTable<TodoItem>();

				textNewTodo = FindViewById<EditText>(Resource.Id.textNewTodo);

				// Create an adapter to bind the items with the view
				adapter = new TodoItemAdapter(this, Resource.Layout.Row_List_To_Do);
				var listViewTodo = FindViewById<ListView>(Resource.Id.listViewTodo);
				listViewTodo.Adapter = adapter;

				// Load the items from the Mobile Service
				await RefreshItemsFromTableAsync();

			} 
            catch (Java.Net.MalformedURLException) 
            {
				CreateAndShowDialog(new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
			} 
            catch (Exception e) 
            {
				CreateAndShowDialog(e, "Error");
			}
		}
Ejemplo n.º 4
0
 /// <summary>
 /// Creates a new progress reporter.
 /// </summary>
 /// <param name="handler">Report through this handler.</param>
 public Progress(ProgressHandler handler)
 {
     this.handler = handler;
       this.fractions = new Stack<double>();
       this.fractions.Push(1d);
       this.value = 0d;
       this.lastProgressSet = 0;
 }
Ejemplo n.º 5
0
 internal RemoteCallbacks(FetchOptions fetchOptions)
 {
     Ensure.ArgumentNotNull(fetchOptions, "fetchOptions");
     Progress = fetchOptions.OnProgress;
     DownloadTransferProgress = fetchOptions.OnTransferProgress;
     UpdateTips = fetchOptions.OnUpdateTips;
     Credentials = fetchOptions.Credentials;
 }
        protected override async void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Activity_To_Do);

            progressBar = FindViewById<ProgressBar> (Resource.Id.loadingProgressBar);

            // Initialize the progress bar
            progressBar.Visibility = ViewStates.Gone;

            // Create ProgressFilter to handle busy state
            var progressHandler = new ProgressHandler ();
            progressHandler.BusyStateChange += (busy) => {
                if (progressBar != null) 
                    progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
            };

            try {
                CurrentPlatform.Init ();
                // Create the Mobile Service Client instance, using the provided
                // Mobile Service URL and key
                client = new MobileServiceClient (
                    applicationURL,
                    applicationKey, progressHandler);

                string path = 
                    Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "localstore.db");
                
                if (!File.Exists(path))
                {
                    File.Create(path).Dispose();
                }
                var store = new MobileServiceSQLiteStore(path);
                store.DefineTable<ToDoItem>();
                await client.SyncContext.InitializeAsync(store, new SyncHandler(this));

                // Get the Mobile Service Table instance to use
                toDoTable = client.GetSyncTable <ToDoItem> ();

                textNewToDo = FindViewById<EditText> (Resource.Id.textNewToDo);

                // Create an adapter to bind the items with the view
                adapter = new ToDoItemAdapter (this, Resource.Layout.Row_List_To_Do);
                var listViewToDo = FindViewById<ListView> (Resource.Id.listViewToDo);
                listViewToDo.Adapter = adapter;

                // Load the items from the Mobile Service
                await RefreshItemsFromTableAsync ();

            } catch (Java.Net.MalformedURLException) {
                CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
            } catch (Exception e) {
                CreateAndShowDialog (e, "Error");
            }
        }
Ejemplo n.º 7
0
        private ProgressBar progressBar; // Progress spinner to use for table operations

        // Called when the activity initially gets created
		protected override async void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Activity_To_Do);

            // Initialize the progress bar
			progressBar = FindViewById<ProgressBar>(Resource.Id.loadingProgressBar);
			progressBar.Visibility = ViewStates.Gone;

            // TODO:: Uncomment the following code when using a mobile service
            
			// Create ProgressFilter to handle busy state
			var progressHandler = new ProgressHandler ();
			progressHandler.BusyStateChange += (busy) => {
				if (progressBar != null) 
					progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
			};
                     

			try 
            {
                // TODO:: Uncomment the following code to create the mobile services client

				CurrentPlatform.Init ();
				// Create the Mobile Service Client instance, using the provided
				// Mobile Service URL and key
				client = new MobileServiceClient(
					Constants.ApplicationURL,
					Constants.ApplicationKey, progressHandler);

				// Get the Mobile Service Table instance to use
				todoTable = client.GetTable<TodoItem>();

				textNewTodo = FindViewById<EditText>(Resource.Id.textNewTodo);

				// Create an adapter to bind the items with the view
				adapter = new TodoItemAdapter(this, Resource.Layout.Row_List_To_Do);
				var listViewTodo = FindViewById<ListView>(Resource.Id.listViewTodo);
				listViewTodo.Adapter = adapter;

				// Load the items from the Mobile Service
				await RefreshItemsFromTableAsync();

			} 
            catch (Java.Net.MalformedURLException) 
            {
				CreateAndShowDialog(new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
			} 
            catch (Exception e) 
            {
				CreateAndShowDialog(e, "Error");
			}
		}
Ejemplo n.º 8
0
 internal RemoteCallbacks(
     ProgressHandler onProgress = null,
     TransferProgressHandler onDownloadProgress = null,
     UpdateTipsHandler onUpdateTips = null,
     CredentialsHandler credentialsProvider = null)
 {
     Progress = onProgress;
     DownloadTransferProgress = onDownloadProgress;
     UpdateTips = onUpdateTips;
     CredentialsProvider = credentialsProvider;
 }
Ejemplo n.º 9
0
        public OperationPending(string langKey, string TaskName, ProgressHandler progressHandler, Cancel cancelCallback = null, bool AutoClose = false)
            : base(langKey)
        {
            InitializeComponent();
            this.progressHandler = progressHandler;
            this.TaskName = TaskName;
            this.CancelCallback = cancelCallback;
            this.AutoClose = AutoClose;

            this.LangKey = langKey;
            Init();
        }
Ejemplo n.º 10
0
        public static ResultCode Load(ProgressHandler handler)
        {
            currentProgressHandler = handler;
            string gameConfigPath = Configuration.GetPath("GameConfigurations");
            if (gameConfigPath == "")
            {
                Error = ErrorCode.MALFORMED_CONFIGURATION;
                ErrorString = "Couldn't find the game configurations path.";
                Debug.Log("GUIConfiguration", ErrorString, Debug.Type.ERROR);
                return ResultCode.ERROR;
            }

            string gameConfigFile = Path.GetFullPath(gameConfigPath + Path.DirectorySeparatorChar + Configuration.CurrentGame + Path.DirectorySeparatorChar + "GUI.xml");
            if (!File.Exists(gameConfigFile))
            {
                Error = ErrorCode.FILE_NOT_FOUND;
                ErrorString = "Couldn't find the file \"" + gameConfigFile + "\".";
                Debug.Log("GUIConfiguration", ErrorString, Debug.Type.ERROR);
                return ResultCode.ERROR;
            }

            Debug.Log("GUIConfiguration", "Parsing the GUI configuration file \"" + gameConfigFile + "\".");
            try
            {
                XDocument configuration = XDocument.Load(gameConfigFile);
                Tabs = new List<Tab>();
                if (!ParseTabs(configuration.Root))
                {
                    Error = ErrorCode.MALFORMED_CONFIGURATION;
                    ErrorString = "The configuration file \"" + gameConfigFile + "\" contains invalid elements.";
                    Debug.Log("GUIConfiguration", ErrorString, Debug.Type.ERROR);
                    return ResultCode.ERROR;
                }
            }
            catch (System.Xml.XmlException ex)
            {
                Error = ErrorCode.MALFORMED_CONFIGURATION;
                ErrorString = "The file \"" + gameConfigFile + "\" couldn't be parsed. Exception: " + ex.ToString();
                Debug.Log("GUIConfiguration", ErrorString, Debug.Type.ERROR);
                return ResultCode.ERROR;
            }
            catch (Exception ex)
            {
                Error = ErrorCode.MALFORMED_CONFIGURATION;
                ErrorString = "The file \"" + gameConfigFile + "\" couldn't be parsed. Unexpected exception: " + ex.ToString();
                Debug.Log("GUIConfiguration", ErrorString, Debug.Type.ERROR);
                return ResultCode.ERROR;
            }
            Debug.Log("GUIConfiguration", "Successfully parsed the GUI configuration.");
            ChangeProgress(100f);
            return ResultCode.OK;
        }
Ejemplo n.º 11
0
 public virtual void Fetch(
     Remote remote,
     TagFetchMode? tagFetchMode = null,
     ProgressHandler onProgress = null,
     UpdateTipsHandler onUpdateTips = null,
     TransferProgressHandler onTransferProgress = null,
     Credentials credentials = null)
 {
     Fetch(remote, new FetchOptions
     {
         TagFetchMode = tagFetchMode,
         OnProgress = onProgress,
         OnUpdateTips = onUpdateTips,
         OnTransferProgress = onTransferProgress,
         Credentials = credentials
     });
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Fetch from the <see cref="Remote"/>.
        /// </summary>
        /// <param name="remote">The remote to fetch</param>
        /// <param name="tagFetchMode">Optional parameter indicating what tags to download.</param>
        /// <param name="onProgress">Progress callback. Corresponds to libgit2 progress callback.</param>
        /// <param name="onUpdateTips">UpdateTips callback. Corresponds to libgit2 update_tips callback.</param>
        /// <param name="onTransferProgress">Callback method that transfer progress will be reported through.
        /// Reports the client's state regarding the received and processed (bytes, objects) from the server.</param>
        /// <param name="credentials">Credentials to use for username/password authentication.</param>
        public virtual void Fetch(
            Remote remote,
            TagFetchMode? tagFetchMode = null,
            ProgressHandler onProgress = null,
            UpdateTipsHandler onUpdateTips = null,
            TransferProgressHandler onTransferProgress = null,
            Credentials credentials = null)
        {
            Ensure.ArgumentNotNull(remote, "remote");

            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true))
            {
                var callbacks = new RemoteCallbacks(onProgress, onTransferProgress, onUpdateTips, credentials);
                GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks();

                if (tagFetchMode.HasValue)
                {
                    Proxy.git_remote_set_autotag(remoteHandle, tagFetchMode.Value);
                }

                // It is OK to pass the reference to the GitCallbacks directly here because libgit2 makes a copy of
                // the data in the git_remote_callbacks structure. If, in the future, libgit2 changes its implementation
                // to store a reference to the git_remote_callbacks structure this would introduce a subtle bug
                // where the managed layer could move the git_remote_callbacks to a different location in memory,
                // but libgit2 would still reference the old address.
                //
                // Also, if GitRemoteCallbacks were a class instead of a struct, we would need to guard against
                // GC occuring in between setting the remote callbacks and actual usage in one of the functions afterwords.
                Proxy.git_remote_set_callbacks(remoteHandle, ref gitCallbacks);

                try
                {
                    Proxy.git_remote_connect(remoteHandle, GitDirection.Fetch);
                    Proxy.git_remote_download(remoteHandle);
                    Proxy.git_remote_update_tips(remoteHandle);
                }
                finally
                {
                    Proxy.git_remote_disconnect(remoteHandle);
                }
            }
        }
Ejemplo n.º 13
0
        private void handleProgress(int i)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.InvokeRequired)
            {
                ProgressHandler call = new ProgressHandler(handleProgress);
                this.BeginInvoke(call, new object[] { i });
            }
            else
            {
                if (0 <= i && i <= 100)
                {
                    progressBar1.Value = i;
                    progressBar1.Invalidate();
                }
                else this.Close();

            }
        }
Ejemplo n.º 14
0
    // Virtual solely so that we can subclass for testing, because mocks don't work with delegates.
    public virtual void Download(string pid, AtStartHandler atStart, ProgressHandler progress, AtEndHandler atEnd) {
      var page = GetIphonePage(pid);

      if (!page.IsAvailable) {
        atEnd(DownloadStatus.Unavailable, pid);
        return;
      }

      var finalPath = FilenameSafe(GetTitle(pid)) + page.FileExtension;
      var tempPath  = finalPath + ".partial";

      if (File.Exists(finalPath)){
        atEnd(DownloadStatus.AlreadyExists, finalPath);
        return;
      }

      atStart(finalPath);

      var request       = new CoreMediaRequest(page.EmbeddedMediaUrl, cookies);
      var contentLength = request.ContentLength;
      int totalReceived = 0;

      using (var localStream = new FileStream(tempPath, FileMode.Append, FileAccess.Write, FileShare.Read)) {
        totalReceived = (int)localStream.Position;
        request.GetResponseStreamFromOffset(totalReceived, remoteStream => {
          ReadFromStream(remoteStream, (buffer, bytesRead) => {
            localStream.Write(buffer, 0, bytesRead);
            totalReceived += bytesRead;
            progress(totalReceived, contentLength);
          });
        });
      }

      if (totalReceived >= contentLength) {
        File.Move(tempPath, finalPath);
        atEnd(DownloadStatus.Complete, finalPath);
      } else {
        atEnd(DownloadStatus.Incomplete, tempPath);
      }
    }
Ejemplo n.º 15
0
        private ProgressBar progressBar; // Progress spinner to use for table operations

        // Called when the activity initially gets created
		protected override async void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Activity_To_Do);

            // Initialize the progress bar
			progressBar = FindViewById<ProgressBar>(Resource.Id.loadingProgressBar);
			progressBar.Visibility = ViewStates.Gone;

			// Create ProgressFilter to handle busy state
			var progressHandler = new ProgressHandler ();
			progressHandler.BusyStateChange += (busy) => {
				if (progressBar != null) 
					progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
			};

			try 
            {
				CurrentPlatform.Init ();
				// Create the Mobile Service Client instance, using the provided
				// Mobile Service URL and key
				client = new MobileServiceClient(
					Constants.ApplicationURL,
					Constants.ApplicationKey, progressHandler);

                await Authenticate();
                await CreateTable();
			} 
            catch (Java.Net.MalformedURLException) 
            {
				CreateAndShowDialog(new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
			} 
            catch (Exception e) 
            {
				CreateAndShowDialog(e, "Error");
			}
		}
Ejemplo n.º 16
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.LoginScreen);

            var submitButton = FindViewById<Button>(Resource.Id.BtnLogin);
            var urlInput = FindViewById<EditText>(Resource.Id.LoginScreenServerUrlInput);
            var keyInput = FindViewById<EditText>(Resource.Id.LoginScreenUserKeyInput);

            var login = new Login();
            urlInput.Text = login.Url;
            keyInput.Text = login.Key;

            submitButton.Click += delegate
                {
                    var dialog = ProgressDialog.Show(this, "", "Connecting to server and validating key...", true);
                    var handler = new ProgressHandler(dialog);

                    new Login().ValidateAndStore(urlInput.Text, keyInput.Text, (valid) => RunOnUiThread(() =>
                        {
                            if (valid == Login.ValidationSuccess)
                            {
                                dialog.SetMessage("Successfully connected to " + urlInput.Text);
                                var widgetContainer = new Intent(this, typeof(WidgetContainer));
                                StartActivity(widgetContainer);
                                Finish();
                                handler.SendEmptyMessage(0);
                            } else
                            {
                                dialog.SetMessage("Connection failed. Please try again");
                                handler.SendEmptyMessage(0);
                                NotifyInvalidInput();
                            }
                        }));
                };
        }
Ejemplo n.º 17
0
 private static int Match(byte[] data, ProgressHandler handler)
 {
     int matched = 0;
     int ret = -1;
     int pctstep = data.Length/100;
     for (int i = 0; i < data.Length; i++)
     {
         if ((i % pctstep) == 0)
             handler(i/pctstep);
         if (!Mask[matched])
         {
             matched++;
             continue;
         }
         if (data[i] == Bytes[matched])
             matched++;
         else
             matched = 0;
         if (matched == Bytes.Length)
         {
             // -1 to give back the offset to the crucial instruction (0f 85 / jnz)
             ret = i - 1;
             break;
         }
     }
     handler(100);
     return ret;
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Handles the callback progress content
 /// </summary>
 /// <param name="complete"></param>
 /// <param name="message"></param>
 /// <param name="data"></param>
 /// <returns></returns>
 private int GdalProgressFunc(double complete, IntPtr message, IntPtr data)
 {
     ProgressHandler.Progress("Copy Progress", Convert.ToInt32(complete), "Copy Progress");
     return(0);
 }
Ejemplo n.º 19
0
 public void SetProgressHandler(ProgressHandler pHandler)
 {
     assimp_swigPINVOKE.Importer_SetProgressHandler(swigCPtr, ProgressHandler.getCPtr(pHandler));
 }
 public void LaunchBuildOnTarget(BuildProperties buildProperties, DeploymentTargetId targetId, ProgressHandler progressHandler = null)
 {
     m_Extension.LaunchBuildOnTarget(m_Context, buildProperties, targetId, progressHandler);
 }
Ejemplo n.º 21
0
        public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name, long fixedTarget)
        {
            //IL_0008: Unknown result type (might be due to invalid IL or missing references)
            //IL_0016: Unknown result type (might be due to invalid IL or missing references)
            //IL_0024: Unknown result type (might be due to invalid IL or missing references)
            //IL_003e: Unknown result type (might be due to invalid IL or missing references)
            //IL_004c: Unknown result type (might be due to invalid IL or missing references)
            //IL_00d0: Unknown result type (might be due to invalid IL or missing references)
            //IL_00d5: Unknown result type (might be due to invalid IL or missing references)
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (buffer.Length < 128)
            {
                throw new ArgumentException("Buffer is too small", "buffer");
            }
            if (progressHandler == null)
            {
                throw new ArgumentNullException("progressHandler");
            }
            bool flag = true;

            global::System.DateTime now = global::System.DateTime.get_Now();
            long num    = 0L;
            long target = 0L;

            if (fixedTarget >= 0)
            {
                target = fixedTarget;
            }
            else if (source.get_CanSeek())
            {
                target = source.get_Length() - source.get_Position();
            }
            ProgressEventArgs e = new ProgressEventArgs(name, num, target);

            progressHandler(sender, e);
            bool flag2 = true;

            while (flag)
            {
                int num2 = source.Read(buffer, 0, buffer.Length);
                if (num2 > 0)
                {
                    num  += num2;
                    flag2 = false;
                    destination.Write(buffer, 0, num2);
                }
                else
                {
                    destination.Flush();
                    flag = false;
                }
                if (global::System.DateTime.get_Now() - now > updateInterval)
                {
                    flag2 = true;
                    now   = global::System.DateTime.get_Now();
                    e     = new ProgressEventArgs(name, num, target);
                    progressHandler(sender, e);
                    flag = e.ContinueRunning;
                }
            }
            if (!flag2)
            {
                e = new ProgressEventArgs(name, num, target);
                progressHandler(sender, e);
            }
        }
Ejemplo n.º 22
0
 public void SetProgressHandler(ProgressHandler pHandler) {
   AssimpPINVOKE.Importer_SetProgressHandler(swigCPtr, ProgressHandler.getCPtr(pHandler));
 }
Ejemplo n.º 23
0
        private void Restore_Click(object sender, RoutedEventArgs e)
        {
            ProgressHandler progressHandler = new ProgressHandler();
            progressHandler.OnComplete += (s, ev) => Dispatcher.Invoke((Action) delegate() {
                Task.Complete();
            });
            Thread t = new Thread(delegate() {
                try
                {
                    string steamPath = Configurations.Configuration.GetPath("Steam");
                    Process p = new Process();
                    p.StartInfo.FileName = steamPath + System.IO.Path.DirectorySeparatorChar + "Steam.exe";
                    p.StartInfo.Arguments = "steam://validate/" + App.Game.GameConfiguration.SteamAppID;
                    p.StartInfo.UseShellExecute = false;
                    p.Start();
                    progressHandler.Task = "Restore";
                    progressHandler.Progress = 50f;
                    int state = 0;
                    string lastLine = "";
                    while (true)
                    {
                        Process[] processes = Process.GetProcesses();
                        bool foundSteam = false;
                        foreach (Process pp in processes)
                        {
                            try
                            {
                                if (!pp.HasExited && pp.ProcessName == "Steam")
                                {
                                    foundSteam = true;
                                    break;
                                }
                            }
                            catch (System.Exception ex)
                            {
                            }
                        }

                        string logFile = steamPath + System.IO.Path.DirectorySeparatorChar + "logs" + System.IO.Path.DirectorySeparatorChar + "content_log.txt";
                        System.IO.FileStream s = new System.IO.FileStream(logFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                        System.IO.FileInfo f = new System.IO.FileInfo(logFile);
                        byte[] data = new byte[f.Length];
                        s.Read(data, 0, (int)f.Length);
                        string content = System.Text.Encoding.UTF8.GetString(data);

                        string[] l = content.Split(new string[] { "\r\n" }, System.StringSplitOptions.None);// System.IO.File.ReadAllLines(SteamPath + "\\logs\\content_log.txt");
                        if (lastLine == "")
                            lastLine = l[l.Length - 2];
                        bool check = false;
                        foreach (string n in l)
                        {
                            if (n == lastLine)
                                check = true;
                            if (check)
                            {
                                if (n.EndsWith("AppID " + App.Game.GameConfiguration.SteamAppID + " state changed : Fully Installed,"))
                                    state = 3;
                                else if (n.Contains("AppID " + App.Game.GameConfiguration.SteamAppID) && n.Contains("(Suspended)"))
                                    state = 1;
                                else if (n.Contains("Failed to get list of download sources from any known CS!"))
                                    state = 2;
                            }
                        }

                        if (state == 0 && !foundSteam)
                        {
                            state = 4;
                        }

                        if (state > 0)
                            break;

                        Thread.Sleep(500);

                    }

                    if (state == 3)
                    {
                        progressHandler.Task = "Finish";
                        progressHandler.Progress = 100f;
                    }
                    else
                    {
                        if (state == 1)
                            progressHandler.Task = "Error.Cancelled";
                        else if (state == 2)
                            progressHandler.Task = "Error.NoConnection";
                        else if (state == 4)
                            progressHandler.Task = "Error.SteamClosed";

                        Dispatcher.Invoke((Action)delegate()
                        {
                            Task.Complete();
                        });
                    }

                }
                catch (Exception exx)
                {
                    System.Console.WriteLine(exx.ToString());
                }
            });

            Close();
            ModAPI.Windows.SubWindows.OperationPending win4 = new ModAPI.Windows.SubWindows.OperationPending("Lang.Windows.OperationPending", "RestoreGameFiles", progressHandler, null, true);
            if (!win4.Completed)
            {
                win4.ShowSubWindow();
            }
            t.Start();
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This method should be called after the object is created.
        /// </summary>
        /// <param name="dirs">
        /// collection of strings (directory names)
        /// for each directory in this collection, its sub-directories
        /// are scanned for plugin.xml
        /// </param>
        /// <param name="errorHandler"></param>
        /// <param name="progressHandler"></param>
        public static void Init(ICollection dirs, ProgressHandler progressHandler, IPluginErrorHandler errorHandler)
        {
            Set       pluginSet    = new Set();
            Hashtable errorPlugins = new Hashtable();
            int       errCount     = 0;
            int       count        = 0;
            float     c_max        = dirs.Count * 4;
            bool      errBreak     = false;

            if (errorHandler == null)
            {
                errorHandler = new SilentPluginErrorHandler();
            }

            // locate plugins
            foreach (string dir in dirs)
            {
                progressHandler("Searching for plugins...\n" + Path.GetFileName(dir), ++count / c_max);
                //! progressHandler("プラグインを検索中\n"+Path.GetFileName(dir),++count/c_max);

                if (!File.Exists(Path.Combine(dir, "plugin.xml")))
                {
                    continue;   // this directory doesn't have the plugin.xml file.
                }
                PluginDefinition p = null;
                try
                {
                    p = new PluginDefinition(dir);
                    p.loadContributionFactories();
                }
                catch (Exception e)
                {
                    errCount++;
                    p = PluginDefinition.loadFailSafe(dir);
                    errorPlugins.Add(p, e);
                    errBreak = errorHandler.OnPluginLoadError(p, e);
                    if (errBreak)
                    {
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                if (pluginMap.Contains(p.name))
                {
                    errCount++;
                    // loaded more than once
                    Exception e = new Exception(string.Format(
                                                    "Plugin \"{0}\" is loaded from more than one place ({1} and {2})",
                                                    //! "プラグイン「{0}」は{1}と{2}の二箇所からロードされています",
                                                    p.name, p.dirName, ((PluginDefinition)pluginMap[p.name]).dirName));
                    errBreak = errorHandler.OnNameDuplicated(pluginMap[p.name] as PluginDefinition, p, e);
                    errorPlugins.Add(p, e);
                    if (errBreak)
                    {
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                pluginMap.Add(p.name, p);
                pluginSet.Add(p);
            }
            if (errBreak)
            {
                Environment.Exit(-1);
            }

            {// convert it to an array by sorting them in the order of dependency
                plugins = new PluginDefinition[pluginSet.Count];
                int ptr            = 0;
                PluginDefinition p = null;
                while (!pluginSet.IsEmpty)
                {
                    progressHandler("Sorting dependencies...", ++count / c_max);
                    //! progressHandler("依存関係を整理中",++count/c_max);
                    p = (PluginDefinition)pluginSet.GetOne();
                    try
                    {
                        while (true)
                        {
                            PluginDefinition[] deps = p.getDependencies();
                            int i;
                            for (i = 0; i < deps.Length; i++)
                            {
                                if (pluginSet.Contains(deps[i]))
                                {
                                    break;
                                }
                            }
                            if (i == deps.Length)
                            {
                                break;
                            }
                            else
                            {
                                p = deps[i];
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        errCount++;
                        errBreak = errorHandler.OnPluginLoadError(p, e);
                        if (!errorPlugins.ContainsKey(p))
                        {
                            errorPlugins.Add(p, e);
                        }
                        if (errBreak)
                        {
                            break;
                        }
                    }
                    pluginSet.Remove(p);
                    plugins[ptr++] = p;
                }
            }
            if (errBreak)
            {
                Environment.Exit(-2);
            }

            //	 load all the contributions
            foreach (PluginDefinition p in plugins)
            {
                progressHandler("Loading contributions...\n" + Path.GetFileName(p.dirName), ++count / c_max);
                //! progressHandler("コントリビューションをロード中\n"+Path.GetFileName(p.dirName),++count/c_max);
                try
                {
                    p.loadContributions();
                }
                catch (Exception e)
                {
                    errCount++;
                    errBreak = errorHandler.OnPluginLoadError(p, e);
                    if (!errorPlugins.ContainsKey(p))
                    {
                        errorPlugins.Add(p, e);
                    }
                    if (errBreak)
                    {
                        break;
                    }
                }
            }
            if (errBreak)
            {
                Environment.Exit(-3);
            }

            // initialize contributions
            count  = (int)c_max;
            c_max += PublicContributions.Length;
            foreach (Contribution contrib in PublicContributions)
            {
                progressHandler("Initializing contributions...\n" + contrib.BaseUri, ++count / c_max);
                //! progressHandler("コントリビューションを初期化中\n"+contrib.baseUri,++count/c_max);
                try
                {
                    contrib.OnInitComplete();
                }
                catch (Exception e)
                {
                    errCount++;
                    errBreak = errorHandler.OnContributionInitError(contrib, e);
                    PluginDefinition p = contrib.Parent;
                    if (!errorPlugins.ContainsKey(p))
                    {
                        errorPlugins.Add(p, e);
                    }
                    if (errBreak)
                    {
                        break;
                    }
                }
            }
            if (errBreak)
            {
                Environment.Exit(-4);
            }

            {// make sure there's no duplicate id
                progressHandler("Checking for duplicate IDs...", 1.0f);
                //! progressHandler("重複IDのチェック中",1.0f);
                IDictionary dic = new Hashtable();
                foreach (Contribution contrib in PublicContributions)
                {
                    if (dic[contrib.Id] != null)
                    {
                        errCount++;
                        Exception e = new FormatException("ID:" + contrib.Id + " is not unique");
                        //! Exception e = new FormatException("ID:"+contrib.id+"が一意ではありません");
                        errBreak = errorHandler.OnContribIDDuplicated(dic[contrib.Id] as Contribution, contrib, e);
                        PluginDefinition p = contrib.Parent;
                        if (!errorPlugins.ContainsKey(p))
                        {
                            errorPlugins.Add(p, e);
                        }
                        if (errBreak)
                        {
                            break;
                        }
                    }
                    else
                    {
                        dic[contrib.Id] = contrib;
                    }
                }
            }
            if (errBreak)
            {
                Environment.Exit(-5);
            }
            if (errCount > 0)
            {
                if (errorHandler.OnFinal(errorPlugins, errCount))
                {
                    Environment.Exit(errCount);
                }
            }
        }
Ejemplo n.º 25
0
 public UploadCallback(ProgressHandler progressHandler)
 {
     ProgressHandler = progressHandler;
 }
Ejemplo n.º 26
0
 private void HandlerOnProgressStart(ProgressHandler handler)
 {
     UpdateProgress();
 }
Ejemplo n.º 27
0
 private void HandlerOnProgressChanged(ProgressHandler handler)
 {
     UpdateProgress();
 }
Ejemplo n.º 28
0
 protected override void XukOutChildren(XmlWriter destination, Uri baseUri, ProgressHandler handler)
 {
     //nothing new here
     base.XukOutChildren(destination, baseUri, handler);
 }
Ejemplo n.º 29
0
 protected override void XukInChild(XmlReader source, ProgressHandler handler)
 {
     //nothing new here
     base.XukInChild(source, handler);
 }
Ejemplo n.º 30
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ProgressHandler obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Copy the contents of one <see cref="Stream"/> to another.
        /// </summary>
        /// <param name="source">The stream to source data from.</param>
        /// <param name="destination">The stream to write data to.</param>
        /// <param name="buffer">The buffer to use during copying.</param>
        /// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
        /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
        /// <param name="sender">The source for this event.</param>
        /// <param name="name">The name to use with the event.</param>
        /// <param name="fixedTarget">A predetermined fixed target value to use with progress updates.
        /// If the value is negative the target is calculated by looking at the stream.</param>
        /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
        static public void Copy(Stream source, Stream destination,
                                byte[] buffer,
                                ProgressHandler progressHandler, TimeSpan updateInterval,
                                object sender, string name, long fixedTarget)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            // Ensure a reasonable size of buffer is used without being prohibitive.
            if (buffer.Length < 128)
            {
                throw new ArgumentException("Buffer is too small", "buffer");
            }

            if (progressHandler == null)
            {
                throw new ArgumentNullException("progressHandler");
            }

            bool copying = true;

            DateTime marker    = DateTime.Now;
            long     processed = 0;
            long     target    = 0;

            if (fixedTarget >= 0)
            {
                target = fixedTarget;
            }
            else if (source.CanSeek)
            {
                target = source.Length - source.Position;
            }

            // Always fire 0% progress..
            ProgressEventArgs args = new ProgressEventArgs(name, processed, target);

            progressHandler(sender, args);

            bool progressFired = true;

            while (copying)
            {
                int bytesRead = source.Read(buffer, 0, buffer.Length);
                if (bytesRead > 0)
                {
                    processed    += bytesRead;
                    progressFired = false;
                    destination.Write(buffer, 0, bytesRead);
                }
                else
                {
                    destination.Flush();
                    copying = false;
                }

                if (DateTime.Now - marker > updateInterval)
                {
                    progressFired = true;
                    marker        = DateTime.Now;
                    args          = new ProgressEventArgs(name, processed, target);
                    progressHandler(sender, args);

                    copying = args.ContinueRunning;
                }
            }

            if (!progressFired)
            {
                args = new ProgressEventArgs(name, processed, target);
                progressHandler(sender, args);
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 快速解压
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="extractPath">解压路径</param>
        /// <param name="pwd">压缩密码</param>
        /// <param name="progressFun">进程</param>
        /// <param name="seconds">触发时间</param>
        public static void ExtractZipFile(string zipFilePath, string extractPath, string pwd, ProgressHandler progressFun, double seconds)
        {
            FastZipEvents events = new FastZipEvents();

            if (progressFun != null)
            {
                events.Progress         = progressFun;
                events.ProgressInterval = TimeSpan.FromSeconds(seconds);
            }
            FastZip zip = new FastZip(events);

            zip.CreateEmptyDirectories = true;
            if (!string.IsNullOrEmpty(pwd))
            {
                zip.Password = pwd;
            }
            zip.UseZip64 = UseZip64.On;
            zip.RestoreAttributesOnExtract = true;
            zip.RestoreDateTimeOnExtract   = true;
            zip.ExtractZip(zipFilePath, extractPath, FastZip.Overwrite.Always, null, "", "", true);
        }
Ejemplo n.º 33
0
        internal RemoteCallbacks(FetchOptionsBase fetchOptions)
        {
            if (fetchOptions == null)
            {
                return;
            }

            Progress = fetchOptions.OnProgress;
            DownloadTransferProgress = fetchOptions.OnTransferProgress;
            UpdateTips = fetchOptions.OnUpdateTips;
            CredentialsProvider = fetchOptions.CredentialsProvider;
            CertificateCheck = fetchOptions.CertificateCheck;
        }
Ejemplo n.º 34
0
        /// <summary>
        /// post multi-part data form to remote server
        /// used to upload file
        /// </summary>
        /// <param name="pUrl"></param>
        /// <param name="pHeaders"></param>
        /// <param name="pPostParams"></param>
        /// <param name="httpFormFile"></param>
        /// <param name="pProgressHandler"></param>
        /// <param name="pCompletionHandler"></param>
        public void postMultipartDataRaw(string pUrl, Dictionary<string, string> pHeaders,
            HttpFormFile pFormFile, ProgressHandler pProgressHandler, RecvDataHandler pRecvDataHandler)
        {
            if (pFormFile == null)
            {
                if (pRecvDataHandler != null)
                {
                    pRecvDataHandler(ResponseInfo.fileError(new Exception("no file specified")), null);
                }
                return;
            }

            HttpWebRequest vWebReq = null;
            HttpWebResponse vWebResp = null;
            try
            {
                vWebReq = (HttpWebRequest)WebRequest.Create(pUrl);
                vWebReq.ServicePoint.Expect100Continue = false;
            }
            catch (Exception ex)
            {
                if (pRecvDataHandler != null)
                {
                    pRecvDataHandler(ResponseInfo.invalidRequest(ex.Message), null);
                }
                return;
            }

            try
            {
                vWebReq.UserAgent = this.getUserAgent();
                vWebReq.AllowAutoRedirect = false;
                vWebReq.Method = "POST";

                //create boundary
                string formBoundaryStr = this.createFormDataBoundary();
                string contentType = string.Format("multipart/form-data; boundary={0}", formBoundaryStr);
                vWebReq.ContentType = contentType;
                if (pHeaders != null)
                {
                    foreach (KeyValuePair<string, string> kvp in pHeaders)
                    {
                        if (!kvp.Key.Equals("Content-Type"))
                        {
                            vWebReq.Headers.Add(kvp.Key, kvp.Value);
                        }
                    }
                }

                //write post body
                vWebReq.AllowWriteStreamBuffering = true;

                byte[] formBoundaryBytes = Encoding.UTF8.GetBytes(string.Format("{0}{1}\r\n",
                    FORM_BOUNDARY_TAG, formBoundaryStr));
                byte[] formBoundaryEndBytes = Encoding.UTF8.GetBytes(string.Format("\r\n{0}{1}{2}\r\n",
                    FORM_BOUNDARY_TAG, formBoundaryStr, FORM_BOUNDARY_TAG));

                using (Stream vWebReqStream = vWebReq.GetRequestStream())
                {
                    vWebReqStream.Write(formBoundaryBytes, 0, formBoundaryBytes.Length);

                    //write file name
                    string filename = pFormFile.Filename;
                    if (string.IsNullOrEmpty(filename))
                    {
                        filename = this.createRandomFilename();
                    }
                    byte[] filePartTitleData = Encoding.UTF8.GetBytes(
                                string.Format("Content-Disposition: form-data; name=\"data\"; filename=\"{0}\"\r\n", filename));
                    vWebReqStream.Write(filePartTitleData, 0, filePartTitleData.Length);
                    //write content type
                    string mimeType = FORM_MIME_OCTECT;  //!!!注意这里 @fengyh 2016-08-17 15:00
                    if (!string.IsNullOrEmpty(pFormFile.ContentType))
                    {
                        mimeType = pFormFile.ContentType;
                    }
                    byte[] filePartMimeData = Encoding.UTF8.GetBytes(string.Format("Content-Type: {0}\r\n\r\n", mimeType));
                    vWebReqStream.Write(filePartMimeData, 0, filePartMimeData.Length);

                    //write file data
                    switch (pFormFile.BodyType)
                    {
                        case HttpFileType.FILE_PATH:
                            try
                            {
                                FileStream fs = File.Open(pFormFile.BodyFile, FileMode.Open, FileAccess.Read);
                                this.writeHttpRequestBody(fs, vWebReqStream);
                            }
                            catch (Exception fex)
                            {
                                if (pRecvDataHandler != null)
                                {
                                    pRecvDataHandler(ResponseInfo.fileError(fex), null);
                                }
                            }
                            break;
                        case HttpFileType.FILE_STREAM:
                            this.writeHttpRequestBody(pFormFile.BodyStream, vWebReqStream);
                            break;
                        case HttpFileType.DATA_BYTES:
                            vWebReqStream.Write(pFormFile.BodyBytes, 0, pFormFile.BodyBytes.Length);
                            break;
                        case HttpFileType.DATA_SLICE:
                            vWebReqStream.Write(pFormFile.BodyBytes, pFormFile.Offset, pFormFile.Count);
                            break;
                    }

                    vWebReqStream.Write(formBoundaryEndBytes, 0, formBoundaryEndBytes.Length);
                    vWebReqStream.Flush();
                }

                //fire request
                vWebResp = (HttpWebResponse)vWebReq.GetResponse();
                handleWebResponse(vWebResp, pRecvDataHandler);
            }
            catch (Exception exp)
            {
                if(pRecvDataHandler!=null)
                {
                    pRecvDataHandler(ResponseInfo.networkError(exp.Message), null);
                }
            }
            finally
            {
                if (vWebResp != null)
                {
                    vWebResp.Close();
                    vWebResp = null;
                }

                if (vWebReq != null)
                {
                    vWebReq.Abort();
                    vWebReq = null;
                }
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Cast a vote and pack it in an envelope.
        /// </summary>
        /// <param name="votingMaterial">Voting material.</param>
        /// <param name="voterCertificate">Private certificate of this voter.</param>
        /// <param name="vota">List of vota.</param>
        /// <returns>Signed envelope containing the ballot.</returns>
        public Signed<Envelope> Vote(VotingMaterial votingMaterial, Certificate voterCertificate, IEnumerable<IEnumerable<int>> vota, ProgressHandler progressHandler)
        {
            if (votingMaterial == null)
            throw new ArgumentNullException("votingMaterial");

              bool acceptMaterial = SetVotingMaterial(votingMaterial);

              if (vota == null)
            throw new ArgumentNullException("vota");
              if (vota.Count() != this.parameters.Questions.Count())
            throw new ArgumentException("Bad vota count.");

              if (acceptMaterial)
              {
            List<Tuple<IEnumerable<int>, VotingParameters, Question, BigInt>> inputs = new List<Tuple<IEnumerable<int>, VotingParameters, Question, BigInt>>();

            for (int questionIndex = 0; questionIndex < this.parameters.Questions.Count(); questionIndex++)
            {
              IEnumerable<int> questionVota = vota.ElementAt(questionIndex);
              Question question = this.parameters.Questions.ElementAt(questionIndex);

              if (questionVota == null)
            throw new ArgumentNullException("questionVota");
              if (questionVota.Count() != question.Options.Count())
            throw new ArgumentException("Bad vota count.");
              if (!questionVota.All(votum => votum.InRange(0, 1)))
            throw new ArgumentException("Votum out of range.");

              inputs.Add(new Tuple<IEnumerable<int>, VotingParameters, Question, BigInt>(questionVota, this.parameters, question, this.publicKey));
            }

            List<Ballot> ballots = Parallel
              .Work<Tuple<IEnumerable<int>, VotingParameters, Question, BigInt>, Ballot>(CreateBallot, inputs, progressHandler);

            Envelope ballotContainer = new Envelope(this.parameters.VotingId, voterCertificate.Id, ballots);

            return new Signed<Envelope>(ballotContainer, voterCertificate);
              }
              else
              {
            return null;
              }
        }
        protected override async void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set View From Main Layout Resource
            SetContentView(Resource.Layout.MainActivity);

            // Set Title
            ActionBar.Title = "Daily Update";

            // Set Date Text View
            dateTextView = FindViewById<TextView>(Resource.Id.dateTextView);
            dateTextView.Text = DateTime.Today.ToShortDateString();

            // Initialize Progress Bar
            progressBar = FindViewById<ProgressBar>(Resource.Id.loadingProgressBar);
            progressBar.Visibility = ViewStates.Gone;

            // Create Adapter To Bind The Reminder Items To The View
            reminderAdapter = new ReminderAdapter(this);
            reminderListView = FindViewById<ListView>(Resource.Id.listViewRemindersMain);
            reminderListView.Adapter = reminderAdapter;

            // Create Progress Filter To Handle Busy State
            var progressHandler = new ProgressHandler();
            progressHandler.BusyStateChange += (busy) =>
            {
                if (progressBar != null)
                    progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
            };

            // Set Meal Text Views
            breakfastTextView = FindViewById<TextView>(Resource.Id.breakfastTextView);
            lunchTextView = FindViewById<TextView>(Resource.Id.lunchTextView);
            dinnerTextView = FindViewById<TextView>(Resource.Id.dinnerTextView);

            // Set Sober Driver Button
            soberDriverButton = FindViewById<Button>(Resource.Id.soberDriverButton);

            // Sober Driver Button
            soberDriverButton.Click += (object sender, EventArgs e) =>
            {
                // On Button Click, Attempt To Dial
                var callDialog = new AlertDialog.Builder(this);
                callDialog.SetMessage("Call Sober Driver?");
                callDialog.SetPositiveButton("Call", delegate
                {
                    // Create Intent To Dial Phone
                    var callIntent = new Intent(Intent.ActionCall);
                    callIntent.SetData(Android.Net.Uri.Parse("tel:8168309808")); // TODO: Change Number
                    StartActivity(callIntent);
                });

                // Create Negative Button And Show Dialog
                callDialog.SetNegativeButton("Cancel", delegate { });
                callDialog.Show();
            };

            // Connect To Azure Mobile Service
            try
            {
                // Initialize
                CurrentPlatform.Init();

                // Create Mobile Service Client Instance
                client = new MobileServiceClient(Constants.APPLICATION_URL, Constants.APPLICATION_KEY);

                // Retrieve Tables
                reminderTable = client.GetTable<ReminderItem>();
                mealTable = client.GetTable<MealItem>();

                // Load Data From The Mobile Service
                await RefreshRemindersFromTableAsync();
                await RefreshMealsFromTableAsync(DateTime.Today);

            }
            catch (Exception e)
            {
                CreateAndShowDialog(e, "Connection Error");
            }   
        }
Ejemplo n.º 37
0
        private void SaveDisk(VirtualDisk disk, ProgressHandler handler)
        {
            if (disk.FileName == null && disk is VirtualHardDisk) {
                disk.FileName = GetNewDiskPath ();
            }

            if (!File.Exists (disk.FileName) && disk is VirtualHardDisk) {
                VirtualHardDisk hd = disk as VirtualHardDisk;

                if (hd.BusType == DiskBusType.Scsi) {
                    hd.ScsiDeviceType = OperatingSystem.SuggestedScsiDeviceType;
                }

                hd.Create (handler);
            }

            string diskFile = disk.FileName;

            if (diskFile != null && diskFile != "auto detect" && Path.IsPathRooted (diskFile) &&
                Path.GetDirectoryName (diskFile) == Path.GetDirectoryName (file)) {
                diskFile = Path.GetFileName (diskFile);
            }

            string basekey = GetDiskBaseKey (disk);
            dict[basekey + "present"] = "TRUE";
            dict[basekey + "fileName"] = diskFile;

            string disktype;
            if (disk is VirtualHardDisk) {
                disktype = "disk";
            } else {
                CdDeviceType cdtype = (disk as VirtualCdDrive).CdDeviceType;
                if (OperatingSystem.IsLegacy && cdtype == CdDeviceType.Raw) {
                    cdtype = CdDeviceType.Legacy;
                }

                disktype = Utility.CdDeviceTypeToString (cdtype);
            }

            dict[basekey + "deviceType"] = disktype;
        }
Ejemplo n.º 38
0
        /// <summary>
        /// 向指定URL使用POST方法发送数据的例程,本函数不进行错误处理
        /// </summary>
        /// <param name="strURL">URL字符串</param>
        /// <param name="bytSend">要发送的二进制数据</param>
        /// <param name="SendProgress">发送数据时的进度处理</param>
        /// <param name="AcceptProgress">接受数据时的进度处理</param>
        /// <returns>接受到的二进制数据</returns>
        public static byte[] HttpPostData(
            string strURL,
            byte[] bytSend,
            ProgressHandler SendProgress,
            ProgressHandler AcceptProgress)
        {
            // 发送数据
            System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strURL);
            myReq.Method = "POST";
            System.IO.Stream myStream = myReq.GetRequestStream();
            int iCount = 0;

            if (SendProgress != null)
            {
                SendProgress(0, bytSend.Length);
            }
            while (iCount < bytSend.Length)
            {
                if (iCount + 1024 > bytSend.Length)
                {
                    myStream.Write(bytSend, iCount, bytSend.Length - iCount);
                    iCount = bytSend.Length;
                }
                else
                {
                    myStream.Write(bytSend, iCount, 1024);
                    iCount += 1024;
                }
                if (SendProgress != null)
                {
                    SendProgress(iCount, bytSend.Length);
                }
            }            //while
            if (SendProgress != null)
            {
                SendProgress(bytSend.Length, bytSend.Length);
            }
            myStream.Close();

            // 接受数据
            System.Net.HttpWebResponse myRes = null;
            myRes = myReq.GetResponse() as System.Net.HttpWebResponse;

            myStream = myRes.GetResponseStream();
            System.IO.MemoryStream myBuf = new System.IO.MemoryStream(1024);
            byte[] bytBuf        = new byte[1024];
            int    ContentLength = (int)myRes.ContentLength;
            int    AcceptLength  = 0;

            if (AcceptProgress != null)
            {
                AcceptProgress(0, ContentLength);
            }
            while (true)
            {
                int iLen = myStream.Read(bytBuf, 0, 1024);
                if (iLen == 0)
                {
                    break;
                }
                myBuf.Write(bytBuf, 0, iLen);
                AcceptLength += iLen;
                if (AcceptLength > ContentLength)
                {
                    ContentLength = AcceptLength;
                }
                if (AcceptProgress != null)
                {
                    AcceptProgress(AcceptLength, ContentLength);
                }
            }            //while
            if (AcceptProgress != null)
            {
                AcceptProgress(AcceptLength, ContentLength);
            }
            myStream.Close();
            myRes.Close();
            myReq.Abort();
            byte[] bytReturn = myBuf.ToArray();
            myBuf.Close();
            return(bytReturn);
        }        // public static byte[] HttpPostData()
Ejemplo n.º 39
0
 public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name)
 {
     //IL_0004: Unknown result type (might be due to invalid IL or missing references)
     Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1L);
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Copy the contents of one <see cref="Stream"/> to another.
 /// </summary>
 /// <param name="source">The stream to source data from.</param>
 /// <param name="destination">The stream to write data to.</param>
 /// <param name="buffer">The buffer to use during copying.</param>
 /// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
 /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
 /// <param name="sender">The source for this event.</param>
 /// <param name="name">The name to use with the event.</param>
 /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
 public static void Copy(Stream source, Stream destination,
     byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name)
 {
     Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1);
 }
Ejemplo n.º 41
0
        public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name, long fixedTarget)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (buffer.Length < 0x80)
            {
                throw new ArgumentException("Buffer is too small", "buffer");
            }
            if (progressHandler == null)
            {
                throw new ArgumentNullException("progressHandler");
            }
            bool     continueRunning = true;
            DateTime now             = DateTime.Now;
            long     processed       = 0L;
            long     target          = 0L;

            if (fixedTarget >= 0L)
            {
                target = fixedTarget;
            }
            else if (source.CanSeek)
            {
                target = source.Length - source.Position;
            }
            ProgressEventArgs e = new ProgressEventArgs(name, processed, target);

            progressHandler(sender, e);
            bool flag2 = true;

            while (continueRunning)
            {
                int count = source.Read(buffer, 0, buffer.Length);
                if (count > 0)
                {
                    processed += count;
                    flag2      = false;
                    destination.Write(buffer, 0, count);
                }
                else
                {
                    destination.Flush();
                    continueRunning = false;
                }
                if ((DateTime.Now - now) > updateInterval)
                {
                    flag2 = true;
                    now   = DateTime.Now;
                    e     = new ProgressEventArgs(name, processed, target);
                    progressHandler(sender, e);
                    continueRunning = e.ContinueRunning;
                }
            }
            if (!flag2)
            {
                e = new ProgressEventArgs(name, processed, target);
                progressHandler(sender, e);
            }
        }
Ejemplo n.º 42
0
 public static Task InstallAsync(ProgressHandler handler = default, bool overwrite = false)
 => Task.Run(() => { Install(handler, overwrite); });
 public virtual void LaunchBuildOnTarget(BuildProperties buildProperties, DeploymentTargetId targetId, ProgressHandler progressHandler = null)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 44
0
        // Token: 0x060007C4 RID: 1988 RVA: 0x0002CF5C File Offset: 0x0002B15C
        public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name, long fixedTarget)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (buffer.Length < 128)
            {
                throw new ArgumentException("Buffer is too small", "buffer");
            }
            if (progressHandler == null)
            {
                throw new ArgumentNullException("progressHandler");
            }
            bool     flag   = true;
            DateTime now    = DateTime.Now;
            long     num    = 0L;
            long     target = 0L;

            if (fixedTarget >= 0L)
            {
                target = fixedTarget;
            }
            else if (source.CanSeek)
            {
                target = source.Length - source.Position;
            }
            ProgressEventArgs progressEventArgs = new ProgressEventArgs(name, num, target);

            progressHandler(sender, progressEventArgs);
            bool flag2 = true;

            while (flag)
            {
                int num2 = source.Read(buffer, 0, buffer.Length);
                if (num2 > 0)
                {
                    num  += (long)num2;
                    flag2 = false;
                    destination.Write(buffer, 0, num2);
                }
                else
                {
                    destination.Flush();
                    flag = false;
                }
                if (DateTime.Now - now > updateInterval)
                {
                    flag2             = true;
                    now               = DateTime.Now;
                    progressEventArgs = new ProgressEventArgs(name, num, target);
                    progressHandler(sender, progressEventArgs);
                    flag = progressEventArgs.ContinueRunning;
                }
            }
            if (!flag2)
            {
                progressEventArgs = new ProgressEventArgs(name, num, target);
                progressHandler(sender, progressEventArgs);
            }
        }
Ejemplo n.º 45
0
        public static ResultCode Load(ProgressHandler progressHandler = null)
        {
            Configuration.progressHandler = progressHandler;

            string ConfigurationFileName = FindConfiguration(System.IO.Directory.GetCurrentDirectory());

            if (ConfigurationFileName != "" && File.Exists(ConfigurationFileName))
            {
                try
                {
                    XDocument configXML = XDocument.Load(ConfigurationFileName);
                    if (ParseGeneric(configXML) != ResultCode.OK)
                    {
                        Debug.Log("Configuration", "Failed parsing generic configuration file \"" + ConfigurationFileName + "\".", Debug.Type.ERROR);
                        return(ResultCode.ERROR);
                    }

                    Debug.Log("Configuration", "Generic configuration file \"" + ConfigurationFileName + "\" parsed successfully.");
                    ChangeProgress(15f);

                    string gameConfigPath = GetPath("GameConfigurations");
                    if (gameConfigPath == "")
                    {
                        Error       = ErrorCode.MALFORMED_CONFIGURATION;
                        ErrorString = "GameConfigurations Path is not set.";
                        Debug.Log("Configuration", ErrorString, Debug.Type.ERROR);
                        return(ResultCode.ERROR);
                    }
                    if (GetString("Game") == "")
                    {
                        Error       = ErrorCode.MALFORMED_CONFIGURATION;
                        ErrorString = "No game defined in configuration.";
                        Debug.Log("Configuration", ErrorString, Debug.Type.ERROR);
                        return(ResultCode.ERROR);
                    }

                    string[] gameConfigFiles = Directory.GetFiles(gameConfigPath, "*.xml");
                    foreach (string gameConfigFile in gameConfigFiles)
                    {
                        try
                        {
                            XDocument         gameConfig        = XDocument.Load(gameConfigFile);
                            GameConfiguration gameConfiguration = new GameConfiguration(gameConfig);
                            Games.Add(gameConfiguration.ID, gameConfiguration);
                            Debug.Log("Configuration", "Game configuration file for \"" + gameConfiguration.ID + "\" parsed successfully.");
                        }
                        catch (System.Xml.XmlException e)
                        {
                            Debug.Log("Configuration", "The file \"" + gameConfigFile + "\" could not be parsed. Exception: " + e.ToString(), Debug.Type.WARNING);
                        }
                        catch (Exception e)
                        {
                            Debug.Log("Configuration", "The file \"" + gameConfigFile + "\" could not be parsed. Unexpected exception: " + e.ToString(), Debug.Type.WARNING);
                        }
                    }
                    ChangeProgress(30f);

                    if (!Games.ContainsKey(GetString("Game")))
                    {
                        Error       = ErrorCode.MALFORMED_CONFIGURATION;
                        ErrorString = "The game configuration for \"" + GetString("Game") + "\" couldn't be found.";
                        Debug.Log("Configuration", ErrorString, Debug.Type.ERROR);
                        return(ResultCode.ERROR);
                    }

                    CurrentGame = GetString("Game");
                    Debug.Log("Configuration", "Selected the Game \"" + GetString("Game") + "\" successfully.");

                    string configPath = GetPath("Configurations");
                    if (configPath == "")
                    {
                        Debug.Log("Configuration", "Can't load the UserConfiguration.xml because the Configuration Path is missing.", Debug.Type.WARNING);
                    }
                    else
                    {
                        string userConfigFile = Path.GetFullPath(configPath + Path.DirectorySeparatorChar + "UserConfiguration.xml");
                        if (File.Exists(userConfigFile))
                        {
                            try
                            {
                                XDocument userConfigXML = XDocument.Load(userConfigFile);
                                if (ParseGeneric(userConfigXML, true) != ResultCode.OK)
                                {
                                    Debug.Log("Configuration", "Couldn't load the UserConfiguration.xml.", Debug.Type.WARNING);
                                }
                                else
                                {
                                    Debug.Log("Configuration", "Generic configuration file \"" + userConfigFile + "\" parsed successfully.");
                                }
                            }
                            catch (System.Xml.XmlException e)
                            {
                                Debug.Log("Configuration", "The file \"" + userConfigFile + "\" could not be parsed. Exception: " + e.ToString(), Debug.Type.WARNING);
                            }
                            catch (Exception e)
                            {
                                Debug.Log("Configuration", "The file \"" + userConfigFile + "\" could not be parsed. Unexpected exception: " + e.ToString(), Debug.Type.WARNING);
                            }
                        }
                        else
                        {
                            Debug.Log("Configuration", "Couldn't load the UserConfiguration.xml because it's missing.", Debug.Type.WARNING);
                        }
                    }
                    ChangeProgress(50f);

                    if (ParseLanguages() != ResultCode.OK)
                    {
                        return(ResultCode.ERROR);
                    }

                    ChangeProgress(100f);
                    return(ResultCode.OK);
                }
                catch (System.Xml.XmlException ex)
                {
                    Error       = ErrorCode.MALFORMED_CONFIGURATION;
                    ErrorString = "The file \"" + ConfigurationFile + "\" could not be parsed. Exception: " + ex.ToString();
                    Debug.Log("Configuration", ErrorString, Debug.Type.ERROR);
                    return(ResultCode.ERROR);
                }
                catch (Exception ex)
                {
                    Error       = ErrorCode.MALFORMED_CONFIGURATION;
                    ErrorString = "The file \"" + ConfigurationFile + "\" could not be parsed. Unexpected exception: " + ex.ToString();
                    Debug.Log("Configuration", ErrorString, Debug.Type.ERROR);
                    return(ResultCode.ERROR);
                }
            }
            else
            {
                Error       = ErrorCode.CONFIGURATION_NOT_FOUND;
                ErrorString = "Could not find \"" + ConfigurationFile + "\".";
                Debug.Log("Configuration", ErrorString, Debug.Type.ERROR);
                return(ResultCode.ERROR);
            }
        }
Ejemplo n.º 46
0
 void resetStatus(object sender, RunWorkerCompletedEventArgs e)
 {
     ProgressHandler.value = 0;
     ProgressHandler.restoreMessage();
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Shrinks the selected files using tinyPng, storing the shrunk files in the output location.
        /// </summary>
        /// <param name="key">The the tinyPng API key to use.</param>
        /// <param name="input">The input file, files or directory to upload.</param>
        /// <param name="output">The directory to output processed files to.</param>
        /// <param name="logger">A LogHandler with which to perform logging.</param>
        /// <param name="progress">A ProgressHandler with which to update the progress.</param>
        /// <param name="running">A StateToggleable to enable the caller to be informed when the process starts and stops.</param>
        public void smallifyFiles(string key, string input, string output, LogHandler logger, ProgressHandler progress, StateToggleable running)
        {
            running.ToggleState();
            WebClient client = new WebClient();
            string    auth   = Convert.ToBase64String(Encoding.UTF8.GetBytes("api:" + key));

            client.Headers.Add(HttpRequestHeader.Authorization, "Basic " + auth);

            List <string> Errors            = new List <string>();
            long          totalSaved        = 0;
            double        totalSavedPercent = 0;
            int           filesProcessed    = 0;

            if (key != "" && input != "" && output != "")
            {
                try
                {
                    string[] files = getFilesFromInputString(input);

                    progress.ResetProgress();
                    progress.SetProgressMax(files.Length);

                    for (int i = 0; i < files.Length; i++)
                    {
                        string file = files[i];
                        if (File.Exists(file))
                        {
                            string fileExt = Path.GetExtension(file).ToLower();
                            if (fileExt == ".png" || fileExt == ".jpg" || fileExt == ".jpeg")
                            {
                                string inputFileName = Path.GetFileName(file);
                                logger.LogLine("Processing file: " + inputFileName);
                                string outputFilePath = Path.Combine(output, inputFileName);

                                if ((outputFilePath = downloadFile(client, file, outputFilePath)) == "")
                                {
                                    logger.LogLine("Error processing file: " + inputFileName);
                                    Errors.Add(inputFileName);
                                }
                                else
                                {
                                    filesProcessed++;
                                    long   sizeBefore   = new FileInfo(file).Length;
                                    long   sizeAfter    = new FileInfo(outputFilePath).Length;
                                    long   saved        = sizeBefore - sizeAfter;
                                    double savedPercent = ((double)saved / (double)sizeBefore) * 100f;
                                    totalSavedPercent += savedPercent;
                                    totalSaved        += saved;
                                    logger.LogLine(string.Format("\tSize before: {0}", SizeSuffix(sizeBefore)));
                                    logger.LogLine(string.Format("\tSize After: {0}", SizeSuffix(sizeAfter)));
                                    logger.LogLine(string.Format("\tSaved: {0} or {1}%", SizeSuffix(saved), savedPercent.ToString("0.00")));
                                }
                            }
                        }

                        progress.SetProgress(i + 1);
                    }
                    if (Errors.Count == 0)
                    {
                        logger.LogLine("All done!");
                    }
                    else
                    {
                        string errorMessage = "Done, but there were errors processing the following files:";
                        foreach (string error in Errors)
                        {
                            errorMessage += System.Environment.NewLine + error;
                        }

                        logger.LogLine(errorMessage);
                    }

                    logger.LogLine(string.Format("Total Saved: {0} or {1}%",
                                                 SizeSuffix(totalSaved),
                                                 (totalSavedPercent / (double)filesProcessed).ToString("0.00")));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    running.ToggleState();
                }
            }
            else
            {
                MessageBox.Show("Please fill in all of the fields");
            }
        }
 public virtual List <DeploymentTargetIdAndStatus> GetKnownTargets(ProgressHandler progressHandler = null)
 {
     return(new List <DeploymentTargetIdAndStatus>());
 }
Ejemplo n.º 49
0
 /// <summary>
 /// Copy the contents of one <see cref="Stream"/> to another.
 /// </summary>
 /// <param name="source">The stream to source data from.</param>
 /// <param name="destination">The stream to write data to.</param>
 /// <param name="buffer">The buffer to use during copying.</param>
 /// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
 /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
 /// <param name="sender">The source for this event.</param>
 /// <param name="name">The name to use with the event.</param>
 /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
 static public void Copy(Stream source, Stream destination,
                         byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name)
 {
     Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1);
 }
Ejemplo n.º 50
0
 internal RemoteCallbacks(ProgressHandler onProgress = null, CompletionHandler onCompletion = null, UpdateTipsHandler onUpdateTips = null)
 {
     Progress   = onProgress;
     Completion = onCompletion;
     UpdateTips = onUpdateTips;
 }
Ejemplo n.º 51
0
 private Vote CreateVote(Tuple<int, BigInt, BaseParameters, BigInt> input, ProgressHandler progressHandler)
 {
     return new Vote(input.First, input.Second, input.Third, input.Fourth, new Progress(progressHandler));
 }
Ejemplo n.º 52
0
        public static ResultCode Load(ProgressHandler progressHandler = null)
        {
            ProgressHandler = progressHandler;

            var configurationFileName = FindConfiguration(Directory.GetCurrentDirectory());

            if (configurationFileName != "" && File.Exists(configurationFileName))
            {
                try
                {
                    var configXml = XDocument.Load(configurationFileName);
                    if (ParseGeneric(configXml) != ResultCode.Ok)
                    {
                        Debug.Log("Configuration", "Failed parsing generic configuration file \"" + configurationFileName + "\".", Debug.Type.Error);
                        return(ResultCode.ERROR);
                    }

                    Debug.Log("Configuration", "Generic configuration file \"" + configurationFileName + "\" parsed successfully.");
                    ChangeProgress(15f);

                    var gameConfigPath = GetPath("GameConfigurations");
                    if (gameConfigPath == "")
                    {
                        Error       = ErrorCode.MalformedConfiguration;
                        ErrorString = "GameConfigurations Path is not set.";
                        Debug.Log("Configuration", ErrorString, Debug.Type.Error);
                        return(ResultCode.ERROR);
                    }
                    if (GetString("Game") == "")
                    {
                        Error       = ErrorCode.MalformedConfiguration;
                        ErrorString = "No game defined in configuration.";
                        Debug.Log("Configuration", ErrorString, Debug.Type.Error);
                        return(ResultCode.ERROR);
                    }

                    var gameConfigFiles = Directory.GetFiles(gameConfigPath, "*.xml");
                    foreach (var gameConfigFile in gameConfigFiles)
                    {
                        try
                        {
                            var gameConfig        = XDocument.Load(gameConfigFile);
                            var gameConfiguration = new GameConfiguration(gameConfig);
                            Games.Add(gameConfiguration.Id, gameConfiguration);
                            Debug.Log("Configuration", "Game configuration file for \"" + gameConfiguration.Id + "\" parsed successfully.");
                        }
                        catch (XmlException e)
                        {
                            Debug.Log("Configuration", "The file \"" + gameConfigFile + "\" could not be parsed. Exception: " + e, Debug.Type.Warning);
                        }
                        catch (Exception e)
                        {
                            Debug.Log("Configuration", "The file \"" + gameConfigFile + "\" could not be parsed. Unexpected exception: " + e, Debug.Type.Warning);
                        }
                    }
                    ChangeProgress(30f);

                    if (!Games.ContainsKey(GetString("Game")))
                    {
                        Error       = ErrorCode.MalformedConfiguration;
                        ErrorString = "The game configuration for \"" + GetString("Game") + "\" couldn't be found.";
                        Debug.Log("Configuration", ErrorString, Debug.Type.Error);
                        return(ResultCode.ERROR);
                    }

                    CurrentGame = GetString("Game");
                    Debug.Log("Configuration", "Selected the Game \"" + GetString("Game") + "\" successfully.");

                    var configPath = GetPath("Configurations");
                    if (configPath == "")
                    {
                        Debug.Log("Configuration", "Can't load the UserConfiguration.xml because the Configuration Path is missing.", Debug.Type.Warning);
                    }
                    else
                    {
                        var userConfigFile = Path.GetFullPath(configPath + Path.DirectorySeparatorChar + "UserConfiguration.xml");
                        if (File.Exists(userConfigFile))
                        {
                            try
                            {
                                var userConfigXml = XDocument.Load(userConfigFile);
                                if (ParseGeneric(userConfigXml, true) != ResultCode.Ok)
                                {
                                    Debug.Log("Configuration", "Couldn't load the UserConfiguration.xml.", Debug.Type.Warning);
                                }
                                else
                                {
                                    Debug.Log("Configuration", "Generic configuration file \"" + userConfigFile + "\" parsed successfully.");
                                }
                            }
                            catch (XmlException e)
                            {
                                Debug.Log("Configuration", "The file \"" + userConfigFile + "\" could not be parsed. Exception: " + e, Debug.Type.Warning);
                            }
                            catch (Exception e)
                            {
                                Debug.Log("Configuration", "The file \"" + userConfigFile + "\" could not be parsed. Unexpected exception: " + e, Debug.Type.Warning);
                            }
                        }
                        else
                        {
                            Debug.Log("Configuration", "Couldn't load the UserConfiguration.xml because it's missing.", Debug.Type.Warning);
                        }
                    }
                    ChangeProgress(50f);

                    if (ParseLanguages() != ResultCode.Ok)
                    {
                        return(ResultCode.ERROR);
                    }

                    ChangeProgress(100f);
                    return(ResultCode.Ok);
                }
                catch (XmlException ex)
                {
                    Error       = ErrorCode.MalformedConfiguration;
                    ErrorString = "The file \"" + ConfigurationFile + "\" could not be parsed. Exception: " + ex;
                    Debug.Log("Configuration", ErrorString, Debug.Type.Error);
                    return(ResultCode.ERROR);
                }
                catch (Exception ex)
                {
                    Error       = ErrorCode.MalformedConfiguration;
                    ErrorString = "The file \"" + ConfigurationFile + "\" could not be parsed. Unexpected exception: " + ex;
                    Debug.Log("Configuration", ErrorString, Debug.Type.Error);
                    return(ResultCode.ERROR);
                }
            }
            Error       = ErrorCode.ConfigurationNotFound;
            ErrorString = "Could not find \"" + ConfigurationFile + "\".";
            Debug.Log("Configuration", ErrorString, Debug.Type.Error);
            return(ResultCode.ERROR);
        }
Ejemplo n.º 53
0
 public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name, long fixedTarget)
 {
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     if (destination == null)
     {
         throw new ArgumentNullException("destination");
     }
     if (buffer == null)
     {
         throw new ArgumentNullException("buffer");
     }
     if (buffer.Length < 0x80)
     {
         throw new ArgumentException("Buffer is too small", "buffer");
     }
     if (progressHandler == null)
     {
         throw new ArgumentNullException("progressHandler");
     }
     bool continueRunning = true;
     DateTime now = DateTime.Now;
     long processed = 0L;
     long target = 0L;
     if (fixedTarget >= 0L)
     {
         target = fixedTarget;
     }
     else if (source.CanSeek)
     {
         target = source.Length - source.Position;
     }
     ProgressEventArgs e = new ProgressEventArgs(name, processed, target);
     progressHandler(sender, e);
     bool flag2 = true;
     while (continueRunning)
     {
         int count = source.Read(buffer, 0, buffer.Length);
         if (count > 0)
         {
             processed += count;
             flag2 = false;
             destination.Write(buffer, 0, count);
         }
         else
         {
             destination.Flush();
             continueRunning = false;
         }
         if ((DateTime.Now - now) > updateInterval)
         {
             flag2 = true;
             now = DateTime.Now;
             e = new ProgressEventArgs(name, processed, target);
             progressHandler(sender, e);
             continueRunning = e.ContinueRunning;
         }
     }
     if (!flag2)
     {
         e = new ProgressEventArgs(name, processed, target);
         progressHandler(sender, e);
     }
 }
Ejemplo n.º 54
0
        private bool BuildDocumentWithOcr(ProgressHandler progressCallback, CancellationToken cancelToken, PdfDocument document, PdfCompat compat, ICollection <ScannedImage.Snapshot> snapshots, IOcrEngine ocrEngine, OcrParams ocrParams)
        {
            int progress = 0;

            progressCallback(progress, snapshots.Count);

            List <(PdfPage, Task <OcrResult>)> ocrPairs = new List <(PdfPage, Task <OcrResult>)>();

            // Step 1: Create the pages, draw the images, and start OCR
            foreach (var snapshot in snapshots)
            {
                if (cancelToken.IsCancellationRequested)
                {
                    break;
                }

                bool importedPdfPassThrough = snapshot.Source.FileFormat == null && !snapshot.TransformList.Any();

                PdfPage page;
                if (importedPdfPassThrough)
                {
                    page = CopyPdfPageToDoc(document, snapshot.Source);
                    if (PageContainsText(page))
                    {
                        // Since this page already contains text, don't use OCR
                        continue;
                    }
                }
                else
                {
                    page = document.AddPage();
                }

                string tempImageFilePath = Path.Combine(Paths.Temp, Path.GetRandomFileName());

                using (Stream stream = scannedImageRenderer.RenderToStream(snapshot).Result)
                    using (var img = XImage.FromStream(stream))
                    {
                        if (cancelToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (!importedPdfPassThrough)
                        {
                            DrawImageOnPage(page, img, compat);
                        }

                        if (cancelToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (!ocrRequestQueue.HasCachedResult(ocrEngine, snapshot, ocrParams))
                        {
                            img.GdiImage.Save(tempImageFilePath);
                        }
                    }

                if (cancelToken.IsCancellationRequested)
                {
                    File.Delete(tempImageFilePath);
                    break;
                }

                // Start OCR
                var ocrTask = ocrRequestQueue.QueueForeground(ocrEngine, snapshot, tempImageFilePath, ocrParams, cancelToken);
                ocrTask.ContinueWith(task =>
                {
                    // This is the best place to put progress reporting
                    // Long-running OCR is done, and drawing text on the page (step 2) is very fast
                    if (!cancelToken.IsCancellationRequested)
                    {
                        Interlocked.Increment(ref progress);
                        progressCallback(progress, snapshots.Count);
                    }
                }, TaskContinuationOptions.ExecuteSynchronously);
                // Record the page and task for step 2
                ocrPairs.Add((page, ocrTask));
            }

            // Step 2: Wait for all the OCR results, and draw the text on each page
            foreach (var(page, ocrTask) in ocrPairs)
            {
                if (cancelToken.IsCancellationRequested)
                {
                    break;
                }
                if (ocrTask.Result == null)
                {
                    continue;
                }
                DrawOcrTextOnPage(page, ocrTask.Result);
            }

            return(!cancelToken.IsCancellationRequested);
        }
Ejemplo n.º 55
0
 /// <summary>
 /// Create a ballot.
 /// </summary>
 /// <remarks>
 /// Used to multi-thread ballot creation.
 /// </remarks>
 /// <param name="input">Parameters needed to create the ballot.</param>
 /// <param name="progressHandler">Handles the progress done.</param>
 /// <returns>A ballot.</returns>
 private static Ballot CreateBallot(Tuple<IEnumerable<int>, VotingParameters, Question, BigInt> input, ProgressHandler progressHandler)
 {
     return new Ballot(input.First, input.Second, input.Third, input.Fourth, new Progress(progressHandler));
 }
Ejemplo n.º 56
0
        public async Task <bool> Export(string path, ICollection <ScannedImage.Snapshot> snapshots, PdfSettings settings, OcrParams ocrParams, ProgressHandler progressCallback, CancellationToken cancelToken)
        {
            return(await Task.Factory.StartNew(() =>
            {
                var forced = appConfigManager.Config.ForcePdfCompat;
                var compat = forced == PdfCompat.Default ? settings.Compat : forced;

                var document = new PdfDocument();
                document.Info.Author = settings.Metadata.Author;
                document.Info.Creator = settings.Metadata.Creator;
                document.Info.Keywords = settings.Metadata.Keywords;
                document.Info.Subject = settings.Metadata.Subject;
                document.Info.Title = settings.Metadata.Title;

                if (settings.Encryption.EncryptPdf &&
                    (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
                {
                    document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                    if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                    {
                        document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                    }

                    if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                    {
                        document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                    }

                    document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                    document.SecuritySettings.PermitAnnotations = settings.Encryption.AllowAnnotations;
                    document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                    document.SecuritySettings.PermitExtractContent = settings.Encryption.AllowContentCopying;
                    document.SecuritySettings.PermitFormsFill = settings.Encryption.AllowFormFilling;
                    document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                    document.SecuritySettings.PermitModifyDocument = settings.Encryption.AllowDocumentModification;
                    document.SecuritySettings.PermitPrint = settings.Encryption.AllowPrinting;
                }

                IOcrEngine ocrEngine = null;
                if (ocrParams?.LanguageCode != null)
                {
                    var activeEngine = ocrManager.ActiveEngine;
                    if (activeEngine == null)
                    {
                        Log.Error("Supported OCR engine not installed.", ocrParams.LanguageCode);
                    }
                    else if (!activeEngine.CanProcess(ocrParams.LanguageCode))
                    {
                        Log.Error("OCR files not available for '{0}'.", ocrParams.LanguageCode);
                    }
                    else
                    {
                        ocrEngine = activeEngine;
                    }
                }

                bool result = ocrEngine != null
                    ? BuildDocumentWithOcr(progressCallback, cancelToken, document, compat, snapshots, ocrEngine, ocrParams)
                    : BuildDocumentWithoutOcr(progressCallback, cancelToken, document, compat, snapshots);
                if (!result)
                {
                    return false;
                }

                var now = DateTime.Now;
                document.Info.CreationDate = now;
                document.Info.ModificationDate = now;
                if (compat == PdfCompat.PdfA1B)
                {
                    PdfAHelper.SetCidStream(document);
                    PdfAHelper.DisableTransparency(document);
                }

                if (compat != PdfCompat.Default)
                {
                    PdfAHelper.SetColorProfile(document);
                    PdfAHelper.SetCidMap(document);
                    PdfAHelper.CreateXmpMetadata(document, compat);
                }

                PathHelper.EnsureParentDirExists(path);
                document.Save(path);
                return true;
            }, TaskCreationOptions.LongRunning));
        }
Ejemplo n.º 57
0
        public static List <GameEntry> detectGames(List <GameID> these_games)
        {
            ProgressHandler.clearMessage();
            ProgressHandler.state = ProgressState.Normal;
            List <GameEntry> detected_games = new List <GameEntry>();

            Core.monitor.stop();

            //            if (model.Count == 0) {
            if (these_games == null || these_games.Count == 0 || model.Count == 0)
            {
                loadXml();
            }
            //          }

            int game_count;

            game_count = model.Count;

            if (these_games != null)
            {
                ProgressHandler.max = these_games.Count;
            }
            else
            {
                ProgressHandler.max = game_count;
            }


            ProgressHandler.value = 1;

            Dictionary <string, int> contribs = new Dictionary <string, int>();

            string string_to_use = "DetectingGames";

            if (Core.settings.MonitoredGames.Count > 0 && Core.AppMode == AppMode.Main)
            {
                string_to_use = "DetectingMonitoringGames";
            }

            TranslatingProgressHandler.setTranslatedMessage(string_to_use);


            foreach (GameEntry game in model)
            {
                //if (_cancelling)
                //    break;

                if (these_games != null && !these_games.Contains(game.id))
                {
                    continue;
                }

                ProgressHandler.suppress_communication = true;

                game.Detect();

                if (game.IsMonitored && Core.AppMode == AppMode.Main)
                {
                    game.startMonitoring(null, null);
                }

                ProgressHandler.suppress_communication = false;


                //foreach (string contrib in game.Contributors) {
                //    if (contribs.ContainsKey(contrib))
                //        contribs[contrib]++;
                //    else
                //        contribs.Add(contrib, 1);
                //}


                //if (!force_redetect && game.IsDetected && !game.id.deprecated)
                //    model.AddWithSort(game);

                detected_games.Add(game);

                ProgressHandler.value++;
            }

            //foreach (KeyValuePair<string, int> pair in contribs) {
            //    contributors.AddWithSort(new ContributorHandler(pair.Key, pair.Value));
            //}

            ProgressHandler.state = ProgressState.None;
            ProgressHandler.value = 0;

            game_count = detected_games_count;

            model.IsEnabled = true;
            if (game_count > 1)
            {
                TranslatingProgressHandler.setTranslatedMessage("GamesDetected", detected_games_count.ToString());
            }
            else if (game_count > 0)
            {
                TranslatingProgressHandler.setTranslatedMessage("GameDetected");
            }
            else
            {
                TranslatingProgressHandler.setTranslatedMessage("NoGamesDetected");
                //GameHandler no_games = new GameHandler(new GameID(Strings.getGeneralString("NoGamesDetected"), GamePlatform.Multiple, null));
                //no_games.title = Strings.getGeneralString("NoGamesDetected");
                model.IsEnabled = false;
            }
            StaticNotifyPropertyChanged("GamesDetected");

            return(detected_games);
        }
Ejemplo n.º 58
0
        public void Save(ProgressHandler handler)
        {
            CheckConflictingDisks ();

            string vmdir = Path.GetDirectoryName (file);
            if (!Directory.Exists (vmdir)) {
                Directory.CreateDirectory (vmdir);
            }

            if (!File.Exists (file)) {
                dict["nvram"] = Name + ".nvram";
                dict["checkpoint.vmState"] = Name + ".vmss";
            }

            // remove all the existing ide/scsi related values
            foreach (string key in new List<string> (dict.Keys)) {
                if (key.StartsWith ("ide") || key.StartsWith ("scsi")) {
                    dict.Remove (key);
                }
            }

            // save hard disks
            for (int i = 0; i < hardDisks.Count; i++) {
                VirtualDisk disk = hardDisks[i];
                if (handler != null) {
                    SaveDisk (disk, delegate (object o, ProgressArgs args) {
                        double progress = (double) i / (double) hardDisks.Count;
                        progress += args.Progress * ((double) 1 / (double) hardDisks.Count);
                        handler (this, new ProgressArgs (progress));
                    });
                } else {
                    SaveDisk (disk, null);
                }
            }

            // save cd drives
            foreach (VirtualDisk disk in cds) {
                SaveDisk (disk, handler);
            }

            // save ethernet devices
            for (int i = 0; i < ethernetDevices.Count; i++) {
                VirtualEthernet ethernet = ethernetDevices[i];

                string basekey = String.Format ("ethernet{0}.", i);

                this[basekey + "present"] = "TRUE";
                this[basekey + "connectionType"] = Utility.NetworkTypeToString (ethernet.NetworkType);

                if (ethernet.Address != null) {
                    this[basekey + "address"] = ethernet.Address;
                } else {
                    dict.Remove (basekey + "address");
                }

                this[basekey + "virtualDev"] = Utility.EthernetDeviceTypeToString (ethernet.EthernetType);
            }

            // write the file out
            using (StreamWriter writer = new StreamWriter (File.Open (file, FileMode.Create))) {
                List<string> keys = new List<string> (dict.Keys);
                keys.Sort ();

                foreach (string key in keys) {
                    writer.WriteLine ("{0} = \"{1}\"", key, dict[key]);
                }
            }

            CreateWatcher ();
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Copy the contents of one <see cref="Stream"/> to another.
        /// </summary>
        /// <param name="source">The stream to source data from.</param>
        /// <param name="destination">The stream to write data to.</param>
        /// <param name="buffer">The buffer to use during copying.</param>
        /// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
        /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
        /// <param name="sender">The source for this event.</param>
        /// <param name="name">The name to use with the event.</param>
        /// <param name="fixedTarget">A predetermined fixed target value to use with progress updates.
        /// If the value is negative the target is calculated by looking at the stream.</param>
        /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
        public static void Copy(Stream source, Stream destination,
            byte[] buffer,
            ProgressHandler progressHandler, TimeSpan updateInterval,
            object sender, string name, long fixedTarget)
        {
            if (source == null) {
                throw new ArgumentNullException("source");
            }

            if (destination == null) {
                throw new ArgumentNullException("destination");
            }

            if (buffer == null) {
                throw new ArgumentNullException("buffer");
            }

            // Ensure a reasonable size of buffer is used without being prohibitive.
            if (buffer.Length < 128) {
                throw new ArgumentException("Buffer is too small", "buffer");
            }

            if (progressHandler == null) {
                throw new ArgumentNullException("progressHandler");
            }

            bool copying = true;

            DateTime marker = DateTime.Now;
            long processed = 0;
            long target = 0;

            if (fixedTarget >= 0) {
                target = fixedTarget;
            }
            else if (source.CanSeek) {
                target = source.Length - source.Position;
            }

            // Always fire 0% progress..
            ProgressEventArgs args = new ProgressEventArgs(name, processed, target);
            progressHandler(sender, args);

            bool progressFired = true;

            while (copying) {
                int bytesRead = source.Read(buffer, 0, buffer.Length);
                if (bytesRead > 0) {
                    processed += bytesRead;
                    progressFired = false;
                    destination.Write(buffer, 0, bytesRead);
                }
                else {
                    destination.Flush();
                    copying = false;
                }

                if (DateTime.Now - marker > updateInterval) {
                    progressFired = true;
                    marker = DateTime.Now;
                    args = new ProgressEventArgs(name, processed, target);
                    progressHandler(sender, args);

                    copying = args.ContinueRunning;
                }
            }

            if (!progressFired) {
                args = new ProgressEventArgs(name, processed, target);
                progressHandler(sender, args);
            }
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Sends an email described by the given message object.
        /// </summary>
        /// <param name="message">The object describing the email message.</param>
        /// <param name="progressCallback"></param>
        /// <param name="cancelToken"></param>
        /// <returns>Returns true if the message was sent, false if the user aborted.</returns>
        public async Task <bool> SendEmail(EmailMessage message, ProgressHandler progressCallback, CancellationToken cancelToken)
        {
            var configuredClientName = userConfigManager.Config.EmailSetup?.SystemProviderName;

            MapiSendMailReturnCode EmailInProc(string clientName) => mapiWrapper.SendEmail(clientName, message);

            MapiSendMailReturnCode EmailByWorker(string clientName)
            {
                using (var worker = workerServiceFactory.Create())
                {
                    return(worker.Service.SendMapiEmail(clientName, message));
                }
            }

            return(await Task.Factory.StartNew(() =>
            {
                // It's difficult to get 32/64 bit right when using mapi32.dll:
                // https://docs.microsoft.com/en-us/office/client-developer/outlook/mapi/building-mapi-applications-on-32-bit-and-64-bit-platforms
                // Also some people have had issues with bad DLL paths (?), so we can fall back to mapi32.dll.

                var emailFuncs = new List <Func <MapiSendMailReturnCode> >();
                if (configuredClientName != null)
                {
                    if (mapiWrapper.CanLoadClient(configuredClientName))
                    {
                        emailFuncs.Add(() => EmailInProc(configuredClientName));
                    }
                    if (UseWorker)
                    {
                        emailFuncs.Add(() => EmailByWorker(configuredClientName));
                    }
                }
                if (mapiWrapper.CanLoadClient(null))
                {
                    emailFuncs.Add(() => EmailInProc(null));
                }
                if (UseWorker)
                {
                    emailFuncs.Add(() => EmailByWorker(null));
                }

                var returnCode = MapiSendMailReturnCode.Failure;
                foreach (var func in emailFuncs)
                {
                    try
                    {
                        returnCode = func();
                        if (returnCode != MapiSendMailReturnCode.Failure)
                        {
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        // Should only happen for DLLs that can't be loaded by the worker
                    }
                }

                // Process the result
                if (returnCode == MapiSendMailReturnCode.UserAbort)
                {
                    return false;
                }

                if (returnCode != MapiSendMailReturnCode.Success)
                {
                    Log.Error("Error sending email. MAPI error code: {0}", returnCode);
                    errorOutput.DisplayError(MiscResources.EmailError, $"MAPI returned error code: {returnCode}");
                    return false;
                }

                return true;
            }));
        }