c# Creating simple app using NinjaTrader API



1 First of all register there
http://www.ninjatraderbrokerage.com/free_futures_trading_demo

2 Download and install ninja trader
http://www.ninjatrader.com/ninjatrader/nt7/setup.exe

3 Create your project in Visual studio

4 Dont forget to add a link to NinjaTrader.client.dll


5 Add this code

6 Dont forget to type your demo login, password

7 Order was added !




8 Check out another functions of this DLL
http://www.ninjatrader.com/support/helpGuides/nt7/index.html?functions.htm


c# Create custom exception

  public class CertNotValidException : Exception
    {
        public CertNotValidException()
            : base() { }
 
        public CertNotValidException(string message)
            : base(message) { }
 
        public CertNotValidException(string format, params object[] args)
            : base(string.Format(format, args)) { }
 
        public CertNotValidException(string message, Exception innerException)
            : base(message, innerException) { }
 
        public CertNotValidException(string format, Exception innerException, params object[] args)
            : base(string.Format(format, args), innerException) { }
    }

Jquery UI Dialog

    $("#dialog").dialog({
        autoOpen: false,
        height: 500,
        width: 960
    });
 
$("#dialog").dialog("open");


<div id="dialog" title="Dialog title"></div>

ASP NET MVC JQuery table with ajax refresh



       var oProtocolTable = $('#ProtocolTable').DataTable({
        "bPaginate": false,
        "ordering": false,
        "bFilter": false,
        "bInfo": false,
        "bProcessing": true,
        "bLengthChange": false,
        "ajax": "/Home/ProtocolAjaxHandler",
        "language": {
            "url": "Content/Russian.txt"
        },
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "GroupID", "value": GroupID });
            aoData.push({ "name": "OrgInn", "value": orgINN });
            aoData.push({ "name": "check_id", "value": check_id });
        }
    });
 
    $('#OrganisationRisk tbody').on('click', 'tr', function () {
        check_id = oOrganisationRisk.cell(this, 0).data();
        oProtocolTable.ajax.reload();
    });

 /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho{ get; set; }
 
        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch{ get; set; }
 
        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength{ get; set; }
 
        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart{ get; set; }
 
        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns{ get; set; }
 
        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols{ get; set; }
 
        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns{ get; set; }
 
    }


  public ActionResult ProtocolAjaxHandler(JQueryDataTableParamModel param, int? GroupID, string OrgInn, int? check_id)
        {
            var riski = RiskiRepository.Show_Protocol(OrgInn ?? "", GroupID ?? 0, check_id ?? 0);
            if (riski == null)
                return Json(new
                {
                    data = new List<string>()
                },
                JsonRequestBehavior.AllowGet);
            return Json(new
            {
                aaData = from emp in riski
                         select new[] { emp.description, emp.date_check.ToShortDateString() }
 
            },
            JsonRequestBehavior.AllowGet);
 
        }

ASP NET MVC JQUERY send ajax request and get results

