public static void ErrorExit(ILog log, IntPtr serviceHandle, UInt32 serviceSpecificExitCode)
 {
     var status = new SERVICE_STATUS
     {
         dwServiceType             = SERVICE_TYPES.SERVICE_WIN32_OWN_PROCESS,
         dwCurrentState            = SERVICE_STATE.SERVICE_STOPPED,
         dwControlsAccepted        = 0,
         dwWin32ExitCode           = ERROR_SERVICE_SPECIFIC_ERROR,
         dwServiceSpecificExitCode = serviceSpecificExitCode,
         dwCheckPoint              = 0,
         dwWaitHint                = 5000,
     };
     bool serviceStatusRV = SetServiceStatus(serviceHandle, ref status);
     log.Debug("SetServiceStatus rv: {0}", serviceStatusRV);
 }
 private void PauseService(IntPtr service, bool wait = true)
 {
     if (this.GetServiceStatus(service) != ServiceState.Running)
         throw new ServiceOperationException(this._serviceName, "Pause", "Cannot pause a service which isn't already running");
     var status = new SERVICE_STATUS();
     ControlService(service, ServiceControl.Pause, status);
     if (wait)
     {
         var changedStatus = this.WaitForServiceStatus(service, ServiceState.PausePending, ServiceState.Paused);
         if (!changedStatus)
             throw new ServiceOperationException(this._serviceName, "Pause", "Unable to pause service");
     }
 }
 private void ContinueService(IntPtr service, bool wait = true)
 {
     if (this.GetServiceStatus(service) != ServiceState.Paused)
         throw new ServiceOperationException(this._serviceName, "Continue", "Cannot continue a service not in the paused state");
     var status = new SERVICE_STATUS();
     ControlService(service, ServiceControl.Continue, status);
     if (wait)
     {
         var changedStatus = this.WaitForServiceStatus(service, ServiceState.ContinuePending, ServiceState.Running);
         if (!changedStatus)
             throw new ServiceOperationException(this._serviceName, "Continue", "Unable to continue service");
     }
 }
 public static extern bool ControlService(SafeServiceHandle hService, uint control, out SERVICE_STATUS serviceStatus);
 /// <summary>
 /// Stars the provided windows service
 /// </summary>
 /// <param name="hService">The handle to the windows service</param>
 private static void StartService(IntPtr hService)
 {
     SERVICE_STATUS status = new SERVICE_STATUS();
     StartService(hService, 0, 0);
     WaitForServiceStatus(hService, ServiceState.Starting, ServiceState.Run);
 }
    public async void AcademicSearch(string text, int count = 30, int offset = 0)
    {
        academicStatus = SERVICE_STATUS.PENDING;

        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", labsKey);

        var parameters = new List <string>();

        var           textArray   = text.Split(' ');
        List <string> newTextList = new List <string>();
        string        expr        = "expr=And(";

        for (int j = 0; j < textArray.Length; ++j)
        {
            string candidate = new string(textArray[j].Where(Char.IsLetterOrDigit).ToArray());
            if (candidate.Length > 1)
            {
                newTextList.Add(string.Format("W=\'{0}\'", candidate.ToLower()));
            }
        }
        if (newTextList.Count == 0)
        {
            academicResult = "AcademicSearch Error: Keywords not valid <" + text + ">.";
            //Debug.LogError(academicErrInfo);
            academicStatus = SERVICE_STATUS.ERROR;
            return;
        }
        expr = string.Format("expr=And({0})", string.Join(",", newTextList));
        //string backupExpr = string.Format("expr=Or({0})", string.Join(",", newTextArray));
        parameters.Add(expr);

        parameters.Add("model=latest");
        parameters.Add(string.Format("count={0}", count));
        parameters.Add(string.Format("offset={0}", offset));
        // Title, AuthorName, ConferenceName, JournalName, Year, Extra (include:DisplayName, resource type, resoure url)
        parameters.Add(string.Format("attributes=Ti,AA.AuN,Y,C.CN,J.JN,E"));

        // Request parameter.
        string requestParameters = string.Join("&", parameters);

        // Assemble the URI for the REST API Call.
        string uri = labsUri + "evaluate?" + requestParameters;
        //Debug.Log("requested uri:" + uri);

        HttpResponseMessage response = null;

        response = await client.GetAsync(uri);

        //Debug.Log(response.StatusCode);
        //academicErrInfo = response.StatusCode.ToString();
        using (HttpContent content = response.Content)
        {
            Task <string> task       = content.ReadAsStringAsync();
            string        jsonResult = task.Result;
            Debug.Log("Got result from Academic API:" + jsonResult.Length);
            //academicResult = ParseJSONResults(jsonResult);
            //ParseJSONResults(jsonResult);
            academicResult = jsonResult;
            academicStatus = SERVICE_STATUS.DONE;
            //Debug.Log("Finish parsing in API Helper:" + academicResult.Count);
            // Display the JSON response.
            //Debug.Log("\nResponse:\n");
            //Debug.Log(JsonPrettyPrint(jsonResult));
        }
    }
