Exemplo n.º 1
0
        public void GetMyLastTransactionsNoMemoOrDepositAddress()
        {
            string content = Post(Routes.kGetMyLastTransactions, RestHelpers.BuildPostArgs(WebForms.kLimit, 1));
            string reality = JsonSerializer.SerializeToString <TransactionsRow[]>(new TransactionsRow[] {});

            content.Should().Be.EqualTo(reality);
        }
Exemplo n.º 2
0
        } /* GetCallByResourceID() */

        public void DeleteCall(string ResourceID)
        {
            String requestUri = String.Format("http://{0}:{1}/default/calls/{2}?appid={3}",
                                              RestSettings.Instance.ServerIP,
                                              RestSettings.Instance.ServerPort,
                                              ResourceID,
                                              RestSettings.Instance.AppID);

            T currentCall = GetCallByResourceID(ResourceID);

            if (currentCall != null && !currentCall.IsDeleted)
            {
                String responseString = String.Empty;

                if (RestHelpers.SendHttpRequest(out responseString, requestUri, "DELETE"))
                {
                    currentCall.IsDeleted = true;

                    LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "CallDispatcher::Hangup : Call resource deleted");

                    this.Calls.Remove(currentCall);
                    currentCall.Dispose();
                }
            }
        } /* DeleteCall() */
