示例#1
0
        /// <summary>
        /// Retrieves details about the identified record from the server.
        /// </summary>
        /// <param name='uid'>
        /// The UID of the record to be read.
        /// </param>
        /// <param name='read_key'>
        /// A token that grants permission to read the record.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 2.5.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        /// <exception cref="Exceptions.NotFoundError">
        /// The requested record was not found.
        /// </exception>
        /// <exception cref="Exceptions.NotPresentError">
        /// The requested record was found, but no content is available.
        /// </exception>
        /// <exception cref="Exceptions.NotAuthorisedError">
        /// The requested record was not accessible with the given credentials.
        /// </exception>
        public Structures.Internal.Description Describe(string uid, string read_key, float timeout=2.5f)
        {
            Jayrock.Json.JsonObject describe = new Jayrock.Json.JsonObject();
            describe.Add("uid", uid);

            Jayrock.Json.JsonObject keys = new Jayrock.Json.JsonObject();
            keys.Add("read", read_key);
            describe.Add("keys", keys);

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.server.GetHost() + Libraries.Communication.SERVER_DESCRIBE, describe);
            Structures.Internal.Description description = new Structures.Internal.Description(Libraries.Communication.SendRequest(request, timeout:timeout).ToDictionary());
            if(!description.Physical.Exists){
                throw new Exceptions.NotPresentError(description);
            }
            return description;
        }
示例#2
0
        /// <summary>
        /// Sends the specified signal to the client.
        /// </summary>
        /// <param name="signal">The signal.</param>
        public void Signal(KeePassRPC.DataExchangeModel.Signal signal, string methodName)
        {
            try
            {
                Jayrock.Json.JsonObject call = new Jayrock.Json.JsonObject();
                call["id"]     = ++_currentCallBackId;
                call["method"] = methodName;
                call["params"] = new int[] { (int)signal };

                StringBuilder sb = new StringBuilder();
                Jayrock.Json.Conversion.JsonConvert.Export(call, sb);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                this.ConnectionStreamWrite(bytes);
            }
            catch (System.IO.IOException)
            {
                // Sometimes a connection is unexpectedly closed e.g. by Firefox
                // or (more likely) dodgy security "protection". From one year's
                // worth of bug reports (35) 100% of unexpected application
                // exceptions were IOExceptions.
                //
                // We will now ignore this type of exception and allow KeeFox to
                // re-establish the link to KeePass as part of its regular polling loop.
                //
                // The requested KPRPC signal will never be recieved by KeeFox
                // but this should be OK in practice becuase KeeFox will
                // re-establish the relevant state information as soon as it reconnects.
                //
                // BUT: the exception to this rule is when KeeFox fails to receive the
                // "shutdown" signal - it then gets itself in an inconsistent state
                // and has no opportunity to recover until KeePass is running again.
                return;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("ERROR! Please click on this box, press CTRL-C on your keyboard and paste into a new post on the KeeFox forum (http://keefox.org/help/forum). Doing this will help other people to use KeeFox without any unexpected error messages like this. Please briefly describe what you were doing when the problem occurred, which version of KeeFox, KeePass and Firefox you use and what other security software you run on your machine. Thanks! Technical detail follows: " + ex.ToString());
            }
        }
        //Ticker[] tickers = new Ticker[]
        //{
        //new Ticker { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
        //new Ticker { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
        //new Ticker { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        //};

        //public IEnumerable<Ticker> GetAllTickers()
        //{
        //    return tickers;
        //}

        public IHttpActionResult GetTicker()
        {
            //var ticker = tickers.FirstOrDefault();
            //if (tickers == null)
            //{
            //    return NotFound();
            //}
            //return Ok(ticker);

            KrakenConsumer consumer = new KrakenConsumer();

            Jayrock.Json.JsonObject response = consumer.GetTicker(new List <string> {
                Constants.CurrencyPairs.BTCUSD
            });
            //ticker = (Ticker)Jayrock.Json.Conversion.JsonConvert.Import(typeof(Ticker), response.ToString());
            ticker = JsonConvert.DeserializeObject <Ticker>(response.ToString());

            if (ticker == null)
            {
                return(NotFound());
            }
            return(Ok(ticker));
        }