Exemple #7
0
 public static extern bool ControlService(SafeServiceHandle hService, ServiceControl dwControl, ref SERVICE_STATUS lpServiceStatus);
 private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);
Exemple #9
0
 public static extern bool ControlService(
     IntPtr hService,
     uint dwControl,
     out SERVICE_STATUS lpServiceStatus
     );
Exemple #10
0
 public static extern bool ControlService(IntPtr hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus);
Exemple #11
0
 public static extern bool QueryServiceStatus(IntPtr hService, ref SERVICE_STATUS lpServiceStatus);
Exemple #12
0
 private static extern int ControlService(IntPtr h_service, ServiceControl dw_control, SERVICE_STATUS lp_service_status);
Exemple #13
0
 private static extern bool QueryServiceStatus(IntPtr hService, ref SERVICE_STATUS dwServiceStatus);
 private static extern bool SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
    //public List<ARDocument> academicResult = new List<ARDocument>();
    //public string academicErrInfo = "";

    //public List<ARDocument> parseResults = null;

#if !UNITY_EDITOR
    /// <summary>
    /// Do OCR with Azure service
    /// </summary>
    /// <param name="imageName">Image path in CameraRoll</param>
    /// <param name="topLeft"></param>
    /// <param name="botRight"></param>
    public async void MakeOCRRequest(string imageName, Vector2 topLeft, Vector2 botRight)
    {
        // Check the boundary
        double widthRatio  = botRight.x - topLeft.x;
        double heightRatio = botRight.y - topLeft.y;

        ocrStatus = SERVICE_STATUS.PENDING;
        Debug.Log(string.Format("OCR on file:{0}, start point {1}, size {2}, {3}", imageName, topLeft.ToString(), widthRatio, heightRatio));

        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", azureKey);

        // Request parameters.
        string requestParameters = "language=en&detectOrientation=true";

        // Assemble the URI for the REST API Call.
        string uri = azureUri + "ocr?" + requestParameters;

        HttpResponseMessage response;

        // Request body. Posts a locally stored JPEG image.
        byte[] byteData     = new byte[1];
        byte[] croppedBytes = new byte[1];

        /* Crop Function by Diederik Krols.
         * Refer: https://github.com/XamlBrewer/UWP-ImageCropper-/blob/master/XamlBrewer.Uwp.Controls/Helpers/CropBitmap.cs
         * */
        StorageFolder storageFolder = KnownFolders.CameraRoll;
        var           file          = (StorageFile)await storageFolder.TryGetItemAsync(imageName);

        uint width = 0, height = 0;

        if (file == null)
        {
            string errInfo = "MakeOCRRequest Error: Image File not exist." + imageName;
            Debug.Log(errInfo);
            ocrResult = errInfo;
            ocrStatus = SERVICE_STATUS.ERROR;
            return;
        }

        using (var stream = await file.OpenAsync(FileAccessMode.Read))
        {
            // Create a decoder from the stream. With the decoder, we can get the properties of the image.
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            double originalCroppedWidth  = decoder.PixelWidth * widthRatio + 2;
            double originalCroppedHeight = decoder.PixelHeight * heightRatio + 2;
            // make sure the image is larger than 50x50 in real pixels.
            double scale = Math.Max(1.0f, Math.Max(AZURE_API_MIN_SIZE / originalCroppedWidth, AZURE_API_MIN_SIZE / originalCroppedHeight));

            uint startPointX = (uint)Math.Floor(decoder.PixelWidth * topLeft.x * scale) - 1;
            uint startPointY = (uint)Math.Floor(decoder.PixelHeight * topLeft.y * scale) - 1;
            width  = (uint)Math.Floor(originalCroppedWidth * scale);
            height = (uint)Math.Floor(originalCroppedHeight * scale);

            // The scaledSize of original image.
            uint scaledWidth  = (uint)Math.Floor(decoder.PixelWidth * scale);
            uint scaledHeight = (uint)Math.Floor(decoder.PixelHeight * scale);

            // Refine the start point and the size.
            if (startPointX + width > scaledWidth)
            {
                startPointX = scaledWidth - width;
            }

            if (startPointY + height > scaledHeight)
            {
                startPointY = scaledHeight - height;
            }

            // Get the cropped pixels.
            BitmapTransform transform = new BitmapTransform();
            BitmapBounds    bounds    = new BitmapBounds();
            bounds.X         = startPointX;
            bounds.Y         = startPointY;
            bounds.Height    = height;
            bounds.Width     = width;
            transform.Bounds = bounds;

            transform.ScaledWidth  = scaledWidth;
            transform.ScaledHeight = scaledHeight;

            // Get the cropped pixels within the bounds of transform.
            PixelDataProvider pix = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.ColorManageToSRgb);

            croppedBytes = pix.DetachPixelData();
        }

        // Again, I have to save to file stream

        /* byte[] to image.
         * https://code.msdn.microsoft.com/windowsapps/How-to-save-WriteableBitmap-bd23d455
         * */
        var tempFile = await storageFolder.CreateFileAsync("tempOCR.jpg", CreationCollisionOption.GenerateUniqueName);

        using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, width, height, 96, 96, croppedBytes);
            await encoder.FlushAsync();

            var reader = new DataReader(stream.GetInputStreamAt(0));
            byteData = new byte[stream.Size];
            await reader.LoadAsync((uint)stream.Size);

            reader.ReadBytes(byteData);
        }
        await tempFile.DeleteAsync();

        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            // This example uses content type "application/octet-stream".
            // The other content types you can use are "application/json" and "multipart/form-data".
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Execute the REST API call.
            response = await client.PostAsync(uri, content);

            // Get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();

            // Display the JSON response.
            Debug.Log("\nResponse:\n");
            Debug.Log(JsonPrettyPrint(contentString));

            // Parse to output the result.
            var result = JsonConvert.DeserializeObject <JSONOCR.RootObject>(contentString);
            var texts  = new List <string>();
            foreach (var region in result.regions)
            {
                foreach (var line in region.lines)
                {
                    foreach (var word in line.words)
                    {
                        texts.Add(word.text);
                    }
                }
            }
            if (texts.Count > 0)
            {
                ocrResult = string.Join(" ", texts);
                Debug.Log("MakeOCRRequest succeeded:" + ocrResult);
                ocrStatus = SERVICE_STATUS.DONE;
            }
            else
            {
                string errInfo = "MakeOCRRequest succeeded but the result is empty.";
                ocrResult = errInfo;
                Debug.Log(errInfo);
                ocrStatus = SERVICE_STATUS.ERROR;
            }
        }
    }
