public ContactChooserPage()
        {
            InitializeComponent();

            // Create contacts
            contacts = new Contacts();

            // Set progress text and show
            ProgressIndicator.Text = Mowbly.GetString(Constants.STRING_CONTACTS_LOADING);
            ShowProgress();

            // Initialize empty groups
            InitGroups();
        }
Esempio n. 2
0
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            string callbackId = message.CallbackId;

            switch (message.Method)
            {
            case "request":
                try
                {
                    // Read args
                    HttpOptions options =
                        JsonConvert.DeserializeObject <HttpOptions>(message.Args[0].ToString());

                    // Check network available
                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        await Request(options, callbackId);
                    }
                    else
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = Mowbly.GetString(Constants.STRING_NO_CONNECTIVITY)
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("Error in Http request. Reason - " + e.Message);
                    InvokeCallbackJavascript(callbackId, new MethodResult
                    {
                        Code  = MethodResult.FAILURE_CODE,
                        Error = new MethodError
                        {
                            Message = e.Message
                        }
                    });
                }

                break;

            default:
                Logger.Error("Feature " + Name + " does not support method " + message.Method);
                break;
            }
        }
        public void OnLoaded(object sender, RoutedEventArgs e)
        {
            string param = String.Empty;
            string type  = String.Empty;

            NavigationContext.QueryString.TryGetValue(KEY_PARAM, out param);
            NavigationContext.QueryString.TryGetValue(KEY_TYPE, out type);

            if (param != String.Empty && type != String.Empty)
            {
                Contacts contacts = new Contacts();
                contacts.SearchCompleted += OnContactsSearchCompleted;
                switch (type)
                {
                case "phone":
                    contacts.SearchAsync(param, FilterKind.PhoneNumber, null);
                    break;

                case "name":
                    contacts.SearchAsync(param, FilterKind.DisplayName, null);
                    break;

                case "email":
                    contacts.SearchAsync(param, FilterKind.EmailAddress, null);
                    break;

                case "none":
                    ContactName.Text = Mowbly.GetString(Constants.STRING_CONTACT_SEARCH_PARAM_MISSING);
                    break;
                }
            }
            else
            {
                ContactName.Text = Mowbly.GetString(Constants.STRING_CONTACT_SEARCH_PARAM_MISSING);
            }
        }
        void onTransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            if (TransferStatusChanged != null)
            {
                TransferStatusChanged(sender, e);
            }

            BackgroundTransferRequest request = e.Request;

            switch (request.TransferStatus)
            {
            case TransferStatus.Completed:
                if (request.StatusCode == 200 || request.StatusCode == 206)
                {
                    if (TransferSuccess != null)
                    {
                        TransferSuccess(sender, e);
                    }
                }
                else
                {
                    if (TransferError != null)
                    {
                        TransferError(sender,
                                      new MowblyBackgroundTransferEventArgs(
                                          e, e.Request.StatusCode.ToString()));
                    }
                }

                // Remove the request from queue
                Remove(request);
                break;

            case TransferStatus.Unknown:
            case TransferStatus.None:
                // Unknown status, request is not usable. Remove from queue.
                Logger.Error("Request [" + e.Request.RequestUri + "] has gone into status - " + request.TransferStatus);
                Remove(request);
                if (TransferError != null)
                {
                    TransferError(sender,
                                  new MowblyBackgroundTransferEventArgs(
                                      e, Mowbly.GetString(Constants.STRING_UNKNOWN_ERROR)));
                }
                break;

            case TransferStatus.Waiting:
            case TransferStatus.WaitingForExternalPower:
            case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
            case TransferStatus.WaitingForNonVoiceBlockingNetwork:
            case TransferStatus.WaitingForWiFi:
                Logger.Error("Request [" + e.Request.RequestUri + "] has gone into status - " + request.TransferStatus);
                Remove(request);
                if (TransferError != null)
                {
                    TransferError(sender,
                                  new MowblyBackgroundTransferEventArgs(
                                      e, Mowbly.GetString(Constants.STRING_BACKGROUND_TRANSFER_WAITING)));
                }
                break;

            case TransferStatus.Paused:
                Logger.Debug("Request [" + e.Request.RequestUri + "] paused");
                break;
            }
        }
        private void OnContactsSearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            try
            {
                IEnumerator <Contact> contacts = e.Results.GetEnumerator();
                if (contacts.MoveNext())
                {
                    Contact contact = contacts.Current;
                    List <ContactDetail> details = new List <ContactDetail>();
                    ContactDetail.Type   type;
                    string value;
                    string kind;

                    // Name & NickName
                    CompleteName name = contact.CompleteName;
                    if (name != null)
                    {
                        string cName = name.Title + " " + name.FirstName + " " + name.MiddleName + " " + name.LastName;
                        ContactName.Text = cName.ToUpper();
                    }
                    else
                    {
                        ContactName.Text = contact.DisplayName;
                    }

                    // Photos
                    Stream stream = contact.GetPicture();
                    if (stream == null)
                    {
                        Picture.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        BitmapImage img = new BitmapImage();
                        img.SetSource(stream);
                        Picture.Source = img;
                    }

                    // Phones
                    type = ContactDetail.Type.Phone;
                    foreach (ContactPhoneNumber phoneNumber in contact.PhoneNumbers)
                    {
                        if (phoneNumber.PhoneNumber != null)
                        {
                            value = phoneNumber.PhoneNumber;
                            kind  = phoneNumber.Kind.ToString();
                            details.Add(new ContactDetail(type, value, kind));

                            // Sms, if mobile
                            if (phoneNumber.Kind == PhoneNumberKind.Mobile)
                            {
                                details.Add(new ContactDetail(ContactDetail.Type.Sms, value, kind));
                            }
                        }
                    }

                    // Urls
                    type = ContactDetail.Type.Website;
                    foreach (string website in contact.Websites)
                    {
                        value = website;
                        kind  = String.Empty;
                    }

                    // Emails
                    type = ContactDetail.Type.Email;
                    foreach (ContactEmailAddress email in contact.EmailAddresses)
                    {
                        value = email.EmailAddress;
                        kind  = email.Kind.ToString().ToLower();

                        details.Add(new ContactDetail(type, value, kind));
                    }

                    // Organizations
                    IEnumerator <ContactCompanyInformation> companies = contact.Companies.GetEnumerator();
                    ContactCompanyInformation company;
                    while (companies.MoveNext())
                    {
                        company = (ContactCompanyInformation)companies.Current;

                        if (company.CompanyName != null)
                        {
                            type  = ContactDetail.Type.Company;
                            value = company.CompanyName;
                            kind  = String.Empty;
                            details.Add(new ContactDetail(type, value, kind));
                        }

                        if (company.JobTitle != null)
                        {
                            type  = ContactDetail.Type.JobTitle;
                            value = company.JobTitle;
                            kind  = String.Empty;
                            details.Add(new ContactDetail(type, value, kind));
                        }
                    }

                    // Address
                    type = ContactDetail.Type.Address;
                    foreach (ContactAddress address in contact.Addresses)
                    {
                        CivicAddress ca = address.PhysicalAddress;
                        // Street, City, PostalCode, Region, Country
                        value = ca.AddressLine1 + " " + ca.AddressLine2 + " " + ca.Building + "\n" +
                                ca.City + " " + ca.StateProvince + " " + ca.PostalCode + "\n" +
                                ca.CountryRegion;
                        kind = address.Kind.ToString();

                        details.Add(new ContactDetail(type, value, kind));
                    }

                    // Display the data
                    DetailsList.DataContext = details;
                }
                else
                {
                    ContactName.Text        = Mowbly.GetString(Constants.STRING_CONTACT_NOT_FOUND);
                    ContactAccounts.Text    = "";
                    Picture.Visibility      = System.Windows.Visibility.Collapsed;
                    DetailsList.DataContext = null;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to view contact.Reason: " + ex.Message);
            }
        }
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            string callbackId = message.CallbackId;

            try
            {
                // Variables
                SqliteConnection connection;
                DBConfig         dbConfig;
                DbTransaction    transaction;
                string           connectionId, query, queryId;
                long             dbSize;
                JObject          o;

                switch (message.Method)
                {
                case "openDatabase":

                    string    dbName     = message.Args[0] as string;
                    Int64     dblevel    = (Int64)message.Args[1];
                    FileLevel level      = (FileLevel)dblevel;
                    Int64     version    = (Int64)message.Args[2];
                    float     dbVersion  = (float)version;
                    string    dbPassword = message.Args[3] as string;
                    string    dbPath     = null;
                    if (dbName.Equals(Mowbly.GetProperty <string>(Constants.PROPERTY_LOGS_DB)))
                    {
                        dbPath = Mowbly.LogDatabaseFile;
                        if (!FileManager.FileExists(dbPath))
                        {
                            FileManager.CreateFile(dbPath);
                        }
                    }
                    else
                    {
                        dbPath = FileManager.GetAbsolutePath(new FilePath
                        {
                            Path        = Path.Combine(Constants.DIR_DB, String.Concat(dbName, dbVersion.ToString())),
                            Level       = level,
                            StorageType = StorageType.Internal
                        });
                    }

                    dbSize = FileManager.GetFileSize(dbPath);

                    // Create new connection
                    try
                    {
                        connection = new SqliteConnection();
                        connection.ConnectionString = DBUtils.GetConnectionString(dbPath, dbPassword);
                        connection.Open();
                        connectionId = Guid.NewGuid().ToString();
                        dbConfigDict.Add(connectionId, new DBConfig
                        {
                            DBName     = dbName,
                            DBVersion  = dbVersion,
                            DBPath     = dbPath,
                            DBPassword = dbPassword,
                            Connection = connection
                        });

                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = connectionId
                        });
                    }
                    catch (SqliteException se)
                    {
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_DATABASE_OPEN_ERROR), se.Message);
                        Logger.Error(error);
                        JToken  opt = message.Args[0] as JToken;
                        string  Id  = opt["queryId"].ToObject <string>();
                        JObject obj = new JObject();
                        obj.Add("queryId", Id);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = obj,
                            Error  = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                case "executeQuery":

                    // Get connection id
                    JToken options = message.Args[0] as JToken;
                    connectionId = options["id"].ToObject <string>();
                    dbConfig     = dbConfigDict[connectionId];

                    // Read args
                    queryId = options["queryId"].ToObject <string>();
                    query   = options["sql"].ToObject <string>().Trim();
                    List <object> queryParams = options["params"].ToObject <List <object> >();

                    // Execute query
                    try
                    {
                        JArray data         = null;
                        int    rowsAffected = 0;
                        connection = dbConfig.Connection;

                        // Throw exception is connection is null
                        if (connection == null)
                        {
                            throw new ArgumentException(Mowbly.GetString(Constants.STRING_DATABASE_NO_CONNECTION_OPEN_ERROR));
                        }

                        // Execute query
                        if (query.ToLower().StartsWith("select"))
                        {
                            data = ProcessSelectQuery(ref connection, query, queryParams);
                        }
                        else
                        {
                            rowsAffected = ProcessNonQuery(ref connection, query, queryParams);
                        }

                        // Create result
                        o = new JObject();
                        o.Add("queryId", queryId);

                        JObject d = new JObject();
                        d.Add("rowsAffected", rowsAffected);
                        d.Add("insertId", connection.LastInsertRowId);
                        d.Add("rows", data);
                        o.Add("data", d);

                        // Notify JS
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = o
                        });
                    }
                    catch (SqliteException se)
                    {
                        // Error
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_DATABASE_QUERY_ERROR), se.Message);
                        Logger.Error(error);

                        // Create result
                        o = new JObject();
                        o.Add("queryId", queryId);

                        // Notify Js
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = o,
                            Error  = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                case "beginTransaction":

                    connectionId = message.Args[0] as string;
                    dbConfig     = dbConfigDict[connectionId];

                    // Begin transaction
                    try
                    {
                        connection = dbConfig.Connection;
                        // Throw exception is connection is null
                        if (connection == null)
                        {
                            throw new ArgumentException(Mowbly.GetString(Constants.STRING_DATABASE_NO_CONNECTION_OPEN_ERROR));
                        }

                        transaction          = connection.BeginTransaction();
                        dbConfig.Transaction = transaction;

                        // Notify JS
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (SqliteException se)
                    {
                        // Error; Notify JS
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_DATABASE_TRANSACTION_ERROR), se.Message);
                        Logger.Error(error);
                        JToken  opt = message.Args[0] as JToken;
                        string  Id  = opt["queryId"].ToObject <string>();
                        JObject obj = new JObject();
                        obj.Add("queryId", Id);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = obj,
                            Error  = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                case "commit":

                    connectionId = message.Args[0] as string;
                    dbConfig     = dbConfigDict[connectionId];

                    // Commit transaction
                    try
                    {
                        transaction = dbConfig.Transaction;
                        // Throw exception is transaction is null
                        if (transaction == null)
                        {
                            throw new ArgumentException(Mowbly.GetString(Constants.STRING_DATABASE_NO_TRANSACTION_ACTIVE_ERROR));
                        }
                        transaction.Commit();

                        queryId      = message.Args[1] as string;
                        o            = new JObject();
                        o["queryId"] = queryId;
                        o["data"]    = true;

                        // Notify JS
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = o
                        });
                    }
                    catch (SqliteException se)
                    {
                        // Error; Notify JS
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_DATABASE_TRANSACTION_ERROR), se.Message);
                        Logger.Error(error);
                        JToken  opt = message.Args[0] as JToken;
                        string  Id  = opt["queryId"].ToObject <string>();
                        JObject obj = new JObject();
                        obj.Add("queryId", Id);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = obj,
                            Error  = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                case "rollback":

                    connectionId = message.Args[0] as string;
                    dbConfig     = dbConfigDict[connectionId];

                    // Commit transaction
                    try
                    {
                        transaction = dbConfig.Transaction;
                        transaction.Rollback();

                        queryId      = message.Args[1] as string;
                        o            = new JObject();
                        o["queryId"] = queryId;
                        o["data"]    = true;

                        // Notify JS
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = o
                        });
                    }
                    catch (SqliteException se)
                    {
                        // Error; Notify JS
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_DATABASE_TRANSACTION_ERROR), se.Message);
                        Logger.Error(error);
                        JToken  opt = message.Args[0] as JToken;
                        string  Id  = opt["queryId"].ToObject <string>();
                        JObject obj = new JObject();
                        obj.Add("queryId", Id);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = obj,
                            Error  = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                default:
                    Logger.Error("Feature " + Name + " does not support method " + message.Method);
                    break;
                }
            }
            catch (Exception e)
            {
                // Error; Notify JS
                string error = String.Concat(Mowbly.GetString(Constants.STRING_DATABASE_OPERATION_ERROR), e.Message);
                Logger.Error(error);
                JToken  opt = message.Args[0] as JToken;
                string  Id  = opt["queryId"].ToObject <string>();
                JObject obj = new JObject();
                obj.Add("queryId", Id);
                InvokeCallbackJavascript(callbackId, new MethodResult
                {
                    Code   = MethodResult.FAILURE_CODE,
                    Result = obj,
                    Error  = new MethodError
                    {
                        Message = error
                    }
                });
            }
            await Task.FromResult(0);
        }