示例#4
0
        /// <summary>
        /// Sends the specified signal to the client.
        /// </summary>
        /// <param name="signal">The signal.</param>
        public void Signal(KeePassRPC.DataExchangeModel.Signal signal, string methodName)
        {
            try
            {
                Jayrock.Json.JsonObject call = new Jayrock.Json.JsonObject();
                call["id"]     = ++_currentCallBackId;
                call["method"] = methodName;
                call["params"] = new int[] { (int)signal };

                StringBuilder sb = new StringBuilder();
                Jayrock.Json.Conversion.JsonConvert.Export(call, sb);
                if (WebSocketConnection != null)
                {
                    KPRPCMessage data2client = new KPRPCMessage();
                    data2client.protocol = "jsonrpc";
                    data2client.version  = ProtocolVersion;
                    data2client.jsonrpc  = Encrypt(sb.ToString());

                    // If there was a problem encrypting our message, just abort - the
                    // client won't be able to do anything useful with an error message
                    if (data2client.jsonrpc == null)
                    {
                        if (KPRPC.logger != null)
                        {
                            KPRPC.logger.WriteLine("Encryption error when trying to send signal: " + signal);
                        }
                        return;
                    }

                    // Signalling through the websocket needs to be processed on a different thread becuase handling the incoming messages results in a lock on the list of known connections (which also happens before this Signal function is called) so we want to process this as quickly as possible and avoid deadlocks.
                    // Not sure why this doesn't happen on the standard network port implementation in previous versions (maybe the networking stack created threads automatically before passing on the incoming messages?)

                    //TODO1.3: Does this work in .NET 2?
                    // Respond to each message on a different thread
                    ThreadStart work = delegate
                    {
                        WebSocketConnection.Send(Jayrock.Json.Conversion.JsonConvert.ExportToString(data2client));
                    };
                    Thread messageHandler = new Thread(work);
                    messageHandler.Name = "signalDispatcher";
                    messageHandler.Start();
                }
                else
                {
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                    this.ConnectionStreamWrite(bytes);
                }
            }
            catch (System.IO.IOException)
            {
                // Sometimes a connection is unexpectedly closed e.g. by Firefox
                // or (more likely) dodgy security "protection". From one year's
                // worth of bug reports (35) 100% of unexpected application
                // exceptions were IOExceptions.
                //
                // We will now ignore this type of exception and allow KeeFox to
                // re-establish the link to KeePass as part of its regular polling loop.
                //
                // The requested KPRPC signal will never be recieved by KeeFox
                // but this should be OK in practice becuase KeeFox will
                // re-establish the relevant state information as soon as it reconnects.
                //
                // BUT: the exception to this rule is when KeeFox fails to receive the
                // "shutdown" signal - it then gets itself in an inconsistent state
                // and has no opportunity to recover until KeePass is running again.
                return;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("ERROR! Please click on this box, press CTRL-C on your keyboard and paste into a new post on the KeeFox forum (http://keefox.org/help/forum). Doing this will help other people to use KeeFox without any unexpected error messages like this. Please briefly describe what you were doing when the problem occurred, which version of KeeFox, KeePass and Firefox you use and what other security software you run on your machine. Thanks! Technical detail follows: " + ex.ToString());
            }
        }
示例#5
0
        /// <summary>
        /// Sends the specified signal to the client.
        /// </summary>
        /// <param name="signal">The signal.</param>
        public void Signal(KeePassRPC.DataExchangeModel.Signal signal, string methodName)
        {
            try
            {
                Jayrock.Json.JsonObject call = new Jayrock.Json.JsonObject();
                call["id"] = ++_currentCallBackId;
                call["method"] = methodName;
                call["params"] = new int[] { (int)signal };

                StringBuilder sb = new StringBuilder();
                Jayrock.Json.Conversion.JsonConvert.Export(call, sb);
                KPRPCMessage data2client = new KPRPCMessage();
                data2client.protocol = "jsonrpc";
                data2client.version = ProtocolVersion;
                data2client.jsonrpc = Encrypt(sb.ToString());

                // If there was a problem encrypting our message, just abort - the
                // client won't be able to do anything useful with an error message
                if (data2client.jsonrpc == null)
                {
                    if (KPRPC.logger != null) KPRPC.logger.WriteLine("Encryption error when trying to send signal: " + signal);
                    return;
                }

                // Signalling through the websocket needs to be processed on a different thread becuase handling the incoming messages results in a lock on the list of known connections (which also happens before this Signal function is called) so we want to process this as quickly as possible and avoid deadlocks.

                // Respond to each message on a different thread
                ThreadStart work = delegate
                {
                    WebSocketConnection.Send(Jayrock.Json.Conversion.JsonConvert.ExportToString(data2client));
                };
                Thread messageHandler = new Thread(work);
                messageHandler.Name = "signalDispatcher";
                messageHandler.Start();
            }
            catch (System.IO.IOException)
            {
                // Sometimes a connection is unexpectedly closed e.g. by Firefox
                // or (more likely) dodgy security "protection". From one year's
                // worth of bug reports (35) 100% of unexpected application
                // exceptions were IOExceptions.
                //
                // We will now ignore this type of exception and allow KeeFox to
                // re-establish the link to KeePass as part of its regular polling loop.
                //
                // The requested KPRPC signal will never be recieved by KeeFox
                // but this should be OK in practice becuase KeeFox will
                // re-establish the relevant state information as soon as it reconnects.
                //
                // BUT: the exception to this rule is when KeeFox fails to receive the
                // "shutdown" signal - it then gets itself in an inconsistent state
                // and has no opportunity to recover until KeePass is running again.
                return;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("ERROR! Please click on this box, press CTRL-C on your keyboard and paste into a new post on the KeeFox forum (http://keefox.org/help/forum). Doing this will help other people to use KeeFox without any unexpected error messages like this. Please briefly describe what you were doing when the problem occurred, which version of KeeFox, KeePass and Firefox you use and what other security software you run on your machine. Thanks! Technical detail follows: " + ex.ToString());
            }
        }