Exemple #16
0
 private static bool StartService(IntPtr service)
 {
     SERVICE_STATUS status = new SERVICE_STATUS();
     StartService(service, 0, 0);
     var changedStatus = WaitForServiceStatus(service, ServiceState.StartPending, ServiceState.Running);
     if (!changedStatus)
         return false;
     return true;
 }
 private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);
Exemple #18
0
 private static extern bool ControlService(
     IntPtr hService,
     SERVICE_CONTROL_TYPE dwControl,
     ref SERVICE_STATUS lpServiceStatus);
 private static void StopService(IntPtr service)
 {
     SERVICE_STATUS status = new SERVICE_STATUS();
     ControlService(service, ServiceControl.Stop, status);
     var changedStatus = WaitForServiceStatus(service, ServiceState.StopPending, ServiceState.Stopped);
     if (!changedStatus)
         throw new ApplicationException("Unable to stop service");
 }
Exemple #20
0
 public static extern int SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
Exemple #21
0
 public static extern bool SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
Exemple #22
0
 private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);
 public static extern unsafe bool SetServiceStatus(IntPtr serviceStatusHandle, SERVICE_STATUS* status);
Exemple #24
0
 private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);
 /// <summary>
 /// Stops the provided windows service
 /// </summary>
 /// <param name="hService">The handle to the windows service</param>
 private static void StopService(IntPtr hService)
 {
     SERVICE_STATUS status = new SERVICE_STATUS();
     ControlService(hService, ServiceControl.Stop, status);
     WaitForServiceStatus(hService, ServiceState.Stopping, ServiceState.Stop);
 }