Exemplo n.º 3
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("Forge Viewer Token Retrieval: C# HTTP trigger function processed a request.");


            string forgeClientId = Environment.GetEnvironmentVariable("forge_client_id", EnvironmentVariableTarget.Process);
            string forgeSecret   = Environment.GetEnvironmentVariable("forge_secret", EnvironmentVariableTarget.Process);

            var client = RestHelpers.CreateHttpClient();

            string scopes  = "viewables:read";
            string content = $"client_id={forgeClientId}&client_secret={forgeSecret}&grant_type=client_credentials&scope={scopes}";

            using (HttpRequestMessage r = RestHelpers.CreateRequest("https://developer.api.autodesk.com/authentication/v1/authenticate", HttpMethod.Post))
            {
                r.Content = new StringContent(content);
                r.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                using (var response = await client.SendAsync(r))
                {
                    var ret = await RestHelpers.ReadResponseContentAsync <BearerToken>(response);

                    if (ret == null)
                    {
                        return(new BadRequestResult());
                    }
                    else
                    {
                        var authData = new JsonResult(ret);
                        return(authData);
                    }
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>	Executes the produce report action. </summary>
        ///
        /// <remarks>	Paul, 14/03/2015. </remarks>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        public Task OnProduceReport(RequestContext ctx, T dummy)
        {
            uint   sinceTid = RestHelpers.GetQueryArg <uint, ApiExceptionMissingParameter>(ctx, WebForms.kSince);
            string market   = RestHelpers.GetQueryArg <string>(ctx, WebForms.kSymbolPair);

            MarketRow m = m_database.GetMarket(market);

            if (m == null)
            {
                throw new ApiExceptionUnknownMarket(market);
            }

            List <TransactionsRow> allTrans = m_database.GetCompletedTransactionsInMarketSince(market, sinceTid);

            StringWriter stream = new StringWriter();

            stream.WriteLine("All completed transactions in market " + market + " since tid " + sinceTid + "<br/>");
            stream.WriteLine("<br/>");
            stream.WriteLine("Tid, Type, Price, Amount, Fee, Date<br/>");
            foreach (TransactionsRow t in allTrans)
            {
                stream.WriteLine(t.uid + "," + t.order_type + "," + t.price + "," + t.amount + "," + t.fee + "," + t.date + "<br/>");
            }

            ctx.Respond(stream.ToString(), System.Net.HttpStatusCode.OK);
            return(null);
        }
Exemplo n.º 5
0
        public void GetMarketInvalidMarket()
        {
            string market  = "BTC_BTC";
            string content = Post(Routes.kGetMarket, RestHelpers.BuildPostArgs(WebForms.kSymbolPair, market));

            ReplyIsApiError(content, new ApiExceptionUnknownMarket(market));
        }
Exemplo n.º 6
0
        public void GetOrderStatusNotFound()
        {
            string txid    = "sfkjshfkh";
            string content = Post(Routes.kGetOrderStatus, RestHelpers.BuildPostArgs(WebForms.kTxId, txid));

            ReplyIsApiError(content, new ApiExceptionOrderNotFound(txid));
        }
Exemplo n.º 7
0
        /// <summary>	Executes the get all transactions since action. </summary>
        ///
        /// <remarks>	Paul, 20/02/2015. </remarks>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        public Task OnGetAllTransactionsSinceInternal(RequestContext ctx, T dummy)
        {
            uint tid = RestHelpers.GetPostArg <uint>(ctx, WebForms.kSince);

            //ctx.Respond<List<TransactionsRow>>(m_database.GetAllTransactionsSince(tid));
            SendCorsResponse <List <TransactionsRow> >(ctx, m_database.GetAllTransactionsSince(tid));
            return(null);
        }
Exemplo n.º 8
0
        /// <summary>	Forward post specific. </summary>
        ///
        /// <remarks>	Paul, 19/02/2015. </remarks>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        Task <string> ForwardPostSpecific(RequestContext ctx, IDummy dummy)
        {
            // pull out the daemon address from the market row
            string    symbolPair = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kSymbolPair);
            MarketRow m          = dummy.m_database.GetMarket(symbolPair);

            // forward the post on
            return(ForwardTrackIpBans(ctx, c => Rest.ExecutePostAsync(ApiUrl(m.daemon_url, c.Request.Url.LocalPath), c.Request.PostArgString)));
        }
Exemplo n.º 9
0
        void GetMarketSuccess(string market)
        {
            string content = Post(Routes.kGetMarket, RestHelpers.BuildPostArgs(WebForms.kSymbolPair, market));

            MarketRow check   = GetMarket(market);
            string    reality = JsonSerializer.SerializeToString <MarketRow>(check);

            content.Should().Be.EqualTo(reality);
        }
Exemplo n.º 10
0
        /// <summary>	Executes the get transactions action. </summary>
        ///
        /// <remarks>	Paul, 06/02/2015. </remarks>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        public Task OnGetLastTransactions(RequestContext ctx, T dummy)
        {
            uint   limit  = RestHelpers.GetPostArg <uint, ApiExceptionMissingParameter>(ctx, WebForms.kLimit);
            string market = RestHelpers.GetPostArg <string>(ctx, WebForms.kSymbolPair);

            //ctx.Respond<List<TransactionsRowNoUid>>(m_database.GetLastTransactions(limit, market));
            SendCorsResponse <List <TransactionsRowNoUid> >(ctx, m_database.GetLastTransactions(limit, market));
            return(null);
        }
Exemplo n.º 11
0
        public void SubmitInvalidSymbolPair()
        {
            string market  = "dfsdfsf";
            string content = Post(Routes.kSubmitAddress, RestHelpers.BuildPostArgs(WebForms.kReceivingAddress, kBitcoinAddress,
                                                                                   WebForms.kSymbolPair, market,
                                                                                   WebForms.kOrderType, MetaOrderType.sell));

            ReplyIsApiError(content, new ApiExceptionUnknownMarket(market));
        }
Exemplo n.º 12
0
        /// <summary>	Executes the get my last transactions action. </summary>
        ///
        /// <remarks>	Paul, 11/02/2015. </remarks>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        public Task OnGetMyLastTransactions(RequestContext ctx, T dummy)
        {
            uint   limit          = RestHelpers.GetPostArg <uint, ApiExceptionMissingParameter>(ctx, WebForms.kLimit);
            string memo           = RestHelpers.GetPostArg <string>(ctx, WebForms.kMemo);
            string depositAddress = RestHelpers.GetPostArg <string>(ctx, WebForms.kDepositAddress);

            //ctx.Respond<List<TransactionsRowNoUid>>(m_database.GetLastTransactionsFromDeposit(memo, depositAddress, limit));
            SendCorsResponse <List <TransactionsRowNoUid> >(ctx, m_database.GetLastTransactionsFromDeposit(memo, depositAddress, limit));
            return(null);
        }
Exemplo n.º 13
0
 string SubmitAddress(string receivingAddress, MetaOrderType type, string symbolPair = null)
 {
     if (symbolPair == null)
     {
         symbolPair = m_defaultSymbolPair;
     }
     return(Post(Routes.kSubmitAddress, RestHelpers.BuildPostArgs(WebForms.kReceivingAddress, receivingAddress,
                                                                  WebForms.kSymbolPair, symbolPair,
                                                                  WebForms.kOrderType, type)));
 }
Exemplo n.º 14
0
        } /* PlayFile() */

        /// <summary>
        /// This is an example of how to populate and call a more complicated
        /// RESTapi structure. We play an audio/video file from here...
        /// </summary>
        /// <param name="audioUri"></param>
        /// <param name="videoUri"></param>
        ///
        protected virtual void PlayFile(String audioUri, RESTapi.audio_type_option audioType = RESTapi.audio_type_option.audioxwav, String videoUri = "", RESTapi.video_type_option videoType = RESTapi.video_type_option.videoxvid)
        {
            bool hasAudio = !String.IsNullOrWhiteSpace(audioUri);
            bool hasVideo = !String.IsNullOrWhiteSpace(videoUri);

            RESTapi.web_service ws = new RESTapi.web_service()
            {
                Item = new RESTapi.call()
                {
                    call_action = new RESTapi.call_action()
                    {
                        Item = new RESTapi.play()
                        {
                            offset      = "0s",
                            repeat      = "0",
                            delay       = "0s",
                            play_source = new RESTapi.play_source()
                            {
                                audio_uri           = hasAudio ? audioUri : String.Empty,
                                audio_type          = audioType,
                                audio_typeSpecified = hasAudio,
                                video_uri           = hasVideo ? videoUri : String.Empty,
                                video_type          = videoType,
                                video_typeSpecified = hasVideo,
                            }
                        }
                    }
                }
            };

            if (hasAudio)
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "Call::PlayFile : Playing audio \"{0}\"...", audioUri);
            }

            if (hasVideo)
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "Call::PlayFile : Playing video \"{0}\"...", videoUri);
            }

            String responseString = String.Empty;

            if (RestHelpers.SendHttpRequest(out responseString, CallURI, "PUT", ws))
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "Call::PlayFile : Play file OK");
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, responseString);
            }
            else
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Error, "Call::PlayFile : Play file failed!");
                PutEvent(RESTapi.event_type.end_play);
            }
        } /* PlayFile() */
Exemplo n.º 15
0
        /// <summary>	Executes the get order status action. </summary>
        ///
        /// <remarks>	Paul, 05/02/2015. </remarks>
        ///
        /// <exception cref="ApiExceptionOrderNotFound">	Thrown when an API exception order not found
        ///                                                 error condition occurs. </exception>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        public Task OnGetOrderStatus(RequestContext ctx, T dummy)
        {
            string txid = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kTxId);

            TransactionsRow t = m_database.GetTransaction(txid);

            if (t == null)
            {
                throw new ApiExceptionOrderNotFound(txid);
            }

            //ctx.Respond<TransactionsRow>(t);
            SendCorsResponse <TransactionsRow>(ctx, t);
            return(null);
        }