示例#6
0
        /// <summary>
        /// Sends the specified signal to the client.
        /// </summary>
        /// <param name="signal">The signal.</param>
        public void Signal(KeePassRPC.DataExchangeModel.Signal signal, string methodName)
        {
            try
            {
                Jayrock.Json.JsonObject call = new Jayrock.Json.JsonObject();
                call["id"] = ++_currentCallBackId;
                call["method"] = methodName;
                call["params"] = new int[] { (int)signal };

                StringBuilder sb = new StringBuilder();
                Jayrock.Json.Conversion.JsonConvert.Export(call, sb);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                this.ConnectionStreamWrite(bytes);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("ERROR! Please click on this box, press CTRL-C on your keyboard and paste into a new post on the KeeFox forum (http://keefox.org/help/forum). Doing this will help other people to use KeeFox without any unexpected error messages like this. Please briefly describe what you were doing when the problem occurred, which version of KeeFox, KeePass and Firefox you use and what other security software you run on your machine. Thanks! Technical detail follows: " + ex.ToString());
            }
        }
示例#7
0
        /// <summary>
        /// Stores the content of <c>data</c> in the proxy's buffers, returning information about how to access it later.
        ///
        /// It is important to note that the data is NOT actually stored when this pointer is returned,
        /// but rather that the pointer will be valid at some point in the future (typically very soon,
        /// but not within a predictable timeframe).
        /// </summary>
        /// <param name='data'>
        /// The path to the content to be stored.
        /// </param>
        /// <param name='mime'>
        /// The MIME-type of the content being stored.
        /// </param>
        /// <param name='family'>
        /// The case-sensitive, arbitrary family to which the data belongs; defaults to <c>null</c>, for the
        /// generic family.
        /// </param>
        /// <param name='compression'>
        /// The type of compression to apply when storing the file; defaults to <c>COMPRESSION.NONE</c>
        /// </param>
        /// <param name='compress_on_server'>
        /// Indicates whether the proxy should require the server to perform compression, rather than trying
        /// locally; defaults to <c>false</c>.
        /// </param>
        /// <param name='deletion_policy'>
        /// May either be <c>null</c>, the default, which means the file is never removed or a <see cref="Structures.DeletionPolicy"/>
        /// instance.
        /// </param>
        /// <param name='compression_policy'>
        /// May either be <c>null</c>, the default, which means the file is never compressed or a <see cref="Structures.CompressionPolicy"/>
        /// instance.
        /// </param>
        /// <param name='meta'>
        /// Any additional metadata with which to tag the file; defaults to <c>null</c>, meaning no metadata.
        /// </param>
        /// <param name='uid'>
        /// If not implementing a proxy, leave this value at its default of <c>null</c> to have an identifier auto-generated or pick something that
        /// has no chance of colliding with a UUID(1).
        /// </param>
        /// <param name='keys'>
        /// In general, you should not need to specify anything, leaving it at <c>null</c>, but if you have a homogenous
        /// or anonymous access policy, a <see cref="Structures.Keys"/> instance may be used, with either key set to an arbitrary string or
        /// <c>null</c>, with <c>null</c> granting anonymous access to the corresponding facet.
        ///
        /// Either element may be omitted to have it generated by the server.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 3.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        public Structures.Storage Put(
         string data, string mime, string family=null,
         COMPRESSION compression=COMPRESSION.NONE, bool compress_on_server=false,
         Structures.DeletionPolicy deletion_policy=null,
         Structures.CompressionPolicy compression_policy=null,
         COMPRESSION compression_policy_format=COMPRESSION.NONE,
         System.Collections.Generic.IDictionary<string, object> meta=null,
         string uid=null, Structures.Keys keys=null,
         float timeout=3.0f
        )
        {
            Jayrock.Json.JsonObject put = new Jayrock.Json.JsonObject();
            put.Add("uid", uid);
            put.Add("keys", keys);
            put.Add("meta", meta);

            Jayrock.Json.JsonObject physical = new Jayrock.Json.JsonObject();
            physical.Add("family", family);

            Jayrock.Json.JsonObject format = new Jayrock.Json.JsonObject();
            format.Add("mime", mime);
            format.Add("comp", compression != COMPRESSION.NONE ? compression.ToString().ToLower() : null);
            physical.Add("format", format);
            put.Add("physical", physical);

            Jayrock.Json.JsonObject policy = new Jayrock.Json.JsonObject();
            policy.Add("delete", deletion_policy != null ? deletion_policy.ToDictionary() : null);
            policy.Add("compress", compression_policy != null ? compression_policy.ToDictionary() : null);
            put.Add("policy", policy);

            Jayrock.Json.JsonObject proxy = new Jayrock.Json.JsonObject();
            proxy.Add("server", this.server.ToDictionary());
            proxy.Add("data", data);
            put.Add("proxy", proxy);

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.proxy + Libraries.Communication.SERVER_PUT, put);
            return new Structures.Storage(Libraries.Communication.SendRequest(request, timeout:timeout).ToDictionary());
        }
