How to check whether user is following an another user in twitter with Twitter API and TweetSharp

When you have the required keys and tokens you can check whether the user is following another user in twitter by using the Twitter API. I am using TweetSharp c# library to perform this task. I have tried with below code and worked for me. If you ever want to do it, try using below code segment.

_consumerKey = Your consumer key
_consumerSecret = Your consumer secret
_token = Authorized token
_tokenSecret = Token secret
TwitterService service = new TwitterService(_consumerKey, _consumerSecret);
service.AuthenticateWith(_token, _tokenSecret);
var user =  service.VerifyCredentials(new VerifyCredentialsOptions());
var twitterFriendship = service.GetFriendshipInfo(new GetFriendshipInfoOptions() { SourceScreenName = user.ScreenName, TargetScreenName = "profileName goes here" });

Now you have the required object and you check it using below condition.

(twitterFriendship.Relationship.Source.Following && twitterFriendship.Relationship.Target.FollowedBy)?true:false;

Cmder console for windows

Found this console for windows. It is a combination of ConEmu and Clink. This is a portable application and need to add into our PATH( not mandatory). With the full version, you have git for windows installed. So just download, unzip and run. We can add custom themes for cmder. This support multiple tabs with different users. If you are working with vs code, you can integrate cmder as the terminal. You can downlod cmder from here.

https://github.com/PandaTheme/Panda-Theme-Cmder

Integrate with vscode

https://github.com/Microsoft/vscode/issues/12006

Different between Local Storage, Session Storage and Cookies

There are many places over the internet which describe and explain this in details. I thought to gather few of them into one place.


Local Storage

  • This is a part of the web storage API.
  • Store data as key value pairs.
  • Can share between sub domains.
  • Store data in user’s browser and can be inspected by developer tools.
  • Large amounts of data can be stored locally, without affecting website performance.
  • Information will never transferred into the server.
  • From all pages can store and access data.
  • Support up to 10MB storage for most of modern browsers.
  • No expiration.
// Save data into local storage
let key = 'Key 1';
localStorage.setItem(key, 'damith');

// Get data from local storage
let myItem = localStorage.getItem(key);

// Update excising value 
localStorage.setItem(key, 'damithw');

// Remove key from local storage
localStorage.removeItem(key);

// Clear all local storage data for current origin
localStorage.clear();

Session Storage

  • This is a part of the web storage API.
  • Store data as key value pairs.
  • Get cleared after page session ends.
  • Opening page in different tab or window cause a new session to be initiated.
  • Information will never transferred into the server.
  • Support up to 10MB storage for most of modern browsers.
  • Expire after browser or tab closed.
// Save data to sessionStorage
sessionStorage.setItem('name', 'damith');

// Get saved data from sessionStorage
var data = sessionStorage.getItem('name');

// Remove saved data from sessionStorage
sessionStorage.removeItem('name');

// Remove all saved data from sessionStorage
sessionStorage.clear();

Cookies

  • We can set expiration period to each cookie
  • The browser may store it and send it back with the next request to the same server
  • Keep stateful information for the stateless HTTP protocol. ( Ex: User logged-in )
  • Mainly used for
    • Session management – Logins, shopping carts
    • Personalization – Themes, User preferences
    • Tracking – Recording and analyzing user behavior
  • Stored in client’s browser
  • Sent with every request
  • Two types of cookies are
    • Session cookies – It is deleted when client shut down
    • Permanent cookies – Can have expiry date
  • Domain and path directives define the scope of the cookie
  • Should consider about Session hijacking and XSS

 

For more information please refer below source urls

https://www.w3schools.com/Html/html5_webstorage.asp

https://www.html5rocks.com/en/tutorials/offline/quota-research/

https://alligator.io/js/introduction-localstorage-sessionstorage/

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

How to bind and ajax spinner when kendo grid datasource read

Let’s think we want to bind an ajax spinner into kendo grid data Source before and after calling the request. Here is how we do it.

I have an kendo grid names as grid. Now with jQuery I am going to bind two events into grid’d data source.

