Wednesday, November 11, 2015

Remove Skype Annoying Adverts

Skype was a great app all the time but after Microsoft brought Skype. whole team seems more focus on advertising on Skype  you also might have seen annoying adverts on top of Skype. There's small hack to remove Skype annoying adverts completely with two steps.

1st Step

  1. Open-up the control panel.
  2. Open-up "Network & Internet" then "Internet Options".
  3. Go to the "Security" tab.
  4. Click on the "Restricted Sites" icon, then the "Sites" button below it.
  5. Type "" (without the quotes) into the text box and click "Add"
  6. Close and apply the changes.
2nd Step
  1. Go to:  %AppData%\Skype\ 
  2. Click on the folder that is the same name as your Skype User name.
  3. Open the config.xml in  your fav txt editor and change this line: <AdvertPlaceholder>1</AdvertPlaceholder>
  4. Change the 1 to 0 (zero). 
  5. Mark the file as read only.


Tuesday, November 10, 2015

Constructor Inject for abstract implementation on Dependency Injection

When dependency injection pattern with constructor injection for some cases you won't be able to inject some interface implementation to constructor ( ex: IDbConnection) because it having abstract implementation which cannot invoke iOC container. I normally use simple injector because light weight and well documented.

so as my first try i tried to inject IDbConnection in to my repository class as below
public class Repository : IRepositoryAsync where TEntity : class
    public Repository(IDbConnection connection)
        Connection = connection;

    public IDbConnection Connection { get; }

and i registered to container

container.Register(typeof(IDbConnection), typeof(Repository));

but ended up with exception like this

[ArgumentException: The supplied type Repository does not implement IDbConnection.Parameter name: implementationType]SimpleInjector.Requires.ThrowSuppliedTypeDoesNotInheritFromOrImplement(Type service, Type implementation, String paramName) +63SimpleInjector.Requires.ServiceIsAssignableFromImplementation(Type service, Type implementation, String paramName) +47SimpleInjector.Container.Register(Type serviceType, Type implementationType, Lifestyle lifestyle, String serviceTypeParamName, String implementationTypeParamName) +159SimpleInjector.Container.Register(Type serviceType, Type implementationType) +52TimeTrackerService.Service.DependencyConfig..cctor() in D:\TimeTracking\TimeTrackerService\libs\TimeTrackerService.Service\DependencyConfig.cs:47[TypeInitializationException: The type initializer for 'TimeTrackerService.Service.DependencyConfig' threw an exception.]TimeTrackerService.Service.DependencyConfig.get_Container() in D:\TimeTracking\TimeTrackerService\libs\TimeTrackerService.Service\DependencyConfig.cs:40 TimeTrackerService.WcfServiceFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) in D:\TimeTracking\TimeTrackerService\TimeTrackerService\WcfServiceFactory.cs:15 System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +524System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1420System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +52System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +641[ServiceActivationException: The service '/TrackerService.svc' cannot be activated due to an exception during compilation. The exception message is: The type initializer for 'TimeTrackerService.Service.DependencyConfig' threw an exception..]System.Runtime.AsyncResult.End(IAsyncResult result) +489035System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +174System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest(IAsyncResult ar) +350322System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +9747521

so i did work around created my own interface factory class to return IDbConnection and it's implementation.

private readonly string _providerName;
private readonly DbProviderFactory _provider;
public string ConnectionString { get; set; }

public DataFactory()
    var con = ConfigurationManager.ConnectionStrings["TrackerConnection"];
    if (con == null)
        throw new Exception("Failed to find connection");
    ConnectionString = con.ConnectionString;
    _providerName = con.ProviderName;
    _provider = DbProviderFactories.GetFactory(con.ProviderName);
public IDbConnection Connection
        var connection = _provider.CreateConnection();
        if (connection == null)
            throw new Exception($"Failed to create a connection using the connection string named '{_providerName}' in app.config or web.config.");
        connection.ConnectionString = ConnectionString;
        return connection;

It's work like charm once i registered IDataFactory in to dependency container

also there's another solution overriding SimpleInjecor Register method without creating own implementation for return IDbConnection which i believe more robust.