示例#8
0
        private void GetData()
        {
            WebClient webClient = new WebClient();

            webClient.Headers.Add("user-agent", "Only a test!");
            BusLayer.Currency currencyHelper = new BusLayer.Currency();

            KrakenClient.KrakenClient client = new KrakenClient.KrakenClient();

            DataLayer.MstCurrencyList.MstCurrencyListDataTable currentLisTbl = currencyHelper.GetCurrentListRows();

            DataLayer.PrmCurrency.PrmCurrencyDataTable currencyTable = currencyHelper.GetCurrencyRows();

            try
            {
                foreach (DataLayer.MstCurrencyList.MstCurrencyListRow listRow in currentLisTbl)
                {
                    string currencyCode = listRow.Code;

                    if (currencyCode == "BTC")
                    {
                        currencyCode = "XBT";
                    }

                    foreach (DataLayer.PrmCurrency.PrmCurrencyRow currencyRow in currencyTable)
                    {
                        try
                        {
                            string newcurrencyCode = currencyCode + currencyRow.Currency;

                            Jayrock.Json.JsonObject js5on = client.GetTicker(new List <string> {
                                newcurrencyCode
                            });

                            string innerRes = string.Empty;
                            if (newcurrencyCode == "XBTUSD")
                            {
                                innerRes = "XXBTZUSD";
                            }
                            else if (newcurrencyCode == "XBTEUR")
                            {
                                innerRes = "XXBTZEUR";
                            }
                            else if (newcurrencyCode == "ETHUSD")
                            {
                                innerRes = "XETHZUSD";
                            }
                            else if (newcurrencyCode == "ETHEUR")
                            {
                                innerRes = "XETHZEUR";
                            }
                            else if (newcurrencyCode == "XRPUSD")
                            {
                                innerRes = "XXRPZUSD";
                            }
                            else if (newcurrencyCode == "XRPEUR")
                            {
                                innerRes = "XXRPZEUR";
                            }
                            else if (newcurrencyCode == "LTCUSD")
                            {
                                innerRes = "XLTCZUSD";
                            }
                            else if (newcurrencyCode == "LTCEUR")
                            {
                                innerRes = "XLTCZEUR";
                            }
                            else if (newcurrencyCode == "ZECUSD")
                            {
                                innerRes = "XZECZUSD";
                            }
                            else if (newcurrencyCode == "ZECEUR")
                            {
                                innerRes = "XZECZEUR";
                            }
                            else if (newcurrencyCode == "DASHUSD")
                            {
                                innerRes = "DASHUSD";
                            }
                            else if (newcurrencyCode == "DASHEUR")
                            {
                                innerRes = "DASHEUR";
                            }



                            if (innerRes != string.Empty)
                            {
                                Dictionary <string, object> values = JsonConvert.DeserializeObject <Dictionary <string, object> >(js5on["result"].ToString());

                                Dictionary <string, object> Innervalues = JsonConvert.DeserializeObject <Dictionary <string, object> >(values[innerRes].ToString());

                                //create the new row
                                DataLayer.TrnKrakenValue.TrnKrakenValueDataTable newTbl = new DataLayer.TrnKrakenValue.TrnKrakenValueDataTable();
                                DataLayer.TrnKrakenValue.TrnKrakenValueRow       newRow = newTbl.NewTrnKrakenValueRow();

                                newRow.TrnKrakenValueGuid  = Guid.NewGuid();
                                newRow.MstCurrencyListGuid = listRow.MstCurrencyListGuid;
                                newRow.Ask                 = decimal.Parse(JsonConvert.DeserializeObject <List <string> >(Innervalues["a"].ToString())[0], new CultureInfo("en-US"));
                                newRow.Bid                 = decimal.Parse(JsonConvert.DeserializeObject <List <string> >(Innervalues["b"].ToString())[0], new CultureInfo("en-US"));
                                newRow.CreateDate          = DateTime.Now;
                                newRow.PrmCurrencyId       = currencyRow.PrmCurrencyId;
                                newRow.PrmCurrencySourceId = 3;


                                newTbl.AddTrnKrakenValueRow(newRow);
                                currencyHelper.UpdateCurrencyValue(newRow);
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

            //kraken is ask

            /*
             * XBTEUR
             * XBTUSD
             *
             * ETHEUR
             * ETHUSD
             *
             * XRPEUR
             * XRPUSD
             *
             *
             * LTC
             * ZEC
             * DASH
             *
             * <pair_name> = pair name
             * a = ask array(<price>, <whole lot volume>, <lot volume>),
             * b = bid array(<price>, <whole lot volume>, <lot volume>),
             * c = last trade closed array(<price>, <lot volume>),
             * v = volume array(<today>, <last 24 hours>),
             * p = volume weighted average price array(<today>, <last 24 hours>),
             * t = number of trades array(<today>, <last 24 hours>),
             * l = low array(<today>, <last 24 hours>),
             * h = high array(<today>, <last 24 hours>),
             * o = today's opening price
             *
             *
             *
             *
             *
             *
             * bitstamp
             * https://www.bitstamp.net/api/
             *
             * btcusd, btceur,
             * ethusd, etheur,
             * xrpusd, xrpeur
             *
             *
             * {"high": "1.74000",
             * "last": "1.68754",
             * "timestamp": "1516295176" ,  to use
             * "bid": "1.68001",  to use
             * "vwap": "1.33150",
             * "volume": "164572084.34820374",
             * "low": "0.94344",
             *      "ask": "1.68749",  to use
             * "open": "1.29849"}
             *
             */
        }
示例#9
0
        /// <summary>
        /// Updates attributes of an existing record on a server.
        /// </summary>
        /// <param name='uid'>
        /// The UID of the record to be updated.
        /// </param>
        /// <param name='write_key'>
        /// A token that grants permission to modify the record.
        /// </param>
        /// <param name='new_meta'>
        /// Any newly added metadata; defaults to <c>null</c>.
        /// </param>
        /// <param name='removed_meta'>
        /// A list of all metadata to be removed; defaults to <c>null</c>.
        /// </param>
        /// <param name='deletion_policy'>
        /// May either be <c>null</c>, the default, which means no change, or a
        /// dictionary containing one or both of the following:
        /// <list>
        ///     <item>'fixed': The number of seconds to retain the file from the time it was uploaded</item>
        ///     <item>'stale': The number of seconds that must elapse after the file was last downloaded to qualify it for deletion</item>
        /// </list>
        /// </param>
        /// <param name='compression_policy'>
        /// May either be <c>null</c>, the default, which means the file is never compressed, or a
        /// dictionary containing one or both of the following:
        /// <list>
        ///     <item>'fixed': The number of seconds to leave the file alone from the time it was uploaded</item>
        ///     <item>'stale': The number of seconds that must elapse after the file was last downloaded to qualify it for compression</item>
        /// </list>
        /// </param>
        /// <param name='compression_policy_format'>
        /// The format into which the file will be compressed once the compression policy activates; defaults to <c>COMPRESSION.NONE</c>.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 2.5.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        /// <exception cref="Exceptions.NotFoundError">
        /// The requested record was not found.
        /// </exception>
        /// <exception cref="Exceptions.NotAuthorisedError">
        /// The requested record was not accessible with the given credentials.
        /// </exception>
        public void Update(string uid, string write_key,
         System.Collections.Generic.IDictionary<string, object> new_meta=null,
         System.Collections.Generic.IList<string> removed_meta=null,
         Structures.DeletionPolicy deletion_policy=null,
         Structures.CompressionPolicy compression_policy=null,
         float timeout=2.5f
        )
        {
            Jayrock.Json.JsonObject update = new Jayrock.Json.JsonObject();
            update.Add("uid", uid);

            Jayrock.Json.JsonObject keys = new Jayrock.Json.JsonObject();
            keys.Add("write", write_key);
            update.Add("keys", keys);

            Jayrock.Json.JsonObject policy = new Jayrock.Json.JsonObject();
            policy.Add("delete", deletion_policy != null ? deletion_policy.ToDictionary() : null);
            policy.Add("compress", compression_policy != null ? compression_policy.ToDictionary() : null);
            update.Add("policy", policy);

            Jayrock.Json.JsonObject meta = new Jayrock.Json.JsonObject();
            meta.Add("new", new_meta != null ? new_meta : new System.Collections.Generic.Dictionary<string, object>());
            meta.Add("removed", removed_meta != null ? removed_meta : new System.Collections.Generic.List<string>());
            update.Add("meta", meta);

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.server.GetHost() + Libraries.Communication.SERVER_UPDATE, update);
            Libraries.Communication.SendRequest(request, timeout:timeout);
        }
示例#10
0
        /// <summary>
        /// Unlinks the identified data on the server.
        /// </summary>
        /// <param name='uid'>
        /// The UID of the record to be unlinked.
        /// </param>
        /// <param name='write_key'>
        /// A token that grants permission to modify the record.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 2.5.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        /// <exception cref="Exceptions.NotFoundError">
        /// The requested record was not found.
        /// </exception>
        /// <exception cref="Exceptions.NotAuthorisedError">
        /// The requested record was not accessible with the given credentials.
        /// </exception>
        public void Unlink(string uid, string write_key, float timeout=2.5f)
        {
            Jayrock.Json.JsonObject unlink = new Jayrock.Json.JsonObject();
            unlink.Add("uid", uid);

            Jayrock.Json.JsonObject keys = new Jayrock.Json.JsonObject();
            keys.Add("write", write_key);
            unlink.Add("keys", keys);

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.server.GetHost() + Libraries.Communication.SERVER_UNLINK, unlink);
            Libraries.Communication.SendRequest(request, timeout:timeout);
        }
示例#11
0
        /// <summary>
        /// Stores the content of <c>data</c> on the server, returning information about how to access it later.
        /// </summary>
        /// <param name='data'>
        /// The content to be stored.
        /// </param>
        /// <param name='mime'>
        /// The MIME-type of the content being stored.
        /// </param>
        /// <param name='family'>
        /// The case-sensitive, arbitrary family to which the data belongs; defaults to <c>null</c>, for the
        /// generic family.
        /// </param>
        /// <param name='compression'>
        /// The type of compression to apply when storing the file; defaults to <c>COMPRESSION.NONE</c>
        /// </param>
        /// <param name='compress_on_server'>
        /// Indicates whether the client should require the server to perform compression, rather than trying
        /// locally; defaults to <c>false</c>.
        /// </param>
        /// <param name='deletion_policy'>
        /// May either be <c>null</c>, the default, which means the file is never removed or a <see cref="Structures.DeletionPolicy"/>
        /// instance.
        /// </param>
        /// <param name='compression_policy'>
        /// May either be <c>null</c>, the default, which means the file is never compressed or a <see cref="Structures.CompressionPolicy"/>
        /// instance.
        /// </param>
        /// <param name='meta'>
        /// Any additional metadata with which to tag the file; defaults to <c>null</c>, meaning no metadata.
        /// </param>
        /// <param name='uid'>
        /// If not implementing a proxy, leave this value at its default of <c>null</c> to have an identifier auto-generated or pick something that
        /// has no chance of colliding with a UUID(1).
        /// </param>
        /// <param name='keys'>
        /// In general, you should not need to specify anything, leaving it at <c>null</c>, but if you have a homogenous
        /// or anonymous access policy, a <see cref="Structures.Keys"/> instance may be used, with either key set to an arbitrary string or
        /// <c>null</c>, with <c>null</c> granting anonymous access to the corresponding facet.
        ///
        /// Either element may be omitted to have it generated by the server.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 10.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        public Structures.Storage Put(
         System.IO.Stream data, string mime, string family=null,
         COMPRESSION compression=COMPRESSION.NONE, bool compress_on_server=false,
         Structures.DeletionPolicy deletion_policy=null,
         Structures.CompressionPolicy compression_policy=null,
         System.Collections.Generic.IDictionary<string, object> meta=null,
         string uid=null, Structures.Keys keys=null,
         float timeout=10.0f
        )
        {
            Jayrock.Json.JsonObject put = new Jayrock.Json.JsonObject();
            put.Add("uid", uid);
            put.Add("keys", keys);
            put.Add("meta", meta);

            Jayrock.Json.JsonObject physical = new Jayrock.Json.JsonObject();
            physical.Add("family", family);

            Jayrock.Json.JsonObject format = new Jayrock.Json.JsonObject();
            format.Add("mime", mime);
            format.Add("comp", compression != COMPRESSION.NONE ? compression.ToString().ToLower() : null);
            physical.Add("format", format);
            put.Add("physical", physical);

            Jayrock.Json.JsonObject policy = new Jayrock.Json.JsonObject();
            policy.Add("delete", deletion_policy != null ? deletion_policy.ToDictionary() : null);
            policy.Add("compress", compression_policy != null ? compression_policy.ToDictionary() : null);
            put.Add("policy", policy);

            System.Collections.Generic.Dictionary<string, string> headers = new System.Collections.Generic.Dictionary<string, string>();
            if(!compress_on_server){
                try{
                    data = Libraries.Compression.GetCompressor(compression).Invoke(data);
                    headers.Add(Libraries.Communication.HEADER_COMPRESS_ON_SERVER, Libraries.Communication.HEADER_COMPRESS_ON_SERVER_FALSE);
                }catch(System.Exception){
                    headers.Add(Libraries.Communication.HEADER_COMPRESS_ON_SERVER, Libraries.Communication.HEADER_COMPRESS_ON_SERVER_TRUE);
                }
            }else{
                headers.Add(Libraries.Communication.HEADER_COMPRESS_ON_SERVER, Libraries.Communication.HEADER_COMPRESS_ON_SERVER_TRUE);
            }

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.server.GetHost() + Libraries.Communication.SERVER_PUT, put, headers:headers, data:data);
            return new Structures.Storage(Libraries.Communication.SendRequest(request, timeout:timeout).ToDictionary());
        }
示例#12
0
        /// <summary>
        /// Retrieves the identified data from the server.
        /// </summary>
        /// <returns>
        /// Returns the content's MIME and the decompressed data as a stream (optionally that
        /// supplied as <c>output_file</c>), along with the length of the content in bytes.
        /// </returns>
        /// <param name='uid'>
        /// The UID of the record to be retrieved.
        /// </param>
        /// <param name='read_key'>
        /// A token that grants permission to read the record.
        /// </param>
        /// <param name='output_file'>
        /// An optional stream into which retrieved content may be written; if <c>null</c>, the
        /// default, an on-disk, self-cleaning tempfile, is used instead.
        /// </param>
        /// <param name='decompress_on_server'>
        /// Favours decompression of content on the server; defaults to <c>false</c>.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 5.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        /// <exception cref="Exceptions.NotFoundError">
        /// The requested record was not found.
        /// </exception>
        /// <exception cref="Exceptions.NotAuthorisedError">
        /// The requested record was not accessible with the given credentials.
        /// </exception>
        public Structures.Internal.Content Get(string uid, string read_key, System.IO.Stream output_file=null, bool decompress_on_server=false, float timeout=5.0f)
        {
            Jayrock.Json.JsonObject get_json = new Jayrock.Json.JsonObject();
            get_json.Add("uid", uid);

            Jayrock.Json.JsonObject keys = new Jayrock.Json.JsonObject();
            keys.Add("read", read_key);
            get_json.Add("keys", keys);

            System.Collections.Generic.Dictionary<string, string> headers = new System.Collections.Generic.Dictionary<string, string>();
            if(!decompress_on_server){
                headers.Add(Libraries.Communication.HEADER_SUPPORTED_COMPRESSION, string.Join(Libraries.Communication.HEADER_SUPPORTED_COMPRESSION_DELIMITER.ToString(), Libraries.Compression.SupportedFormats));
            }

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.server.GetHost() + Libraries.Communication.SERVER_GET, get_json, headers:headers);

            System.IO.Stream output;
            if(output_file != null){
                output = output_file;
            }else{
                output = new Libraries.TempFileStream();
            }

            Libraries.Communication.Response response = Libraries.Communication.SendRequest(request, output:output, timeout:timeout);

            Structures.Internal.Content content = new Structures.Internal.Content();
            content.Data = response.Data;
            content.Mime = (string)response.Properties[Libraries.Communication.PROPERTY_CONTENT_TYPE];
            content.Length = (long)response.Properties[Libraries.Communication.PROPERTY_CONTENT_LENGTH];

            //Evaluate decompression requirements
            object applied_compression = response.Properties[Libraries.Communication.PROPERTY_APPLIED_COMPRESSION];
            if(applied_compression != null){
                System.IO.Stream decompressed_data = Libraries.Compression.GetDecompressor((COMPRESSION)applied_compression).Invoke(content.Data);
                if(output_file != null){ //Write to the given stream, since the caller might expect to use that
                    output_file.Seek(0, System.IO.SeekOrigin.Begin);
                    output_file.SetLength(0); //Truncate the file
                    decompressed_data.CopyTo(output_file);
                    output_file.Seek(0, System.IO.SeekOrigin.Begin);
                    content.Data = output_file;
                    content.Length = output_file.Length;
                }
            }

            return content;
        }
