Esempio n. 1
0
        public async Task <MediaItem []> PerformAppleMusicGetRecentlyPlayedAsync(string userToken)
        {
            var developerToken = FetchDeveloperToken();

            if (developerToken == null)
            {
                throw new ArgumentNullException(nameof(developerToken), "Developer Token not configured. See README for more details.");
            }

            var urlRequest      = AppleMusicRequestFactory.CreateRecentlyPlayedRequest(developerToken, userToken);
            var dataTaskRequest = await UrlSession.CreateDataTaskAsync(urlRequest);

            var urlResponse = dataTaskRequest.Response as NSHttpUrlResponse;

            if (urlResponse?.StatusCode != 200)
            {
                return(new MediaItem [0]);
            }

            var jsonDictionary = NSJsonSerialization.Deserialize(dataTaskRequest.Data, NSJsonReadingOptions.AllowFragments, out NSError error) as NSDictionary;

            if (error != null)
            {
                throw new NSErrorException(error);
            }

            var results = jsonDictionary [ResponseRootJsonKeys.Data] as NSArray ??
                          throw new SerializationException(ResponseRootJsonKeys.Data);

            return(ProcessMediaItems(results));
        }
Esempio n. 2
0
        void FirebaseDatabaseService.BatchSetChildValues(string nodeKey, Dictionary <string, object> dict, Action onSuccess, Action <string> onError)
        {
            DatabaseReference rootRef = Database.DefaultInstance.GetRootReference();

            DatabaseReference nodeRef = rootRef.GetChild(nodeKey);

            NSDictionary nsDict = null;

            if (dict != null)
            {
                string objectJsonString = JsonConvert.SerializeObject(dict);
                NSData nsData           = NSData.FromString(objectJsonString);

                NSError jsonError = null;
                nsDict = NSJsonSerialization.Deserialize(nsData, NSJsonReadingOptions.AllowFragments, out jsonError) as NSDictionary;
            }

            //nodeRef.SetValue(nsObj, (NSError error, DatabaseReference reference) =>
            nodeRef.UpdateChildValues(nsDict, (NSError error, DatabaseReference reference) =>
            {
                if (error == null)
                {
                    if (onSuccess != null)
                    {
                        onSuccess();
                    }
                }
                else if (onError != null)
                {
                    onError(error.Description);
                }
            });
        }
Esempio n. 3
0
        void FirebaseDatabaseService.SetValue(string nodeKey, object obj, Action onSuccess, Action <string> onError)
        {
            DatabaseReference rootRef = Database.DefaultInstance.GetRootReference();

            DatabaseReference nodeRef = rootRef.GetChild(nodeKey);

            NSObject nsObj = null;

            if (obj != null)
            {
                string  objectJsonString = JsonConvert.SerializeObject(obj);
                NSError jsonError        = null;
                NSData  nsData           = NSData.FromString(objectJsonString);

                nsObj = NSJsonSerialization.Deserialize(nsData, NSJsonReadingOptions.AllowFragments, out jsonError);
            }

            nodeRef.SetValue(nsObj, (NSError error, DatabaseReference reference) =>
            {
                if (error == null)
                {
                    if (onSuccess != null)
                    {
                        onSuccess();
                    }
                }
                else if (onError != null)
                {
                    onError(error.Description);
                }
            });
        }
        private string parseFacebookUserIdFromSettings(ACAccount account)
        {
            SLRequest sl = SLRequest.Create(SLServiceKind.Facebook, SLRequestMethod.Get, new NSUrl("https://graph.facebook.com/me"), null);

            sl.Account = account;

            AutoResetEvent completedEvent = new AutoResetEvent(false);
            var            id             = string.Empty;

            sl.PerformRequest((data, response, error) =>
            {
                if (error == null)
                {
                    NSError parseError;
                    NSDictionary jsonDict = (NSDictionary)NSJsonSerialization.Deserialize(data, 0, out parseError);
                    if (jsonDict != null)
                    {
                        NSObject obj = jsonDict.ValueForKey(new NSString("id"));
                        id           = obj?.ToString();
                    }
                }

                completedEvent.Set();
            });

            completedEvent.WaitOne();
            return(id);
        }
