Contents tagged with C#

  • Acumatica DAC class generator

    Hello everyboydy,

    today I want to share with anybody mine implementation of DAC class generator.

    By default Acumatica provides you with DAC class generator which is pretty good.

    But time from the time I had a need to generate DAC class into text field, and then

    put it somewhere in my solution, and Acumatica DAC class generator didn't feet to

    mine needs. So I decided to create my own DAC class generator. 

    This form has simple interface. In the first line you enter Connection string, at second

    line you enter table name, press at generate, and receive DAC class.

    You can download source code here. 

    Below goes also some C# code which I've comment later:

        public  … more

  • How to create plugins that can be loaded/unloaded

    Hello everybody,

    today I want to show sample of code that you can use for your plugins.

    Sometime it can happen that you have some application with it's dlls and you can decide to make ad hoc dlls.

    In order to demonstrate how to do it I prepared following code:

    Create first class library as BaseLib:

    using System;

    namespace BaseClass

    {

        public class BaseClass : MarshalByRefObject

        {

            public virtual bool IsProcessable(string message)

            {

                return true;

            }

            public virtual void Process(string message)

            {

                

            }

        }

    }

    Then create following implementation:

    using System;

    namespace Ext1

    {

        public  … more

  • How to convert excel file to CSV file

    Hello everybody,

    today I want to document a few lines of code which can help to convert excel file to CSV file with help of OLE:

    static void ConvertExcelToCsv(string excelFileName, string csvOutputFileName, int worksheetNumber = 1)

    {

        if (!File.Exists(excelFileName)) throw new FileNotFoundException(excelFileName);

        if (File.Exists(csvOutputFileName)) throw new ArgumentException("File already exists: " + csvOutputFileName);

        var connectionString =

            $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={excelFileName};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"";

        var oleDbConnection = new OleDbConnection(connectionString);

        // get schema, then data

        var  … more

  • How to check if type in Assembly implements particular Interface

    Hello everybody,

    today I want to give sample of reading available types from dll .net assembly, check if at least one of them implements interface, and if implements then to create instance of that type and return it. 

    So, imagine you have such interface declaration in your code:

    public interface ILogger

        {

            /// <summary>

            /// Convert <see cref="LoggerMessage"/> to string based on the formats specified.

            /// </summary>

            /// <param name="message">The message to be converted.</param>

            /// <returns>Converted <paramref name="message"/>.</returns>

            LoggerMessage Handle(LoggerMessage message);

            bool Handlable(LoggerMessage message); … more

  • Concurent collections of C#

    Hello everybody,

    today I want to write few words about Concurent collections in C#. First of all  I want to point there there are only four of them:

    ConcurrentDictionary

    ConcurrentQueue

    ConcurrentStack

    ConcurrentBag

    BlockingCollection

    Partitioner

    EnumerablePartitionerOptions

    IProducerConsumerCollection

    OrderablePartitioner

    Not very impressive set of collections if to compare with diversity of other collections in .Net.

    Also keep in mind that ConcurrentQueue, ConcurrentStack and ConcurrentBag are not suitable for a lot of purposes. For example those last three do not allow direct access to any element in the collection which makes them unfitting for many goals. In practical … more

  • 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 … more

  • 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 … more

  • 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 … more

  • 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:// … more

  • 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" … more

  • 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: 

    Each method has IsOneWay set to true in … more

  • 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", … more

  • 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:

    price is above moving average 20

    price is above moving average 30

    stochastic is above 40

    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(movingAverage20 … more

  • 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.

    You enter search request. At screenshot you can see that search request was i7 … more

  • 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 … more

  • C# Task, ContinueWith

    Hello everybody,

    today I want to write few words about Task Paralel library, and in particular two methods: Task.Start, and Task.ContinueWith.

    Snippet

    System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(

                    () => {

                        //some heavy code like intensive calculations, reading from db, etc.

                        

                    }

                );

                System.Threading.Tasks.Task t2 = t.ContinueWith(

                    (a) => {

                    //Code to update UI

                    },

                    TaskScheduler.FromCurrentSynchronizationContext()

                );

    Following template has the following structure. You need to split your code … more

  • Generate TypeScript from Enum

    Hello everybody,

    today I want to share with the world code, which generates typescript from enum declaration. I suppose everything should be understandable from code itself:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Linq;

    using System.Reflection;

    using System.Text;

    using System.Threading.Tasks;

    namespace System

    {

    public static class AttributesSimplification

    {

    /*

     

    [Description("Enumerations")]

    public enum EnumSample

    {

    [Description("Choice One")]

    ChoiceOne,

    [Description("Choice Two")]

    ChoiceTwo,

    }

       gives following ts:

    module Enumerations {

    export module EnumSample {

    export enum Enum {

    ChoiceOne = 0, … more

  • One more summary of Moq library

    Examples of Mock usages

    Mock - is a simple and lightweight isolation framework, which is built on the basis of anonymous methods and expression trees. To create them it uses code generation, thus allowing to mock interfaces, virtual methods (and even protected methods) and does not allow to mock non-virtual and static methods.

    NOTE

    At market exists only two frameworks that allow to mock anything. These are TypeMockIsolator and Microsoft Fakes, available in Visual Studio 2012 and higher. These frameworks, unlike Mock ( which uses code generation) use CLR Profiling API, allowing to mock any method even for static, virtual and private methods. IMHO they are good for testing legacy code … more

  • C# and continue operator in cycles

    Hello everybody,

    today I want to write a notice about word continue in C#. 

    So, how it look like:

    for( int i = 0; i < 10; i++ )

    {

         if(i == 5)

         {

              continue;

         }

        //do some other staff

    }

    In this code, //do some other staff will be executed only 9 times, because for fifth it is written as continue. Continue can be compared to situation, when you bust some boxes, but then you see, that some box doesn't feet to your needs. Then you'll say to C# compiler, skip the box, and continue to bust another boxes. more

  • CQRS in in C# most trivial possible example

    Hello everybody,

    today I want to make compendium of CQRS for very simple case.

    So, at one of the projects I seen following way of implementing code:

    public class WriteModel

    {

    //common properties

    public int SomeEntity {get;set; } // ID of some entity

    }

    public class ReadModel : WriteModel

    {

    public string AdditionalProperty {get;set; }

    }

    and that way of implementing it was proudly named CQRS. To be honest I wasn't very agreeable on that part, so I decided to hear opinions of other people, not only mine understanding of what I read in book.

    And I'd like to save one of the comments not only at stackoverflow, but also at my web site.

    So, what's wrong with … more