public static List <CreditHistoryEntry> ToCreditHistoryArray(NSObject[] data)
        {
            List <CreditHistoryEntry> list = new List <CreditHistoryEntry> ();

            if (data != null)
            {
                NSError  error      = null;
                NSData   jsonData   = null;
                NSString jsonString = null;

                foreach (NSObject obj in data)
                {
                    if (obj != null)
                    {
                        jsonData   = NSJsonSerialization.Serialize(obj, NSJsonWritingOptions.PrettyPrinted, out error);
                        jsonString = new NSString(jsonData, NSStringEncoding.UTF8);

                        list.Add(JsonConvert.DeserializeObject <CreditHistoryEntry> ((string)jsonString));
                    }
                }
            }

            return(list);
        }
        void FetchQuakes(object sender, EventArgs e)
        {
            fetchQuakesButton.Enabled = false;
            var jsonURL           = new NSUrl("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson");
            var session           = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.EphemeralSessionConfiguration);
            NSUrlSessionTask task = session.CreateDataTask(jsonURL, (data, response, error) => {
                if (data == null)
                {
                    Console.WriteLine("Error connecting: {0}", error.LocalizedDescription);
                    return;
                }

                NSError anyError;
                NSManagedObjectContext taskContext = CreatePrivateQueueContext(out anyError);
                var jsonDictionary = NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.AllowFragments, out anyError);

                if (jsonDictionary == null)
                {
                    Console.WriteLine("Error creating JSON dictionary: {0}", anyError.LocalizedDescription);
                    return;
                }

                var featuresArray     = (NSArray)jsonDictionary.ValueForKey((NSString)"features");
                int totalFeatureCount = (int)featuresArray.Count;

                int numBatches = totalFeatureCount / BatchSize;
                numBatches    += totalFeatureCount % BatchSize > 0 ? 1 : 0;
                for (int batchNumber = 0; batchNumber < numBatches; batchNumber++)
                {
                    int rangeStart  = batchNumber * BatchSize;
                    int rangeLength = Math.Min(BatchSize, totalFeatureCount - batchNumber * BatchSize);

                    NSArray featuresBatchArray = featuresArray.SubarrayWithRange(new NSRange(rangeStart, rangeLength));
                    // Create a request to fetch existing quakes with the same codes as those in the JSON data.
                    // Existing quakes will be updated with new data; if there isn't a match, then create a new quake to represent the event.
                    NSFetchRequest matchingQuakeRequest = NSFetchRequest.FromEntityName("Quake");

                    // Get the codes for each of the features and store them in an array.
                    NSArray codesDump = (NSArray)featuresBatchArray.ValueForKeyPath((NSString)"properties.code");

                    matchingQuakeRequest.Predicate = NSPredicate.FromFormat("code in %@", codesDump);
                    var rawFetch = taskContext.ExecuteFetchRequest(matchingQuakeRequest, out anyError);
                    Quake[] allMatchingQuakes = Array.ConvertAll(rawFetch, item => (Quake)item);
                    NSString[] codes          = NSArray.FromArray <NSString> (codesDump);

                    for (int k = 0; k < codes.Length; k++)
                    {
                        var code           = codes [k];
                        var matchingQuakes = allMatchingQuakes.Where(q => q.Code == code).ToArray <Quake> ();

                        Quake quake = null;

                        int matchingLength = matchingQuakes.Length;
                        switch (matchingLength)
                        {
                        case 0:
                            //Insert new item
                            quake = (Quake)NSEntityDescription.InsertNewObjectForEntityForName("Quake", taskContext);
                            break;

                        case 1:
                            //Update existing item
                            quake = matchingQuakes [0];
                            break;

                        default:
                            //Remove duplicates
                            for (int i = 1; i < matchingQuakes.Length; i++)
                            {
                                taskContext.DeleteObject(matchingQuakes [i]);
                            }

                            quake = matchingQuakes [0];
                            break;
                        }

                        var result          = featuresBatchArray.GetItem <NSDictionary> ((nuint)k);
                        var quakeDictionary = (NSDictionary)result.ObjectForKey((NSString)"properties");
                        quake.UpdateFromDictionary(quakeDictionary);
                    }

                    if (!taskContext.Save(out anyError))
                    {
                        Console.WriteLine("Error saving batch: {0}", anyError.LocalizedDescription);
                        return;
                    }

                    taskContext.Reset();
                }

                // Bounce back to the main queue to reload the table view and reenable the fetch button.
                NSOperationQueue.MainQueue.AddOperation(() => {
                    ReloadTableView();
                    fetchQuakesButton.Enabled = true;
                });
            });

            task.Resume();
        }
        // Performs a Userinfo API call using OIDAuthState.withFreshTokensPerformAction.
        partial void Userinfo(UIButton sender)
        {
            var userinfoEndpoint = AuthState.LastAuthorizationResponse.Request.Configuration.DiscoveryDocument.UserinfoEndpoint;

            if (userinfoEndpoint == null)
            {
                Console.WriteLine($"Userinfo endpoint not declared in discovery document");
                return;
            }

            var currentAccessToken = AuthState.LastTokenResponse.AccessToken;

            Console.WriteLine($"Performing userinfo request");

            AuthState.PerformWithFreshTokens(async(accessToken, idToken, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine($"Error fetching fresh tokens: {error.LocalizedDescription}");
                    return;
                }

                // log whether a token refresh occurred
                if (currentAccessToken != accessToken)
                {
                    Console.WriteLine($"Access token was refreshed automatically ({currentAccessToken} to {accessToken})");
                }
                else
                {
                    Console.WriteLine($"Access token was fresh and not updated {accessToken}");
                }

                // creates request to the userinfo endpoint, with access token in the Authorization header
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // performs HTTP request
                var response = await httpClient.GetAsync(userinfoEndpoint);
                var content  = await response.Content.ReadAsStringAsync();
                NSError deserializeError;
                var data = (NSDictionary)NSJsonSerialization.Deserialize(NSData.FromString(content), 0, out deserializeError);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"Success: {content}");

                    new UIAlertView("OpenID AppAuth", $"Hello, {data["name"]}!", null, "Hi").Show();
                }
                else
                {
                    // server replied with an error

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        // "401 Unauthorized" generally indicates there is an issue with the authorization
                        // grant. Puts OIDAuthState into an error state.
                        var authError = ErrorUtilities.CreateResourceServerAuthorizationError(0, data, error);
                        AuthState.Update(authError);
                        // log error
                        Console.WriteLine($"Authorization Error ({authError}). Response: {content}");
                    }
                    else
                    {
                        // log error
                        Console.WriteLine($"HTTP Error ({response.StatusCode}). Response: {content}");
                    }
                }
            });
        }