Esempio n. 5
0
        MediaItem [] [] ProcessMediaItemSections(NSData json)
        {
            var jsonDictionary = NSJsonSerialization.Deserialize(json, NSJsonReadingOptions.AllowFragments, out NSError error) as NSDictionary;

            if (error != null)
            {
                throw new NSErrorException(error);
            }

            var results = jsonDictionary [ResponseRootJsonKeys.Results] as NSDictionary ??
                          throw new SerializationException(ResponseRootJsonKeys.Results);

            var mediaItems      = new List <MediaItem []> ();
            var songsDictionary = results [ResourceTypeJsonKeys.Songs] as NSDictionary;
            var dataArray       = songsDictionary? [ResponseRootJsonKeys.Data] as NSArray;

            if (dataArray != null)
            {
                mediaItems.Add(ProcessMediaItems(dataArray));
            }

            var albumsDictionary = results [ResourceTypeJsonKeys.Albums] as NSDictionary;

            dataArray = albumsDictionary? [ResponseRootJsonKeys.Data] as NSArray;

            if (dataArray != null)
            {
                mediaItems.Add(ProcessMediaItems(dataArray));
            }

            return(mediaItems.ToArray());
        }
Esempio n. 6
0
        public void StartReadingBerlinData()
        {
            DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Low).DispatchAsync(() =>
            {
                var file        = NSBundle.MainBundle.PathForResource(@"Berlin-Data", "json");
                var inputStream = new NSInputStream(file);
                inputStream.Open();

                NSError error;
                var dataAsJson  = (NSArray)NSJsonSerialization.Deserialize(inputStream, 0, out error);
                var annotations = new List <(double lat, double lon, string title)>(BATCH_COUNT);

                for (uint i = 0; i < dataAsJson.Count; i++)
                {
                    var annotationAsJson = dataAsJson.GetItem <NSDictionary>(i);

                    var lat   = (NSNumber)annotationAsJson.ValueForKeyPath(new NSString("location.coordinates.latitude"));
                    var lon   = (NSNumber)annotationAsJson.ValueForKeyPath(new NSString("location.coordinates.longitude"));
                    var title = (NSString)annotationAsJson.ValueForKeyPath(new NSString("person.lastName"));

                    annotations.Add((lat.DoubleValue, lon.DoubleValue, title.ToString()));

                    if (annotations.Count == BATCH_COUNT)
                    {
                        DispatchAnnotations(annotations.ToArray());
                        annotations.Clear();
                    }
                }

                DispatchAnnotations(annotations.ToArray());
            });
        }
Esempio n. 7
0
        public static NSPredicate ToPredicate(this Expressions.Expression expression)
        {
            var json = JsonConvert.SerializeObject(expression.ToArray());

#if DEBUG
            System.Diagnostics.Debug.WriteLine(json);
#endif

            var obj = NSJsonSerialization.Deserialize(NSData.FromString(json), 0, out var error);

            if (error != null)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(error.UserInfo.DebugDescription);
#endif
                return(null);
            }

            if (obj is NSArray array)
            {
                var result = ToPredicate(array);

#if DEBUG
                System.Diagnostics.Debug.WriteLine(result.ToString());
#endif

                return(result);
            }

            return(null);
        }