Exemplo n.º 16
0
        protected virtual void AnswerCall(RESTapi.media_type MediaType = RESTapi.media_type.audiovideo, bool AsyncCompletion = true)
        {
            /// <call answer="yes" media="audiovideo" signaling="yes" dtmf_mode="rfc2833" async_completion="yes"
            ///       async_dtmf="yes" async_tone="yes" rx_delta="+0dB" tx_delta="+0dB" cpa="no" info_ack_mode="automatic"/>
            ///

            RESTapi.web_service ws = new RESTapi.web_service()
            {
                Item = new RESTapi.call()
                {
                    answer                    = RESTapi.boolean_type.yes,
                    answerSpecified           = true,
                    async_completion          = AsyncCompletion ? RESTapi.boolean_type.yes : RESTapi.boolean_type.no,
                    async_completionSpecified = true,
                    media                  = MediaType,
                    mediaSpecified         = true,
                    dtmf_mode              = RESTapi.dtmf_mode_option.rfc2833,
                    async_dtmf             = RESTapi.boolean_type.yes,
                    async_dtmfSpecified    = true,
                    async_tone             = RESTapi.boolean_type.yes,
                    async_toneSpecified    = true,
                    info_ack_mode          = RESTapi.ack_mode_option.automatic,
                    info_ack_modeSpecified = true,
                }
            };

            String responseString = String.Empty;

            if (RestHelpers.SendHttpRequest(out responseString, CallURI, "PUT", ws))
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "Call::AnswerCall : AnswerCall OK");
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, responseString);

                // Note: If we use async_completion, we DON'T have to put the event
                // manually as it will (or rather... should) appear as a separate
                // event from the XMS server...
                //
                if (!AsyncCompletion)
                {
                    PutEvent(RESTapi.event_type.answered);
                }
            }
            else
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Error, "Call::AnswerCall : AnswerCall failed!");
                Hangup();
            }
        }
Exemplo n.º 17
0
        } /* DeleteCall() */

        public void Hangup(string ResourceID)
        {
            String requestUri = String.Format("http://{0}:{1}/default/calls/{2}?appid={3}",
                                              RestSettings.Instance.ServerIP,
                                              RestSettings.Instance.ServerPort,
                                              ResourceID,
                                              RestSettings.Instance.AppID);

            T currentCall = GetCallByResourceID(ResourceID);

            if (currentCall != null)
            {
                RESTapi.web_service ws = new RESTapi.web_service()
                {
                    Item = new RESTapi.call()
                    {
                        call_action = new RESTapi.call_action()
                        {
                            Item = new RESTapi.hangup()
                            {
                                content_type = "text/plain",
                                content      = "data",
                            }
                        }
                    }
                };

                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "CallDispatcher::Hangup : Hanging up call with ID \"{0}\"...", ResourceID);

                String responseString = String.Empty;

                /// Send the hangup request...
                ///
                if (RestHelpers.SendHttpRequest(out responseString, requestUri, "PUT", ws))
                {
                    LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "CallDispatcher::Hangup : Hangup OK");
                    LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, responseString);
                }
                else
                {
                    LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Error, "CallDispatcher::Hangup : Hangup failed!");
                }

                /// Remember to delete the call resource...
                ///
                DeleteCall(ResourceID);
            }
        } /* Hangup() */
Exemplo n.º 18
0
        /// <summary>	Executes the submit address action. </summary>
        ///
        /// <remarks>	Paul, 19/02/2015. </remarks>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        async Task OnSubmitAddress(RequestContext ctx, IDummy dummy)
        {
            // intercept the response and stick it in the site database so we can handle forwarding future queries
            string symbolPair       = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kSymbolPair);
            uint   referralUser     = RestHelpers.GetPostArg <uint>(ctx, WebForms.kReferralId);
            string receivingAddress = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kReceivingAddress);

            // do this at the site level, because we need to prevent this from occuring across nodes
            if (dummy.m_database.IsAnyDepositAddress(receivingAddress))
            {
                throw new ApiExceptionInvalidAddress("<internal deposit address>");
            }

            // forward the post on
            string response = await ForwardPostSpecific(ctx, dummy);

            if (response != null)
            {
                // get the juicy data out
                SubmitAddressResponse data = JsonSerializer.DeserializeFromString <SubmitAddressResponse>(response);

                // pull the market out of the request
                MarketRow m = dummy.m_database.GetMarket(symbolPair);

                // stick it in the master database
                dummy.m_database.InsertSenderToDeposit(data.receiving_address, data.deposit_address, m.symbol_pair, referralUser, true);

                if (referralUser > 0)
                {
                    // track referrals
                    string depositAddress;

                    if (data.memo != null)
                    {
                        depositAddress = data.memo;
                    }
                    else
                    {
                        depositAddress = data.deposit_address;
                    }

                    dummy.m_database.InsertReferralAddress(depositAddress, referralUser);
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>	Executes the get market action. </summary>
        ///
        /// <remarks>	Paul, 28/02/2015. </remarks>
        ///
        /// <exception cref="ApiExceptionUnknownMarket">	Thrown when an API exception unknown market
        ///                                                 error condition occurs. </exception>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        Task OnGetMarket(RequestContext ctx, IDummy dummy)
        {
            string symbolPair = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kSymbolPair);

            MarketRow market = m_Database.GetMarket(symbolPair);

            if (market == null)            // || !market.visible)
            {
                throw new ApiExceptionUnknownMarket(symbolPair);
            }
            else
            {
                //ctx.Respond<MarketRow>(market);
                m_api.SendCorsResponse <MarketRow>(ctx, market);
            }

            return(null);
        }
Exemplo n.º 20
0
        /// <summary>	Executes the get statistics action. </summary>
        ///
        /// <remarks>	Paul, 30/01/2015. </remarks>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        Task OnGetStats(RequestContext ctx, IDummy dummy)
        {
            uint sinceTid = RestHelpers.GetPostArg <uint, ApiExceptionMissingParameter>(ctx, WebForms.kLimit);

            List <TransactionsRow> lastTransactions = m_database.Query <TransactionsRow>("SELECT * FROM transactions WHERE uid>@uid ORDER BY uid;", sinceTid);
            SiteStatsRow           stats            = new SiteStatsRow
            {
                bid_price     = m_bidPrice,
                ask_price     = m_askPrice,
                max_bitassets = m_bitsharesDepositLimit,
                max_btc       = m_bitcoinDepositLimit
            };

            ctx.Respond <StatsPacket>(new StatsPacket {
                m_lastTransactions = lastTransactions, m_stats = stats
            });

            return(null);
        }
Exemplo n.º 21
0
        protected virtual void AcceptCall(bool EarlyMedia = true, RESTapi.media_type MediaType = RESTapi.media_type.audiovideo)
        {
            /// <call accept="yes" early_media="yes" media="audiovideo" signaling="yes" dtmf_mode="rfc2833"
            ///       async_dtmf="yes" async_tone="yes" rx_delta="+0dB" tx_delta="+0dB" cpa="no" info_ack_mode="automatic"/>
            ///
            RESTapi.web_service ws = new RESTapi.web_service()
            {
                Item = new RESTapi.call()
                {
                    accept               = RESTapi.boolean_type.yes,
                    acceptSpecified      = true,
                    early_media          = EarlyMedia ? RESTapi.boolean_type.yes : RESTapi.boolean_type.no,
                    early_mediaSpecified = true,
                    media                  = MediaType,
                    mediaSpecified         = true,
                    dtmf_mode              = RESTapi.dtmf_mode_option.rfc2833,
                    async_dtmf             = RESTapi.boolean_type.yes,
                    async_dtmfSpecified    = true,
                    async_tone             = RESTapi.boolean_type.yes,
                    async_toneSpecified    = true,
                    info_ack_mode          = RESTapi.ack_mode_option.automatic,
                    info_ack_modeSpecified = true,
                }
            };

            String responseString = String.Empty;

            if (RestHelpers.SendHttpRequest(out responseString, CallURI, "PUT", ws))
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "Call::AcceptCall : Accept call OK");
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, responseString);

                PutEvent(RESTapi.event_type.ringing);
            }
            else
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Error, "Call::AcceptCall : Accept call failed!");
                Hangup();
            }
        }
