working on it ...

Filters

Explore Public Snippets

Sort by

Found 107 snippets matching: uwp

    public by guantalamo56 modified Sep 25, 2019  36  0  4  0

    UWP: turn byte array into image

    Given a byte array, let's turn it into an Image that can be used in UWP UI contexts.
    public static async Task<Image> ToImage(this byte[] input)
    {
    	if (input == null)
    		return null;
    	BitmapImage biSource = new BitmapImage();
    	using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
    	{
    		await stream.WriteAsync(input.AsBuffer());
    		stream.Seek(0);
    		await biSource.SetSourceAsync(stream);
    	}
    
    	return new Image { Source = biSource };
    }					

    public by guantalamo56 modified Sep 25, 2019  28  0  4  0

    UWP: Get an image from local resources

    Build an Image object from local resources. The image should be stored as content in the Assets folder of the project.
    public static Image ImageFromName(this string imageName)
    {
    	if (imageName == null)
    		return null;
    	if (!imageName.StartsWith("ms-appx:///Assets/"))
    		imageName = "ms-appx:///Assets/" + imageName;
    	return new Image
    	{
    		Source = new BitmapImage(new Uri(imageName, UriKind.RelativeOrAbsolute))
    	};
    }				

    public by troy modified Sep 25, 2019  154  0  5  0

    What is the size of this file?

    Tells me the size of the given file using the basic properties of UWP StorageFile.
    public static async Task<ulong> GetFileSize(this string filename)
    {
    	StorageFile file = await GetFile(filename);
    	if (file == null)
    		return 0;
    	try
    	{
    		BasicProperties fileSize = await file.GetBasicPropertiesAsync();
    		return fileSize.Size;
    	}
    	catch (Exception e)
    	{
    		s_log.ErrorFormat("Cannot read file {0} due to {1}", filename, e.Message);
    		return 0;
    	}
    }						

    public by guantalamo56 modified Sep 25, 2019  33  0  4  0

    UWP: retrieve the binary content of a file, given its URL

    This is meant to be used with images, but can be applied to any kind of binary content...
    public static async Task<byte[]> ToByteArrayImage(this Uri imageUri)
    {
    	RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(imageUri);
    	IRandomAccessStreamWithContentType streamWithContent = await streamRef.OpenReadAsync();
    	byte[] buffer = new byte[streamWithContent.Size];
    	await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
    	return buffer;
    }				

    public by troy modified Sep 25, 2019  40  1  4  1

    How can I get an image from raw binary pixel content?

    Given a raw binary content, this gives me a stream that can be easily turned into an Image
    public static async Task<InMemoryRandomAccessStream> ImageFromBytes(this byte[] imagePixels, int width, int dpi, Rect frame)
    {
    	//BitmapImage bitmap = new BitmapImage();
    	int xStart = (int)frame.X;
    	int yStart = (int)frame.Y;
    	int frameWidth = (int)frame.Width;
    	int frameHeight = (int)frame.Height;
    	byte[] framePixels = new byte[4 * frameWidth * frameHeight];
    	for (int y = 0; y < frameHeight; y++)
    	{
    		for (int x = 0; x < frameWidth; x++)
    		{
    			int frameOffset = (4 * y * frameWidth) + (4 * x);
    			int imageOffset = (4 * (y + yStart) * width) + (4 * (x + xStart));
    			framePixels[frameOffset] = imagePixels[imageOffset];
    			framePixels[frameOffset + 1] = imagePixels[imageOffset + 1];
    			framePixels[frameOffset + 2] = imagePixels[imageOffset + 2];
    			framePixels[frameOffset + 3] = imagePixels[imageOffset + 3];
    		}
    	}
    
    	InMemoryRandomAccessStream bitmapStream = new InMemoryRandomAccessStream();
    	BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, bitmapStream);
    	encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)frameWidth, (uint)frameHeight, dpi, dpi, framePixels);
    
    	try
    	{
    		await encoder.FlushAsync();
    	}
    	catch
    	{
    		return bitmapStream;
    	}
    
    	return bitmapStream;
    }				

    public by cicero81 modified Sep 25, 2019  41  0  3  0

    Create your own test suite to run

    This set of methods allow to run a test suite without unit test frameworks like XUnit etc. It can be used across all the C# applications, e.g. UWP
        public static async Task<List<TestResult>> RunTests()
    		{
    			List<TestResult> res = new List<TestResult>();
    
    			// Consider the namespace of the tests:
    			IEnumerable<Type> typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "LiquidTextUWP.Tests");
    			foreach (Type testClass in typelist)
    			{
    				// Get all the test methods in the class:
    				foreach (MethodInfo method in testClass.GetMethods())
    				{
    					LTTestAttribute testAttr = method.GetCustomAttributes<LTTestAttribute>().FirstOrDefault();
    					if (testAttr == null)
    						continue;
    					object instance = Activator.CreateInstance(testClass);
    					try
    					{
    						if (testAttr.IsAsync)
    							await (Task) method.Invoke(instance, null);
    						else
    							method.Invoke(instance, null);
    						res.Add(new TestResult(true));
    					}
    					catch (Exception e)
    					{
    						res.Add(new TestResult(false, string.Format("{0} - {1}", e.Message, e.InnerException?.Message)));
    					}
    				}
    			}
    
    			return res;
    		}
    
    		private static IEnumerable<Type> GetTypesInNamespace(Assembly assembly, string nameSpace)
    		{
    			return assembly.GetTypes().Where(t => (t.Namespace != null) && t.Namespace.StartsWith(nameSpace));
    		}
    		
    		public struct TestResult
    	{
    		public bool Success { get; set; }
    		public string ErrorMsg { get; set; }
    
    		public TestResult(bool success, string msg = "")
    		{
    			Success = success;
    			ErrorMsg = msg;
    		}
    	}
    
    	[AttributeUsage(AttributeTargets.Method)]
    	public class LTTestAttribute : Attribute
    	{
    		public bool IsAsync { get; set; } = false;
    	}

    external by lindexi modified Jan 2, 2017  0  0  1  0

    Uwp 获取csproj 所有文件,并获取文件生成选项. Uwp Get all the files in the *.csproj.Uwp

    Uwp 获取csproj 所有文件,并获取文件生成选项. Uwp Get all the files in the *.csproj.Uwp: GetAlltheFileInCsproj
    /// <summary>
    /// 获取csproj 所有文件,并获取文件生成选项
    /// Get all the files in the *.csproj
    /// </summary>
    /// <param name="doc">csproj 文件的XDocument</param>
    /// <returns>
    /// 文件路径和文件生成选项列表
    /// The List that include the file path and it's compile options
    /// </returns>
    public static List<PrjFile> GetPrjFile(XDocument doc)
    {
        var projectXml = doc.Root;
        var name = projectXml.Attribute("xmlns")?.Value;//NameSpace
    
        //如果只写 projectXml.Elements("ItemGroup"),结果null
        //It return null when use projectXml.Elements("ItemGroup") rather than use  projectXml.Elements(XName.Get("ItemGroup", name))
        //foreach (var file in projectXml.Elements(XName.Get("ItemGroup", name)))
        //{
        //    获取所有的项
        //    foreach (var temp in file.Elements())
        //    {
        //        prjFile.Add(new PrjFile()
        //        {
        //            File = temp.Attribute(XName.Get("Include")).Value,
        //            Form = temp.Name.LocalName  
        //        });
        //    }
        //}
        return (from file in projectXml.Elements(XName.Get("ItemGroup", name))
            from temp in file.Elements()
            select new PrjFile()
            {
                File = temp.Attribute(XName.Get("Include")).Value,
                Form = temp.Name.LocalName
            }).ToList();
    }
    
    
    

    external by lamwaihen modified Nov 4, 2016  841  112  3  0

    Google Drive API v3 file upload using C# for UWP

    Google Drive API v3 file upload using C# for UWP: googledrive.cs
    public static async Task<File> UploadAsync(DriveService driveService, IList<string> parents, StorageFile file)
            {
                // Prepare the JSON metadata
                string json = "{\"name\":\"" + file.Name + "\"";
                if (parents.Count > 0)
                {
                    json += ", \"parents\": [";
                    foreach (string parent in parents)
                    {
                        json += "\"" + parent + "\", ";
                    }
                    json = json.Remove(json.Length - 2) + "]";
                }
                json += "}";
                Debug.WriteLine(json);
    
                File uploadedFile = null;
                try
                {
                    BasicProperties prop = await file.GetBasicPropertiesAsync();
                    ulong fileSize = prop.Size;
                    
                    // Step 1: Start a resumable session
                    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
                    httpRequest.Headers["Content-Type"] = "application /json; charset=UTF-8";
                    httpRequest.Headers["Content-Length"] = json.Length.ToString();
                    httpRequest.Headers["X-Upload-Content-Type"] = file.ContentType;
                    httpRequest.Headers["X-Upload-Content-Length"] = fileSize.ToString();
                    httpRequest.Headers["Authorization"] = "Bearer " + ((UserCredential)driveService.HttpClientInitializer).Token.AccessToken;
                    httpRequest.Method = "POST";
    
                    using (System.IO.Stream requestStream = await httpRequest.GetRequestStreamAsync())
                    using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(requestStream))
                    {
                        streamWriter.Write(json);
                    }
    
                    // Step 2: Save the resumable session URI
                    HttpWebResponse httpResponse = (HttpWebResponse)(await httpRequest.GetResponseAsync());
                    if (httpResponse.StatusCode != HttpStatusCode.OK)
                        return null;
    
                    // Step 3: Upload the file
                    httpRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=" + httpResponse.Headers["x-guploader-uploadid"]);
                    httpRequest.Headers["Content-Type"] = file.ContentType;
                    httpRequest.Headers["Content-Length"] = fileSize.ToString();
                    httpRequest.Method = "PUT";
    
                    using (System.IO.Stream requestStream = await httpRequest.GetRequestStreamAsync())
                    using (System.IO.FileStream fileStream = new System.IO.FileStream(file.Path, System.IO.FileMode.Open))
                    {
                        await fileStream.CopyToAsync(requestStream);
                    }
    
                    httpResponse = (HttpWebResponse)(await httpRequest.GetResponseAsync());
                    if (httpResponse.StatusCode != HttpStatusCode.OK)
                        return null;
    
                    // Try to retrieve the file from Google
                    FilesResource.ListRequest request = driveService.Files.List();
                    if (parents.Count > 0)
                        request.Q += "'" + parents[0] + "' in parents and ";
                    request.Q += "name = '" + file.Name + "'";
                    FileList result = request.Execute();
                    if (result.Files.Count > 0)
                        uploadedFile = result.Files[0];
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
    
                return uploadedFile;
            }
    
    

    external by Kevin Sidwar modified May 11, 2016  68  0  1  0

    Observable Class for UWP Data Binding

    Observable Class for UWP Data Binding: Observable.cs
    public class Observable : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void Changed([CallerMemberName]string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        protected void SetProperty<T>(ref T field, T val, [CallerMemberName]string propertyName = null)
        {
            if (object.Equals(field, val)) return;
            field = val;
            Changed(propertyName);
        }
    }
    
    

    external by Calebsem modified Sep 29, 2015  3554  17  3  0

    Bindable InkCanvas for UWP

    Bindable InkCanvas for UWP: bindableinkcanvas.cs
    using Windows.UI.Input.Inking;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    
    public class BindableInkCanvas : InkCanvas
    {
        public static readonly DependencyProperty StrokesProperty = DependencyProperty.RegisterAttached(
             "Strokes",
             typeof(InkStrokeContainer),
             typeof(BindableInkCanvas),
             new PropertyMetadata(null, StrokesChanged)
           );
    
        private static void StrokesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var instance = d as BindableInkCanvas;
            if (instance != null)
            {
                instance.InkPresenter.StrokeContainer = instance.Strokes;
            }
        }
    
        public InkStrokeContainer Strokes
        {
            get { return (InkStrokeContainer)GetValue(StrokesProperty); }
            set { SetValue(StrokesProperty, value); }
        }
    }
    
    
    • Public Snippets
    • Channels Snippets