Esempio n. 8
0
        public bool LoadMesh()
        {
            NSInputStream inputStream = NSInputStream.FromFile(mMeshPath);

            if (inputStream != null)
            {
                inputStream.Open();
                NSError error;
                try {
                    var jsonMesh = NSJsonSerialization.Deserialize(inputStream, new NSJsonReadingOptions(), out error);
                    if (error == null)
                    {
                        NSArray      values = null;
                        nuint        i;
                        NSDictionary dictVertices;
                        NSDictionary dictTriangles;

                        NSArray  arrayVertices = (jsonMesh as NSDictionary)["vertices"] as NSArray;
                        NSArray  arrayTriangles = (jsonMesh as NSDictionary)["connectivity"] as NSArray;
                        NSString nameVertices, nameTriangles;
                        for (i = 0; i < arrayVertices.Count; i++)
                        {
                            dictVertices = arrayVertices.GetItem <NSDictionary>(i);
                            values       = dictVertices["values"] as NSArray;
                            nameVertices = dictVertices["name"] as NSString;
                            if (nameVertices == "position_buffer")
                            {
                                mVertices = VerticesToFloat(values);
                            }
                            else if (nameVertices == "normal_buffer")
                            {
                                mNormals = ToFloatArray(values);
                            }
                            else if (nameVertices == "texcoord_buffer")
                            {
                                mTexCoords = ToFloatArray(values);
                            }
                        }

                        for (i = 0; i < arrayTriangles.Count; i++)
                        {
                            dictTriangles = arrayTriangles.GetItem <NSDictionary>(i);
                            nameTriangles = dictTriangles["name"] as NSString;
                            if (nameTriangles == "triangles")
                            {
                                values          = dictTriangles["indices"] as NSArray;
                                mIndices_Number = (int)values.Count;
                                mIndex          = ToShortIntArray(values);
                            }
                        }
                    }
                } catch (Exception ee) {
                    Console.WriteLine("Errore durante LoadMesh {0}", ee.Message);
                    inputStream.Close();
                    return(false);
                }
                inputStream.Close();
            }
            return(true);
        }
Esempio n. 9
0
        public static List <StockDataPoint> LoadStockPoints(int maxItems)
        {
            List <StockDataPoint> stockPoints = new List <StockDataPoint> ();

            string          filePath  = NSBundle.MainBundle.PathForResource("AppleStockPrices", "json");
            NSData          json      = NSData.FromFile(filePath);
            NSError         error     = new NSError();
            NSArray         data      = (NSArray)NSJsonSerialization.Deserialize(json, NSJsonReadingOptions.AllowFragments, out error);
            NSDateFormatter formatter = new NSDateFormatter();

            formatter.DateFormat = "dd-MM-yyyy";

            for (int i = 0; i < (int)data.Count; i++)
            {
                if (i == maxItems)
                {
                    break;
                }
                NSDictionary   jsonPoint = data.GetItem <NSDictionary> ((nuint)i);
                StockDataPoint dataPoint = new StockDataPoint();
                dataPoint.DataXValue = formatter.Parse((NSString)jsonPoint ["date"]);
                dataPoint.Open       = (NSNumber)jsonPoint ["open"];
                dataPoint.Low        = (NSNumber)jsonPoint ["low"];
                dataPoint.Close      = (NSNumber)jsonPoint ["close"];
                dataPoint.Volume     = (NSNumber)jsonPoint ["volume"];
                dataPoint.High       = (NSNumber)jsonPoint ["high"];
                stockPoints.Add(dataPoint);
            }

            return(stockPoints);
        }
Esempio n. 10
0
        /// <summary>
        /// Deserializa tareas.
        /// </summary>
        /// <param name="json">JSON con datos.</param>
        /// <returns>Tareas.</returns>
        public static Tarea[] DeserializeTareas(string json)
        {
            // Tareas
            List <Tarea> tareas = null;

            // Deserializo JSON
            NSArray data = (NSArray)NSJsonSerialization.Deserialize(json, 0, out NSError e);

            // Compruebo datos
            if (data != null)
            {
                // Inicializo lista
                tareas = new List <Tarea>();

                // Recorro tareas
                for (uint i = 0; i < data.Count; i++)
                {
                    // Creo y añado
                    tareas.Add(new Tarea(data.GetItem <NSDictionary>(i)));
                }
            }

            // Devuelvo datos
            return(tareas.ToArray());
        }
Esempio n. 11
0
            public async void SreateCustomerKeyWithAPIVersion(string apiVersion,
                                                              STPJSONResponseCompletionBlock completion)
            {
                var result = await _stripeRemoteService.GetEphemeralKeyAsync(apiVersion);

                if (result == null)
                {
                    completion(null, new NSError());
                    return;
                }

                var nsError      = default(NSError);
                var nsDictionary = default(NSDictionary);

                try
                {
                    var nsData = NSData.FromString(result);
                    nsDictionary = (NSDictionary)NSJsonSerialization.Deserialize(
                        nsData,
                        NSJsonReadingOptions.MutableContainers,
                        out nsError);
                }
                catch (Exception ex)
                {
                    _logger.Error(ex);
                }

                completion(nsDictionary, nsError);
            }