示例#13
0
        /// <summary>
        /// Serialises the query object as a media-storage-query-compatible, JSON-friendly data-structure.
        /// </summary>
        /// <returns>
        /// A JSON-friendly dictionary representation of the query object in its current state.
        /// </returns>
        internal System.Collections.Generic.IDictionary<string, object> ToDictionary()
        {
            Jayrock.Json.JsonObject json_struct = new Jayrock.Json.JsonObject();

            Jayrock.Json.JsonObject ctime = new Jayrock.Json.JsonObject();
            ctime.Add("min", Libraries.Structures.ToUnixTimestamp(this.CtimeMin));
            ctime.Add("max", Libraries.Structures.ToUnixTimestamp(this.CtimeMax));
            json_struct.Add("ctime", ctime);

            Jayrock.Json.JsonObject atime = new Jayrock.Json.JsonObject();
            atime.Add("min", Libraries.Structures.ToUnixTimestamp(this.AtimeMin));
            atime.Add("max", Libraries.Structures.ToUnixTimestamp(this.AtimeMax));
            json_struct.Add("atime", atime);

            Jayrock.Json.JsonObject accesses = new Jayrock.Json.JsonObject();
            accesses.Add("min", this.AccessesMin);
            accesses.Add("max", this.AccessesMax);
            json_struct.Add("accesses", accesses);

            json_struct.Add("family", this.Family);
            json_struct.Add("mime", this.Mime);
            json_struct.Add("meta", this.Meta);

            return json_struct;
        }
