basquang™ on clouds

November 28, 2018

UWP: Mouse wheel on horizontal ListView

Filed under: UWP — basquang @ 7:48 PM

Problem:

By default ListView is vertical orientation and scrollable. To change ListView horizontal we set in it ItemsPanelTemplate: <ItemsStackPanel Orientation=”Horizontal”/>. But in mouse wheel is not working on horizontal ListView

Solution:

  1. Fixed width for the ListView
  2. Disable parent scrollviewer horizontal by setting ScrollViewer.HorizontalScrollMode = “Disabled” if the ListView inside scrollviewer
Advertisements

UWP: ListViewItem remove spacing

Filed under: UWP — basquang @ 4:53 PM

Problem:
Annotation 2018-11-28 162601
Space is not balance between list view item.

Solution:

<Setter Property=”ItemContainerStyle”>
<Setter.Value>
<Style TargetType=”ListViewItem”>
<Setter Property=”Padding” Value=”2″/>
<Setter Property=”Margin” Value=”0″/>
<Setter Property=”MinHeight” Value=”0″/>
<Setter Property=”MinWidth” Value=”0″/>
</Style>
</Setter.Value>
</Setter>

Result:
Annotation 2018-11-28 163035

September 26, 2018

UWP: Disable Pivot swipe left/right while horizontal scroll ListView inside

Filed under: UWP — basquang @ 8:17 AM

Problem:
– You have Pivot
– You have horizontal ListView inside PivotItem
– When you scroll ListView items to the last, the pivot automatically swipe to next PivotItem. So you want remain the current PivotItem view without go to next PivotItem?

Cause:
– Both Pivot and ListView have ScrollViewer by default inside. By default these ScrollViewer have ScrollViewer.IsHorizontalScrollChainingEnabled Property set to True. It means that “true to enable horizontal scroll chaining from child to parent; otherwise, false.” base on MSDN

Solution:
Set the property ScrollViewer.IsHorizontalScrollChainingEnabled=”False” for the ListView inside PivotItem to avoid this problem.

Reference:
https://stackoverflow.com/questions/35207827/disable-pivot-swipe-during-scrolling-on-uwp-app

August 23, 2018

UWP: Set status bar to remove empty white space on top in Mobile Emulator

Filed under: UWP — basquang @ 8:49 AM

Problem:
– Having empty white space on top of Windows 10 Mobile Emulator

StatusBar
Cause:
– The status bar is not set correctly
Solution:
– Set background color for the status bar
– Hide the status bar if needed
Set the code below in App.cs OnLaunched
Code:

//Set Status bar
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
{
	var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
	statusBar.BackgroundColor = Windows.UI.Colors.Green;
	statusBar.BackgroundOpacity = 1;
	await statusBar.HideAsync();
}

Note:
You must add reference to Extensions | Windows Mobile Extensions for the UWP

StatusBarAfter

May 11, 2017

Xap packaging failed. Cannot access a closed Stream

Filed under: Windows Phone — basquang @ 5:53 PM

Problem:

  • When you try to build Windows Phone 8.0 Silverlight project

18448072_10208528682447253_61194586_n

Solution:

  • Reinstall Windows Phone SDK 8.0 for Visual Studio

Hope this help!

April 27, 2017

Calling Untrusted SSL HTTPS request using HttpClient give “Message=The remote certificate is invalid according to the validation procedure”

Filed under: JSON,Microsoft Technology,MVC,WebAPI — basquang @ 3:36 PM

Scenario:

+You want to deploy web application server (for example ASP.NET Web API) which require SSL certificate and HTTPS

+You want to make a call to that server using HttpClient

Problem:

+You may see the following errors message when make a call to https required url using HttpClient
HResult=-2146233079
Message=The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

HResult=-2146233087
Message=The remote certificate is invalid according to the validation procedure.

HResult=-2146233088
Message=An error occurred while sending the request.

Solution:

Using this lines of code to accept all server certificates from client. This line of code is using for testing purpose only with you are using self-signed or untrusted certificates

//Accept all server certificate
ServicePointManager.ServerCertificateValidationCallback =
    delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };

For example you want to make a https POST to Web API method in this post Hello ASP.NET Web API

static async Task PostSampleAsync()
        {
            //Accept all server certificate
            ServicePointManager.ServerCertificateValidationCallback =
                delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };
            client.BaseAddress = new Uri("https://10.1.16.193/WebAPISample/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.PostAsJsonAsync("api/values", "hello!");
            response.EnsureSuccessStatusCode();
            var result = response.Content.ReadAsAsync<string>().Result;
            Console.WriteLine(result);
        }

Happy coding!

Hello ASP.NET Web API

Filed under: JSON,Microsoft Technology,MVC,WebAPI — basquang @ 3:13 PM

1. Create a simple ASP.NET Web API project with HTTP GET and POST method

Create a simple Web API Controller like this:

    public class ValuesController : ApiController
    {
        string[] list = new string[] { "value1", "value2" };
        // GET api/values
        public IEnumerable<string> Get() { return list; }

        // GET api/values/1
        public string Get(int id) { return list[id]; }

        // POST api/values
        public string Post([FromBody]string value) { return value; }
    }

2. Test the Web API using web browser or POSTMAN

Navigate GET method by web browser

http://localhost:3649/api/values

webapi1

in POSTMAN http://localhost:3649/api/values/1

webapi2

in POSTMAN test HTTP POST method

webapi3

3. Call the Web API using HttpClient

+ Create a console application

+ Install Nuget package

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />
</packages>

+ Create a method to consume Web API method GET like this