Esempio n. 7
0
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            string callbackId = message.CallbackId;

            switch (message.Method)
            {
            case "getActiveNetwork":
                Tuple <NetworkType, string> activeNetwork = GetActiveNetwork();
                InvokeCallbackJavascript(callbackId, new MethodResult
                {
                    Code   = (int)activeNetwork.Item1,
                    Result = activeNetwork.Item2
                });
                break;

            case "isHostReachable":
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    string url     = message.Args[0] as string;
                    long   timeout = (long)message.Args[1];
                    try
                    {
                        using (HttpClient httpClient = new HttpClient())
                        {
                            httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                            HttpResponseMessage response = await httpClient.GetAsync(new Uri(url));

                            int code = MethodResult.SUCCESS_CODE;
                            if (response.StatusCode != HttpStatusCode.OK)
                            {
                                code = MethodResult.FAILURE_CODE;
                            }
                            InvokeCallbackJavascript(callbackId, new MethodResult
                            {
                                Code   = code,
                                Result = (response.StatusCode != HttpStatusCode.NotFound)
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Error checking reachability of host. Reason - " + e.Message);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                }
                else
                {
                    string error = Mowbly.GetString(Constants.STRING_NO_CONNECTIVITY);
                    InvokeCallbackJavascript(callbackId, new MethodResult
                    {
                        Code  = MethodResult.FAILURE_CODE,
                        Error = new MethodError
                        {
                            Message = error
                        }
                    });
                }
                break;

            default:
                Logger.Error("Feature " + Name + " does not support method " + message.Method);
                break;
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            string callbackId = message.CallbackId;

            FilePath options =
                JsonConvert.DeserializeObject <FilePath>(message.Args[message.Args.Length - 1].ToString());

            // Set the file path in FilePath options
            // Normal file operations get path as first parameter and options as second
            // Unzip method receives a file object with path in it already.
            if (!message.Method.Equals("unzip"))
            {
                options.Path = message.Args[0] as string;
            }


            string path;

            try
            {
                switch (message.Method)
                {
                case "deleteDirectory":
                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Delete directory
                    try
                    {
                        FileManager.DeleteDirectory(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "deleteFile":

                    // Get the absolute path
                    //Open : Ask
                    path = FileManager.GetAbsolutePath(options, false);

                    // Delete file
                    try
                    {
                        FileManager.DeleteFile(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "getDirectory":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Create directory
                    try
                    {
                        FileManager.CreateDirectory(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "getFile":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Create file
                    try
                    {
                        FileManager.CreateFile(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "getFilesJSONString":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Get files list
                    Tuple <bool, List <Dictionary <string, object> >, string> getFilesResult =
                        await FileManager.GetFoldersAndFilesAsync(path, options.StorageType);

                    if (getFilesResult.Item1)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Result = getFilesResult.Item2
                        });
                    }
                    else
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = getFilesResult.Item3
                            }
                        });
                    }
                    break;

                case "getRootDirectory":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Return root directory
                    InvokeCallbackJavascript(callbackId, new MethodResult {
                        Result = path
                    });
                    break;

                case "read":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Read file
                    try
                    {
                        string fileContentStr = FileManager.ReadAsString(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = fileContentStr
                        });
                    }
                    catch (Exception e)
                    {
                        Logger.Error("File not found" + e.Message);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = Mowbly.GetString(Constants.STRING_FILE_NOT_FOUND)
                            }
                        });
                    }
                    break;

                case "readData":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Read file
                    try
                    {
                        string fileContentData = Convert.ToBase64String(FileManager.ReadAsBytes(path));
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = fileContentData
                        });
                    }
                    catch (Exception e)
                    {
                        Logger.Error("File not found" + e.Message);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = Mowbly.GetString(Constants.STRING_FILE_NOT_FOUND)
                            }
                        });
                    }
                    break;

                case "testDirExists":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Test dir exists
                    try
                    {
                        bool isDirExists = FileManager.DirectoryExists(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = isDirExists
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "testFileExists":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Test file exists
                    try
                    {
                        bool isFileExists = FileManager.FileExists(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = isFileExists
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "unzip":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Source file
                    FilePath srcFileOptions = JsonConvert.DeserializeObject <FilePath>(message.Args[0].ToString());
                    string   srcFilePath    = FileManager.GetAbsolutePath(srcFileOptions, false);

                    if (!FileManager.FileExists(srcFilePath))
                    {
                        throw new Exception(Mowbly.GetString(Constants.STRING_FILE_NOT_FOUND));
                    }

                    // Unzip
                    try
                    {
                        FileManager.unzip(srcFilePath, path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "write":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Write content to file
                    try
                    {
                        string fileContentStr      = message.Args[1] as string;
                        bool   shouldAppendContent = (bool)message.Args[2];
                        FileManager.WriteStringToFile(path, fileContentStr, shouldAppendContent);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "writeData":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Write content to file
                    try
                    {
                        byte[] fileContentBytes    = Convert.FromBase64String(message.Args[0] as string);
                        bool   shouldAppendContent = (bool)message.Args[1];
                        FileManager.WriteDataToFile(path, fileContentBytes, shouldAppendContent);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                default:
                    Logger.Error("Feature " + Name + " does not support method " + message.Method);
                    break;
                }
            }
            catch (Exception ce)
            {
                Logger.Error("Exception occured. Reason - " + ce.Message);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            switch (message.Method)
            {
            case "getPicture":
                int           source  = Convert.ToInt32(message.Args[0]);
                CameraOptions options =
                    JsonConvert.DeserializeObject <CameraOptions>(message.Args[1].ToString());
                string callbackId = message.CallbackId;
                try
                {
                    if (source == (int)Camera.Source.CAMERA)
                    {
                        FilePath filePath         = options.FilePath;
                        bool     isWriteToGallery = (filePath == null);
                    }

                    // Create the CameraTask
                    CameraTask cameraTask;
                    if (source == (int)Camera.Source.CAMERA)
                    {
                        Logger.Debug("Launching camera...");
                        cameraTask = new MowblyCameraCaptureTask(callbackId, options);
                    }
                    else
                    {
                        Logger.Debug("Launching photo chooser...");
                        cameraTask = new MowblyPhotoChooserTask(callbackId, options);
                    }

                    // Subscribe to CameraTask Completed event
                    cameraTask.Completed += OnCameraTaskCompleted;

                    // Show the CameraTask
                    UiDispatcher.BeginInvoke(() =>
                    {
                        cameraTask.Show();
                    });

                    // Make a note that app is navigated to external task
                    Mowbly.AppNavigatedToExternalPage = true;
                }
                catch (Exception ce)
                {
                    Logger.Error("Exception has occured. Reason - " + ce.Message);
                }

                break;

            case "getConfiguration":
                List <CameraConfig> cameraConfigList = await GetCameraConfigurations();

                MethodResult result = cameraConfigList.Count > 0 ?
                                      new MethodResult
                {
                    Result = cameraConfigList
                } :
                new MethodResult
                {
                    Code  = MethodResult.FAILURE_CODE,
                    Error = new MethodError
                    {
                        Message = Mowbly.GetString(Constants.STRING_CAMERA_INITIALIZATION_ERROR)
                    }
                };
                InvokeCallbackJavascript(message.CallbackId, result);
                break;

            default:
                Logger.Error("Feature " + Name + " does not support method " + message.Method);
                break;
            }
        }
Esempio n. 10
0
        // Event handler called when the camera capture task is completed
        private void OnCameraTaskCompleted(object sender, PhotoResult e)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();
            bool       status     = false;
            string     error      = String.Empty;
            CameraTask cameraTask = sender as CameraTask;
            string     callbackId = cameraTask.CallbackId;

            if (e.TaskResult == TaskResult.OK)
            {
                if (e.Error == null)
                {
                    CameraOptions options  = cameraTask.Options;
                    string        filePath = (options.FilePath != null) ?
                                             FileManager.GetAbsolutePath(options.FilePath) :
                                             FileManager.GetAbsolutePath(new FilePath
                    {
                        Path        = Path.GetFileName(e.OriginalFileName),
                        Level       = FileLevel.App,
                        StorageType = StorageType.Cache
                    });
                    result.Add(KEY_PATH, filePath);


                    if (cameraTask.Type == CameraTaskType.PhotoChooser || options.ReadData)
                    {
                        // Load the image as bitmap to know dimensions
                        BitmapImage bi = new BitmapImage();
                        bi.SetSource(e.ChosenPhoto);
                        int imgWidth  = bi.PixelWidth;
                        int imgHeight = bi.PixelHeight;

                        // Get the target dimensions with user requested width/height
                        int width, height;
                        if (options.Width == -1)
                        {
                            if (options.Height == -1)
                            {
                                // Auto width and height. Do nothing.
                                height = imgHeight;
                                width  = imgWidth;
                            }
                            else
                            {
                                // Auto width, scale by height
                                float scale = imgHeight / options.Height;
                                width  = (int)(imgWidth * scale);
                                height = options.Height;
                            }
                        }
                        else
                        {
                            if (options.Height == -1)
                            {
                                // Auto height, scale by width
                                float scale = imgWidth / options.Width;
                                height = (int)(imgHeight * scale);
                                width  = options.Width;
                            }
                            else
                            {
                                // User provided required dimensions. Scale to them.
                                height = options.Height;
                                width  = options.Width;
                            }
                        }

                        // Format the image as specified in options
                        // Though width and height can be same as the captured image,
                        // formatting is required as quality might be different
                        try
                        {
                            e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
                            byte[] data = FormatImage(e.ChosenPhoto, width, height, options.Quality);
                            if (data != null)
                            {
                                try
                                {
                                    // Write to File
                                    FileManager.WriteDataToFile(filePath, data, false);

                                    // Set data in result
                                    if (options.ReadData)
                                    {
                                        result.Add(KEY_DATA, Convert.ToBase64String(data));
                                    }
                                    status = true;
                                }
                                catch (Exception ex)
                                {
                                    // Error writing picture
                                    error = String.Concat(Mowbly.GetString(Constants.STRING_CAMERA_WRITE_PICTURE_ERROR), ex.Message);
                                }
                            }
                            {
                                // Error in formatting picture
                                error = Mowbly.GetString(Constants.STRING_CAMERA_FORMAT_ERROR);
                            }
                        }
                        catch (Exception ex)
                        {
                            // Error formatting picture
                            error = String.Concat(Mowbly.GetString(Constants.STRING_CAMERA_PROCESS_PICTURE_ERROR), ex.Message);
                        }
                    }
                    else
                    {
                        try
                        {
                            // Choose pic with no read
                            FileManager.WriteDataToFile(filePath, e.ChosenPhoto, false);

                            status = true;
                        }
                        catch (Exception ex)
                        {
                            // Error writing picture
                            error = String.Concat(Mowbly.GetString(Constants.STRING_CAMERA_WRITE_PICTURE_ERROR), ex.Message);
                        }
                    }
                }
                else
                {
                    // Error in capturing picture
                    error = String.Concat(Mowbly.GetString(Constants.STRING_CAMERA_CAPTURE_ERROR), e.Error.Message);
                }
            }
            else
            {
                // User cancelled the task
                error = Mowbly.GetString(Constants.STRING_ACTIVITY_CANCELLED);
            }

            if (status)
            {
                InvokeCallbackJavascript(callbackId, new MethodResult
                {
                    Result = result
                });
            }
            else
            {
                Logger.Error(error);
                InvokeCallbackJavascript(callbackId, new MethodResult
                {
                    Code  = MethodResult.FAILURE_CODE,
                    Error = new MethodError
                    {
                        Message = error
                    }
                });
            }
            Logger.Debug(cameraTask.Name + " completed");
        }
Esempio n. 11
0
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            string        callbackId = message.CallbackId;
            List <string> properties = null;

            try
            {
                switch (message.Method)
                {
                case "callContact":

                    Logger.Info("Calling contact...");

                    // Get the phone number
                    string phonenumber = message.Args[0] as string;

                    // Create and show the PhoneCall task
                    PhoneCallTask phoneCallTask = new PhoneCallTask();
                    phoneCallTask.PhoneNumber = phonenumber;
                    UiDispatcher.BeginInvoke(() =>
                    {
                        phoneCallTask.Show();
                    });

                    // Set app navigated to external page
                    Mowbly.AppNavigatedToExternalPage = true;
                    break;

                case "deleteContact":

                    Logger.Info("Deleting contact...");

                    string contactId = message.Args[0] as string;

                    try
                    {
                        ContactStore contactStore = await ContactStore.CreateOrOpenAsync(
                            ContactStoreSystemAccessMode.ReadWrite,
                            ContactStoreApplicationAccessMode.ReadOnly);

                        await contactStore.DeleteContactAsync(contactId);

                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        string error = String.Concat(
                            Mowbly.GetString(Constants.STRING_CONTACT_DELETE_ERROR),
                            e.Message);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = error
                            }
                        });
                    }
                    break;

                case "findContact":

                    // Read args
                    string filter  = message.Args[0] as string;
                    JToken options = message.Args[1] as JToken;
                    properties = options["properties"].ToObject <List <string> >();
                    double limit = (double)options["limit"];

                    Logger.Info("Searching contacts for " + filter);

                    // Contacts search results handler
                    EventHandler <MowblyContactsSearchEventArgs> OnContactsSearchCompleted = null;
                    OnContactsSearchCompleted = (sender, e) =>
                    {
                        if (e.Status)
                        {
                            // Notify result to JS
                            InvokeCallbackJavascript(message.CallbackId, new MethodResult {
                                Result = e.W3Contacts
                            });
                        }
                        else
                        {
                            InvokeCallbackJavascript(message.CallbackId, new MethodResult {
                                Result = null
                            });
                        }
                    };

                    if (Regex.IsMatch(filter, @"^[0-9()-]+$"))
                    {
                        // Only numbers, search by phone number
                        SearchContactInUserDataAsync(filter, OnContactsSearchCompleted, true, FilterKind.PhoneNumber, limit, properties);
                    }
                    else
                    {
                        // Search by display name
                        SearchContactInUserDataAsync(filter, OnContactsSearchCompleted, true, FilterKind.DisplayName, limit, properties);
                    }
                    break;

                case "pickContact":


                    properties = ((JToken)message.Args[0]).ToObject <List <string> >();
                    ContactChooserTask contactChooserTask = new ContactChooserTask(callbackId);
                    EventHandler <ContactChooserTaskEventArgs> OnContactChooserTaskCompleted = null;
                    OnContactChooserTaskCompleted = (sender, e) =>
                    {
                        // Unsubscribe
                        contactChooserTask.OnCompleted -= OnContactChooserTaskCompleted;

                        // Notify result to JS
                        if (e.Contact != null)
                        {
                            W3Contact contact = new W3Contact(e.Contact, properties);
                            InvokeCallbackJavascript(e.CallbackId, new MethodResult {
                                Result = contact
                            });
                        }
                        else
                        {
                            InvokeCallbackJavascript(e.CallbackId, new MethodResult
                            {
                                Code  = MethodResult.FAILURE_CODE,
                                Error = new MethodError
                                {
                                    Message = Mowbly.GetString(Constants.STRING_ACTIVITY_CANCELLED)
                                }
                            });
                        }
                    };

                    // Subscribe to OnCompleted event
                    contactChooserTask.OnCompleted += OnContactChooserTaskCompleted;

                    // Show contact chooser task
                    UiDispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            contactChooserTask.Show();
                        }
                        catch (Exception e)
                        {
                            // Might fail at times since navigation is not allowed when task is not in foreground
                            string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_CHOOSE_FAILED), e.Message);
                            Logger.Error(error);
                            InvokeCallbackJavascript(callbackId, new MethodResult
                            {
                                Code  = MethodResult.FAILURE_CODE,
                                Error = new MethodError
                                {
                                    Message = error
                                }
                            });
                        }
                    });
                    break;

                case "saveContact":

                    try
                    {
                        // Create W3Contact object from JS contact
                        W3Contact w3Contact       = JsonConvert.DeserializeObject <W3Contact>(message.Args[0].ToString());
                        string    storedContactId = await w3Contact.SaveToNativeContactStore();

                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Result = storedContactId
                        });
                    }
                    catch (Exception e)
                    {
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_SAVE_FAILED), e.Message);
                        Logger.Error(error);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                case "viewContact":

                    // Get the param and type
                    string id = message.Args[0] as string;
                    Tuple <string, string> paramAndType = await GetSearchParamAndType(id);

                    if (paramAndType != null)
                    {
                        string            param             = paramAndType.Item1;
                        string            type              = paramAndType.Item2;
                        ContactViewerTask contactViewerTask = new ContactViewerTask(param, type);

                        // Show contact viewer task
                        UiDispatcher.BeginInvoke(() =>
                        {
                            try
                            {
                                contactViewerTask.Show();
                            }
                            catch (Exception e)
                            {
                                // Might fail at times since navigation is not allowed when task is not in foreground
                                string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_VIEW_FAILED), e.Message);
                                Logger.Error(error);
                                InvokeCallbackJavascript(callbackId, new MethodResult
                                {
                                    Code  = MethodResult.FAILURE_CODE,
                                    Error = new MethodError
                                    {
                                        Message = error
                                    }
                                });
                            }
                        });
                    }
                    else
                    {
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_VIEW_FAILED),
                                                     Mowbly.GetString(Constants.STRING_CONTACT_NOT_FOUND));
                        Logger.Error(error);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                default:
                    Logger.Error("Feature " + Name + " does not support method " + message.Method);
                    break;
                }
            }
            catch (Exception e)
            {
                Logger.Error("Exception occured. Reason - " + e.Message);
            }
        }