Exemple #26
0
 public static extern bool ControlService(SafeServiceHandle hService, ServiceControl dwControl, ref SERVICE_STATUS lpServiceStatus);
 public static extern bool QueryServiceStatus(SafeServiceHandle handle, out SERVICE_STATUS serviceStatus);
Exemple #28
0
 public static extern int ControlService( int hService,
     uint dwControl,
     ref SERVICE_STATUS lpServiceStatus);
        private ServiceState GetServiceStatus(IntPtr service)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            if (QueryServiceStatus(service, status) == 0)
                throw new ServiceOperationException(this._serviceName, "GetServiceStatus", "Failed to query service status");
            return status.dwCurrentState;
        }
Exemple #30
0
 public static extern int QueryServiceStatus( int hService,
     ref SERVICE_STATUS lpServiceStatus);
        private void StopService(IntPtr service, bool wait = true)
        {
            if (this.GetServiceStatus(service) != ServiceState.Running)
                return;
            var process = Process.GetProcessById(this.ServicePID);
            SERVICE_STATUS status = new SERVICE_STATUS();
            ControlService(service, ServiceControl.Stop, status);
            const string op = "Stop";
            if (wait)
            {
                var changedStatus = this.WaitForServiceStatus(service, ServiceState.StopPending, ServiceState.Stopped);
                if (!changedStatus)
                    throw new ServiceOperationException(this._serviceName, op, "Unable to stop service");
                var waitLevel = 0;
                try
                {
                    if (!process.HasExited)
                    {
                        waitLevel++;
                        if (!process.WaitForExit((int)this._serviceStopTimeoutMS))
                        {
                            waitLevel++;
                            process.Kill();
                        }
                    }
                }
                catch (Exception ex)
                {
                    switch (waitLevel)
                    {
                        case 0:
                            throw new ServiceOperationException(this._serviceName, op,
                                GenerateStopExceptionMessageWith("but threw errors when interrogating process state", ex));
                        case 1:
                            throw new ServiceOperationException(this._serviceName, op,
                                GenerateStopExceptionMessageWith("and we got an error whilst waiting 10 seconds for graceful exit", ex));
                        case 2:
                            throw new ServiceOperationException(this._serviceName, op,
                                GenerateStopExceptionMessageWith("and we got an error after trying to kill it when it didn't gracefully exit within 10 seconds", ex));

                    }
                }
            }
        }
Exemple #32
0
 public static extern int SetServiceStatus( int hServiceStatus,
     ref SERVICE_STATUS lpServiceStatus);