static HttpClient client = new HttpClient();
        static void Main(string[] args)
        {
            RunAsync().Wait();
        }

        static async Task RunAsync()
        {
            //await PostSampleAsync();
            await GetSampleAsync();

            Console.ReadLine();
        }
static async Task GetSampleAsync()
        {
            // this is where we will send it
            string uri = "http://localhost:3649/api/values";

            // create a request
            HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create(uri); request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "GET";

            /*====HTTP POST====*/
            //request.Method = "POST";
            //// turn our request string into a byte stream
            //byte[] postBytes = Encoding.ASCII.GetBytes("hello"); //param

            //// this is important - make sure you specify type this way
            //request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentLength = postBytes.Length;
            //Stream requestStream = request.GetRequestStream();

            //// now send it
            //requestStream.Write(postBytes, 0, postBytes.Length);
            //requestStream.Close();

            // grab te response and print it out to the console along with the status code
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
            Console.WriteLine(response.StatusCode);
        }

+ Run debug application you will see the result as below

webapi4

+ Create a method to consume Web API method POST like this

static async Task PostSampleAsync()
        {
            client.BaseAddress = new Uri("http://localhost:3649/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.PostAsJsonAsync("api/values", "hello!");
            response.EnsureSuccessStatusCode();
            var result = response.Content.ReadAsAsync<string>().Result;
            Console.WriteLine(result);
        }

+ Run debug application for this method you will see the result as below

webapi5.PNG

Happy coding!

November 25, 2015

Transfer large data with WCF

Filed under: Uncategorized,WCF — basquang @ 3:16 PM
Tags:

[MSDN]: Introduction to Building Windows Communication Foundation Services

[MSDN]: Large Data and Streaming

[MSDN] Transferring large blobs of data with WCF

[MSDN]: Streaming Message Transfer

Transferring large files using WCF

File Transfer with WCF

WCF Streaming: Upload files over HTTP

Transferring large data over the wire using WCF

Passing Large Files in Windows Communication Foundation (WCF) using Streaming and TCP

MTOM vs. Streaming vs. Compression – Large attachments over WCF

Streaming Files (for Upload/Download) in WCF (Message Contracts)

 

November 10, 2015

Secure your WCF Web Services resource references

Filed under: Digital Signature,WCF — basquang @ 3:52 PM
Tags:

You want to secure your WCF web services, you want to sign digital signature on your web service here are some good references

[MSDN]: Using Message Contracts

[MSDN]How to: Set the ProtectionLevel Property

[VS Magazine] Security Considerations and Best Practices for WCF 4 Apps

[MSDN] Message Security with a Certificate Client

[MSDN] Message Security Certificate

[CodeProject] WCF Service Method Level Security using Message Contract

October 26, 2015

TFS 2015: Fail to create Team Project

Filed under: TFS — basquang @ 2:03 PM
Tags:

You may receive following error when try to create TFS Team Project from Visual Studio

Problem: Fail to create team project

Error
The Project Creation Wizard encountered an error while creating reports to the SQL Server Reporting Services on http://win-i20evd01dob/ReportServer/ReportService2005.asmx.
Explanation
The Project Creation Wizard encountered a problem while creating reports on the SQL Server Reporting Services on http://win-i20evd01dob/ReportServer/ReportService2005.asmx. The reason for the failure cannot be determined at this time. Because the operation failed, the wizard was not able to finish creating the SQL Server Reporting Services site.
User Action
Contact the administrator for the SQL Server Reporting Services on http://win-i20evd01dob/ReportServer/ReportService2005.asmx to confirm that the SQL Server Reporting Services server is running and you have sufficient privileges to create a project. Your user account on SQL Server Reporting Services must have Content Manager permission to create a new project. Also, you might find additional helpful information in the project creation log. The log shows each action taken by the wizard at the time of the failure and may include additional details about the error.
Open the log file you may see:
Event Description: TF30162: Task “Populate Reports” from Group “Reporting” failed
Exception Type: Microsoft.TeamFoundation.Client.PcwException
Exception Message: The Project Creation Wizard encountered an error while creating reports to the SQL Server Reporting Services
Exception Message: TF30225: Error uploading report ‘Backlog Overview’: The current action cannot be completed. The user data source credentials do not meet the requirements to run this report or shared dataset. Either the user data source credentials are not stored in the report server database, or the user data source is configured not to require credentials but the unattended execution account is not specified. —> Microsoft.ReportingServices.Diagnostics.Utilities.InvalidDataSourceCredentialSettingException: The current action cannot be completed. The user data source credentials do not meet the requirements to run this report or shared dataset. Either the user data source credentials are not stored in the report server database, or the user data source is configured not to require credentials but the unattended execution account is not specified. (type ReportingUploaderException)
Assumption:
1. The SQL Server Reporting Services is running
2. You are logged in as [DOMAIN]\AccountName to Team Foundation Server to create Team Project
Solution:
You have following items to check:
1. Open Team Foundation Administration Console
a. In Application Tier | Reporting Services Summary has valid Reader Account for example [DOMAIN]\AccountName. If not enter that account
b. In Reporting tab, Edit the Reporting configuration and in Reports tab enter valid account for “Account for accessing datasource” for example [DOMAIN]\AccountName
2. Open Reporting Services Configuration Manager
a. In Encryption Keys tab, try to delete Encrypted Content
b. In Execution Account tab, enter valid account for example [DOMAIN]\AccountName
c. In Database tab, enter try to enter valid account for “Current Report Server Database Credential” for example [DOMAIN]\AccountName
3. Open Report Manager URL at http:/……/Reports
Open security setting for your TFS Reports Database and make sure that your account [DOMAIN]\AccountName. has Content Manager and Team Foundation Content Manager Role Assigment
Hop this help!
Next Page »

Blog at WordPress.com.