$(document).ready(function () {

        function start() {
         // load spinner
        }

        function end() {
            //close spinner
        }

        $("#grid").data("kendoGrid").dataSource.bind('requestStart', start);
        $("#grid").data("kendoGrid").dataSource.bind('requestEnd', end);
});

So when you call data source like below, it will automatically display your ajax spinner.

$("#grid").data("kendoGrid").dataSource.read({ foo: Math.random() });

MSMQ with WCF

Today I am going to show you how use Message Queuing (MSMQ) with Windows Communication Foundation (WCF). Message queue comes to show in different reasons like decoupling processes , ordering the process, handle bulk messages.

Writing an message into MSMQ is not a different, but processing the messages with effective ways is the challenge. As an example we had a problem which delay of sending emails and SMS from our side. Later when we were investigating the issue, we found that we were taking all messages and try to iterate at once.  This solution can be used to prevent kind of scenarios.

Hope you guys have installed the MSMQ before starting the development. So first create an empty solution and add two console projects. In my solution I have added three projects.

solution

 

  • Dto – contains data transfer objects
  • MSMQ – project used to write messages into message queue
  • WcfServer – read messages from message queue and process

 

Dto project contains this class.

[DataContract]
    public class User
    {
        public User()
        {
            
        }
        [DataMember(IsRequired = true)]
        public int UserId { get; set; }

        [DataMember(IsRequired = true)]
        public string FirstName { get; set; }

        [DataMember(IsRequired = false)]
        public string LastName { get; set; }

        [DataMember(IsRequired = true)]
        public string UserName { get; set; }

        [DataMember(IsRequired = true)]
        public string Email { get; set; }
    }

MSMQ project contains the code for write message into message queue

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;

namespace MSMQ
{
    class Program
    {
        
        static void Main(string[] args)
        {
            try
            {
                WriteToQueue();
            }
            catch (Exception ex)
            {
                throw ex;
            }
           
        }

        /// <summary>
        /// References : Thanks to below URLs
        /// http://www.dotnetcurry.com/wcf/1156/using-wcf-msmq-message-service-oriented-solutions
        /// 
        /// </summary>
        public static void WriteToQueue()
        {
            int i = 1;

            while (true)
            {
                Console.WriteLine("Creating new user");

                var user = new Dto.User()
                {
                    UserId = i,
                    FirstName = "Damith" + i,
                    LastName = "Wanninayake" + i,
                    Email = "damith.uwu@gmail.com",
                    UserName = "damith" + i
                };


                // Create a Message and set the body to the order object above
                var msmqPath = ConfigurationManager.AppSettings["MessageQueuePath"];
                var msg = new Message {Body = user};

                // Create a transaction
                using (var ts = new TransactionScope(TransactionScopeOption.Required))
                {
                    MessageQueue queue = null;

                    if (MessageQueue.Exists(msmqPath))
                    {
                        queue = new MessageQueue(msmqPath);
                    }
                    else
                    {
                        // Create transactional message queue
                        MessageQueue.Create(msmqPath, true);
                        queue = new MessageQueue(msmqPath);
                    }
                    queue.Send(user,"User registration",MessageQueueTransactionType.Automatic); // send the message
                    ts.Complete(); // complete the transaction
                }

                i += 1;
                Console.WriteLine("Message Sent");

                Thread.Sleep(5000);
            }
            
        }

    }
}

Here the app.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="MessageQueuePath" value=".\Private$\EmailQueue"/>
      <!--<add key="MessageQueuePath" value="FormatName:Direct=TCP:127.0.0.1\private$\emailqueue"/>-->
    </appSettings>
</configuration>

Please be kind to adjust the code per your requirement. Here I want to add more and more messages into message queue quickly.

Run the project and see whether you have messages in your queue or not. Please see the below images of my queue.
write_console

queue

message

Now we have messages in out queue and need to read this messages. My requirement is when I receive a new message into queue, without looking into queue, automatically read method should be fired like a trigger.

I have a interface like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.MsmqIntegration;
using System.Text;
using System.Threading.Tasks;
using Dto;