var ooData = { GroupID: GroupID, OrgInn: orgINN, check_id: oOrganisationRisk.cell(this, 0).data() };
var jqxhr = $.post("/Home/ProtocolAjaxHandler", ooData, function (data) {
var ss = "";
$.each(data, function (i) {
  ss = ss + "<tr><td>" + this.description + "</td><td>" + this.date_check + "</td></tr>";
  });
$("#ProtocolTable").html(ss);


        [HttpPost]
        public ActionResult ProtocolAjaxHandler(ProtocolPost _param)
        {
            var riski = RiskiRepository.Show_Protocol(_param.OrgInn ?? "", _param.GroupID ?? 0, _param.check_id ?? 0);
            return Json(riski);
        }


        public class ProtocolPost
        {
            public string OrgInn {get;set;}
            public int? GroupID { get; set; }
            public int? check_id { get; set; }
        }




ASP NET JQuery Table with refreshing content

http://www.codeproject.com/Articles/177335/Refreshing-content-of-the-table-using-AJAX-in-ASP

https://evolpin.wordpress.com/2011/04/12/asp-net-mvc-partialview-with-ajax/
simple example of jquery ajax mvc

c# timer without timer

public void OnStart()
{
    _stop.Reset();
    _registeredWait = ThreadPool.RegisterWaitForSingleObject(_stop, 
        new WaitOrTimerCallback(PeriodicProcess), null, 5000, false);
}

public void OnStop()
{
    _stop.Set();
}

private void PeriodicProcess(object state, bool timeout)
{
    if (timeout)
    {
        // Periodic processing here
    }
    else
        // Stop any more events coming along
        _registeredWait.Unregister(null);
}

private ManualResetEvent _stop = new ManualResetEvent(false);
private RegisteredWaitHandle _registeredWait;


//It's the method for periodically calling some methothds without using Timers. I think it is more elegant solution for this.

//Waiting process works in separate thread pool. Calling method works in main thread. Be carefull with that.


c# send get responce/request

using System.Net;
using System.Collections.Specialized;
POST
using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.mydomain.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
}
GET
using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.mydomain.com/recepticle.aspx");
}
WebProxy wproxy = new WebProxy("10.10.0.2:8080", true);
wproxy.Credentials = new NetworkCredential("int", "FSinet1234", "fsrar");
webclient.Proxy=wpproxy;


http://stackoverflow.com/questions/4015324/http-request-with-post

c# XML Creating class for serialization

What do we want

How to do

    public class wo_ids
    {
        [System.Xml.Serialization.XmlElementAttribute("id")]
        public string[] id {get;set;}
    }

c# RunProcedure with logging

    string RunProc(string s,Func<string,string> _a)
        {
            try
            {
                return _a.Invoke(s);
            }
            catch (Exception e)
            {
                var msg = e.Message;
                if (e.InnerException != null)
                    msg = msg + e.InnerException.Message + e.StackTrace;
                msg = msg + "||InString:" + s;
                Common.WriteLog(DateTime.Now.ToString() + ":" + msg);
                return msg;
            }
        }
            return RunProc(s,(x) =>
            {
                return "success";
            });

c# - Xml serialization - Hide tags with null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.
For example, if your class property is called MyNullableInt you could have
public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}
Here is a full sample
public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}
Serialized with the following code
Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);
Results in the followng XML - Notice there is no Age
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

Пишем СМЭВ сервис c#

Для проверки валидности вашего xml
http://smev.gosuslugi.ru/portal/services-tools.jsp

Будем делать чтобы сервис соответствовал методическим рекомендациям по разработке веб-сервисов версии 2.5.6

Подпись по формату ЭП-ОВ

Отправляем тем способом который без доп обертки в Envelope
http://msnet-developer.blogspot.ru/2013/03/wcf.html


c# How to install cert to remote computer and get all certs from store of remote computer

using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;

namespace ServiceCACryptLib
{
    public enum CertStoreName
    {
        MY,
        ROOT,
        TRUST,
        CA
    }
    public class CertStoreReader
    {

        #region P/Invoke Interop

        private static int CERT_STORE_PROV_SYSTEM = 10;
        private static int CERT_SYSTEM_STORE_CURRENT_USER = (1 << 16);
        private static int CERT_SYSTEM_STORE_LOCAL_MACHINE = (2 << 16);