示例#14
0
        /// <summary>
        /// Retrieves details about the requested record from the cache.
        ///
        /// The provided details may not be entirely current, since cached copies will be used when possible.
        /// </summary>
        /// <param name='uid'>
        /// The UID of the record to be read.
        /// </param>
        /// <param name='read_key'>
        /// A token that grants permission to read the record.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 2.5.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        /// <exception cref="Exceptions.NotFoundError">
        /// The requested record was not found.
        /// </exception>
        /// <exception cref="Exceptions.NotAuthorisedError">
        /// The requested record was not accessible with the given credentials.
        /// </exception>
        public Structures.Internal.Description Describe(string uid, string read_key, float timeout=2.5f)
        {
            Jayrock.Json.JsonObject describe = new Jayrock.Json.JsonObject();
            describe.Add("uid", uid);

            Jayrock.Json.JsonObject keys = new Jayrock.Json.JsonObject();
            keys.Add("read", read_key);
            describe.Add("keys", keys);

            Jayrock.Json.JsonObject proxy = new Jayrock.Json.JsonObject();
            proxy.Add("server", this.server.ToDictionary());
            describe.Add("proxy", proxy);

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.proxy + Libraries.Communication.SERVER_DESCRIBE, describe);
            return new Structures.Internal.Description(Libraries.Communication.SendRequest(request, timeout:timeout).ToDictionary());
        }