Esempio n. 12
0
        private Task perform()
        {
            mTcs = new TaskCompletionSource <bool>();

#if __ANDROID__
            var mds    = (Com.Movesense.Mds.Mds)CrossMovesense.Current.MdsInstance;
            var serial = Util.GetVisibleSerial(mDeviceName);
            if (mRestOp == MdsOp.POST)
            {
                mds.Post(Plugin.Movesense.CrossMovesense.Current.SCHEME_PREFIX + mPrefixPath + serial + mPath, mBody, this);
            }
            else if (mRestOp == MdsOp.GET)
            {
                mds.Get(Plugin.Movesense.CrossMovesense.Current.SCHEME_PREFIX + mPrefixPath + serial + mPath, null, this);
            }
            else if (mRestOp == MdsOp.DELETE)
            {
                mds.Delete(Plugin.Movesense.CrossMovesense.Current.SCHEME_PREFIX + mPrefixPath + serial + mPath, null, this);
            }
            else if (mRestOp == MdsOp.PUT)
            {
                mds.Put(Plugin.Movesense.CrossMovesense.Current.SCHEME_PREFIX + mPrefixPath + serial + mPath, mBody, this);
            }
#endif

#if __IOS__
            var          mds      = (Movesense.MDSWrapper)CrossMovesense.Current.MdsInstance;
            var          serial   = Util.GetVisibleSerial(mDeviceName);
            NSDictionary bodyDict = new NSDictionary();
            if (mRestOp == MdsOp.POST)
            {
                if (!string.IsNullOrEmpty(mBody))
                {
                    NSData  data  = NSData.FromString(mBody);
                    NSError error = new NSError();
                    bodyDict = (NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.MutableContainers, out error);
                }
                mds.DoPost(mPrefixPath + serial + mPath, contract: bodyDict, completion: (arg0) => CallCompletionCallback(arg0));
            }
            else if (mRestOp == MdsOp.GET)
            {
                mds.DoGet(mPrefixPath + serial + mPath, contract: bodyDict, completion: (arg0) => CallCompletionCallback(arg0));
            }
            else if (mRestOp == MdsOp.DELETE)
            {
                mds.DoDelete(mPrefixPath + serial + mPath, contract: bodyDict, completion: (arg0) => CallCompletionCallback(arg0));
            }
            else if (mRestOp == MdsOp.PUT)
            {
                if (!string.IsNullOrEmpty(mBody))
                {
                    NSData  data  = NSData.FromString(mBody);
                    NSError error = new NSError();
                    bodyDict = (NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.MutableContainers, out error);
                }
                mds.DoPut(mPrefixPath + serial + mPath, bodyDict, completion: (arg0) => CallCompletionCallback(arg0));
            }
#endif
            return(mTcs.Task);
        }
Esempio n. 13
0
        public void Search(string searchText, EventHandler handler)
        {
            NSUrl url = GetUrl(searchText);
            NSUrlSessionDataTask dataTask = session.CreateDataTask(url, (data, response, error) =>
            {
                NSError er;
                NSDictionary dict = (NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.AllowFragments, out er);

                string status = dict["stat"].ToString();
                Console.WriteLine("stat = " + dict["stat"]);
                NSArray arr = (NSArray)((NSDictionary)dict["photos"])["photo"];
                List <FlickrPhoto> photosList = new List <FlickrPhoto>();
                for (nuint i = 0; i < arr.Count; i++)
                {
                    //Console.WriteLine(arr.GetItem<NSDictionary>(i));
                    NSDictionary elemt = arr.GetItem <NSDictionary>(i);
                    FlickrPhoto photo  = new FlickrPhoto(elemt["id"].ToString(), elemt["farm"].ToString(), elemt["server"].ToString(), elemt["secret"].ToString(), elemt["title"].ToString());
                    photosList.Add(photo);
                }
                //Console.WriteLine("photos = " + ((NSDictionary)dict["photos"])["photo"]);
                var arg        = new PhotosDounloadEventArg();
                arg.PhotosList = photosList;
                //FinishHandler(this, arg);
                handler(this, arg);

                Console.WriteLine("dict = " + dict);
                Console.WriteLine("data = " + data);
                Console.WriteLine("error = " + error);
            });

            dataTask.Resume();
        }