Exemplo n.º 22
0
        /// <summary>	Executes the submit address action. </summary>
        ///
        /// <remarks>	Paul, 05/02/2015. </remarks>
        ///
        /// <exception cref="ApiExceptionUnknownMarket">	Thrown when an API exception unknown market
        ///                                                 error condition occurs. </exception>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        Task OnSubmitAddress(RequestContext ctx, IDummyDaemon dummy)
        {
            if (m_suspended)
            {
                throw new ApiExceptionNetworkAlert();
            }
            else
            {
                string        symbolPair       = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kSymbolPair);
                string        receivingAddress = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kReceivingAddress);
                MetaOrderType orderType        = RestHelpers.GetPostArg <MetaOrderType, ApiExceptionMissingParameter>(ctx, WebForms.kOrderType);
                uint          referralUser     = RestHelpers.GetPostArg <uint>(ctx, WebForms.kReferralId);

                if (!m_marketHandlers.ContainsKey(symbolPair))
                {
                    throw new ApiExceptionUnknownMarket(symbolPair);
                }

                // prevent our own deposit addresses from being used as receiving addresses
                if (m_dataAccess.GetSenderDepositFromDeposit(receivingAddress, symbolPair, referralUser) != null)
                {
                    throw new ApiExceptionInvalidAddress("<internal deposit address>");
                }
                else if (m_bitsharesAccount == receivingAddress)
                {
                    throw new ApiExceptionInvalidAccount(m_bitsharesAccount);
                }

                // get the handler for this market
                MarketBase market = m_marketHandlers[symbolPair];

                // get the response and send it
                SubmitAddressResponse response = market.OnSubmitAddress(receivingAddress, orderType, referralUser);

                //ctx.Respond<SubmitAddressResponse>(response);
                m_api.SendCorsResponse <SubmitAddressResponse>(ctx, response);
            }

            return(null);
        }
Exemplo n.º 23
0
        public void GivenIDeleteAllButFollowingForms(Table table)
        {
            var section = (NameValueCollection)ConfigurationManager.GetSection("ApiEndPoints");

            var request = new RestRequest(Method.GET)
            {
                Resource = section["get_all_forms"]
            };
            //TODO Replace following
            var tempBaseUrl =
                new Uri(
                    "http://j2mntosint01.dgtest.local:19081/Jet2.OverseasOps.SystemAdministration.Api.sfApp/Jet2.OverseasOps.SystemAdministration.Api.sfHost/api");

            _responseFormData = RestHelpers.Execute <GetForms>(request, tempBaseUrl);

            var formIdToDelet = new List <string>();

            foreach (var row in table.Rows)
            {
                var ignoreList = row["ignore_form_list"].ConvertStringIntoList();
                foreach (var form in _responseFormData.Data)
                {
                    if (ignoreList.Contains(form.Id))
                    {
                        continue;
                    }
                    formIdToDelet.Add(form.Id);
                }
            }

            foreach (var id in formIdToDelet)
            {
                var req = new RestRequest(Method.DELETE)
                {
                    Resource = section["delete_form"].Replace("form_id", id)
                };
                RestHelpers.Execute(req, tempBaseUrl);
            }
        }
