Contents tagged with C#

  • Entity Framework one to many relationship

    Hello everybody,

    today I want to make short post on how to confiugre one to many relationship in Entity Framework 6.

    Imagine following: One group can have multiple students. So one to many relationship. For this purpose you can use following convention configuration agreement:

    public class Student

    {

        public int StudentId { get; set; }

        public string StudentName { get; set; }

    }

    public class Group

    {

        public int GroupId { get; set; }

        public string GroupName { get; set; }

        public string Department { get; set; }

        public List<Student> Students { get; set; }

    }

    In presented example class group includes navigation property Students. 

    Another convention is … more

  • Linear regression behavior with free weight

    Hello everybody,

    recently I've decided to implement some ML library in C#. But mine ultimate goal of that C# library was to make it use as much as possible TPL features of C#. 

    I'm aware about other ML libraries, but as often is said, if you wish to understand how some ML algorithm works, program it by yourself. I've decided to start with Linear regression.

    Here you can see how mine library utilizes processor:

    as you can see it uses 85% of mine 4-cores CPU, which is impossible with only one thread running.

    First step for me was to understand how that algorithm works. In order to understand it I've took course Machine Learning Specializationfrom University of Washington.

    I'll omit … more

  • C# async/await usage

    Hello everybody,

    today I want to describe in simple words what C# does for .Net cases in IIS.

    Before I continue, I want to point the following. As usually IIS has 500 threads. It means that one IIS server can simultaneously server 500 customers. Keeping this idea in mind

    take a look at the following code:

    [HttpGet]

    public IEnumerable<string> GetSync()

    {

        string val1 = "value" +  LongRunningMethod().ToString();

        string val2 = "value2";

        return new[] { val1, val2 };

    }

    private int LongRunningMethod()

    {

        Thread.Sleep(10000);

        return 10;

    }

    and imagine that you have 600 customers simultaneously. For 500 lucky users of your web site it will mean that their … more

  • C# feature nameof

    Hello everybody,

    today I want to share with you one cool feature of C#.  It is nameof. Take a look at the following code:

    var abc = 3;

    var varName = nameof(abc);

    How do you think, what will go into varName? It will be equal to "abc". Probably you can puzzle why on earth I can need such an operator?

    Consdier following cases:

    1. If you work with reflection, then instead of rely on hard coding names of fields, you can rely on compiler to subsitute it instead of you. 

    class Program

    {

        public class NameOffDemo

        {

            public string SomePropertyOne { get; set; }

            public string SomePropertyTwo { get; set; }

        }

        static void Main(string[] args)

        {

             … more

  • How to construct complicated queries in BQL of Acumatica

    Hello everybody,

    today I want to describe the following situation. Imagine that you have to write following SQL statement in Acumatica:

    SELECT InventoryItem.InventoryCD, InventoryItem.imageUrl, UploadFile.Name, NoteDoc.FileId, * FROM InventoryItem

    LEFT JOIN UploadFile ON InventoryItem.imageUrl = UploadFile.Name

    LEFT JOIN NoteDoc ON UploadFile.FileID = NoteDoc.FileID where imageurl is not null

    I myself prefer to have way to write a code that is easy to modify and maintain. So instead of creating one big BQL statement I'd like to make it as few smaller statements. Is it achievable with Acumatica BQL? Yes, it's achievable. Take a look at following code that does exactly what I've … more

  • Convenient parsing of XML nodes in C#

    Hello everybody,

    today I want to share with you code that I use in order to conveniently to parse different xml nodes in C#. 

    Take a look at this class:

    public static class XmlNodeProcessor

        {

            public static int? ParseInt(this string s)

            {

                if (string.IsNullOrEmpty(s))

                {

                    return null;

                }

                return int.Parse(s);

            }

            public static long? ParseLong(this string s)

            {

                if (string.IsNullOrEmpty(s))

                {

                    return null;

                }

                return long.Parse(s);

            }

            public static Guid? ParseGuid(this string s)

            {

          … more

  • InvokeIfRequired template

    Hello everybody,

    today I want to document simple but very useful feature if you work with multiple threads in Winforms application. 

    Quite often it happens that you execute in some paralel thread long running calculations and would like time from the time notify results to UI. 

    But if you try to do this then you'll get an error that will say to you that parallel thread doesn't have permissions to some control because it didn't create such a control. So, how then update UI?

    The answer is simple, you should use method Invoke of the control. In that case everything inside of method Invoke will be executed from UI thread. 

    Needless to say that such approach is workable but to some degree … more

  • 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