Exemple #33
0
 private static bool StopService(IntPtr service)
 {
     SERVICE_STATUS status = new SERVICE_STATUS();
     ControlService(service, ServiceControl.Stop, status);
     var changedStatus = WaitForServiceStatus(service, ServiceState.StopPending, ServiceState.Stopped);
     if (!changedStatus)
         return false;
     return true;
 }
		public override void ExecuteCommand (int command)
		{
			string serviceName = ServiceController.ServiceName;
			string machineName = ServiceController.MachineName;
			IntPtr scHandle = IntPtr.Zero;
			IntPtr svcHandle = IntPtr.Zero;

			try {
				scHandle = OpenServiceControlManager (machineName,
					SERVICE_MANAGER_RIGHTS.SC_MANAGER_CONNECT);

				// MSDN: the hService handle must have the SERVICE_USER_DEFINED_CONTROL
				// access right
				svcHandle = OpenService (scHandle, serviceName, SERVICE_RIGHTS.SERVICE_USER_DEFINED_CONTROL);
				if (svcHandle == IntPtr.Zero)
					throw CreateCannotOpenServiceException (serviceName,
						machineName);

				SERVICE_STATUS status = new SERVICE_STATUS ();
				if (!ControlService (svcHandle, (SERVICE_CONTROL_TYPE) command, ref status))
					throw new InvalidOperationException (string.Format (
						CultureInfo.CurrentCulture, "Cannot control {0} service"
						+ " on computer '{1}'.", serviceName, machineName),
						new Win32Exception ());
			} finally {
				if (svcHandle != IntPtr.Zero)
					CloseServiceHandle (svcHandle);
				if (scHandle != IntPtr.Zero)
					CloseServiceHandle (scHandle);
			}
		}
        private static ServiceState GetServiceStatus(IntPtr service)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            if (QueryServiceStatus(service, status) == 0)
                throw new ApplicationException("Failed to query service status.");

            return status.dwCurrentState;
        }
		public override void Stop ()
		{
			string serviceName = ServiceController.ServiceName;
			string machineName = ServiceController.MachineName;
			IntPtr scHandle = IntPtr.Zero;
			IntPtr svcHandle = IntPtr.Zero;

			try {
				scHandle = OpenServiceControlManager (machineName,
					SERVICE_MANAGER_RIGHTS.SC_MANAGER_CONNECT);

				svcHandle = OpenService (scHandle, serviceName, SERVICE_RIGHTS.SERVICE_STOP);
				if (svcHandle == IntPtr.Zero)
					throw CreateCannotOpenServiceException (serviceName,
						machineName);

				SERVICE_STATUS status = new SERVICE_STATUS ();
				if (!ControlService (svcHandle, SERVICE_CONTROL_TYPE.SERVICE_CONTROL_STOP, ref status))
					throw new InvalidOperationException (string.Format (
						CultureInfo.CurrentCulture, "Cannot stop {0} service"
						+ " on computer '{1}'.", serviceName, machineName),
						new Win32Exception ());
			} finally {
				if (svcHandle != IntPtr.Zero)
					CloseServiceHandle (svcHandle);
				if (scHandle != IntPtr.Zero)
					CloseServiceHandle (scHandle);
			}
		}
 private static void StartService(IntPtr service)
 {
     SERVICE_STATUS status = new SERVICE_STATUS();
     StartService(service, 0, 0);
     var changedStatus = WaitForServiceStatus(service, ServiceState.StartPending, ServiceState.Running);
     if (!changedStatus)
         throw new ApplicationException("Unable to start service");
 }
		private static extern bool ControlService (
			IntPtr hService,
			SERVICE_CONTROL_TYPE dwControl,
			ref SERVICE_STATUS lpServiceStatus);
        private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();

            QueryServiceStatus(service, status);
            if (status.dwCurrentState == desiredStatus) return true;

            int dwStartTickCount = Environment.TickCount;
            int dwOldCheckPoint = status.dwCheckPoint;

            while (status.dwCurrentState == waitStatus)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.

                int dwWaitTime = status.dwWaitHint / 10;

                if (dwWaitTime < 1000) dwWaitTime = 1000;
                else if (dwWaitTime > 10000) dwWaitTime = 10000;

                Thread.Sleep(dwWaitTime);

                // Check the status again.

                if (QueryServiceStatus(service, status) == 0) break;

                if (status.dwCheckPoint > dwOldCheckPoint)
                {
                    // The service is making progress.
                    dwStartTickCount = Environment.TickCount;
                    dwOldCheckPoint = status.dwCheckPoint;
                }
                else
                {
                    if (Environment.TickCount - dwStartTickCount > status.dwWaitHint)
                    {
                        // No progress made within the wait hint
                        break;
                    }
                }
            }
            return (status.dwCurrentState == desiredStatus);
        }
Exemple #40
0
 public static extern bool ControlService(
     int Service,
     SERVICE_CONTROL Control, 
     ref SERVICE_STATUS ServiceStatus
     );
Exemple #41
0
 public static extern bool QueryServiceStatus(SafeServiceHandle hService, ref SERVICE_STATUS dwServiceStatus);