Exemplo n.º 24
0
        } /* DisconnectFromEventHandler() */

        static public EventDispatcherList <T> GetEventHandlers()
        {
            EventDispatcherList <T> retval = new EventDispatcherList <T>();

            String uri = String.Format("http://{0}:{1}/default/eventhandlers?appid={2}",
                                       RestSettings.Instance.ServerIP,
                                       RestSettings.Instance.ServerPort,
                                       RestSettings.Instance.AppID);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Method          = "GET";
            request.ProtocolVersion = HttpVersion.Version11;

            try
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug2,
                                                  "EventDispatcher::GetEventHandlers : Sent GET {0}", uri);

                /// This waits for a response from the far end...
                ///
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        /// Read the result from the far end...
                        ///
                        String result = stream.ReadToEnd();

                        LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug2,
                                                          "EventDispatcher::GetEventHandlers : Received {0:D} {1}",
                                                          response.StatusCode, response.StatusDescription);

                        LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug3,
                                                          "EventDispatcher::GetEventHandlers : {0}", result);

                        RESTapi.web_service evresponse = RestHelpers.XMLToRESTapi(result, typeof(RESTapi.web_service)) as RESTapi.web_service;

                        if (evresponse != null)
                        {
                            /// We know that the actual object type is "eventhandlers_response"
                            /// in this case so we go ahead and cast it...
                            ///
                            RESTapi.eventhandlers_response evhandlers = evresponse.Item as RESTapi.eventhandlers_response;

                            if (evhandlers != null)
                            {
                                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Info,
                                                                  "EventDispatcher::GetEventHandlers : Found {0} existing event handlers",
                                                                  evhandlers.size);

                                if (evhandlers.eventhandler_response != null)
                                {
                                    foreach (RESTapi.eventhandler_response ev in evhandlers.eventhandler_response)
                                    {
                                        LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug3,
                                                                          "EventDispatcher::GetEventHandlers : Event handler :\n" +
                                                                          "  => identifier = {0}\n" +
                                                                          "  => href       = {1}\n" +
                                                                          "  => appid      = {2}\n",
                                                                          ev.identifier,
                                                                          ev.href,
                                                                          ev.appid);

                                        retval.Add(new EventDispatcher <T>()
                                        {
                                            _OID             = ev.identifier,
                                            _EventHandlerURI = ev.href.Contains("http://") ? String.Format("{0}?appid={1}", ev.href, ev.appid) : String.Format("http://{0}:{1}{2}?appid={3}", RestSettings.Instance.ServerIP, RestSettings.Instance.ServerPort, ev.href, ev.appid),
                                            _ConnectionState = ConnectionStateEnum.Connected,
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse response = ex.Response as HttpWebResponse;

                    if (response != null)
                    {
                        LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Warning,
                                                          "EventDispatcher::GetEventHandlers : Received HTTP failure response {0} {1}",
                                                          (int)response.StatusCode, response.StatusDescription);
                    }
                }
                else
                {
                    LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Warning,
                                                      "EventDispatcher::GetEventHandlers : {0}\n{1}",
                                                      ex.Message.ToString(), ex.StackTrace.ToString());
                }

                return(retval);
            }
            catch (Exception ex)
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Warning,
                                                  "EventDispatcher::GetEventHandlers : {0}\n{1}",
                                                  ex.Message.ToString(), ex.StackTrace.ToString());
                return(retval);
            }

            return(retval);
        } /* GetEventHandlers() */
Exemplo n.º 25
0
 public void GetAllMarketsInvalidParams()
 {
     GetAllMarketsSuccess(Get(Routes.kGetAllMarkets + RestHelpers.BuildArgs("A", "F")));
 }
Exemplo n.º 26
0
        } /* ProcessRequest() */

        /// <summary>
        /// Gets a list of any calls that are already in progress on the XMS server. We can
        /// use this to populate our calls list and potentially do "stuff" with them...
        /// </summary>
        ///
        public void GetCalls()
        {
            String uri = String.Format("http://{0}:{1}/default/calls?appid={2}",
                                       RestSettings.Instance.ServerIP,
                                       RestSettings.Instance.ServerPort,
                                       RestSettings.Instance.AppID);

            String responseString = String.Empty;

            if (RestHelpers.SendHttpRequest(out responseString, uri, "GET"))
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1,
                                                  "CallDispatcher::GetCalls : Received web service request :\n{0}",
                                                  responseString);

                RESTapi.web_service    ws        = (RESTapi.web_service)RestHelpers.XMLToRESTapi(responseString, typeof(RESTapi.web_service));
                RESTapi.calls_response Responses = (RESTapi.calls_response)ws.Item;

                int numCalls = 0;

                if (!int.TryParse(Responses.size, out numCalls))
                {
                    LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Error,
                                                      "CallDispatcher::GetCalls : Oops... RESTapi.calls_response.size is not a number!");
                    return;
                }

                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Info,
                                                  "CallDispatcher::GetCalls : Found {0} RESTapi calls",
                                                  numCalls);

                if (numCalls > 0 && Responses.call_response != null)
                {
                    /// Each "call_response" object corresponds to a single call in progress.
                    ///
                    foreach (RESTapi.call_response Response in Responses.call_response)
                    {
                        bool Exists = false;

                        foreach (T call in Calls)
                        {
                            if (call.ResourceID == Response.identifier)
                            {
                                Exists = true;
                                break;
                            }
                        }

                        if (!Exists)
                        {
                            this.Calls.Add(new T()
                            {
                                Dispatcher = this as ICallDispatcher <CallBase>,
                                ResourceID = Response.identifier,
                                CalledUri  = Response.destination_uri,
                                CallerUri  = Response.source_uri,
                                Direction  = Response.call_type.ToString(),
                                Uri        = Response.destination_uri,
                                Name       = Response.appid,
                                CallState  = Response.connected == RESTapi.boolean_type.yes ? CallBase.CallStateType.Connected : CallBase.CallStateType.Unknown,
                            });
                        }
                    }
                }
            }
        } /* GetCalls() */