Esempio n. 14
0
        /// <summary>
        /// Obtiene datos cliente.
        /// </summary>
        public void GetClienteData()
        {
            // Cliente
            Cliente c;

            // Obtengo datos servidor
            RestManager.Connection().GetData((int)URIS.GetCliente, new string[] { Cliente.ID_Cliente.ToString() }, null, (arg) =>
            {
                // Depuracion
                Console.WriteLine(arg ?? "null");

                // Compruebo datos
                if (!string.IsNullOrWhiteSpace(arg))
                {
                    // Deserializo JSON
                    NSDictionary data = (NSDictionary)NSJsonSerialization.Deserialize(arg, 0, out NSError e);

                    // Cargo datos
                    c       = new Cliente(data);
                    Cliente = c;
                }

                // Continuo
                lock (l)
                {
                    Monitor.Pulse(l);
                }
            });

            // Espero a obtener datos
            lock (l)
            {
                Monitor.Wait(l);
            }
        }
        public XamarinTableViewDataSource()
        {
            var     data = NSData.FromFile(NSBundle.MainBundle.BundlePath + "/data.json");
            NSError error;
            var     json = NSJsonSerialization.Deserialize(data, 0, out error);

            this.dataSource = (NSArray)json;
        }
Esempio n. 16
0
        /// <summary>
        /// Obtiene datos del pais.
        /// </summary>
        public void GetDataPais()
        {
            // Pais
            Pais p;

            // Obtengo pais
            p = SQLiteManager.Connection().GetProvincia(ID_Pais);

            // Compruebo datos
            if (p == null)
            {
                // Obtengo pais del servidor
                RestManager.Connection().GetData((int)URIS.GetPais, new string[] { ID_Pais.ToString() }, null, (arg) =>
                {
                    // Compruebo datos
                    if (!string.IsNullOrWhiteSpace(arg))
                    {
                        // Deserializo JSON
                        NSDictionary data = (NSDictionary)NSJsonSerialization.Deserialize(arg, 0, out NSError e);

                        // Leo datos
                        foreach (NSString key in data.Keys)
                        {
                            switch (key.ToString().ToLower())
                            {
                            case "id_pais":
                                ID_Pais = (int)(NSNumber)data.ValueForKey(key);
                                break;

                            case "nombre":
                                Nombre_Pais = data.ValueForKey(key).ToString();
                                break;
                            }
                        }

                        // Guardo en SQLite
                        SQLiteManager.Connection().SetPais(this);
                    }

                    // Continuo
                    lock (l)
                    {
                        Monitor.Pulse(l);
                    }
                });

                // Espero
                lock (l)
                {
                    Monitor.Wait(l);
                }
            }
            else
            {
                // Cargo nombre
                Nombre_Pais = p.Nombre_Pais;
            }
        }
        public static NSDictionary DictionaryWithJSONData(this NSData This)
        {
            var dict = NSJsonSerialization.Deserialize(This, 0, out NSError err) as NSDictionary;

            if (err != null)
            {
                Debug.WriteLine($"Error parsing JSON: {err.LocalizedDescription}");
            }
            return(dict);
        }
Esempio n. 18
0
        protected override NSDictionary GetSaveValue(IEnumerable <Feedback> existingItems)
        {
            var dict = GetSaveDictionary(existingItems);
            var json = JsonConvert.SerializeObject(dict);

            var data   = NSData.FromString(json);
            var result = NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.AllowFragments, out NSError readError) as NSDictionary;

            return(result);
        }
