Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

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# Переводим с помощью Bing Api translator


using System;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Web;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace BlogSubmitterFXApp
{
    public static class BingTranslate
    {
        public static string Translate(string clientId,string ClientSecret,string TextForTranslate)
        {
            AdmAccessToken admToken;
            string headerValue;
            //Get Client Id and Client Secret from https://datamarket.azure.com/developer/applications/
            //Refer obtaining AccessToken (http://msdn.microsoft.com/en-us/library/hh454950.aspx) 
            AdmAuthentication admAuth = new AdmAuthentication(clientId, ClientSecret);
            try
            {
                admToken = admAuth.GetAccessToken();
                DateTime tokenReceived = DateTime.Now;
                // Create a header with the access_token property of the returned token
                headerValue = "Bearer " + admToken.access_token;
                return BingTranslate.TranslateMethod(headerValue, TextForTranslate);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        static string TranslateMethod(string authToken, string TextForTranslate)
        {
            // Add TranslatorService as a service reference, Address:http://api.microsofttranslator.com/V2/Soap.svc
            TranslatorService.LanguageServiceClient client = new TranslatorService.LanguageServiceClient();
            //Set Authorization header before sending the request
            HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Method = "POST";
            httpRequestProperty.Headers.Add("Authorization", authToken);

            // Creates a block within which an OperationContext object is in scope.
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                //string sourceText = "<UL><LI>Use generic class names. <LI>Use pixels to express measurements for padding and margins. <LI>Use percentages to specify font size and line height. <LI>Use either percentages or pixels to specify table and container width.   <LI>When selecting font families, choose browser-independent alternatives.   </LI></UL>";
                string translationResult;
                //Keep appId parameter blank as we are sending access token in authorization header.
                translationResult = client.Translate("", TextForTranslate, "en", "ru", "text/html", "general");
                return translationResult;
            }
        }
    }

    [DataContract]
    public class AdmAccessToken
    {
        [DataMember]
        public string access_token { get; set; }
        [DataMember]
        public string token_type { get; set; }
        [DataMember]
        public string expires_in { get; set; }
        [DataMember]
        public string scope { get; set; }
    }

    public class AdmAuthentication
    {
        public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
        private string clientId;
        private string cientSecret;
        private string request;

        public AdmAuthentication(string clientId, string clientSecret)
        {
            this.clientId = clientId;
            this.cientSecret = clientSecret;
            //If clientid or client secret has special characters, encode before sending request
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));
        }

        public AdmAccessToken GetAccessToken()
        {
            return HttpPost(DatamarketAccessUri, this.request);
        }

        private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
        {
            //Prepare OAuth request 
            WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
            webRequest.ContentLength = bytes.Length;
            using (Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            using (WebResponse webResponse = webRequest.GetResponse())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
                //Get deserialized object from JSON stream
                AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                return token;
            }
        }
    }
}

C# Post/Add BlogPost to wordpress


using CookComputing.XmlRpc;

namespace BlogSubmitterFXApp.WorkWithAPI
{
    public struct blogInfo
    {
        public string title;
        public string description;
    }

    public interface IgetCatList
    {
        [CookComputing.XmlRpc.XmlRpcMethod("metaWeblog.newPost")]
        string NewPage(int blogId, string strUserName, string strPassword, blogInfo content, int publish);
    }

    public static class WordPress
    {
        public static bool NewPost(string strUserName, string strPassword, string blogurl ,blogInfo bi)
        {


            blogInfo newBlogPost = default(blogInfo);

            newBlogPost.title = bi.title;
            newBlogPost.description = bi.description;

            IgetCatList categories = (IgetCatList)XmlRpcProxyGen.Create(typeof(IgetCatList));
            XmlRpcClientProtocol clientProtocol = (XmlRpcClientProtocol)categories;

            //For example clientProtocol.Url = "http://msnetdeveloper.wordpress.com/xmlrpc.php";
            clientProtocol.Url = blogurl;

            string result = null;
            result = "";

            try
            {
                result = categories.NewPage(1, strUserName, strPassword, newBlogPost, 1);
                return false;
            }
            catch 
            {
                return true;
            }
        }
    }
}

C# Post/Add BlogPost Blogger.com

Download GData.Client https://code.google.com/p/google-gdata/downloads/list



using System;
using Google.GData.Client;