Exemplo n.º 27
0
        /// <summary>
        /// We received a web_service object to process... this function will
        /// determine if the request is for a new call or an existing call.
        /// Additionally, if the request is a hangup, we should delete the call
        /// from our list.
        /// </summary>
        /// <param name="ws"> The web_service request to process</param>
        ///
        public void ProcessRequest(RESTapi.web_service ws)
        {
            T currentCall = null;

            RESTapi.@event @event = ws.Item as RESTapi.@event;

            if (@event.type == RESTapi.event_type.keepalive)
            {
                LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1,
                                                  "CallDispatcher::ProcessRequest : Keepalive received");
                return;
            }

            String response = RestHelpers.RESTapiToXML(ws, typeof(RESTapi.web_service));

            LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1,
                                              "CallDispatcher::ProcessRequest : Received web service request :\n{0}",
                                              response);

            if (@event.type == RESTapi.event_type.incoming)
            {
                /// Note that we probably should check that this is not an existing
                /// call / resource id rather than assuming...
                ///
                currentCall = new T()
                {
                    Dispatcher   = this as ICallDispatcher <CallBase>,
                    Direction    = "inbound",
                    ResourceID   = @event.resource_id,
                    ResourceType = @event.resource_type,
                    CallState    = CallBase.CallStateType.Ringing,
                };

                foreach (RESTapi.event_data data in @event.event_data)
                {
                    switch (data.name.ToLower())
                    {
                    case "caller_uri": currentCall.CallerUri = data.value; break;

                    case "called_uri": currentCall.CalledUri = data.value; break;

                    case "uri":        currentCall.Uri = data.value; break;

                    case "name":       currentCall.Name = data.value; break;
                    }
                }
            }
            else
            {
                foreach (T call in Calls)
                {
                    if (call.ResourceID == @event.resource_id)
                    {
                        currentCall = call;
                        break;
                    }
                }
            }

            if (currentCall != null)
            {
                /// The following is a way of calling a protected / private member
                /// of a class - kind of like using "friend class" in C++. It uses
                /// reflection.
                ///
                MethodInfo handleEventMethod = currentCall.GetType().GetMethod("HandleEvent", BindingFlags.Instance | BindingFlags.NonPublic);

                switch (@event.type)
                {
                case RESTapi.event_type.incoming:
                    Calls.Add(currentCall);
                    handleEventMethod.Invoke(currentCall, new object[] { ws });
                    break;

                case RESTapi.event_type.hangup:
                    handleEventMethod.Invoke(currentCall, new object[] { ws });
                    Calls.Remove(currentCall);
                    break;

                default:
                    handleEventMethod.Invoke(currentCall, new object[] { ws });
                    break;
                }
            }
        } /* ProcessRequest() */
Exemplo n.º 28
0
        public void GetMyLastTransactionsNegativeLimit()
        {
            string content = Post(Routes.kGetMyLastTransactions, RestHelpers.BuildPostArgs(WebForms.kLimit, -1));

            ReplyIsApiError(content, new ApiExceptionMissingParameter());
        }
