protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // build post data for http request
            JSONObject postDataJSON = new JSONObject();
            try
            {
                postDataJSON.Put("apiKey", GetString(1));
                postDataJSON.Put("affId", GetString(2)); //don't have an affId yet
                postDataJSON.Put("transaction", "refillByScan");
                postDataJSON.Put("act", "mweb5Url");
                postDataJSON.Put("view", "mweb5UrlJSON");
                postDataJSON.Put("devinf", "Android,2.3.3");
                postDataJSON.Put("appver", "3.1");
            }
            catch (JSONException e)
            {
                //(TAG, "error building json request", e);
            }

            
            // Create your application here
        }
 // Put a |key|->|value| mapping in |json|.
 private static void jsonPut(JSONObject json, string key, Java.Lang.Object value)
 {
     try
     {
         json.Put(key, value);
     }
     catch (JSONException e)
     {
         throw new Exception("Error", e);
     }
 }
		JSONObject getJsonObject(String name,String type,double count)
		{
			JSONObject obj= new JSONObject();
			obj.Put ("Name", name);
			obj.Put ("Type", type);
			return obj;
		}
Beispiel #4
0
        /// <summary>
        /// Requests that the specified Purchasable be purchased on behalf of the current user.
        /// The IAP client service is responsible for identifying the user and requesting credentials as appropriate,
        /// as well as providing all of the UI for the purchase flow. When purchases are successful, a Product object
        /// is returned that describes the product that was purchased.
        /// </summary>
        /// <param name="product">The Purchasable object that describes the item to be purchased.</param>
        /// <returns>Returns true if the purchase was successful.</returns>
        public async Task<bool> RequestPurchaseAsync(Product product)
        {
            if (ReferenceEquals(product, null))
                throw new ArgumentNullException("product");

            var tcs = new TaskCompletionSource<bool>();

            // Create the Purchasable object from the supplied product
            var sr = SecureRandom.GetInstance("SHA1PRNG");

            // This is an ID that allows you to associate a successful purchase with
            // it's original request. The server does nothing with this string except
            // pass it back to you, so it only needs to be unique within this instance
            // of your app to allow you to pair responses with requests.
            var uniqueId = sr.NextLong().ToString("X");

            JSONObject purchaseRequest = new JSONObject();
            purchaseRequest.Put("uuid", uniqueId);
            purchaseRequest.Put("identifier", product.Identifier);
            var purchaseRequestJson = purchaseRequest.ToString();

            byte[] keyBytes = new byte[16];
            sr.NextBytes(keyBytes);
            var key = new SecretKeySpec(keyBytes, "AES");

            byte[] ivBytes = new byte[16];
            sr.NextBytes(ivBytes);
            var iv = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding", "BC");
            cipher.Init(CipherMode.EncryptMode, key, iv);
            var payload = cipher.DoFinal(Encoding.UTF8.GetBytes(purchaseRequestJson));

            cipher = Cipher.GetInstance("RSA/ECB/PKCS1Padding", "BC");
            cipher.Init(CipherMode.EncryptMode, _publicKey);
            var encryptedKey = cipher.DoFinal(keyBytes);

            var purchasable = new Purchasable(
                        product.Identifier,
                        Convert.ToBase64String(encryptedKey, Base64FormattingOptions.None),
                        Convert.ToBase64String(ivBytes, Base64FormattingOptions.None),
                        Convert.ToBase64String(payload, Base64FormattingOptions.None));

            var listener = new PurchaseListener(tcs, _publicKey, product, uniqueId);
            RequestPurchase(purchasable, listener);
            // No timeout for purchase as it shows a user dialog
            return await tcs.Task;
        }
 // Encrypt the receipts and save them to file.
 static void ToCache(IList<Receipt> receipts, string gamerUuid)
 {
     OuyaFacade.Log("Caching receipts");
     var json = new JSONObject();
     var array = new JSONArray();
     foreach (var receipt in receipts)
     {
         var r = new JSONObject();
         r.Put("identifier", receipt.Identifier);
         // PriceInCents is now deprecated. Use LocalPrice and CurrencyCode instead.
         // Retain field for compatibility.
         r.Put("priceInCents", 0);
         r.Put("purchaseDate", receipt.PurchaseDate.ToGMTString());
         r.Put("generatedDate", receipt.GeneratedDate.ToGMTString());
         r.Put("gamerUuid", receipt.Gamer);
         r.Put("uuid", receipt.Uuid);
         r.Put("localPrice", receipt.LocalPrice);
         r.Put("currencyCode", receipt.Currency);
         array.Put(r);
     }
     json.Accumulate("receipts", array);
     var text = json.ToString();
     var encryptedReceipts = CryptoHelper.Encrypt(text, gamerUuid);
     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (var writer = new StreamWriter(store.OpenFile(receiptsFileName, FileMode.OpenOrCreate)))
         {
             writer.Write(encryptedReceipts);
         }
     }
 }
 // Encrypt the receipts and save them to file.
 void ToCache(IList<Receipt> receipts)
 {
     OuyaFacade.Log("Caching receipts");
     var json = new JSONObject();
     var array = new JSONArray();
     foreach (var receipt in receipts)
     {
         var r = new JSONObject();
         r.Put("identifier", receipt.Identifier);
         r.Put("priceInCents", receipt.PriceInCents);
         r.Put("purchaseDate", receipt.PurchaseDate.ToGMTString());
         r.Put("generatedDate", receipt.GeneratedDate.ToGMTString());
         r.Put("gamerUuid", receipt.Gamer);
         r.Put("uuid", receipt.Uuid);
         array.Put(r);
     }
     json.Accumulate("receipts", array);
     var text = json.ToString();
     var encryptedReceipts = CryptoHelper.Encrypt(text, _gamerUuid);
     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (var writer = new StreamWriter(store.OpenFile(receiptsFileName, FileMode.OpenOrCreate)))
         {
             writer.Write(encryptedReceipts);
         }
     }
 }
 /// <exception cref="System.Exception"></exception>
 public virtual void TestRemoteConflictResolution()
 {
     // Create a document with two conflicting edits.
     Document doc = database.CreateDocument();
     SavedRevision rev1 = doc.CreateRevision().Save();
     SavedRevision rev2a = CreateRevisionWithRandomProps(rev1, false);
     SavedRevision rev2b = CreateRevisionWithRandomProps(rev1, true);
     // make sure we can query the db to get the conflict
     Query allDocsQuery = database.CreateAllDocumentsQuery();
     allDocsQuery.SetAllDocsMode(Query.AllDocsMode.OnlyConflicts);
     QueryEnumerator rows = allDocsQuery.Run();
     bool foundDoc = false;
     NUnit.Framework.Assert.AreEqual(1, rows.GetCount());
     for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
     {
         QueryRow row = it.Next();
         if (row.GetDocument().GetId().Equals(doc.GetId()))
         {
             foundDoc = true;
         }
     }
     NUnit.Framework.Assert.IsTrue(foundDoc);
     // Push the conflicts to the remote DB.
     Replication push = database.CreatePushReplication(GetReplicationURL());
     RunReplication(push);
     NUnit.Framework.Assert.IsNull(push.GetLastError());
     // Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a.
     JSONObject rev3aBody = new JSONObject();
     rev3aBody.Put("_id", doc.GetId());
     rev3aBody.Put("_rev", rev2a.GetId());
     // Then, delete rev 2b.
     JSONObject rev3bBody = new JSONObject();
     rev3bBody.Put("_id", doc.GetId());
     rev3bBody.Put("_rev", rev2b.GetId());
     rev3bBody.Put("_deleted", true);
     // Combine into one _bulk_docs request.
     JSONObject requestBody = new JSONObject();
     requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody)));
     // Make the _bulk_docs request.
     HttpClient client = new DefaultHttpClient();
     string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs";
     HttpPost request = new HttpPost(bulkDocsUrl);
     request.SetHeader("Content-Type", "application/json");
     string json = requestBody.ToString();
     request.SetEntity(new StringEntity(json));
     HttpResponse response = client.Execute(request);
     // Check the response to make sure everything worked as it should.
     NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode());
     string rawResponse = IOUtils.ToString(response.GetEntity().GetContent());
     JSONArray resultArray = new JSONArray(rawResponse);
     NUnit.Framework.Assert.AreEqual(2, resultArray.Length());
     for (int i = 0; i < resultArray.Length(); i++)
     {
         NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error"));
     }
     WorkaroundSyncGatewayRaceCondition();
     // Pull the remote changes.
     Replication pull = database.CreatePullReplication(GetReplicationURL());
     RunReplication(pull);
     NUnit.Framework.Assert.IsNull(pull.GetLastError());
     // Make sure the conflict was resolved locally.
     NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count);
 }
 protected static void AddToJsonObject(JSONObject jsonObject, string name, short obj)
 {
     jsonObject.Put(name, obj);
 }
 protected static void AddToJsonObject(JSONObject jsonObject, string name, Guid obj)
 {
     jsonObject.Put(name, obj.ToString());
 }
 protected static void AddToJsonObject(JSONObject jsonObject, string name, DateTime obj)
 {
     jsonObject.Put(name, JsonConvert.ToString(obj));
 }
		/// <exception cref="System.Exception"></exception>
		public virtual void TestRemoteConflictResolution()
		{
			// Create a document with two conflicting edits.
			Document doc = database.CreateDocument();
			SavedRevision rev1 = doc.CreateRevision().Save();
			SavedRevision rev2a = rev1.CreateRevision().Save();
			SavedRevision rev2b = rev1.CreateRevision().Save(true);
			// Push the conflicts to the remote DB.
			Replication push = database.CreatePushReplication(GetReplicationURL());
			RunReplication(push);
			// Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a.
			JSONObject rev3aBody = new JSONObject();
			rev3aBody.Put("_id", doc.GetId());
			rev3aBody.Put("_rev", rev2a.GetId());
			// Then, delete rev 2b.
			JSONObject rev3bBody = new JSONObject();
			rev3bBody.Put("_id", doc.GetId());
			rev3bBody.Put("_rev", rev2b.GetId());
			rev3bBody.Put("_deleted", true);
			// Combine into one _bulk_docs request.
			JSONObject requestBody = new JSONObject();
			requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody)));
			// Make the _bulk_docs request.
			HttpClient client = new DefaultHttpClient();
			string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs";
			HttpPost request = new HttpPost(bulkDocsUrl);
			request.SetHeader("Content-Type", "application/json");
			string json = requestBody.ToString();
			request.SetEntity(new StringEntity(json));
			HttpResponse response = client.Execute(request);
			// Check the response to make sure everything worked as it should.
			NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode());
			string rawResponse = IOUtils.ToString(response.GetEntity().GetContent());
			JSONArray resultArray = new JSONArray(rawResponse);
			NUnit.Framework.Assert.AreEqual(2, resultArray.Length());
			for (int i = 0; i < resultArray.Length(); i++)
			{
				NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error"));
			}
			WorkaroundSyncGatewayRaceCondition();
			// Pull the remote changes.
			Replication pull = database.CreatePullReplication(GetReplicationURL());
			RunReplication(pull);
			// Make sure the conflict was resolved locally.
			NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count);
		}