Esempio n. 19
0
        public static NSDictionary ToIOSDictionary(this IDictionary self)
        {
            if (self == null)
            {
                return(null);
            }
            var     jsonString = new NSString(SimpleJson.SerializeObject(self));
            var     jsonData   = jsonString.Encode(NSStringEncoding.UTF8);
            NSError error;

            return((NSDictionary)NSJsonSerialization.Deserialize(jsonData, 0, out error));
        }
        /**
         *  Helper function that will try to parse AnyObject to JSON and return as NSDictionary
         *  :param: AnyObject
         *  :returns: JSON object as NSDictionary if parsing is successful, otherwise nil
         */
        private NSDictionary GetParsedJSON(object obj)
        {
            try
            {
                var jsonString = obj.ToString();
                var jsonData   = NSData.FromString(jsonString, NSStringEncoding.UTF8);
                var parsed     = NSJsonSerialization.Deserialize(jsonData, NSJsonReadingOptions.AllowFragments, out NSError error) as NSDictionary;

                return(parsed);
            }
            catch { }
            return(null);
        }
Esempio n. 21
0
        NSDictionary GetDictionary(object item)
        {
            var json = JsonConvert.SerializeObject(item);

            NSString jsonString = new NSString(json);
            //NSDictionary.from
            var data = NSData.FromString(json, NSStringEncoding.UTF8);

            NSError      error;
            NSDictionary jsonDic = (NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.AllowFragments, out error);

            return(jsonDic);
        }
Esempio n. 22
0
        public static MSDictionaryDocument ToMSDocument <T>(this T document)
        {
            var     jsonString = JsonConvert.SerializeObject(document);
            var     data       = NSData.FromString(jsonString);
            NSError error;
            var     nativeDict = (NSDictionary)NSJsonSerialization.Deserialize(data, new NSJsonReadingOptions(), out error);

            if (error != null)
            {
                throw new NSErrorException(error);
            }
            return(new MSDictionaryDocument().Init(nativeDict));
        }
Esempio n. 23
0
        public CitiesDataSource()
        {
            var citiesJSONURL  = NSBundle.MainBundle.PathForResource("Cities", "json");
            var citiesJSONData = NSData.FromFile(citiesJSONURL);
            var jsonObject     = NSJsonSerialization.Deserialize(citiesJSONData, default(NSJsonReadingOptions), out NSError error);

            if (jsonObject is NSArray jsonCities)
            {
                for (nuint i = 0; i < jsonCities.Count; i++)
                {
                    cities.Add(jsonCities.GetItem <NSString>(i));
                }
            }
        }
        public static NSDictionary DictToNSDict(Dictionary <string, object> dict)
        {
            if (dict == null)
            {
                return(null);
            }

            string       jsonString   = Json.Serialize(dict);
            NSString     jsonNSString = new NSString(jsonString);
            NSData       jsonData     = jsonNSString.Encode(NSStringEncoding.UTF8);
            NSError      error;
            NSDictionary nsDict = NSJsonSerialization.Deserialize(jsonData, 0, out error) as NSDictionary;

            return(nsDict);
        }
Esempio n. 25
0
        public static string GetClientTransactionId(this NSUrl url, out NSError error)
        {
            error = null;
            var parameters = SCC_HTTPGETParameters(url);

            var dataString = parameters.SCC_stringForKey(Constants.SCCAPIResponseDataKey);

            if (dataString.Length == 0)
            {
                if (error == null)
                {
                    error = NSError_SCCAdditions.SCC_missingOrInvalidResponseDataError;
                }
                return(null);
            }

            NSDictionary data       = null;
            var          jsonData   = NSData.FromString(dataString, NSStringEncoding.UTF8);
            var          jsonObject = NSJsonSerialization.Deserialize(jsonData, 0, out error);

            if (!jsonObject.IsKindOfClass(new ObjCRuntime.Class(typeof(NSDictionary))))
            {
                if (error == null)
                {
                    error = NSError_SCCAdditions.SCC_missingOrInvalidResponseJSONDataError;
                }
                return(null);
            }
            else
            {
                data = (NSDictionary)jsonObject;
            }

            var statusString = data.SCC_stringForKey(Constants.SCCAPIResponseStatusKey);
            var status       = SCCAPIResponseStatusFromString(statusString);

            if (status == SCCAPIResponseStatus.Unknown ||
                status == SCCAPIResponseStatus.Error)
            {
                if (error == null)
                {
                    error = NSError_SCCAdditions.SCC_missingOrInvalidResponseStatusError;
                }
                return(null);
            }

            return(data.SCC_stringForKey(Constants.SCCAPIResponseClientTransactionIDKey));
        }