Exemplo n.º 29
0
        public override Task Render(RequestContext ctx, StringWriter stream, IDummy authObj)
        {
                        #if MONO
            AddResource(new JsResource(Constants.kWebRoot, "/js/apiPageCompiled.js", true));
                        #endif

            // render head
            base.Render(ctx, stream, authObj);

            using (new DivContainer(stream, HtmlAttributes.@class, "jumbotron clearfix"))
            {
                using (new DivContainer(stream, HtmlAttributes.@class, "container"))
                {
                    using (new DivContainer(stream, HtmlAttributes.@class, "row"))
                    {
                        using (new DivContainer(stream, HtmlAttributes.@class, "col-xs-12"))
                        {
                            BaseComponent.SPAN(stream, "API", HtmlAttributes.@class, "noTopMargin h1");
                        }
                    }
                }
            }

            using (new DivContainer(stream, HtmlAttributes.@class, "container"))
            {
                P("The API allows developers to access the functionality of Metaexchange without needing to use the website.");
                P("All API requests return data in JSON format.");

                HR();
                H4("API errors");

                P("When an API call fails, an error will be returned. The structure of an error is:");

                using (new Pre(stream, HtmlAttributes.@class, "prettyprint"))
                {
                    stream.WriteLine("{<br/>" +
                                     "\t\"error\":&lt;error code&gt;,<br/>" +
                                     "\t\"message\":&lt;error message&gt,<br/>" +
                                     "}");
                }

                stream.WriteLine(EnumToPrettyTable("Error codes", typeof(ApiErrorCode)));

                HR();
                H4("API summary");

                string[] apiEndpointsAndDescriptions =
                {
                    Routes.kSubmitAddress,         "Submit your receiving address and get back deposit details",
                    Routes.kGetOrderStatus,        "Get the status of your order by TXID",
                    Routes.kGetMyLastTransactions, "Get a list of your last transactions",
                    Routes.kGetAllMarkets,         "Get a list of all supported markets",
                    Routes.kGetMarket,             "Get details of a particular market",
                    Routes.kGetLastTransactions,   "Get a list of the last transactions"
                };

                for (int i = 0; i < apiEndpointsAndDescriptions.Length; i += 2)
                {
                    stream.WriteLine("<b>" + apiEndpointsAndDescriptions[i + 1] + "</b><br/>");
                    stream.WriteLine(DocRefLink(apiEndpointsAndDescriptions[i + 0]) + "<br/><br/>");
                }

                HR();
                H4("API detail");

                string siteUrl = ctx.Request.Url.AbsoluteUri.TrimEnd(ctx.Request.Url.LocalPath);
                string market  = "bitBTC_BTC";

                CodeExample <SubmitAddressResponse>(siteUrl, stream, Routes.kSubmitAddress, WebRequestMethods.Http.Post, "The main function. This will take your supplied receiving address and provide you with a deposit address and a memo (depending on the market).",
                                                    new List <DocParam>
                {
                    new DocParam {
                        description = "This is the symbol pair of the market you would like to trade in. Symbol pairs are of the form <b>" + market + "</b> and are case sensitive. Find out what markets are available by calling " + DocRefLink(Routes.kGetAllMarkets),
                        name        = WebForms.kSymbolPair,
                        type        = DocType.@string
                    },
                    new DocParam {
                        description = "This is where you would like funds to be forwarded. It could be a bitcoin address or a bitshares account depending on the order type and market.",
                        name        = WebForms.kReceivingAddress,
                        type        = DocType.@string
                    },
                    new DocParam {
                        description = "The type of order you want to place. Possible types are <b>" + MetaOrderType.buy + "</b> and <b>" + MetaOrderType.sell + "</b>.",
                        name        = WebForms.kOrderType,
                        type        = DocType.@string
                    },
                },
                                                    null, Routes.kSubmitAddress + RestHelpers.BuildArgs(WebForms.kSymbolPair, market,
                                                                                                        WebForms.kReceivingAddress, "monsterer",
                                                                                                        WebForms.kOrderType, MetaOrderType.buy), new SubmitAddressResponse {
                    deposit_address = "mrveCRH4nRZDpS7fxgAiLTX7GKvJ1cARY9"
                });

                CodeExample <TransactionsRowNoUid>(siteUrl, stream, Routes.kGetOrderStatus, WebRequestMethods.Http.Post, "Get the status of a particular order when you know the blockchain transaction id. Transaction must be in a block before this function will return a result.",
                                                   new List <DocParam>
                {
                    new DocParam {
                        description = "The transaction id of the transaction you sent.",
                        name        = WebForms.kTxId,
                        type        = DocType.@string
                    },
                },
                                                   null, Routes.kGetOrderStatus + RestHelpers.BuildArgs(WebForms.kTxId, "ed7364fd1b8ba4cc3428470072300fb88097c3a343c75b6e604c68799a0148cb"),
                                                   new TransactionsRowNoUid
                {
                    amount          = 0.1M,
                    date            = DateTime.UtcNow,
                    deposit_address = "1-n2HPFvf376vxQV1mo",
                    notes           = null,
                    order_type      = MetaOrderType.sell,
                    sent_txid       = "231500b3ecba3bf2ba3db650f5e7565478382c5b",
                    received_txid   = "70827daa9f08211491297a5ded2c3f8d7a2b654f1e6f3d4e2ff3ad7e14966a85",
                    status          = MetaOrderStatus.completed,
                    symbol_pair     = market
                });

                stream.WriteLine(EnumToPrettyTable("Possible order statuses", typeof(MetaOrderStatus)));

                decimal ask = Numeric.TruncateDecimal(1 / 0.994M, 3);
                decimal bid = Numeric.TruncateDecimal(0.994M, 3);
                decimal bq  = Numeric.TruncateDecimal(1 / ask, 3);
                decimal sq  = Numeric.TruncateDecimal(1 / bid, 3);

                CodeExample <MarketRow>(siteUrl, stream, Routes.kGetMarket, WebRequestMethods.Http.Post, "Get details about a particular market, such as bid/ask price and transaction limits.",
                                        new List <DocParam>
                {
                    new DocParam {
                        description = "The symbol pair identifier for the market. Symbol pairs are of the form <b>" + market + "</b>. Use " + DocRefLink(Routes.kGetAllMarkets) + " to query the list of available markets.",
                        name        = WebForms.kSymbolPair,
                        type        = DocType.@string
                    },
                },
                                        null, Routes.kGetMarket + RestHelpers.BuildArgs(WebForms.kSymbolPair, market),
                                        new MarketRow
                {
                    ask           = ask,
                    bid           = bid,
                    buy_quantity  = bq,
                    sell_quantity = sq,
                    ask_max       = 1,
                    bid_max       = 0.8M,
                    symbol_pair   = market,
                });

                P("The values displayed in metaexchange for 1 BTC conversion quantity appear in the fields (1 BTC ->) <b>buy_quantity</b> and <b>sell_quantity</b> (-> 1 BTC).");

                CodeExample <List <MarketRow> >(siteUrl, stream, Routes.kGetAllMarkets, WebRequestMethods.Http.Get, "Get a list of all available markets along with the best prices and transaction limits.",
                                                null,
                                                null, Routes.kGetAllMarkets,
                                                new List <MarketRow> {
                    new MarketRow
                    {
                        ask           = ask,
                        bid           = bid,
                        buy_quantity  = bq,
                        sell_quantity = sq,
                        ask_max       = 1,
                        bid_max       = 0.8M,
                        symbol_pair   = market,
                    }
                });

                CodeExample <List <TransactionsRowNoUid> >(siteUrl, stream, Routes.kGetLastTransactions, WebRequestMethods.Http.Post, "Get the most recent transactions, sorted in descending order. This will only show transactions with status " + MetaOrderStatus.completed + ".",
                                                           new List <DocParam>
                {
                    new DocParam {
                        description = "The maximum number of results to return.",
                        name        = WebForms.kLimit,
                        type        = DocType.integer
                    },
                },
                                                           new List <DocParam>
                {
                    new DocParam {
                        description = "Market to query.",
                        name        = WebForms.kSymbolPair,
                        type        = DocType.@string
                    },
                }, Routes.kGetLastTransactions + RestHelpers.BuildArgs(WebForms.kSymbolPair, market),
                                                           new List <TransactionsRowNoUid> {
                    new TransactionsRowNoUid
                    {
                        amount          = 0.1M,
                        date            = DateTime.UtcNow,
                        deposit_address = "1-n2HPFvf376vxQV1mo",
                        notes           = null,
                        order_type      = MetaOrderType.sell,
                        sent_txid       = "231500b3ecba3bf2ba3db650f5e7565478382c5b",
                        received_txid   = "70827daa9f08211491297a5ded2c3f8d7a2b654f1e6f3d4e2ff3ad7e14966a85",
                        status          = MetaOrderStatus.completed,
                        symbol_pair     = market
                    },
                    new TransactionsRowNoUid
                    {
                        amount          = 0.00010000M,
                        date            = DateTime.UtcNow,
                        deposit_address = "mpwPhGCtbe8AeoFq3FWq6ToKbeapL7zM8b",
                        notes           = null,
                        order_type      = MetaOrderType.buy,
                        sent_txid       = "4217b7b0dcb940e5732c977473c8d893f52370c4",
                        received_txid   = "70bc0017c21e29738a93b9f4ce21d36814898bf7bcdfc6feba5227e9ab3495d5",
                        status          = MetaOrderStatus.completed,
                        symbol_pair     = market
                    },
                });

                CodeExample <List <TransactionsRowNoUid> >(siteUrl, stream, Routes.kGetMyLastTransactions, WebRequestMethods.Http.Post, "Get your most recent transactions, sorted in descending order. Use this when you know the deposit address to which you sent funds, or the transaction memo. This shows transactions with any status.",
                                                           new List <DocParam>
                {
                    new DocParam {
                        description = "The maximum number of results to return.",
                        name        = WebForms.kLimit,
                        type        = DocType.integer
                    },
                },
                                                           new List <DocParam>
                {
                    new DocParam {
                        description = "Bitcoin deposit address.",
                        name        = WebForms.kDepositAddress,
                        type        = DocType.@string
                    },
                    new DocParam {
                        description = "BitShares transaction memo.",
                        name        = WebForms.kMemo,
                        type        = DocType.@string
                    },
                }, Routes.kGetMyLastTransactions + RestHelpers.BuildArgs(WebForms.kMemo, "1-mqjz4GnADMucWuR4v"),
                                                           new List <TransactionsRowNoUid> {
                    new TransactionsRowNoUid
                    {
                        amount          = 0.700000M,
                        date            = DateTime.UtcNow,
                        deposit_address = "1-n2HPFvf376vxQV1mo",
                        notes           = "Over 0.2 BTC!",
                        order_type      = MetaOrderType.sell,
                        sent_txid       = "f94f79e29110107c917ba41fa02fcfc2ccb5e4cc",
                        received_txid   = "ab265b51259a651c68b4a82b8bce5c501325d323",
                        status          = MetaOrderStatus.refunded,
                        symbol_pair     = market
                    },
                    new TransactionsRowNoUid
                    {
                        amount          = 0.0700000M,
                        date            = DateTime.UtcNow,
                        deposit_address = "1-n2HPFvf376vxQV1mo",
                        order_type      = MetaOrderType.sell,
                        sent_txid       = "ed7364fd1b8ba4cc3428470072300fb88097c3a343c75b6e604c68799a0148cb",
                        received_txid   = "18159b00b90374cb467a7744a031d84663e92136",
                        status          = MetaOrderStatus.completed,
                        symbol_pair     = market
                    },
                });
            }

            return(null);
        }