container.Register(() =>{ 
    var con = ConfigurationManager.ConnectionStrings["TrackerConnection"]; 
    if (con == null) 
        throw new Exception("Failed to find connection"); 

    var _provider = DbProviderFactories.GetFactory(con.ProviderName); 

    var connection = _provider.CreateConnection(); 
    if (connection == null) 
        throw new Exception($"Failed to create a connection using the connection string named '{con.ProviderName}' in app.config or web.config."); 

    connection.ConnectionString = con.ConnectionString; 
    return connection; 


Tuesday, October 20, 2015

Fix FaultException on ExactTarget API

Most of the time when you working with Salesforce ExactTarget SOAP api these type of exceptions might be very familiar 

Reason for this exception is request doesn't have valid authorized header informtion which we need to set before make request

private static string _authToken = string.Empty;
private static string _sandbox = string.Empty;
private const string Version = "FuelSDX-C#-V.9";
private static string _refreshKey = string.Empty;
private static string _clientId = string.Empty;
private static string _clientSecret = string.Empty;
private static string _appSignature = string.Empty;
private static string _soapEndPoint = string.Empty;
private static string _internalAuthToken = string.Empty;
private static DateTime _authTokenExpiration = DateTime.Now;

public static void PerformRetreiveWithAuthToken(bool force = false)
    var binding = new BasicHttpBinding
        Name = "UserNameSoapBinding",
        Security = { Mode = BasicHttpSecurityMode.TransportWithMessageCredential },
        MaxReceivedMessageSize = 2147483647

    var client = new SoapClient(binding, new EndpointAddress(""));
    if ((!string.IsNullOrEmpty(_authToken) && DateTime.Now.AddSeconds(300) <= _authTokenExpiration) && !force)
    var strUrl = "";
    if (_sandbox == "true")
        strUrl = "";
    var request = (HttpWebRequest)WebRequest.Create(strUrl.Trim());
    request.Method = "POST";
    request.ContentType = "application/json";
    request.UserAgent = Version;
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        string json;
        if (_refreshKey.Length > 0)
            json =
                    @"{{""clientId"": ""{0}"", ""clientSecret"": ""{1}"", ""refreshToken"": ""{2}"", ""scope"": ""cas:{3}"" , ""accessType"": ""offline""}}",
                    _clientId, _clientSecret, _refreshKey, _internalAuthToken);
            json = string.Format(@"{{""clientId"": ""{0}"", ""clientSecret"": ""{1}""}}", _clientId, _clientSecret);

    var response = (HttpWebResponse)request.GetResponse();
    var dataStream = response.GetResponseStream();
    if (dataStream == null) return;
    var reader = new StreamReader(dataStream);
    var responseFromServer = reader.ReadToEnd();
    var parsedResponse = JObject.Parse(responseFromServer);
        _internalAuthToken = parsedResponse["legacyToken"].Value().Trim();
        _authToken = parsedResponse["accessToken"].Value().Trim();
        _authTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedResponse["expiresIn"].Value().Trim()));
    if (parsedResponse["refreshToken"] != null)
        _refreshKey = parsedResponse["refreshToken"].Value().Trim();

    using (var scope = new OperationContextScope(client.InnerChannel))
        XNamespace ns = "";
        var oauthElement = new XElement(ns + "oAuthToken", _internalAuthToken);
        var xmlHeader = MessageHeader.CreateHeader("oAuth", "", oauthElement);
        var httpRequest = new HttpRequestMessageProperty();
        OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);
        httpRequest.Headers.Add(HttpRequestHeader.UserAgent, Version);

        //then we make retrive, update, perform or delete request as usual
        client.Retrieve(request, out requestId, out results)


now you good to go, Happy Coding!!

Friday, September 25, 2015

Use custom domain instead of localhost

when you run your mvc application on IIS Express sometimes you might need to change address in to some custom domain( instead of localhost(http://localhost:[port]). In this post i'll explain how to do that. firstly we just change a couple of things.first go to project properties and change values as follow.

then you need to change IISExpress configuration file called applicationhost.config  located at %USERPROFILE%\Documents\IISExpress\config and update relevant site settings like this.

Important: Make a backup of your config file. You can really screw things here.

<site name="Purl" id="1"> 
    <application path="/" applicationPool="Clr4IntegratedAppPool"> 
        <virtualDirectory path="/" physicalPath="D:\Purl\PurlApplication" />                     </application> 
        <binding protocol="http" bindingInformation="*:80:" /> 
        <binding protocol="https" bindingInformation="*:44300:localhost" /> 
and to update host file with relevant example domain open notepad in administrator mode and go to to %SYSTEMROOT%\System32\drivers\etc  open host file
add update like this
Go back to your project and hit Ctrl+F5 to start IIS Express again. some cases site won't run and Visual Studio won't update settings in to localhost in that case start visual studio in administrator mode (run as administrator).

and you are done!!!

Password compare directive angularJs

Some times on your angularjs application you may need to compare your sign up form password and confirm it. here's the simple directive for compare password on the fly.
.directive('validateEquals', [function () {
    return {
      require: 'ngModel',
      link: function (scope, elem, attrs, ctrl) {
        var firstPassword = '#' + attrs.validateEquals;
        elem.add(firstPassword).on('keyup', function () {
          scope.$apply(function () {
            var v = elem.val()===$(firstPassword).val();
            ctrl.$setValidity('inputmatch', v);
On your Html for can setup like this
<input id="input1" name="input1" ng-model="input1" ng-required="" type="password" />
<input id="input2" name="input2" ng-model="input2" ng-required="" type="password" validate-equals="input1" />
to show error message
<div ng-show="myForm.$error">
  <span  ng-show="myForm.input2.$error.inputmatch">
    Passwords don't match.
Happy coding!!!

Thursday, September 24, 2015

How to read and write appSetting

To read and write appSetting vlaue on configuration file in c# we can use below simple two methord
private const string Prefix = "config";
public static T GetValue(string key, string prefix = Prefix)
    var entry = string.Format("{0}:{1}", prefix, key);
    if (entry.IsNullOrWhiteSpace())
        return default(T);
    var value = ConfigurationManager.AppSettings[entry];
    if (value.IsNullOrWhiteSpace())
        return default(T);
    if (typeof (T).IsEnum)
        return (T) Enum.Parse(typeof (T), value, true);
    if (typeof (T) == typeof (bool) && value.Is())
        return (T) Convert.ChangeType(value.As(), typeof (T));
    return (T) Convert.ChangeType(value, typeof (T));
public static T SetValue(string key, string value)
    var entry = string.Format("{0}:{1}", Prefix, key);
    var config = WebConfigurationManager.OpenWebConfiguration("~");
    config.AppSettings.Settings[entry].Value = value;
    return default(T);
so thanks to generic implementation you get the values with their data type
bool isMobile = GetValue<bool>("IsMobile");