Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, 27 February 2017

[Newtonsoft] Checking for null valued keys in parsed JObject

Using Newtonsoft's Json package, when we need to parse a string to get a JObject, we can do it as follows:

JObject o = JObject.Parse(serializedJsonString);
 
This is of course the case when you don't have a model class for the Json response coming in. For keys that can have a null value, checking for null values as follows is intuitive.

o["key"] == null

However, it is also incorrect. Due to the way in which null values are stored in the parsed object, the proper way of checking for null valued keys is as follows:

o["key"].Type == JTokenType.Null
 
Of course, you should do both checks and the former check should be done earlier to ensure that the key exists before checking whether the value is null.

Tuesday, 14 June 2016

Bypassing SSL in WebRequests

Using C#, there are two prevalent ways of making HTTP requests:
- using HttpWebRequest
- using HttpClient

When you have a cancellation token that you want to use, only the later provides the facility for that. So, there are scenarios for each method to be adopted is what I am getting at.

While accessing HTTPS sites whose SSL certificates are not trusted, we manually allow access in case of the browser. The same can b achieved via code using the following methods.

1. Setting ServerCertificateValidationCallback for the request.
This method only for the first method of making HTTP requests.

// provide a custom callback
request.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(SSLValidationDelegate);

// define the callback to allow always
private static bool SSLValidationDelegate(Object o, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors errors){
    return true;
}


2. Setting ServerCertificateValidationCallback for the ServicePointManager class.
This method essentially does the same but instead of doing it at the request level it does that for all.

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
HttpClient client = new HttpClient();
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(1000);
string url = "https://localhost/some/path";
HttpResponseMessage response = client.GetAsync(url, cts.Token).Result;



So when a cancellation needs to be used,we have to take the second route.

Thursday, 10 March 2016

Prefer getters over directly accessing private variables

While doing some regular debugging, I found a rather interesting property of how variables are evaluated during load time in C#. Consider a scenario as follows.

Let us say we have a class that is connecting an application to another environment. So, instantiating this class can fail in the absence of an environment. We shall simulate that by just throwing an exception for now.

    public class Class1
    {
        public static Class1 GetInstance(){
            throw new Exception();
        }

        public void Functionality()
        {
            // some (hopefully) usable functionality
        }

        private static Class1 singletonInstance = new Class1();
    }

Let us consider the following class using  the above class.

    public class UserClass
    {
        private static Class1 variable = Class1.GetInstance();

        public static void SomeFunctionality()
        {
            variable.Functionality();
        }

        public static void SomeOtherFunctionality()
        {

        }
    }

Let us write a test for the above class.

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            UserClass.SomeOtherFunctionality();
        }
    }

Now this test fails even though the code path being tested does not involve the exception being thrown. That is because when UserClass  is loaded, its private member's instantiation fails due to the exception.

If we modify UserClass as follows, the test passes fine.

     public class UserClass
    {
        public static void SomeFunctionality()
        {
            Class1.GetInstance().Functionality();
        }

        public static void SomeOtherFunctionality()
        {

        }
    }

The reason is simple: the static call to GetInstance() within the static method is not evaluated because it is not in the code path being executed. In retrospect this is not very un-intuitive.

However it gives me a reason for preferring getters even within the class when lazy evaluation is desired.

        public static void SomeFunctionality()
        {
            getClass1().Functionality();
        }

        private static Class1 getClass1()
        {
            return Class1.GetInstance();
        }

        public static void SomeOtherFunctionality()
        {

        }