namespace BloggerAPI
{
    public static class Blogger
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="UserblogTitle">If null,then will select first user blog</param>
        public static bool SubmitNewPost(string username, string password, string UserblogTitle)
        {
            Service service = new Service("blogger", "blogger-example");
            service.Credentials = new GDataCredentials(username, password);
            try
            {
                Uri blogPostUri = SelectUserBlog(service, UserblogTitle);
                AtomEntry createdEntry = PostNewEntry(service, blogPostUri);
                return true;
            }
            catch
            {
                return false;
            }
        }

        static AtomEntry PostNewEntry(Service service, Uri blogPostUri)
        {
            AtomEntry createdEntry = null;
            if (blogPostUri != null)
            {
                AtomEntry newPost = new AtomEntry();
                newPost.Title.Text = "Marriage!";
                newPost.Content = new AtomContent();
                newPost.Content.Content = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" +
                    "<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
                    "<p>He is the last man on earth I would ever desire to marry.</p>" +
                    "<p>Whatever shall I do?</p>" +
                    "</div>";
                newPost.Content.Type = "xhtml";
                createdEntry = service.Insert(blogPostUri, newPost);
            }
            return createdEntry;
        }

        static Uri SelectUserBlog(Service service, string UserblogTitle)
        {
            FeedQuery query = new FeedQuery();
            query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
            AtomFeed feed = service.Query(query);
            Uri blogPostUri = null;
            if (feed != null)
                foreach (AtomEntry entry in feed.Entries)
                    if (UserblogTitle == entry.Title.Text || UserblogTitle == null)
                    {
                        for (int i = 0; i < entry.Links.Count; i++)
                            if (entry.Links[i].Rel.Equals("http://schemas.google.com/g/2005#post"))
                                blogPostUri = new Uri(entry.Links[i].HRef.ToString());
                        return blogPostUri;
                    }
            return blogPostUri;
        }
    }
}

C# Post/Add BlogPost to LiveJournal.com Using


public struct blogInfo
{
        public string title;
        public string description;
}

public static class LJ
    {
        public static string NewPost(string strUserName, string strPassword, blogInfo bi)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.livejournal.com/interface/xmlrpc");
            request.Method = "POST";

            string command = String.Format(
            @"<?xml version=""1.0""?><methodCall><methodName>LJ.XMLRPC.postevent</methodName><params><param><value><struct>
                <member><name>username</name>
                    <value><string>{0}</string></value>
                    </member>
                    <member><name>password</name>
                    <value><string>{1}</string></value>
                    </member>
                    <member><name>event</name>
                    <value><string>{3}
                    </string></value>
                    </member>
                    <member><name>subject</name>
                    <value><string>{2}</string></value>
                    </member>
                    <member><name>lineendings</name>
                    <value><string>pc</string></value>
                    </member>
                    <member><name>year</name>
                    <value><int>"+DateTime.Now.Year.ToString()+@"</int></value>
                    </member>
                    <member><name>mon</name>
                    <value><int>" + DateTime.Now.Month.ToString() + @"</int></value>
                    </member>
                    <member><name>day</name>
                    <value><int>" + DateTime.Now.Day.ToString() + @"</int></value>
                    </member>
                    <member><name>hour</name>
                    <value><int>" + DateTime.Now.Hour.ToString() + @"</int></value>
                    </member>
                    <member><name>min</name>
                    <value><int>" + DateTime.Now.Minute.ToString() + @"</int></value>
                    </member>
                    </struct></value>
                    </param>
                    </params>
                    </methodCall>", strUserName, strPassword, bi.title,bi.description);

            byte[] bytes = Encoding.ASCII.GetBytes(command);
            request.ContentLength = bytes.Length;
            using (var stream = request.GetRequestStream())
                stream.Write(bytes, 0, bytes.Length);

            using (var stream = new StreamReader(request.GetResponse().GetResponseStream()))
                return stream.ReadToEnd();

        }
    }

с# работа с API / c# work with API


Для использования в программе API-функций надо, во-первых, добавить постранство имен System.Runtime.InteropServices, во-вторых, добавить заголовок нужной API-функции и в-третьих, вызвать ее в нужном месте.

Код:

using System;
...
//Добавление пространства имен
using System.Runtime.InteropServices;
...
        //Добавление заголовка
[DllImport("user32.dll", EntryPoint="MessageBox")]
        public static extern int MessageBox(int hWnd,
        String strMessage, String strCaption, uint uiType);
...
private void button1_Click(object sender, System.EventArgs e)
        {
            //Вызов API-функции
            MessageBox(0, "Hello!", "Caption", 0);
        }
    ...

В указанном примере при нажатии на кнопку выскочит MessageBox (путем вызова соответствующей API-функции).