Wednesday, February 22, 2017

Fundamentals of Unit Testing: Unit Testing of IOC Code

Original: http://www.c-sharpcorner.com/UploadFile/dacca2/fundamentals-of-unit-testing-unit-testing-of-ioc-code/

This is the Fundamentals of Unit Testing article series. In this article we are discussing various important concepts of unit testing. You can read them here.
This article explains the advantages of IoC implementation in code. I hope we all have a basic concept of IoC and now we will learn how unit testing can be performed in IoC implemented code and then we will see to use a mock object in the same code.

Here is the code snippet that we will test. It's a small message sending operation and the implementation is like the following. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Classes
{
    public interface ISendr
    {
        string send();
    }

    public class smsSender : ISendr
    {
        public string send()
        {
            return "SMS send";
        }
    }

    public class emailSender : ISendr
    {
        public String send()
        {
            return "Email send";
        }
    }

    public class voiceSend : ISendr
    {
        public string send()
        {
            return "VOICE Send";
        }
    }
    public class sender
    {
        public string send(ISendr obj)
        {
            return obj.send();
        }
    }
}

Ok, so now we will write the unit test for this unit of code. Have a look at the following example.

using System;
using Classes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace UNIT
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.AreEqual("SMS send"new sender().send(new smsSender()));
            Assert.AreEqual("Email send"new sender().send(new emailSender()));
            Assert.AreEqual("VOICE Send"new sender().send(new voiceSend()));
        }
    }
}

Since we have implemented all our classes like sendSMS, sendMAIL then we can send a concrete object of the implemented class as the argument of the send() function implemented in the IoC class. And if we run the test, we will see that all the tests passed, here is the output.



Now, let's assume that we did not implemente the ISender interface in any class. Then how will we create the mock object?

To create a mock object we will use the MOQ framework. So provide a reference of the MOQ framework in your project through the Nuget Package Manager.

Now, if we think that we did not implement the ISender interface in any class, then we can create one mock object of ISender and we can pass it as an argument of the send() function defined in the sender() method. Here is a sample implementation.

using System;
using Classes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace UNIT
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mock = new Mock<ISendr>();
            var objsender = new sender().send(mock.Object);
        }
    }
}

If we run the unit test application, we will see that the test passed.



Conclusion

In this article we saw how to implement unit testing of IoC implemented code. I hope it provides a basic understanding of unit testing when an application is implemented using IoC.

Monday, January 30, 2017

Deadlock view script


SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id


Tuesday, December 13, 2016

Deep Dive into Dependency Injection and Writing Decoupled Quality Code and Testable Software



Dependency Injection is one of those terms that advanced programmers throw out with an expectation and assumption of full understanding on the part of the receiver. It's easy to get infatuated by a cool buzz phrase, especially when you hear so many others using it, but to truly understand something you need to start by understanding the problem spaces that it is trying to solve. It's important to learn the concepts behind DI so you can write software that can be properly tested. In this session, we explain dependency injection from concept to implementation, and use raw code samples to show you how it works and what problems it solves. We demonstrate how writing abstracted code can help you test your applications much better, whether or not you use a DI container. Then we get into what a DI container is and differences between Unity, MEF, MEF2, CasttleWindsor, Ninject, etc. and the different techniques, like DI thru Constructor, Properties, Interception, object graph LifeTime, and other topics. We finish by showing you implementation examples in three different platforms.


Tuesday, December 6, 2016

Git. Cases, solutions, flows.

1. Задачу Accept. Переводим в статус In Progress.
2. Create branch
3. Вваливаем себе локальную версию ветки в папке с проектом:
git fetch
git checkout "new_brunch_name_on_server"
(если не нужны локальные изменения то можно git checkout "new_brunch_name_on_server" -f)

4. Когда готово:

git status
git add .
git commit -m "BOOKS-444 commentsdfsd"
git push

5. Открываем ветку из таски, create pull request
6. Переводим


7. PS: Если хотим залить мастер в локальную ветку
git merge master
или если с форсом из мастера, перетирая локальные изменения
git merge -X theirs origin master


8. Если мы хотим удалить запушенный коммит:
git rebase -i HEAD~<количество последних коммитов, которые хотим увидеть>
Прим.: git rebase -i HEAD~3
затем то напротив ветки, которую нужно удалить, что открылось в редакторе нуждо вначале поставить d (means drop)
сохранить
затем git pull

-------------
Переключиться на определенную ветку. Запушать мастер в эту ветку. Сделать изменения, порешать конфликты. Запулить обратно с форсом.

git reset --hard dfgsdfgdfgsdf
git merge origin master
git add --all
git push --force
-------------

сброс всех текущих изменений, до последнего коммита
git reset --hard
git clean --force

--
Принудительно запушать ветку в удаленную:

git push remote_full_brunch_name local_brunch_name:remote_brunch_name


git push --set-upstream localmaster master


https://git-scm.com/book/ru/v1/%D0%92%D0%B5%D1%82%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B2-Git-%D0%9E%D1%81%D0%BD%D0%BE%D0%B2%D1%8B-%D0%B2%D0%B5%D1%82%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F-%D0%B8-%D1%81%D0%BB%D0%B8%D1%8F%D0%BD%D0%B8%D1%8F

Monday, December 5, 2016

MSSQL Mirroring. Useful notes.


The mirror server instance is not caught up to the recent changes to database:


http://www.sqlfingers.com/2016/06/msg-1422-mirror-server-instance-is-not.html

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.
Data Source=myServerAddress;Failover Partner=myMirrorServerAddress;
Initial Catalog
=myDataBase;Integrated Security=True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.


Models:

https://msdn.microsoft.com/en-us/library/ms189852(v=sql.100).aspx


How to: Minimize Downtime for Mirrored Databases When Upgrading Server Instances

https://msdn.microsoft.com/en-us/library/bb677181(v=sql.100).aspx

How to: Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)