示例#15
0
        /// <summary>
        /// Retrieves the requested data from the cache.
        /// </summary>
        /// <returns>
        /// Returns the content's MIME and the decompressed data as a stream (optionally that
        /// supplied as <c>output_file</c>), along with the length of the content in bytes.
        /// </returns>
        /// <param name='uid'>
        /// The UID of the record to be retrieved.
        /// </param>
        /// <param name='read_key'>
        /// A token that grants permission to read the record.
        /// </param>
        /// <param name='output_file'>
        /// An optional stream into which retrieved content may be written; if <c>null</c>, the
        /// default, an on-disk, self-cleaning tempfile, is used instead.
        /// </param>
        /// <param name='decompress_on_server'>
        /// Ignored, since this decision is up to the proxy.
        /// </param>
        /// <param name='timeout'>
        /// The number of seconds to wait for a response; defaults to 5.
        /// </param>
        /// <exception cref="System.Exception">
        /// Some unknown problem occurred.
        /// </exception>
        /// <exception cref="Exceptions.ProtocolError">
        /// A problem occurred related to the transport protocol.
        /// </exception>
        /// <exception cref="Exceptions.UrlError">
        /// A problem occurred related to the network environment.
        /// </exception>
        /// <exception cref="Exceptions.NotFoundError">
        /// The requested record was not found.
        /// </exception>
        /// <exception cref="Exceptions.NotAuthorisedError">
        /// The requested record was not accessible with the given credentials.
        /// </exception>
        public Structures.Internal.Content Get(string uid, string read_key, System.IO.Stream output_file=null, bool decompress_on_server=false, float timeout=5.0f)
        {
            Jayrock.Json.JsonObject get_json = new Jayrock.Json.JsonObject();
            get_json.Add("uid", uid);

            Jayrock.Json.JsonObject keys = new Jayrock.Json.JsonObject();
            keys.Add("read", read_key);
            get_json.Add("keys", keys);

            Jayrock.Json.JsonObject proxy = new Jayrock.Json.JsonObject();
            proxy.Add("server", this.server.ToDictionary());
            get_json.Add("proxy", proxy);

            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(this.proxy + Libraries.Communication.SERVER_GET, get_json);
            Libraries.Communication.Response response = Libraries.Communication.SendRequest(request, timeout:timeout);

            Structures.Internal.Content content = new Structures.Internal.Content();
            if(output_file != null){
                content.Data = output_file;
            }else{
                content.Data = new Libraries.TempFileStream();
            }
            response.Data.CopyTo(content.Data);
            content.Length = content.Data.Length;
            content.Data.Seek(0, System.IO.SeekOrigin.Begin);
            content.Mime = (string)response.Properties[Libraries.Communication.PROPERTY_CONTENT_TYPE];

            return content;
        }