Esempio n. 26
0
        public void getPayementID(Boolean subscription)
        {
            NSUrl url = new NSUrl(paymentIdUrl);
            NSMutableUrlRequest       request  = new NSMutableUrlRequest(url);
            NSUrlSession              session  = null;
            NSUrlSessionConfiguration myConfig = NSUrlSessionConfiguration.DefaultSessionConfiguration;

            session = NSUrlSession.FromConfiguration(myConfig);

            var dictionary = new NSDictionary(
                "Content-Type", "application/json",
                "Authorization", secretKey
                );


            if (subscription)
            {
                var             date       = NSDate.FromTimeIntervalSinceNow((3 * 12 * 30) * 24 * 3600);
                NSDateFormatter dateFormat = new NSDateFormatter();
                dateFormat.DateFormat = "yyyy-MM-dd'T'HH:mm:ss";
                var dateString = dateFormat.ToString(date);

                String data = "{\"subscription\":{\"endDate\":\"{dateString}\",\"interval\":0},\"order\":{\"currency\":\"SEK\",\"amount\":1000,\"reference\":\"MiaSDK-iOS\",\"items\":[{\"unit\":\"pcs\",\"name\":\"Lightning Cable\",\"reference\":\"MiaSDK-iOS\",\"quantity\":1,\"netTotalAmount\":800,\"unitPrice\":800,\"taxRate\":0,\"grossTotalAmount\":800,\"taxAmount\":0},{\"unitPrice\":200,\"quantity\":1,\"grossTotalAmount\":200,\"taxAmount\":0,\"taxRate\":0,\"reference\":\"MiaSDK-iOS\",\"name\":\"Shipping Cost\",\"unit\":\"pcs\",\"netTotalAmount\":200}]},\"checkout\":{\"consumerType\":{\"default\":\"B2C\",\"supportedTypes\":[\"B2C\",\"B2B\"]},\"returnURL\":\"https:\\/\\/127.0.0.1\\/redirect.php\",\"cancelURL\":\"https:\\/\\/127.0.0.1\\/cancel.php\",\"integrationType\":\"HostedPaymentPage\",\"shippingCountries\":[{\"countryCode\":\"SWE\"},{\"countryCode\":\"NOR\"},{\"countryCode\":\"DNK\"}],\"termsUrl\":\"http:\\/\\/localhost:8080\\/terms\"}}";

                request.Body = data.Replace("{dateString}", dateString);
            }
            else
            {
                request.Body = "{\"order\":{\"currency\":\"SEK\",\"amount\":1000,\"reference\":\"MiaSDK-iOS\",\"items\":[{\"unit\":\"pcs\",\"name\":\"Lightning Cable\",\"reference\":\"MiaSDK-iOS\",\"quantity\":1,\"netTotalAmount\":800,\"unitPrice\":800,\"taxRate\":0,\"grossTotalAmount\":800,\"taxAmount\":0},{\"unitPrice\":200,\"quantity\":1,\"grossTotalAmount\":200,\"taxAmount\":0,\"taxRate\":0,\"reference\":\"MiaSDK-iOS\",\"name\":\"Shipping Cost\",\"unit\":\"pcs\",\"netTotalAmount\":200}]},\"checkout\":{\"consumerType\":{\"default\":\"B2C\",\"supportedTypes\":[\"B2C\",\"B2B\"]},\"returnURL\":\"https:\\/\\/127.0.0.1\\/redirect.php\",\"cancelURL\":\"https:\\/\\/127.0.0.1\\/cancel.php\",\"integrationType\":\"HostedPaymentPage\",\"shippingCountries\":[{\"countryCode\":\"SWE\"},{\"countryCode\":\"NOR\"},{\"countryCode\":\"DNK\"}],\"termsUrl\":\"http:\\/\\/localhost:8080\\/terms\"}}";
            }
            request.HttpMethod = "POST";
            request.Headers    = dictionary;

            NSUrlSessionTask task = session.CreateDataTask(request, (data, response, error) => {
                var json = NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.FragmentsAllowed, out error);
                if ((Foundation.NSString)json.ValueForKey((Foundation.NSString) "hostedPaymentPageUrl") != null &&
                    (Foundation.NSString)json.ValueForKey((Foundation.NSString) "paymentId") != null)
                {
                    InvokeOnMainThread(() =>
                    {
                        presentMiaSDK((Foundation.NSString)json.ValueForKey((Foundation.NSString) "paymentId"),
                                      (Foundation.NSString)json.ValueForKey((Foundation.NSString) "hostedPaymentPageUrl"));
                    });
                }
            });

            task.Resume();
        }
 private static NSObject ConvertJsonToData(string dataJson = null)
 {
     if (dataJson == null)
     {
         return(null);
     }
     else
     {
         var data = NSJsonSerialization.Deserialize(NSData.FromString(dataJson, NSStringEncoding.UTF8), 0, out var error);
         if (error != null)
         {
             throw new FirebaseException(error.LocalizedDescription);
         }
         return(data);
     }
 }