Esempio n. 12
0
        // Searches in Contacts for display name and then the phonenumber/email
        void SearchContactInUserDataAsync(
            string filter,
            EventHandler <MowblyContactsSearchEventArgs> OnSearchCompleted,
            bool shouldIncludeW3ContactsInResults = false,
            FilterKind filterKind    = FilterKind.DisplayName,
            double limit             = 1,
            List <string> properties = null)
        {
            Microsoft.Phone.UserData.Contacts oContacts = new Microsoft.Phone.UserData.Contacts();

            EventHandler <ContactsSearchEventArgs> OnContactsSearchCompleted = null;

            OnContactsSearchCompleted = (object sender, ContactsSearchEventArgs e) =>
            {
                // If results are empty, try searching with other contact fields
                if (e.Results.Count() == 0)
                {
                    switch (e.FilterKind)
                    {
                    case FilterKind.PhoneNumber:
                        // Phonenumber failed. Search by Display name
                        oContacts.SearchAsync(e.Filter, FilterKind.DisplayName, e.State);
                        break;

                    case FilterKind.DisplayName:
                        // Display name failed. Search by email
                        oContacts.SearchAsync(e.Filter, FilterKind.EmailAddress, e.State);
                        break;

                    default:
                        // No results
                        // Unsubscribe
                        oContacts.SearchCompleted -= OnContactsSearchCompleted;

                        // Notify event handler - Error
                        OnSearchCompleted(this,
                                          new MowblyContactsSearchEventArgs(
                                              Mowbly.GetString(Constants.STRING_CONTACT_NOT_FOUND)));
                        break;
                    }
                }
                else
                {
                    // Unsubscribe
                    oContacts.SearchCompleted -= OnContactsSearchCompleted;

                    MowblyContactsSearchEventArgs eventArgs;

                    // Create W3Contacts - if requested
                    if (shouldIncludeW3ContactsInResults)
                    {
                        int numResults = 0;
                        List <W3Contact> w3Contacts = new List <W3Contact>();
                        foreach (Contact contact in e.Results)
                        {
                            w3Contacts.Add(new W3Contact(contact, properties));
                            numResults++;
                            if (limit == numResults)
                            {
                                break;
                            }
                        }

                        // Create EventArgs - with W3Contact list
                        eventArgs = new MowblyContactsSearchEventArgs(e.Results, w3Contacts);
                    }
                    else
                    {
                        // Create EventArgs - without W3Contact list
                        eventArgs = new MowblyContactsSearchEventArgs(e.Results);
                    }
                    // Notify event handler - Result
                    OnSearchCompleted(this, eventArgs);
                }
            };
            oContacts.SearchCompleted += new EventHandler <ContactsSearchEventArgs>(OnContactsSearchCompleted);
            // Start search
            oContacts.SearchAsync(filter, filterKind, null);
        }