Exemple #42
0
 public static extern bool QueryServiceStatus(
     int Service, 
     ref SERVICE_STATUS ServiceStatus
     );
 internal static extern unsafe bool QueryServiceStatus(IntPtr serviceHandle, SERVICE_STATUS* pStatus);
    /// <summary>
    /// Recognize the text from handwriting using Microsoft Azure service.
    /// </summary>
    public async void RecognizeInking(IReadOnlyList <InkStroke> strokeList, double pageWidth, double pageHeight)
    {
        // Current bounding box for the strokes.
        double tlX = double.MaxValue;
        double tlY = double.MaxValue;
        double brX = 0;
        double brY = 0;

        inkingStatus = SERVICE_STATUS.PENDING;
        // Make a copy of this list
        List <InkStroke> newList = new List <InkStroke>();

        foreach (InkStroke ss in strokeList)
        {
            newList.Add(ss);

            tlX = Math.Min(tlX, ss.BoundingRect.Left);
            tlY = Math.Min(tlY, ss.BoundingRect.Top);
            brX = Math.Max(brX, ss.BoundingRect.Right);
            brY = Math.Max(brY, ss.BoundingRect.Bottom);
        }
        double originalCroppedWidth  = brX - tlX;
        double originalCroppedHeight = brY - tlY;

        // Create boundary
        tlX = Math.Max(0, tlX - originalCroppedWidth * 0.2);
        tlY = Math.Max(0, tlY - originalCroppedHeight * 0.4);
        brX = Math.Min(pageWidth, brX + originalCroppedWidth * 0.2);
        brY = Math.Min(pageHeight, brY + originalCroppedHeight * 0.4);
        originalCroppedWidth  = brX - tlX;
        originalCroppedHeight = brY - tlY;

        StorageFolder storageFolder = KnownFolders.CameraRoll;
        var           file          = await storageFolder.CreateFileAsync("sampleInking.jpg", CreationCollisionOption.GenerateUniqueName);

        // Render a whole image (paper size * inking scale)
        CanvasDevice       device       = CanvasDevice.GetSharedDevice();
        CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (float)pageWidth, (float)pageHeight, 96);

        //await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        //    () =>
        //    {
        //        using (var ds = renderTarget.CreateDrawingSession())
        //        {
        //            ds.Clear(Colors.White);
        //            ds.DrawInk(strokeList);
        //        }
        //    });
        using (var ds = renderTarget.CreateDrawingSession())
        {
            ds.Clear(Colors.White);
            ds.DrawInk(newList);
        }

        // Crop the image: using same algorithm as in OCR method.
        // croppedBytes: image bytes.
        // byteData: final format, with bmp header.
        byte[] byteData = new byte[1];
        byte[] croppedBytes = new byte[1];
        uint   width = 0, height = 0;

        using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Jpeg, 1f);

            //Debug.Log("Save to:" + file.Name);

            // Crop this image.
            // Create a decoder from the stream. With the decoder, we can get the properties of the image.
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

            // make sure the image is larger than 50x50 in real pixels.
            double scale = Math.Max(1.0f, Math.Max(AZURE_API_MIN_SIZE / originalCroppedWidth, AZURE_API_MIN_SIZE / originalCroppedHeight));

            uint startPointX = (uint)Math.Floor(tlX * scale);
            uint startPointY = (uint)Math.Floor(tlY * scale);
            width  = (uint)Math.Floor(originalCroppedWidth * scale);
            height = (uint)Math.Floor(originalCroppedHeight * scale);

            // The scaledSize of original image.
            uint scaledWidth  = (uint)Math.Floor(decoder.PixelWidth * scale);
            uint scaledHeight = (uint)Math.Floor(decoder.PixelHeight * scale);

            // Refine the start point and the size.
            if (startPointX + width > scaledWidth)
            {
                startPointX = scaledWidth - width;
            }

            if (startPointY + height > scaledHeight)
            {
                startPointY = scaledHeight - height;
            }

            // Get the cropped pixels.
            BitmapTransform transform = new BitmapTransform();
            BitmapBounds    bounds    = new BitmapBounds();
            bounds.X         = startPointX;
            bounds.Y         = startPointY;
            bounds.Height    = height;
            bounds.Width     = width;
            transform.Bounds = bounds;

            transform.ScaledWidth  = scaledWidth;
            transform.ScaledHeight = scaledHeight;

            // Get the cropped pixels within the bounds of transform.
            PixelDataProvider pix = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.ColorManageToSRgb);

            croppedBytes = pix.DetachPixelData();
            //Debug.Log(string.Format("Crop Handwritten image: start: {0},{1}, width:{2}, height:{3}", bounds.X, bounds.Y, bounds.Width, bounds.Height));
        }
        await file.DeleteAsync();

        // Again, I have to save to file stream byte[] to image.
        // https://code.msdn.microsoft.com/windowsapps/How-to-save-WriteableBitmap-bd23d455
        var tempFile = await storageFolder.CreateFileAsync("temp-sampleInking.jpg", CreationCollisionOption.GenerateUniqueName);

        using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, width, height, 96, 96, croppedBytes);
            await encoder.FlushAsync();

            var reader = new DataReader(stream.GetInputStreamAt(0));
            byteData = new byte[stream.Size];
            await reader.LoadAsync((uint)stream.Size);

            reader.ReadBytes(byteData);
        }
        await tempFile.DeleteAsync();

        //ReadHandwrittenText("");
        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", azureKey);

        // Request parameter. Set "handwriting" to false for printed text.
        string requestParameters = "handwriting=true";

        // Assemble the URI for the REST API Call.
        string uri = azureUri + "recognizeText?" + requestParameters;

        HttpResponseMessage response = null;

        // This operation requrires two REST API calls. One to submit the image for processing,
        // the other to retrieve the text found in the image. This value stores the REST API
        // location to call to retrieve the text.
        string operationLocation = null;

        // Request body. Posts a locally stored JPEG image.
        //byte[] byteData = canvasImg;

        ByteArrayContent content = new ByteArrayContent(byteData);

        // This example uses content type "application/octet-stream".
        // You can also use "application/json" and specify an image URL.
        content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        // The first REST call starts the async process to analyze the written text in the image.
        response = await client.PostAsync(uri, content);

        // The response contains the URI to retrieve the result of the process.
        if (response.IsSuccessStatusCode)
        {
            operationLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault();
        }
        else
        {
            // Display the JSON error data.
            string errInfo = "RecognizeInking: PosyAsync Response Error." + response.StatusCode.ToString();
            inkingResult = errInfo;
            inkingStatus = SERVICE_STATUS.ERROR;
            Debug.Log(errInfo + "\n");
            //Debug.Log(JsonPrettyPrint(await response.Content.ReadAsStringAsync()));
            return;
        }

        // The second REST call retrieves the text written in the image.
        //
        // Note: The response may not be immediately available. Handwriting recognition is an
        // async operation that can take a variable amount of time depending on the length
        // of the handwritten text. You may need to wait or retry this operation.
        //
        // This example checks once per second for ten seconds.
        string contentString;
        int    i = 0;

        do
        {
            await Task.Delay(1000);

            response = await client.GetAsync(operationLocation);

            contentString = await response.Content.ReadAsStringAsync();

            ++i;
        }while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1);

        if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1)
        {
            string errInfo = "RecognizeInking: Timeout Error.";
            inkingResult = errInfo;
            Debug.Log(errInfo + "\n");
            inkingStatus = SERVICE_STATUS.ERROR;
            return;
        }

        // Display the JSON response.
        //Debug.Log("\nResponse:\n");
        //Debug.Log(JsonPrettyPrint(contentString));
        // Parse to output the result.
        var result = JsonConvert.DeserializeObject <JSONInking.RootObject>(contentString).recognitionResult;
        var texts  = new List <string>();

        foreach (var line in result.lines)
        {
            texts.Add(line.text);
        }

        if (texts.Count > 0)
        {
            inkingResult = string.Join(" ", texts);
            //Debug.Log("Inking Recognition succeeded:" + inkingResult);
            inkingStatus = SERVICE_STATUS.DONE;
        }
        else
        {
            string errInfo = "Inking Recognition succeeded but the result is empty.";
            inkingResult = errInfo;
            Debug.Log(errInfo);
            inkingStatus = SERVICE_STATUS.ERROR;
        }
    }