Exemplo n.º 30
0
        /// <summary>	Executes the submit address action. </summary>
        ///
        /// <remarks>	Paul, 25/01/2015. </remarks>
        ///
        /// <exception cref="ApiExceptionMessage">		    Thrown when an API exception message error
        ///                                                 condition occurs. </exception>
        /// <exception cref="ApiExceptionMissingParameter">	Thrown when an API exception missing
        ///                                                 parameter error condition occurs. </exception>
        ///
        /// <param name="ctx">      The context. </param>
        /// <param name="dummy">	The dummy. </param>
        ///
        /// <returns>	A Task. </returns>
        Task OnSubmitAddress(RequestContext ctx, IDummy dummy)
        {
            CurrencyTypes fromCurrency     = RestHelpers.GetPostArg <CurrencyTypes, ApiExceptionMissingParameter>(ctx, WebForms.kFromCurrency);
            CurrencyTypes toCurrency       = RestHelpers.GetPostArg <CurrencyTypes, ApiExceptionMissingParameter>(ctx, WebForms.kToCurrency);
            string        receivingAddress = RestHelpers.GetPostArg <string, ApiExceptionMissingParameter>(ctx, WebForms.kReceivingAddress);

            SubmitAddressResponse response;

            if (fromCurrency == CurrencyTypes.BTC && toCurrency == CurrencyTypes.bitBTC)
            {
                string accountName = receivingAddress;

                // try and retrieve a previous entry
                SenderToDepositRow senderToDeposit = m_database.Query <SenderToDepositRow>("SELECT * FROM sender_to_deposit WHERE receiving_address=@s;", accountName).FirstOrDefault();
                if (senderToDeposit == null || !BitsharesWallet.IsValidAccountName(accountName))
                {
                    // no dice, create a new entry

                    // validate bitshares account name
                    try
                    {
                        BitsharesAccount account = m_bitshares.WalletGetAccount(accountName);

                        // generate a new bitcoin address and tie it to this account
                        string depositAdress = m_bitcoin.GetNewAddress();
                        senderToDeposit = InsertSenderToDeposit(account.name, depositAdress);
                    }
                    catch (BitsharesRpcException)
                    {
                        throw new ApiExceptionMessage(accountName + " is not an existing account! Are you sure it is registered?");
                    }
                }

                response = new SubmitAddressResponse {
                    deposit_address = senderToDeposit.deposit_address
                };
            }
            else if (fromCurrency == CurrencyTypes.bitBTC && toCurrency == CurrencyTypes.BTC)
            {
                string bitcoinAddress = receivingAddress;

                // try and retrieve a previous entry
                SenderToDepositRow senderToDeposit = m_database.Query <SenderToDepositRow>("SELECT * FROM sender_to_deposit WHERE receiving_address=@s;", bitcoinAddress).FirstOrDefault();
                if (senderToDeposit == null)
                {
                    // validate bitcoin address
                    byte[] check = Util.Base58CheckToByteArray(bitcoinAddress);
                    if (check == null)
                    {
                        throw new ApiExceptionMessage(bitcoinAddress + " is not a valid bitcoin address!");
                    }

                    // generate a memo field to use instead
                    string start = "meta-";
                    string memo  = start + bitcoinAddress.Substring(0, BitsharesWallet.kBitsharesMaxMemoLength - start.Length);
                    senderToDeposit = InsertSenderToDeposit(bitcoinAddress, memo);
                }

                response = new SubmitAddressResponse {
                    deposit_address = m_bitsharesAccount, memo = senderToDeposit.deposit_address
                };
            }
            else
            {
                throw new ApiExceptionUnsupportedTrade(fromCurrency, toCurrency);
            }

            ctx.Respond <SubmitAddressResponse>(response);

            return(null);
        }