Esempio n. 28
0
        string ProcessStorefront(NSData json)
        {
            var jsonDictionary = NSJsonSerialization.Deserialize(json, NSJsonReadingOptions.AllowFragments, out NSError error) as NSDictionary;

            if (error != null)
            {
                throw new NSErrorException(error);
            }

            var dataArray = jsonDictionary [ResponseRootJsonKeys.Data] as NSArray ??
                            throw new SerializationException(ResponseRootJsonKeys.Data);
            var id = dataArray?.GetItem <NSDictionary> (0) [ResourceJsonKeys.Id]?.ToString() ??
                     throw new SerializationException(ResourceJsonKeys.Id);

            return(id);
        }
Esempio n. 29
0
        private static NSDictionary ReadContainerSettingsFile(string resourceName)
        {
            string filename      = Path.GetFileNameWithoutExtension(resourceName);
            string fileExtension = Path.GetExtension(resourceName)?.Replace(".", "");

            string pathToSettings = NSBundle.MainBundle.PathForResource(filename, fileExtension);
            NSData settingsData   = NSData.FromUrl(NSUrl.FromFilename(pathToSettings));

            NSError      error;
            NSDictionary jsonObject = (NSDictionary)NSJsonSerialization.Deserialize(settingsData, NSJsonReadingOptions.MutableLeaves, out error);

            if (error is not null)
            {
                throw new Exception(error.ToString());
            }

            return(jsonObject);
        }
Esempio n. 30
0
        /// <summary>
        /// Obtengo direccion cliente.
        /// </summary>
        public void GetDireccionData()
        {
            // Obtengo direccion de SQLite
            Direccion d = null;

            // Compruebo datos
            if (d == null)
            {
                // Obtengo direccion del servidor
                RestManager.Connection().GetData((int)URIS.GetDireccionCliente, new string[] { ID_Cliente.ToString() }, null, (arg) =>
                {
                    // Compruebo datos
                    if (!string.IsNullOrWhiteSpace(arg))
                    {
                        // Deserializo JSON
                        NSDictionary data = (NSDictionary)NSJsonSerialization.Deserialize(arg, 0, out NSError e);

                        // Cargo datos
                        d = Direccion = new Direccion(data);

                        // Guardo en SQLite
                        SQLiteManager.Connection().SetDireccion(d);
                    }

                    // Continuo
                    lock (l)
                    {
                        Monitor.Pulse(l);
                    }
                });

                // Espero a obtener datos
                lock (l)
                {
                    Monitor.Wait(l);
                }
            }

            // Obtengo datos ciudad
            d.GetDataCiudad();

            // Cargo direccion
            Direccion = d;
        }