        [DllImport("CRYPT32", EntryPoint = "CertOpenStore", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr CertOpenStore(int storeProvider, int encodingType, int hcryptProv, int flags, string pvPara);

        [DllImport("CRYPT32", EntryPoint = "CertEnumCertificatesInStore", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr CertEnumCertificatesInStore(IntPtr storeProvider, IntPtr prevCertContext);

        [DllImport("CRYPT32", EntryPoint = "CertCloseStore", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CertCloseStore(IntPtr storeProvider, int flags);

        [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool CertAddCertificateContextToStore([In] IntPtr hCertStore, [In] IntPtr pCertContext, [In] uint dwAddDisposition, [In, Out] IntPtr ppStoreContext);

        [DllImport("Crypt32.dll", SetLastError = true)]
        public static extern IntPtr CertCreateCertificateContext(
            Int32 dwCertEncodingType,
            Byte[] pbCertEncoded,
            Int32 cbCertEncoded
        );

        public const Int32 X509_ASN_ENCODING = 0x00000001;

        public const Int32 PKCS_7_ASN_ENCODING = 0x00010000;

        public const Int32 MY_TYPE = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;

        const uint CERT_STORE_ADD_ALWAYS = 4;

        #endregion


        public string ComputerName { get; set; }

        private readonly bool isLocalMachine;
        public CertStoreReader(string machineName)
        {
            ComputerName = machineName;
            if (machineName == string.Empty)
            {
                isLocalMachine = true;
            }
            else
            {
                isLocalMachine = string.Compare(ComputerName, Environment.MachineName, true) == 0 ? true : false;
            }
        }

        public void InstallCert(CertStoreName storeName)
        {
            string fileName = "C:\\temp\\Test2.cer";

            var certificate = new X509Certificate(fileName);
            var certificateBytes = certificate.Export(X509ContentType.Cert);
            var certContextHandle = CertCreateCertificateContext(
                X509_ASN_ENCODING, certificateBytes, certificateBytes.Length);

            var givenStoreName = GetStoreName(storeName);

            if (givenStoreName == string.Empty)
                throw new Exception("Invalid Store Name");

            IntPtr storeHandle = IntPtr.Zero;
            try
            {
                storeHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, string.Format(@"\\{0}\{1}", ComputerName, givenStoreName));

                if (storeHandle == IntPtr.Zero)
                    throw new Exception(string.Format("Cannot connect to remote machine: {0}", ComputerName));

                CertAddCertificateContextToStore(storeHandle, certContextHandle, CERT_STORE_ADD_ALWAYS, IntPtr.Zero);
                CertCloseStore(storeHandle, 0);
            }
            catch (Exception ex)
            {
                throw new Exception("Error opening Certificate Store", ex);
            }
            finally
            {
                if (storeHandle != IntPtr.Zero)
                    CertCloseStore(storeHandle, 0);
            }
        }

        public X509Certificate2Collection GetCertificates(CertStoreName storeName)
        {

            X509Certificate2Collection collectionToReturn = null;
            string givenStoreName = GetStoreName(storeName);

            if (givenStoreName == string.Empty)
            {
                throw new Exception("Invalid Store Name");
            }

            IntPtr storeHandle = IntPtr.Zero;

            try
            {
                storeHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, string.Format(@"\\{0}\{1}", ComputerName, givenStoreName));
                if (storeHandle == IntPtr.Zero)
                {
                    throw new Exception(string.Format("Cannot connect to remote machine: {0}", ComputerName));
                }


                IntPtr currentCertContext = IntPtr.Zero;
                collectionToReturn = new X509Certificate2Collection();
                do
                {
                    currentCertContext = CertEnumCertificatesInStore(storeHandle, currentCertContext);
                    if (currentCertContext != IntPtr.Zero)
                    {
                        collectionToReturn.Add(new X509Certificate2(currentCertContext));
                    }
                }
                while (currentCertContext != (IntPtr)0);


            }
            catch (Exception ex)
            {
                throw new Exception("Error opening Certificate Store", ex);
            }
            finally
            {
                if (storeHandle != IntPtr.Zero)
                    CertCloseStore(storeHandle, 0);
            }

            return collectionToReturn;
        }

        private static string GetStoreName(CertStoreName certStoreName)
        {
            string storeName = string.Empty;
            switch (certStoreName)
            {
                case CertStoreName.MY:
                    storeName = "My";
                    break;

                case CertStoreName.ROOT:
                    storeName = "Root";
                    break;

                case CertStoreName.CA:
                    storeName = "CA";
                    break;

                case CertStoreName.TRUST:
                    storeName = "Trust";
                    break;
            }
            return storeName;
        }
    }
}

Open store remotly for specific user

CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
NULL, 
CERT_SYSTEM_STORE_USERS | CERT_STORE_READONLY_FLAG | CERT_STORE_OPEN_EXISTING_FLAG,
"\\\\computerName\\user_SID\\MY"))

How to get user sid
http://www.windows-commandline.com/get-sid-of-user/