namespace WcfServer.Interfaces
{
    [ServiceContract]
    [ServiceKnownType(typeof(User))]
    public interface IUserInboundMessageHandlerService
    {
        [OperationContract(IsOneWay = true, Action = "*")]
        void ProcessIncomingMessage(MsmqMessage incomingOrderMessage);
    }
}

and implemented class like below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.MsmqIntegration;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dto;
using WcfServer.Interfaces;

namespace WcfServer
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single,
        ReleaseServiceInstanceOnTransactionComplete = false)]
    public class UserInboundMessageHandlerService : IUserInboundMessageHandlerService
    {
        [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
        public void ProcessIncomingMessage(MsmqMessage<User> incomingOrderMessage)
        {
            Console.WriteLine("New Message Recieved.. Procession Output...");
            Console.WriteLine();
            var orderRequest = incomingOrderMessage.Body;
            Console.WriteLine(orderRequest.UserId);
            Console.WriteLine(orderRequest.FirstName);
            Console.WriteLine(orderRequest.LastName);
            Console.WriteLine(orderRequest.Email);
            Console.WriteLine(orderRequest.UserName);
            Console.WriteLine();
            Console.WriteLine("Procession completed...");

            //Thread.Sleep(1000);
        }
    }
}

Above method will be triggered from the MSMQ. But we have to create a Service host to run this wcf service since we are not using the IIS server.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace WcfServer
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(UserInboundMessageHandlerService));
            host.Faulted += host_Faulted;

            host.Open();
            Console.WriteLine("The service is ready");
            Console.WriteLine("Press  to terminate the service");
            Console.ReadLine();

            if (host != null)
            {
                if (host.State == CommunicationState.Faulted)
                {
                    host.Abort();
                }
                host.Close();
            }
        }

        static void host_Faulted(object sender, EventArgs e)
        {
            Console.WriteLine("Faulted!"); // Change to something more sensible – this is just an example showing what happens when the host has faulted.
        }
    }
}

Let’s see the config file which has end point and other configuarations.

  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="IncludeExceptionDetails">
          <callbackDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="WcfServer.UserInboundMessageHandlerService">
        <endpoint address="msmq.formatname:DIRECT=OS:.\private$\EmailQueue" binding="msmqIntegrationBinding" bindingConfiguration="IncomingMessageHandlerBinding" contract="WcfServer.Interfaces.IUserInboundMessageHandlerService">
        </endpoint>
      </service>
    </services>
    <bindings>
      <msmqIntegrationBinding>
        <binding name="IncomingMessageHandlerBinding"
                 closeTimeout="00:30:00"
                 receiveTimeout="01:00:00"
                 retryCycleDelay="00:00:10"
                 receiveRetryCount="0"
                 exactlyOnce="true"
                 maxRetryCycles="3"
                 receiveErrorHandling="Move">
          <security mode="None"/>
        </binding>
      </msmqIntegrationBinding>
    </bindings>
  </system.serviceModel>

All set. We need to run the application now.

final

You can adjust the thread sleep time and check the speed of the reading process.

You can download the code from here

https://github.com/uwudamith/MSMQ

 

How to setup selenium c# web automation project

Recently wen automation is one of popular area and it is good to know about it. Today i am going to show you how to automate testing with Selenium web driver.

What is Selenium?

Selenium automates browsers. That’s it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.

Selenium has the support of some of the largest browser vendors who have taken (or are taking) steps to make Selenium a native part of their browser. It is also the core technology in countless other browser automation tools, APIs and frameworks.

