Features Of System Reflection

 

Hello everybody,

today I want to document few features of System.Reflection namespace.

It has following important types:

Type ( with methods GetType, GetMemberInfo, GetPropertyInfo, GetFieldInfo ), Activator ( with method CreateInstance ), Assembly ( Load, LoadFrom, GetTypes, GetName, GetFiles ), ILGenerator ( Emit ).

Some code fragments for reflection

var lst = new List<double>();

Type listType = typeof(List<double>);

Type[] pars = {typeof(double)};

MethodInfo addMeth = listType.GetMethod("Add", pars);

addMethod.Invoke(lst, new object[] {8.3});

Create an isntace of type:

public static Type GetType(string typeName)

public static object CreateInstance(Type type)

How to work with interfaces

public static Assembly LoadFrom(string assemblyFile); // load assembly

public IEnumberable<Type> ExportedTypes {get; }// Get types exposed on an Assembly

public bool IsAssinableFrom( Type c ); //check if type implements interface

public bool IsSubClassOf(Type c); // check if type inherits another type

public bool IsClass {get; } // check if type is a class

Fully-Qualified type name

Suppose you want to create some instance of interface implementation. You can see following Fully-qualified name:

Repository.Interface.IRepository`2[SomeClass1, System.String]

Question: for what stands 2 after back tick symbol? 2 says the following: Repository.Interface.IRepository has 2 generic type parameters.

Sample of search and Load

IEnumerable<string> assemblyFiles = Directory.EnumerateFiles(assemblyPath, "*.dll", SearchOption.TopDirectoryOnly);

foreach (string assemblyFile in assemblyFiles)
{
      Assembly assembly = Assembly.LoadFrom(assemblyFile);
      foreach (Type type in assembly.ExportedTypes)
      {
            if (type.IsClass && typeof(ISomeInterface).IsAssignableFrom(type))
                  {
                        ISomeInterface interfaceInstance = Activator.CreateInstance(type) as ISomeInterface;
                        implementations.Add(new DynamicOrderRule(interfaceInstance, type.FullName, type.Assembly.GetName().Name));

                   }

      }
}

No Comments

 

Add a Comment
 

 

New Feature Of C That I Ve Discovered

 

Hello everybody,

today I want to describe one new feature of C# that I discovered today. At MSDN it is named Type pattern. It looks like this:

   expr is type varname 

such code gives you to shorter your code.

Take a look at the following code:

using System;

public class Student : IComparable
{
    public String Course { get; set; }
    public int Id { get; set; }

    public int CompareTo(Object o)
    {
        if (o is Student)
        {
            e = o as Student;
if(e == null)
{
throw new ArgumentException("some explanatory error message");
}
return Course.CompareTo(e.Course); } throw new ArgumentException("o is not an Employee object."); } }

Have you ever had such a code? I suppose yes. 

Have you ever wanted to make it shorter? Independently of the answer now you can make it shorter like this:

using System;

public class Student : IComparable
{
    public String Course { get; set; }
    public int Id { get; set; }

    public int CompareTo(Object o)
    {
        if (o is Student e)
        {
            return Course.CompareTo(e.Course);
        }
        throw new ArgumentException("o is not an Employee object.");
    }
}

Take note of e letter in the end of if. For now C# not just check the type, but also will assign value of checked type into varaible. 

One more detail. In case if you work with Visual Studio 2015 most probably VS 2015 will not be able to compile code with Type pattern. In order to educate VS 2015 to know about new features of C# 7 you'll need ask VS 2015 to use newer versoin of C# compiler. In order to do this you'll need to execute following command in package manager console:

Install-Package Microsoft.Net.Compilers

Unfortunatelyy after that command red squiglings will not disapper from your code, but VS 2015 will become able to successfully build your project and execute it.

No Comments

Add a Comment
 

 

Interception

 

Hello everybody,

today I want to write few words about Interception.

First of all one of the questions that requires consideration can be why we may need interception at all? Need in interception arises in cases when we have some kind of logic, that is dispersed around whole application. Some candidates for interception can be:

  • Logging
  • Authorization
  • Validation
  • Exception handling
  • Caching
  • Performance collecting and analysis

etc.... . So, after knowing at which places interception can be used following statement can be considered as explanation: interception is inserting code between calling code and target object. Code can be inserted before or after method call. If code is inserted before call then we have access to input variables, if code is intercepted then we have access to output.

There are following types of interception ( at least interceptions that I was able to find )

  1. Instance interception
  2. Type interception

No Comments

Add a Comment
 

 

How To Get Response From Walmart

 

Hello everybody,

today I want to share with the world another piece of code, producing of which took me significant amount of efforts, getting response from Walmart.

Yesterday I've posted code that signs provided by Walmart credentials.

And today I decided to post code that retrieves orders information from Walmart.

private void MakeRequests()
{
    HttpWebResponse response;

    if (Request_marketplace_walmartapis_com(out response))
    {
        response.Close();
    }
}

private bool Request_marketplace_walmartapis_com(out HttpWebResponse response)
{
    response = null;

    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://marketplace.walmartapis.com/v3/orders?createdStartDate=2016-08-16");

        request.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
        request.Headers.Add("WM_QOS.CORRELATION_ID", "123456abcdef");
        request.Headers.Add("WM_SEC.AUTH_SIGNATURE", "trimmed for security reasons");
        request.Headers.Add("WM_SEC.TIMESTAMP", "1495703564642");
        request.Headers.Add("WM_CONSUMER.ID", @"guid of customer that was provided to you by Walmart");
        request.Headers.Add("WM_CONSUMER.CHANNEL.TYPE", @"0f3e4dd4-0514-4346-b39d-af0e00ea066d");

        response = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException e)
    {
        if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
        else return false;
    }
    catch (Exception)
    {
        if(response != null) response.Close();
        return false;
    }

    return true;
}

In case if you'll have a need to make Walmart request, enjoy.

2 Comments

  • Saurabh said

    Hi -

    I have tried with your code (also taken the code for creating Signature) but I am getting an error "The remote server returned an error: (401) Unauthorized."

    Can you please help with this issue?

    BaseUrl = https://marketplace.walmartapis.com/v3/orders?createdStartDate=2017-10-30

  • docotor said

    Do you have gitlab account? I can give you new version of Walmart reader.

Add a Comment
 

 

Wcf Rabbitmq Binding

 

Hello everybody,

recently I've spent plenty of time with the following task: Create Publisher/Subscriber application that via WCF send/receive messages from RabbitMQ. As foundation for my code I've used code from Dieg web site, just modified binding.

Bindings were modified in App.config files. 

Below goes bindings declarations:

 <system.serviceModel>
    <extensions>
      <bindingExtensions>
        <add name="rabbitMQBinding"
             type="RabbitMQ.ServiceModel.RabbitMQBindingSection, RabbitMQ.ServiceModel, Version=3.5.7.0, Culture=neutral,PublicKeyToken=null"/>
      </bindingExtensions>
    </extensions>
    <client>
      <endpoint address="soap.amq:///myqueue"
          binding="rabbitMQBinding"
          bindingConfiguration="rabbitMQConfig"
          contract="testFancyProxyContracts.ISampleContract"
          name="AMQPCalculatorService" />
    </client>
    <bindings>
      <rabbitMQBinding>
        <binding name="rabbitMQConfig"
          hostname="rabbit.test"   
          port="5672"
          username="guest"
          password="guest"
          virtualHost="/"
          oneWay="true"
          maxmessagesize="8192" />
      </rabbitMQBinding>
    </bindings>
  </system.serviceModel>

 

And if you need to see full source code, you can Download  it. 

No Comments

Add a Comment
 

 

How To Configure Wcf For Msmq

 

Hello everybody,

today I want to document how to configure WCF for usage with MSMQ.

Of course I suppose you know how to add in windows features MSMQ at each instance where WCF service will work.

So, first of all, let's see how to configure basic interface:

[ServiceContract(SessionMode = SessionMode.Required)]
    public interface IService1
    {
        [OperationContract(IsOneWay = true)]
        void GetData(int value);

        [OperationContract(IsOneWay = true)]
        void GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

Take not on two features of each method: 

  1. Each method has IsOneWay set to true in OperationContract
  2. Each method returns void. 

Both of those limiations is caused by MSMQ architecture. MSMQ reliably delivers messages, but doesn't tell you when this message is delivered. That's why you need to configure it in the mentioned way.

But that is not the end of the story. For MSMQ you'll need also to add few more attributes to class implementation:

[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
public void GetData(int value)
{
  //some code
}

Then in your endpoint configuration you can write something like this:

<endpoint address="net.msmq://localhost/public/msmqService"
       bindingConfiguration="NetMsmqBinding"
       binding="netMsmqBinding"
       contract="WcfServiceServer.IService1">
</endpoint>

Hope it can help somebody to save his day.

No Comments

Add a Comment
 

 

How To Send Email In C Windows Forms Application

 

Hello everybody,

sometime people ask me how to send email from C# windows forms application or even ask is it possible at all to accomplish in C#?

I can reassure you that yes, it's possible. 

For this purpose you can use following code sample:

private void btnSendMessage_Click(object sender, EventArgs e)
{
            var from = new MailAddress(txtFrom.Text, "From Name");
            var toEmail = new MailAddress(txtTo.Text, "To Name");
            string passwordFromEmailOfSender = txtPassword.Text;
            string subject = "Subject";
            string body = txtMessage.Text;

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(from.Address, passwordFromEmailOfSender)
            };
            using (var message = new MailMessage(from, toEmail)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp.Send(message);
            }

}

If you are to busy to copy/paste code by yourself with guessing how to locate buttons on the form, you can Download source code and compile it with Visual Studio 2015. Actually Archive contains exe file as well.

If you'll execute program and fill some data you can see something like this:

If your mailbox is from yahoo, you will see something similar to this:

Also you can use presented code for making mass sending of some needed information for your business.

No Comments

Add a Comment
 

 

How To Avoid Many If During Programming For Calgo

 

Hello everybody,

today I want to write few words about how to avoid nested ifs if you program for cAlgo.

Recently I've got following request ( code is modified in order to protect privacy of customers idea ):

buy in following case:

  1. price is above moving average 20
  2. price is above moving average 30
  3. stochastic is above 40
  4. each of indciators from 1 - 3 can be turned on/off

As example consider following case:

if( movingAverage30On && MarketSeries.Low[1] > longMa.Result[1])
{
    if(movingAverage20On && MarketSeries.Low[1] > shortMa.Result[1])
    {
        if(stochasticOn && _stochastic.PercentD[1] > 40)
        {
            //Buy
        }
    }
}

if(movingAverage20On && MarketSeries.Low[1] > shortMa.Result[1])
{
    if( movingAverage30On && MarketSeries.Low[1] > longMa.Result[1])
    {
        if(stochasticOn && _stochastic.PercentD[1] > 40)
        {
            //Buy
        }
    }
}

And that is pretty confusing. The more indicators you want to make on/off, the bigger tree you have to make. In my case it was around 10 different trees. 10 trees is of course not forest, but still pretty decent way to loose way. So I had to think how to modify my solution to become more flexible and readable.

So I've applied ternary logic for my situation. As usually if people hear about ternary logic in C#, they think about bool something = a ==b ? oneResult : anotherResult;

But I mean little bit different solution. In C# bool can have two values: true and false. But bool ? or Nullable<bool> can have three values: null, true, false.

So, in order to use this cool feature which appeared in C# 2.0 or from visual studio 2005, I've made the following logic.

In cAlgo robot can make three decisions with regard to opening positions: buy, sell, abstain.

For simplicity sake I'll describe my solution from standpoint of buy ( sell is mirorly different ).

cAlgo robot can make two decisions: buy, not buy.

Indicator can have two positions: on/off.

So, for each indicator I've wrote functions similar to this:

bool? IsBuyConditionForStochastic()
{
        if (OnStochastic)// OnStochastic stands for Is stochastic in true or in false
        {
           bool isBuyStochastic = _stochastic.PercentD[1] > 40;
           return isBuyStochastic;
        }
        return null;
}

and following code for method, which decides to buy or not buy:

bool IsBuySituation()
{
bool result = false;
.
.
.
if
(IsBuyConditionForStochastic().HasValue) { result = result && IsBuyConditionForStochastic().Value; if (!result) { return result; } }
.
.
.
return result;
}

So, let's assume that user decided to turn stochastic to on position. Then following logic will be applied:

  1. OnStochastic will receive value true
  2. Method IsBuyConditionForStochastic will return true or false
  3. result variable will receive value from function IsBuyConditionForStochastic
  4. that value will be returned if it is false, or will be used in analogical way for taking into account other parameters

Hope it will help somebody with organizing his code and avoid forest of ifs

No Comments

 

Add a Comment
 

 

How To Parse Google Search Results

 

Hello everybody,

today I want to describe how to use C# for scrapping results. 

For me it was surprising to see, that there is a stereotype that for scrapping the best tool or tools only to use are R, Python. And majority of people who needed functionality of parsing wanted that functionality in some of those languages. While I do agree that those are great languages, which really enhance toolbox of developer, I want to show also that in C# you can achieve similar results. 

Below goes screenshot of C# program which sends request to google and receives result:

Application workflow is pretty simple.

  1. You enter search request. At screenshot you can see that search request was i7 skylake
  2. Press at button Request
  3. Application send request to google.
  4. Application parses respond from the first page from google and shows urls and titles of urls.

The program itself can be downloaded from  here

Below I also provide hear of that program:

Snippet

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using NScrape;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
 
namespace WebRequesting
{
    public partial class Form1 : Form
    {
        HtmlAgilityPack.HtmlDocument htmlSnippet = new HtmlAgilityPack.HtmlDocument();
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btn1_Click(object sender, EventArgs e)
        {
            lstTitles.Items.Clear();
            lstUrls.Items.Clear();
            StringBuilder bufferForHtml = new StringBuilder();
            byte[] encodedBytes = new byte[8192];
            var urlForSearch = "http://google.com/search?q=" + txtSearch.Text.Trim();
            var request = (HttpWebRequest)System.Net.WebRequest.Create(urlForSearch);
            var response = (HttpWebResponse)request.GetResponse();
 
            using (Stream responseFromGoogle = response.GetResponseStream())
            {
                var enc = response.GetEncoding();
 
                int count = 0;
                do
                {
                    count = responseFromGoogle.Read(encodedBytes, 0, encodedBytes.Length);
                    if (count != 0)
                    {
                        var tempString = enc.GetString(encodedBytes, 0, count);
                        bufferForHtml.Append(tempString);
                    }
                }
 
                while (count > 0);
            }
            string sbb = bufferForHtml.ToString();
 
            var processedHtml = new HtmlAgilityPack.HtmlDocument
            {
                OptionOutputAsXml = true
            };
            processedHtml.LoadHtml(sbb);
            var doc = processedHtml.DocumentNode;
            
            foreach (var link in doc.SelectNodes("//a[@href]"))
            {
                string hrefValue = link.GetAttributeValue("href", string.Empty);
                if (!hrefValue.ToUpper().Contains("GOOGLE")
                    && hrefValue.Contains("/url?q=")
                    && hrefValue.ToUpper().Contains("HTTP"))
                    
                {
                    int index = hrefValue.IndexOf("&");
                    if (index > 0)
                    {
                        hrefValue = hrefValue.Substring(0, index);
                        lstTitles.Items.Add(hrefValue.Replace("/url?q=", string.Empty));
                        string output = Regex.Replace(link.InnerText, "&quot;\\.?", string.Empty);
                        lstUrls.Items.Add(output);
                    }
                }
            }
        }
    }
}

If you like C#, you'll see, that program in general sends request, receives response, decodes result, and then parses url, and those, which follow certain criteria are added to listbox.

2 Comments

  • Alex said

    That is a great code, however Google may block you for automated searches. How to overcome this limitation? And how would this code solve captcha?

  • docotor said

    Yes, I understand that google can block and actually will block. In order to prevent blocking I as usually apply following options:
    1. Use timer, in order to send requests not often.
    2. With help of Webproxy class make connection via proxies.

Add a Comment
 

 

How Closures Are Implemented By Net

 

Hello everybody,

today I want to share piece of wisdom which is interesting, but hard to explain why somebody may need it. That is how closures are implemented. 

Consider the following code:

Snippet

class Program
    {
        static void Main(string[] args)
        {
            int a = 54;
 
            Task t = new Task(
                () =>
                {
                    a++;
                    Console.WriteLine("Inside task");
                }
                );
            t.Start();
 
        }
    }

Now you may wonder, how a will be passed to closure? How Console.WriteLine will be executed?

For my surprise .Net for closures generates behind the curtains the whole class. And instead of all referencing to variable a, it substitutues it by referencing to member of class.

Take a look at the following screenshot:

The class c__DisplayClass0_0 was generated by .Net compiler. And take note that it has variable a, which is of type int32. 

Also, if to double click on Main with letter S following will be opened ( just without highlighting )

and take note, instance of which class was created? c__DisplayClass0_0 !!!!

And that class was passed to every place, where it is needed to do something with variable a. 

Question, does generated class has only variable a? 

Take note at another screenshot:

.Net generated in class c__DisplayClass0_0 method, and inside of that method is used Console.Writeline with input paramether as string.

No Comments

Add a Comment