Esempio n. 4
0
        public void registerCallForWallets(int wallet, Action completionHandler)
        {
            //#internal_code_section_start
            var merchantURL = new String(@"https://api-gateway-pp.nets.eu/pia/test/merchantdemo/v2/payment/12002835/register");
            //#internal_code_section_end

            /*#external_code_section_start
             * var merchantURL = @"YOUR MERCHANT BACKEND URL HERE";
             #external_code_section_end*/

            NSMutableDictionary jsonDictionary = new NSMutableDictionary();
            NSMutableDictionary amount         = new NSMutableDictionary();
            NSMutableDictionary method         = new NSMutableDictionary();

            amount.SetValueForKey(new NSNumber(1000), new NSString(@"totalAmount"));
            amount.SetValueForKey(new NSNumber(200), new NSString(@"vatAmount"));
            method.SetValueForKey(new NSNumber(0), new NSString(@"fee"));
            switch (wallet)
            {
            case (int)MobileWallet.Vipps:
            {
                amount.SetValueForKey(new NSString(@"NOK"), new NSString(@"currencyCode"));
                method.SetValueForKey(new NSString(@"Vipps"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"Vipps"), new NSString(@"displayName"));
                //#internal_code_section_start
                jsonDictionary.SetValueForKey(new NSString(@"+4748059560"), new NSString(@"phoneNumber"));
                //#internal_code_section_end

                /*#external_code_section_start
                 * jsonDictionary.SetValueForKey(new NSString(@"+471111..."), new NSString(@"phoneNumber"));
                 #external_code_section_end*/
                break;
            }

            case (int)MobileWallet.Swish:
            {
                amount.SetValueForKey(new NSString(@"SEK"), new NSString(@"currencyCode"));
                method.SetValueForKey(new NSString(@"SwishM"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"Swish"), new NSString(@"displayName"));
                break;
            }

            default: break;
            }

            jsonDictionary.SetValueForKey(amount, new NSString(@"amount"));
            jsonDictionary.SetValueForKey(method, new NSString(@"method"));
            jsonDictionary.SetValueForKey(new NSString(@"000011"), new NSString(@"customerId"));
            jsonDictionary.SetValueForKey(new NSString(@"PiaSDK-iOS-xamarin"), new NSString(@"orderNumber"));
            jsonDictionary.SetValueForKey(new NSNumber(false), new NSString(@"storeCard"));


            //#internal_code_section_start
            jsonDictionary.SetValueForKey(new NSString("eu.nets.pia.xamarin://piasdk"), new NSString(@"redirectUrl"));
            //#internal_code_section_end

            /*#external_code_section_start
             * jsonDictionary.SetValueForKey(new NSString("YOUR_APP_SCHEME_URL://piasdk"), new NSString(@"redirectUrl"));
             #external_code_section_end*/



            if (NSJsonSerialization.IsValidJSONObject(jsonDictionary))
            {
                NSError             error1   = null;
                NSData              jsonData = NSJsonSerialization.Serialize(jsonDictionary, NSJsonWritingOptions.PrettyPrinted, out error1);
                NSUrl               url      = new NSUrl(merchantURL);
                NSMutableUrlRequest request  = new NSMutableUrlRequest(url, NSUrlRequestCachePolicy.UseProtocolCachePolicy, 30.0);
                request.HttpMethod = @"POST";
                NSMutableDictionary dic = new NSMutableDictionary();
                dic.Add(new NSString("Content-Type"), new NSString("application/json;charset=utf-8;version=2.0"));
                dic.Add(new NSString("Accept"), new NSString("application/json;charset=utf-8;version=2.0"));
                request.Headers = dic;
                request.Body    = jsonData;

                NSError          error2  = null;
                NSUrlSession     session = NSUrlSession.SharedSession;
                NSUrlSessionTask task    = session.CreateDataTask(request, (data, response, error) =>
                {
                    if (data.Length > 0 && error == null)
                    {
                        NSDictionary resultsDictionary = (Foundation.NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.MutableLeaves, out error2);
                        if (resultsDictionary[@"transactionId"] != null && resultsDictionary[@"walletUrl"] != null)
                        {
                            NSString transactionId = (Foundation.NSString)resultsDictionary[@"transactionId"];
                            NSString walletURL     = (Foundation.NSString)resultsDictionary[@"walletUrl"];
                            transactionInfo        = new NPITransactionInfo(walletURL);
                        }
                        else
                        {
                            transactionInfo = null;
                        }
                        completionHandler();
                    }
                    else
                    {
                        transactionInfo = null;
                        completionHandler();
                    }
                });

                task.Resume();
            }
        }