(Source : http://www.seleniumhq.org/)

I am using visual studio 2013 professional.

Step 01: Setup Unit Testing project

Create unit test project

Step 02: Manager NuGet Packages

  • Selenium WebDriver
  • Selenium WebDriver Support classes
  • Selenium WebDriver Chrome Driver

wen_driver_and_support_classes

Step 03: Let’s add one html file. We can use this file to test. But in real world scenarios, we have to use QA server URL. For demo purpose I will use static html file.

html_file

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1 id="hello">Hello world</h1>
    <input type="button" value="Hello" class="btnHello" onclick="return alert('Hello by button click'); "/>
</body>
</html>

Now we will two methods into out unit testing class.
1. We will click the button
2. We will try to find an element which is not there

Here is out TestClass

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Chrome;
using System.Threading;
using System.IO;
using OpenQA.Selenium;

namespace WebAutomationUnitTest
{
	[TestClass]
	public class UnitTest
	{
		[TestMethod]
		public void TestMethod1()
		{
			using (var driver = new ChromeDriver())
			{
				try
				{
					string curDir = Directory.GetCurrentDirectory();
					driver.Url = new Uri(String.Format("file:///{0}/Index.html", curDir)).ToString();
					driver.Navigate();

                    var element = driver.FindElement(By.ClassName("btnHello"));
                    element.Click();

                    Thread.Sleep(5000);
				}
				catch (Exception)
				{

					throw;
				}

				
			}
		}

        [TestMethod]
        [ExpectedException(typeof(NoSuchElementException))]
        public void TestUndefinedElement()
        {
            using (var driver = new ChromeDriver())
            {
                try
                {
                    string curDir = Directory.GetCurrentDirectory();
                    driver.Url = new Uri(String.Format("file:///{0}/Index.html", curDir)).ToString();
                    driver.Navigate();

                    var element = driver.FindElement(By.ClassName("btnHello_not"));
                    element.Click();

                }
                catch (Exception)
                {

                    throw;
                }


            }
        }
	}
}

And lets run the test cases.

passed

OK. Lets say there is a element which will load by ajax. In that case we have to wait until the element is visible. In this king of scenario you have to use WebDriverWait option.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("btnDynamic")));
IWebElement element = driver.FindElement(By.Id("btnDynamic"));
element.Click();

You can download the project in here and test

(https://github.com/uwudamith/WebAutomationUnitTest)

Simple json editor using c#

editor

I have created a sample project to read json file, edit and save into another file using c# and Newtonsoft.Json library. If anyone want this kind of implementation, you can download project and continue. I have added the sample json file with the project into my Github repository.

Github repository

I have json file format like below.

{
"tasks": [{
"AccountName": "testaccount",
"AccountKey": "0de5edbc-6a02-4450-a139-33d4e760a257",
"ContainerName": "1234",
"RootPath": "/",
"DaysOfHistoryToKeep": 10
}, {
"AccountName": "test2",
"AccountKey": "f15c414b-734a-4a4e-b1a6-eb0794df4e46",
"ContainerName": "2345",
"RootPath": "/",
"DaysOfHistoryToKeep": 15
}]
}

According to that json structure, i am going to build my object structure like below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonEditor
{
    public class Task
    {
        public string AccountName { get; set; }
        public string AccountKey { get; set; }
        public string ContainerName { get; set; }
        public string RootPath { get; set; }
        public int DaysOfHistoryToKeep { get; set; }
    }
}

And I have Tasks class which contains list of Task classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonEditor
{
    public class Tasks
    {
        public List<Task> tasks { get; set; }
    }
}

This is how program going to read the json file and convert into list and bind into grid.

Stream myStream = null;
            OpenFileDialog theDialog = new OpenFileDialog();
            theDialog.Title = "Open Text File";
            theDialog.Filter = "JSON files|*.json";
            theDialog.InitialDirectory = @"C:\";
            if (theDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (theDialog.FileName.Trim() != string.Empty)
                    {
                        using (StreamReader r = new StreamReader(theDialog.FileName))
                        {
                            string json = r.ReadToEnd();
                            Tasks items = JsonConvert.DeserializeObject(json);
                            dgTasks.DataSource = items.tasks;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }

And convert grid data into json file.

Tasks tasks = new Tasks();
            tasks.tasks = (List)dgTasks.DataSource;
            
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.InitialDirectory = @"C:\";
            saveFileDialog1.Filter = "JSON Image|*.json";
            saveFileDialog1.Title = "Save a JSON File";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog1.FileName, JsonConvert.SerializeObject(tasks));
            }

Please download the project and use it in your projects. You have to add exception handling into this project.