Esempio n. 5
0
        public void getTransactionInfo(bool payWithPayPal, Action completionHandler)
        {
            //#internal_code_section_start
            var merchantURL = new String(@"");

            if (payWithPayPal)
            {
                merchantURL = @"https://api-gateway-pp.nets.eu/pia/merchantdemo/v2/payment/493809/register";
            }
            else
            {
                merchantURL = @"https://api-gateway-pp.nets.eu/pia/test/merchantdemo/v2/payment/12002835/register";
            }

            //#internal_code_section_end

            /*#external_code_section_start
             * var merchantURL = @"YOUR MERCHANT BACKEND URL HERE";
             #external_code_section_end*/

            NSMutableDictionary jsonDictionary = new NSMutableDictionary();

            if (payWithPayPal == false)
            {
                NSMutableDictionary amount = new NSMutableDictionary();
                amount.SetValueForKey(new NSNumber(1000), new NSString(@"totalAmount"));
                amount.SetValueForKey(new NSNumber(200), new NSString(@"vatAmount"));
                amount.SetValueForKey(new NSString(@"EUR"), new NSString(@"currencyCode"));

                jsonDictionary.SetValueForKey(amount, new NSString(@"amount"));
            }
            else
            {
                NSMutableDictionary amount = new NSMutableDictionary();
                amount.SetValueForKey(new NSNumber(1000), new NSString(@"totalAmount"));
                amount.SetValueForKey(new NSNumber(0), new NSString(@"vatAmount"));
                amount.SetValueForKey(new NSString(@"DKK"), new NSString(@"currencyCode"));

                jsonDictionary.SetValueForKey(amount, new NSString(@"amount"));
            }

            jsonDictionary.SetValueForKey(new NSString(@"000011"), new NSString(@"customerId"));
            jsonDictionary.SetValueForKey(new NSString(@"PiaSDK-iOS-xamarin"), new NSString(@"orderNumber"));
            jsonDictionary.SetValueForKey(new NSNumber(true), new NSString(@"storeCard"));

            if (payWithPayPal)
            {
                NSMutableDictionary method = new NSMutableDictionary();
                method.SetValueForKey(new NSString(@"PayPal"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"PayPal"), new NSString(@"displayName"));
                method.SetValueForKey(new NSNumber(0), new NSString(@"fee"));
                jsonDictionary.SetValueForKey(method, new NSString(@"method"));
            }

            if (isPayingWithToken)
            {
                // Make sure you have a saved card in your backend.
                NSMutableDictionary method = new NSMutableDictionary();
                method.SetValueForKey(new NSString(@"EasyPayment"), new NSString(@"id"));
                method.SetValueForKey(new NSString(@"Easy Payment"), new NSString(@"displayName"));
                method.SetValueForKey(new NSNumber(0), new NSString(@"fee"));
                jsonDictionary.SetValueForKey(method, new NSString(@"method"));
                jsonDictionary.SetValueForKey(new NSString(@"492500******0004"), new NSString(@"cardId"));
            }

            if (NSJsonSerialization.IsValidJSONObject(jsonDictionary))
            {
                NSError             error1   = null;
                NSData              jsonData = NSJsonSerialization.Serialize(jsonDictionary, NSJsonWritingOptions.PrettyPrinted, out error1);
                NSUrl               url      = new NSUrl(merchantURL);
                NSMutableUrlRequest request  = new NSMutableUrlRequest(url, NSUrlRequestCachePolicy.UseProtocolCachePolicy, 30.0);
                request.HttpMethod = @"POST";
                NSMutableDictionary dic = new NSMutableDictionary();
                dic.Add(new NSString("Content-Type"), new NSString("application/json;charset=utf-8;version=2.0"));
                dic.Add(new NSString("Accept"), new NSString("application/json;charset=utf-8;version=2.0"));
                request.Headers = dic;
                request.Body    = jsonData;

                NSError          error2  = null;
                NSUrlSession     session = NSUrlSession.SharedSession;
                NSUrlSessionTask task    = session.CreateDataTask(request, (data, response, error) =>
                {
                    if (data.Length > 0 && error == null)
                    {
                        NSDictionary resultsDictionary = (Foundation.NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.MutableLeaves, out error2);
                        if (resultsDictionary[@"transactionId"] != null && resultsDictionary[@"redirectOK"] != null)
                        {
                            NSString transactionId = (Foundation.NSString)resultsDictionary[@"transactionId"];
                            NSString redirectOK    = (Foundation.NSString)resultsDictionary[@"redirectOK"];
                            transactionInfo        = new NPITransactionInfo(transactionId, redirectOK);
                        }
                        else
                        {
                            transactionInfo = null;
                        }
                        completionHandler();
                    }
                    else
                    {
                        transactionInfo = null;
                        completionHandler();
                    }
                });

                task.Resume();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Obtengo ciudad de SQLite o del servidor.
        /// </summary>
        public void GetDataCiudad()
        {
            // Ciudad
            Ciudad c;

            // Obtengo ciudad
            c = SQLiteManager.Connection().GetCiudad(ID_Ciudad);

            // Compruebo datos
            if (c == null)
            {
                // Obtengo ciudad del servidor
                RestManager.Connection().GetData((int)URIS.GetCiudad, new string[] { ID_Ciudad.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_ciudad":
                                ID_Ciudad = (int)(NSNumber)data.ValueForKey(key);
                                break;

                            case "id_provincia":
                                ID_Provincia = (int)(NSNumber)data.ValueForKey(key);
                                break;

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

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

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

                // Espero
                lock (l)
                {
                    Monitor.Wait(l);
                }
            }
            else
            {
                // Cargo nombre
                Nombre_Ciudad = c.Nombre_Ciudad;

                // Cargo ID provincia
                ID_Provincia = c.ID_Provincia;
            }

            // Obtengo datos provincia
            GetDataProvincia();
        }