Beispiel #1
0
        internal static void _logOut(NCMBCallback callback)
        {
            string      url     = _getLogOutUrl();    //URL作成
            ConnectType type    = ConnectType.GET;
            string      content = null;

            //ログを確認(通信前)
            NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type + Environment.NewLine + "【content】:" + content);
            //通信処理
            NCMBConnection con = new NCMBConnection(url, type, content, NCMBUser._getCurrentSessionToken());

            con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                try {
                    NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    if (error != null)
                    {
                        NCMBDebug.Log("[DEBUG AFTER CONNECT] Error: " + error.ErrorMessage);
                    }
                    else
                    {
                        _logOutEvent();
                    }
                } catch (Exception e) {
                    error = new NCMBException(e);
                }
                if (callback != null)
                {
                    Platform.RunOnMainThread(delegate {
                        callback(error);
                    });
                }
                return;
            });
        }
Beispiel #2
0
        /// <summary>
        /// 指定IDのオブジェクトを取得を行います。<br/>
        /// 通信結果を受け取るために必ずコールバックを設定を行います。
        /// </summary>
        /// <param name="objectId">  オブジェクトID</param>
        /// <param name="callback">  コールバック</param>
        public void GetAsync(string objectId, NCMBGetCallback <T> callback)
        {
            if (callback == null)
            {
                throw new ArgumentException("It is necessary to always set a callback.");
            }

            new AsyncDelegate(delegate {
                string url = _getSearchUrl(this._className);                 //クラス毎のURL作成
                //オブジェクト取得API
                url += "/" + objectId;
                ConnectType type = ConnectType.GET;                //メソッドタイプの設定
                //通信処理
                NCMBConnection con = new NCMBConnection(url, type, null, NCMBUser._getCurrentSessionToken());
                con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                    Dictionary <string, object> resultObj;
                    NCMBObject objectData = null;
                    try {
                        if (error == null)
                        {
                            resultObj  = MiniJSON.Json.Deserialize(responseData) as Dictionary <string, object>;
                            objectData = _convertGetResponse(resultObj);
                        }
                    } catch (Exception e) {
                        error = new NCMBException(e);
                    }
                    //引数はリスト(中身NCMBObject)とエラーをユーザーに返す
                    Platform.RunOnMainThread(delegate {
                        callback((T)objectData, error);
                    });
                    return;
                });
            }).BeginInvoke((IAsyncResult r) => {
            }, null);
        }
Beispiel #3
0
        /// <summary>
        /// 非同期処理で指定したメールアドレスに対して、<br/>
        /// 会員登録を行うためのメールを送信するよう要求します。<br/>
        /// 通信結果が必要な場合はコールバックを指定するこちらを使用します。
        /// </summary>
        /// <param name="email">メールアドレス</param>
        /// <param name="callback">コールバック</param>
        public static void RequestAuthenticationMailAsync(string email, NCMBCallback callback)
        {
            //URL
            string url = _getmailAddressUserEntryUrl();             //URL

            //コンテント
            NCMBUser user = new NCMBUser();

            user.Email = email;
            string content = user._toJSONObjectForSaving(user.StartSave());

            //Type
            ConnectType type = ConnectType.POST;

            NCMBConnection con = new NCMBConnection(url, type, content, NCMBUser._getCurrentSessionToken());

            NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type + Environment.NewLine + "【content】:" + content);
            con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                if (callback != null)
                {
                    callback(error);
                }
                return;
            });
        }
Beispiel #4
0
        //通信
        internal void Connect(NCMBConnection connection, NCMBExecuteScriptCallback callback)
        {
            GameObject   gameObj  = GameObject.Find("NCMBSettings");
            NCMBSettings settings = gameObj.GetComponent <NCMBSettings> ();

            settings.Connection(connection, callback);
        }
Beispiel #5
0
        /// <summary>
        /// 非同期処理でファイルのダウンロードを行います。<br/>
        /// 通信結果が必要な場合はコールバックを指定するこちらを使用します。
        /// </summary>
        /// <param name="callback">コールバック</param>
        public void FetchAsync(NCMBGetFileCallback callback)
        {
            // fileName必須
            if ((this.FileName == null))
            {
                throw new NCMBException("fileName must not be null.");
            }

            new AsyncDelegate(delegate {
                // 通信処理
                NCMBConnection con = new NCMBConnection(_getBaseUrl(), ConnectType.GET, null, NCMBUser._getCurrentSessionToken(), this);
                con.Connect(delegate(int statusCode, byte[] responseData, NCMBException error) {
                    NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    this.estimatedData ["fileData"] = responseData;
                    if (callback != null)
                    {
                        Platform.RunOnMainThread(delegate {
                            callback(responseData, error);
                        });
                    }
                    return;
                });
            }).BeginInvoke((IAsyncResult r) => {
            }, null);
        }
Beispiel #6
0
        private static void _ncmbLogIn(string name, string password, string email, NCMBCallback callback)
        {
            string      url  = _getLogInUrl();
            ConnectType type = ConnectType.GET;

            Dictionary <string, object> paramDic = new Dictionary <string, object>();

            paramDic["password"] = password;

            //nameがあればLogInAsync経由 無ければLogInWithMailAddressAsync経由、どちらも無ければエラー
            if (name != null)
            {
                paramDic["userName"] = name;
            }
            else if (email != null)
            {
                paramDic["mailAddress"] = email;
            }
            else
            {
                throw new NCMBException(new ArgumentException("UserName or Email can not be null."));
            }

            url = _makeParamUrl(url + "?", paramDic);

            //ログを確認(通信前)
            NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type);
            //通信処理
            NCMBConnection con = new NCMBConnection(url, type, null, null);

            con.Connect(delegate(int statusCode, string responseData, NCMBException error)
            {
                try
                {
                    NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    if (error != null)
                    {
                        NCMBDebug.Log("[DEBUG AFTER CONNECT] Error: " + error.ErrorMessage);
                    }
                    else
                    {
                        Dictionary <string, object> responseDic = MiniJSON.Json.Deserialize(responseData) as Dictionary <string, object>;
                        //save Current user
                        NCMBUser logInUser = new NCMBUser();
                        logInUser._handleFetchResult(true, responseDic);
                        _saveCurrentUser(logInUser);
                    }
                }
                catch (Exception e)
                {
                    error = new NCMBException(e);
                }
                if (callback != null)
                {
                    callback(error);
                }
                return;
            });
        }
Beispiel #7
0
        private static void _ncmbLogIn(string name, string password, string email, NCMBCallback callback)
        {
            string      url  = _getLogInUrl();       //URL作成
            ConnectType type = ConnectType.GET;
            //set username, password
            NCMBUser logInUser = new NCMBUser();

            logInUser.Password = password;

            //nameがあればLogInAsync経由 無ければLogInWithMailAddressAsync経由、どちらも無ければエラー
            if (name != null)
            {
                logInUser.UserName = name;
            }
            else if (email != null)
            {
                logInUser.Email = email;
            }
            else
            {
                throw new NCMBException(new ArgumentException("UserName or Email can not be null."));
            }

            string content = logInUser._toJSONObjectForSaving(logInUser.StartSave());
            Dictionary <string, object> paramDic = (Dictionary <string, object>)MiniJSON.Json.Deserialize(content);

            url = _makeParamUrl(url + "?", paramDic);
            //ログを確認(通信前)
            NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type + Environment.NewLine + "【content】:" + content);
            //通信処理
            NCMBConnection con = new NCMBConnection(url, type, content, NCMBUser._getCurrentSessionToken());

            con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                try {
                    NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    if (error != null)
                    {
                        NCMBDebug.Log("[DEBUG AFTER CONNECT] Error: " + error.ErrorMessage);
                    }
                    else
                    {
                        Dictionary <string, object> responseDic = MiniJSON.Json.Deserialize(responseData) as Dictionary <string, object>;
                        logInUser._handleFetchResult(true, responseDic);
                        //save Current user
                        _saveCurrentUser(logInUser);
                    }
                } catch (Exception e) {
                    error = new NCMBException(e);
                }
                if (callback != null)
                {
                    Platform.RunOnMainThread(delegate {
                        callback(error);
                    });
                }
                return;
            });
        }
Beispiel #8
0
        internal static void TrackAppOpened(string _pushId)             //(Android/iOS)-NCMBManager.onAnalyticsReceived-this.NCMBAnalytics
        {
            //ネイティブから取得したpushIdからリクエストヘッダを作成
            if (_pushId != null && NCMBManager._token != null && NCMBSettings.UseAnalytics)
            {
                string deviceType = "";
                if (SystemInfo.operatingSystem.IndexOf("Android") != -1)
                {
                    deviceType = "android";
                }
                else if (SystemInfo.operatingSystem.IndexOf("iPhone") != -1)
                {
                    deviceType = "ios";
                }

                //RESTリクエストデータ生成
                Dictionary <string, object> requestData = new Dictionary <string, object> {
                    { "pushId", _pushId },
                    { "deviceToken", NCMBManager._token },
                    { "deviceType", deviceType }
                };

                var         json    = Json.Serialize(requestData);
                string      url     = CommonConstant.DOMAIN_URL + "/" + CommonConstant.API_VERSION + "/push/" + _pushId + "/openNumber";
                ConnectType type    = ConnectType.POST;
                string      content = json.ToString();
                NCMBDebug.Log("content:" + content);
                //ログを確認(通信前)
                NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type + Environment.NewLine + "【content】:" + content);
                // 通信処理
                NCMBConnection con = new NCMBConnection(url, type, content, NCMBUser._getCurrentSessionToken());
                con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                    try {
                        NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    } catch (Exception e) {
                        error = new NCMBException(e);
                    }
                    return;
                });

                                #if UNITY_IOS
                                        #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
                NotificationServices.ClearRemoteNotifications();
                                        #else
                UnityEngine.iOS.NotificationServices.ClearRemoteNotifications();
                                        #endif
                                #endif
            }
        }
Beispiel #9
0
        /// <summary>
        /// 非同期処理でファイルの保存を行います。<br/>
        /// 通信結果が必要な場合はコールバックを指定するこちらを使用します。
        /// </summary>
        /// <param name="callback">コールバック</param>
        public override void SaveAsync(NCMBCallback callback)
        {
            if ((this.FileName == null))
            {
                throw new NCMBException("fileName must not be null.");
            }

            new AsyncDelegate(delegate {
                ConnectType type;
                if (this.CreateDate != null)
                {
                    type = ConnectType.PUT;
                }
                else
                {
                    type = ConnectType.POST;
                }
                IDictionary <string, INCMBFieldOperation> currentOperations = null;
                currentOperations  = this.StartSave();
                string content     = _toJSONObjectForSaving(currentOperations);
                NCMBConnection con = new NCMBConnection(_getBaseUrl(), type, content, NCMBUser._getCurrentSessionToken(), this);
                con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                    try {
                        NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                        if (error != null)
                        {
                            // 失敗
                            this._handleSaveResult(false, null, currentOperations);
                        }
                        else
                        {
                            Dictionary <string, object> responseDic = MiniJSON.Json.Deserialize(responseData) as Dictionary <string, object>;
                            this._handleSaveResult(true, responseDic, currentOperations);
                        }
                    } catch (Exception e) {
                        error = new NCMBException(e);
                    }

                    if (callback != null)
                    {
                        Platform.RunOnMainThread(delegate {
                            callback(error);
                        });
                    }
                    return;
                });
            }).BeginInvoke((IAsyncResult r) => {
            }, null);
        }
Beispiel #10
0
        /// <summary>
        /// クエリにマッチするオブジェクト数の取得を行います。<br/>
        /// 通信結果を受け取るために必ずコールバックの設定を行います。
        /// </summary>
        /// <param name="callback">  コールバック</param>
        public void CountAsync(NCMBCountCallback callback)
        {
            if (callback == null)
            {
                throw new ArgumentException("It is necessary to always set a callback.");
            }

            new AsyncDelegate(delegate {
                string url = _getSearchUrl(this._className);                   //クラス毎のURL作成
                url       += WHERE_URL;                                        //「?」をつける

                Dictionary <string, object> beforeJsonData = _getFindParams(); //パラメータDictionaryの作成

                beforeJsonData ["count"] = 1;                                  // カウント条件を追加する

                url = _makeWhereUrl(url, beforeJsonData);                      //urlにパラメータDictionaryを変換して結合

                ConnectType type = ConnectType.GET;                            //メソッドタイプの設定
                //通信処理
                NCMBConnection con = new NCMBConnection(url, type, null, NCMBUser._getCurrentSessionToken());
                con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                    Dictionary <string, object> resultObj;
                    int count = 0;
                    if (error == null)
                    {
                        try {
                            resultObj          = MiniJSON.Json.Deserialize(responseData) as Dictionary <string, object>;
                            object objectCount = null;
                            if (resultObj.TryGetValue("count", out objectCount))
                            {
                                count = Convert.ToInt32(objectCount);                                 //キーcountの値は必ず同じ型なので型チェック時の変換チェックは無し
                            }
                        } catch (Exception e) {
                            error = new NCMBException(e);
                        }
                    }
                    //引数は検索条件のカウント数とエラーをユーザーに返す
                    Platform.RunOnMainThread(delegate {
                        callback(count, error);
                    });
                    return;
                });
            }).BeginInvoke((IAsyncResult r) => {
            }, null);
        }
        internal static void TrackAppOpened(string _pushId)             //(Android/iOS)-NCMBManager.onAnalyticsReceived-this.NCMBAnalytics
        {
            //ネイティブから取得したpushIdからリクエストヘッダを作成
            if (_pushId != null && NCMBManager._token != null && NCMBSettings.UseAnalytics)
            {
                string deviceType = "";
                                #if UNITY_ANDROID
                deviceType = "android";
                                #elif UNITY_IOS
                deviceType = "ios";
                                #endif

                //RESTリクエストデータ生成
                Dictionary <string, object> requestData = new Dictionary <string, object> {
                    { "pushId", _pushId },
                    { "deviceToken", NCMBManager._token },
                    { "deviceType", deviceType }
                };

                var         json    = Json.Serialize(requestData);
                string      url     = NCMBAnalytics._getBaseUrl(_pushId);
                ConnectType type    = ConnectType.POST;
                string      content = json.ToString();

                //ログを確認(通信前)
                NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type + Environment.NewLine + "【content】:" + content);
                // 通信処理
                NCMBConnection con = new NCMBConnection(url, type, content, NCMBUser._getCurrentSessionToken());
                con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                    try {
                        NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    } catch (Exception e) {
                        error = new NCMBException(e);
                    }
                    return;
                });

                /*
                 #if UNITY_IOS
                 *      UnityEngine.iOS.NotificationServices.ClearRemoteNotifications ();
                 #endif
                 */
            }
        }
Beispiel #12
0
        /// <summary>
        /// 同期用の検索メソッド。FindeAsyncで呼び出される。またNCMBObjecとのFetchAllAsyncで扱う。
        /// </summary>
        internal void Find(NCMBQueryCallback <T> callback)
        {
            string url = _getSearchUrl(this._className); //クラス毎のURL作成

            url += WHERE_URL;                            //「?」を末尾に追加する。
            //条件データの作成
            Dictionary <string, object> beforeJsonData = _getFindParams();

            url = _makeWhereUrl(url, beforeJsonData);      //URLの結合
            ConnectType type = ConnectType.GET;            //メソッドタイプの設定

            NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type);
            //通信処理
            NCMBConnection con = new NCMBConnection(url, type, null, NCMBUser._getCurrentSessionToken());

            con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);

                Dictionary <string, object> resultObj;
                List <T> resultList         = new List <T> ();
                ArrayList convertResultList = null;
                //中でエラー処理いるかも
                try {
                    if (error == null)
                    {
                        resultObj         = MiniJSON.Json.Deserialize(responseData) as Dictionary <string, object>;
                        convertResultList = _convertFindResponse(resultObj);
                        foreach (T obj in convertResultList)
                        {
                            resultList.Add(obj);
                        }
                    }
                } catch (Exception e) {
                    error = new NCMBException(e);
                }

                Platform.RunOnMainThread(delegate {
                    callback(resultList, error);
                });

                return;
            });
        }
Beispiel #13
0
    public void ConstructorTest()
    {
        // テストデータ作成
        string      url          = "http://dummylocalhost/";
        ConnectType connectType  = ConnectType.GET;
        string      content      = "dummyContent";
        string      sessionToken = "dummySessionToken";
        NCMBFile    file         = new NCMBFile();

        // フィールド値の読み込み
        NCMBConnection connection_normal = new NCMBConnection(url, connectType, content, sessionToken);
        Type           type_normal       = connection_normal.GetType();
        FieldInfo      field_normal      = type_normal.GetField("_domainUri", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);

        NCMBConnection connection_file = new NCMBConnection(url, connectType, content, sessionToken, file);
        Type           type_file       = connection_file.GetType();
        FieldInfo      field_file      = type_file.GetField("_domainUri", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);

        Assert.AreEqual("http://localhost:3000/", field_normal.GetValue(connection_normal).ToString());
        Assert.AreEqual("http://localhost:3000/", field_file.GetValue(connection_file).ToString());
    }
Beispiel #14
0
        internal static void _logOut(NCMBCallback callback)
        {
            string      url     = _getLogOutUrl();    //URL作成
            ConnectType type    = ConnectType.GET;
            string      content = null;

            //ログを確認(通信前)
            NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type + Environment.NewLine + "【content】:" + content);
            //通信処理
            NCMBConnection con = new NCMBConnection(url, type, content, NCMBUser._getCurrentSessionToken());

            con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                try {
                    NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    if (error != null)
                    {
                        NCMBDebug.Log("[DEBUG AFTER CONNECT] Error: " + error.ErrorMessage);
                    }
                    else
                    {
                        _logOutEvent();
                    }
                } catch (Exception e) {
                    error = new NCMBException(e);
                }
                if (callback != null)
                {
                    //If the system get ErrorCode is E401001 when LogOutAsync, We will return null.
                    if (error != null && NCMBException.INCORRECT_HEADER.Equals(error.ErrorCode))
                    {
                        callback(null);
                    }
                    else
                    {
                        callback(error);
                    }
                }
                return;
            });
        }
Beispiel #15
0
        internal static void _requestPasswordReset(string email, NCMBCallback callback)
        {
            string      url  = _getRequestPasswordResetUrl();       //URL
            ConnectType type = ConnectType.POST;
            //set username, password
            NCMBUser pwresetUser = new NCMBUser();

            pwresetUser.Email = email;
            string content = pwresetUser._toJSONObjectForSaving(pwresetUser.StartSave());

            //ログを確認(通信前)
            NCMBDebug.Log("【url】:" + url + Environment.NewLine + "【type】:" + type + Environment.NewLine + "【content】:" + content);
            //通信処理
            NCMBConnection con = new NCMBConnection(url, type, content, NCMBUser._getCurrentSessionToken());

            con.Connect(delegate(int statusCode, string responseData, NCMBException error) {
                try {
                    NCMBDebug.Log("【StatusCode】:" + statusCode + Environment.NewLine + "【Error】:" + error + Environment.NewLine + "【ResponseData】:" + responseData);
                    if (error != null)
                    {
                        NCMBDebug.Log("[DEBUG AFTER CONNECT] Error: " + error.ErrorMessage);
                    }
                    else
                    {
                        NCMBDebug.Log("[DEBUG AFTER CONNECT] Successful: ");
                    }
                } catch (Exception e) {
                    error = new NCMBException(e);
                }
                if (callback != null)
                {
                    Platform.RunOnMainThread(delegate {
                        callback(error);
                    });
                }
                return;
            });
        }
Beispiel #16
0
 /// <summary>
 /// mobile backendと通信を行います。
 /// </summary>
 internal void Connection(NCMBConnection connection, object callback)
 {
     StartCoroutine(NCMBConnection.SendRequest(connection, connection._request, callback));
 }
Beispiel #17
0
        /// <summary>
        /// 非同期処理でスクリプトの実行を行います。
        /// </summary>
        /// <param name="header">リクエストヘッダー.</param>
        /// <param name="body">リクエストボディ</param>
        /// <param name="query">クエリパラメーター</param>
        /// <param name="callback">コールバック</param>
        public void ExecuteAsync(IDictionary <string, object> header, IDictionary <string, object> body, IDictionary <string, object> query, NCMBExecuteScriptCallback callback)
        {
            //URL作成
            String endpoint  = DEFAULT_SCRIPT_ENDPOINT;
            String scriptUrl = DEFAULT_SCRIPT_ENDPOINT + "/" + DEFAULT_SCRIPT_API_VERSION + "/" + SERVICE_PATH + "/" + this._scriptName;

            if (this._baseUrl == null || this._baseUrl.Length == 0)
            {
                throw new ArgumentException("Invalid baseUrl.");
            }
            else if (!this._baseUrl.Equals(DEFAULT_SCRIPT_ENDPOINT))
            {
                //ユーザー設定時
                endpoint  = _baseUrl;
                scriptUrl = this._baseUrl + "/" + this._scriptName;
            }

            //メソッド作成
            ConnectType type;

            switch (_method)
            {
            case MethodType.POST:
                type = ConnectType.POST;
                break;

            case MethodType.PUT:
                type = ConnectType.PUT;
                break;

            case MethodType.GET:
                type = ConnectType.GET;
                break;

            case MethodType.DELETE:
                type = ConnectType.DELETE;
                break;

            default:
                throw new ArgumentException("Invalid methodType.");
            }

            //コンテント作成
            String content = null;

            if (body != null)
            {
                content = Json.Serialize(body);
            }

            //クエリ文字列作成
            String queryVal    = "";
            String queryString = "?";

            if (query != null && query.Count > 0)
            {
                int count = query.Count;
                foreach (KeyValuePair <string, object> pair in query)
                {
                    if (pair.Value is IList || pair.Value is IDictionary)
                    {
                        //value形式:array,ILis,IDictionaryの場合
                        queryVal = SimpleJSON.Json.Serialize(pair.Value);
                    }
                    else if (pair.Value is DateTime)
                    {
                        //value形式:DateTimeの場合
                        queryVal = NCMBUtility.encodeDate((DateTime)pair.Value);
                    }
                    else
                    {
                        //value形式:上の以外場合
                        queryVal = pair.Value.ToString();
                    }

                    queryString += pair.Key + "=" + Uri.EscapeDataString(queryVal);

                    if (count > 1)
                    {
                        queryString += "&";
                        --count;
                    }
                }

                scriptUrl += queryString;
            }

            ServicePointManager.ServerCertificateValidationCallback = delegate {
                return(true);
            };

            //コネクション作成
            NCMBConnection connection = new NCMBConnection(scriptUrl, type, content, NCMBUser._getCurrentSessionToken(), null, endpoint);

            //オリジナルヘッダー設定
            if (header != null && header.Count > 0)
            {
                foreach (KeyValuePair <string, object> pair in header)
                {
                    connection._request.SetRequestHeader(pair.Key, pair.Value.ToString());
                }
            }

            //通信
            Connect(connection, callback);
        }
Beispiel #18
0
        /// <summary>
        /// 非同期処理でスクリプトの実行を行います。
        /// </summary>
        /// <param name="header">リクエストヘッダー.</param>
        /// <param name="body">リクエストボディ</param>
        /// <param name="query">クエリパラメーター</param>
        /// <param name="callback">コールバック</param>
        public void ExecuteAsync(IDictionary <string, object> header, IDictionary <string, object> body, IDictionary <string, object> query, NCMBExecuteScriptCallback callback)
        {
            new AsyncDelegate(delegate {
                //URL作成
                String endpoint  = DEFAULT_SCRIPT_ENDPOINT;
                String scriptUrl = DEFAULT_SCRIPT_ENDPOINT + "/" + DEFAULT_SCRIPT_API_VERSION + "/" + SERVICE_PATH + "/" + this._scriptName;
                if (this._baseUrl == null || this._baseUrl.Length == 0)
                {
                    throw new ArgumentException("Invalid baseUrl.");
                }
                else if (!this._baseUrl.Equals(DEFAULT_SCRIPT_ENDPOINT))
                {
                    //ユーザー設定時
                    endpoint  = _baseUrl;
                    scriptUrl = this._baseUrl + "/" + this._scriptName;
                }

                //メソッド作成
                ConnectType type;
                switch (_method)
                {
                case MethodType.POST:
                    type = ConnectType.POST;
                    break;

                case MethodType.PUT:
                    type = ConnectType.PUT;
                    break;

                case MethodType.GET:
                    type = ConnectType.GET;
                    break;

                case MethodType.DELETE:
                    type = ConnectType.DELETE;
                    break;

                default:
                    throw new ArgumentException("Invalid methodType.");
                }

                //コンテント作成
                String content = null;
                if (body != null)
                {
                    content = Json.Serialize(body);
                }

                //クエリ文字列作成
                String queryString = "?";
                if (query != null && query.Count > 0)
                {
                    int count = query.Count;
                    foreach (KeyValuePair <string, object> pair in query)
                    {
                        queryString += pair.Key + "=" + pair.Value.ToString();
                        if (count > 1)
                        {
                            queryString += "&";
                            --count;
                        }
                    }
                    scriptUrl += Uri.EscapeUriString(queryString);
                }

                ServicePointManager.ServerCertificateValidationCallback = delegate {
                    return(true);
                };

                //コネクション作成
                NCMBConnection connection = new NCMBConnection(scriptUrl, type, content, NCMBUser._getCurrentSessionToken(), null, endpoint);
                HttpWebRequest request    = connection._returnRequest();

                //コンテント設定
                if (content != null)
                {
                    byte[] postDataBytes = Encoding.Default.GetBytes(content);
                    Stream stream        = null;
                    try {
                        stream = request.GetRequestStream();
                        stream.Write(postDataBytes, 0, postDataBytes.Length);
                    } finally {
                        if (stream != null)
                        {
                            stream.Close();
                        }
                    }
                }

                //オリジナルヘッダー設定
                if (header != null && header.Count > 0)
                {
                    foreach (KeyValuePair <string, object> pair in header)
                    {
                        request.Headers.Add(pair.Key, pair.Value.ToString());
                    }
                }

                //通信
                Connect(connection, request, callback);
            }).BeginInvoke((IAsyncResult r) => {
            }, null);
        }
Beispiel #19
0
        //通信
        internal void Connect(NCMBConnection connection, HttpWebRequest request, NCMBExecuteScriptCallback callback)
        {
            string          responseData   = null;
            NCMBException   error          = null;
            HttpWebResponse httpResponse   = null;
            Stream          streamResponse = null;
            StreamReader    streamRead     = null;

            byte[] result = new byte[32768];
            try {
                //レスポンスデータの書き込み
                httpResponse   = (HttpWebResponse)request.GetResponse();
                streamResponse = httpResponse.GetResponseStream();
                for (; ;)
                {
                    int readSize = streamResponse.Read(result, 0, result.Length);
                    if (readSize == 0)
                    {
                        break;
                    }
                }
            } catch (WebException ex) {
                //失敗
                using (WebResponse webResponse = ex.Response) {                //WebExceptionからWebResponseを取得
                    error = new NCMBException();
                    error.ErrorMessage = ex.Message;
                    if (webResponse != null)
                    {
                        streamResponse = webResponse.GetResponseStream();
                        streamRead     = new StreamReader(streamResponse);
                        responseData   = streamRead.ReadToEnd();                       //データを全てstringに書き出し

                        error.ErrorMessage = responseData;
                        httpResponse       = (HttpWebResponse)webResponse;
                        error.ErrorCode    = httpResponse.StatusCode.ToString();

                        var jsonData = MiniJSON.Json.Deserialize(responseData) as Dictionary <string, object>;                       //Dictionaryに変換
                        if (jsonData != null)
                        {
                            var hashtableData = new Hashtable(jsonData);
                            //statusCode
                            if (hashtableData.ContainsKey("code"))
                            {
                                error.ErrorCode = (hashtableData ["code"].ToString());
                            }
                            else if (hashtableData.ContainsKey("status"))
                            {
                                error.ErrorCode = (hashtableData ["status"].ToString());
                            }
                            //message
                            if (hashtableData.ContainsKey("error"))
                            {
                                error.ErrorMessage = (hashtableData ["error"].ToString());
                            }
                        }
                    }
                }
            } finally {
                //close
                if (httpResponse != null)
                {
                    httpResponse.Close();
                }
                if (streamResponse != null)
                {
                    streamResponse.Close();
                }
                if (streamRead != null)
                {
                    streamRead.Close();
                }
                //check E401001 error
                if (error != null)
                {
                    connection._checkInvalidSessionToken(error.ErrorCode);
                }
                //enqueue callback
                if (callback != null)
                {
                    Platform.RunOnMainThread(delegate {
                        callback(result, error);
                    });
                }
            }
        }
Beispiel #20
0
    private string _makeResponseSignature(HttpListenerRequest request, string responseData)
    {
        string      _url             = request.Url.AbsoluteUri;
        ConnectType _method          = ConnectType.GET;
        string      _applicationKey  = NCMBSettings.ApplicationKey;
        string      _headerTimestamp = request.Headers["X-NCMB-Timestamp"];

        byte[] responseByte = System.Text.Encoding.UTF8.GetBytes(responseData);

        StringBuilder data = new StringBuilder();                                   //シグネチャ(ハッシュ化)するデータの生成
        String        path = _url.Substring(this._domainUri.OriginalString.Length); // パス以降の設定,取得

        String[] temp = path.Split('?');
        path = temp[0];
        String parameter = null;

        if (temp.Length > 1)
        {
            parameter = temp[1];
        }
        Hashtable hashValue = new Hashtable();                       //昇順に必要なデータを格納するリスト

        hashValue[SIGNATURE_METHOD_KEY]   = SIGNATURE_METHOD_VALUE;  //シグネチャキー
        hashValue[SIGNATURE_VERSION_KEY]  = SIGNATURE_VERSION_VALUE; // シグネチャバージョン
        hashValue[HEADER_APPLICATION_KEY] = _applicationKey;
        hashValue[HEADER_TIMESTAMP_KEY]   = _headerTimestamp;
        String[] tempParameter;
        if (parameter != null)
        {
            if (_method == ConnectType.GET)
            {
                foreach (string param in parameter.Split('&'))
                {
                    tempParameter = param.Split('=');
                    hashValue[tempParameter[0]] = tempParameter[1];
                }
            }
        }
        //sort hashTable base on key
        List <string> tmpAscendingList = new List <string>();   //昇順に必要なデータを格納するリスト

        foreach (DictionaryEntry s in hashValue)
        {
            tmpAscendingList.Add(s.Key.ToString());
        }
        StringComparer cmp = StringComparer.Ordinal;

        tmpAscendingList.Sort(cmp);
        //Create data
        data.Append(_method);              //メソッド追加
        data.Append("\n");
        data.Append(this._domainUri.Host); //ドメインの追加
        data.Append("\n");
        data.Append(path);                 //パスの追加
        data.Append("\n");
        foreach (string tmp in tmpAscendingList)
        {
            data.Append(tmp + "=" + hashValue[tmp] + "&");
        }
        data.Remove(data.Length - 1, 1);     //最後の&を削除


        StringBuilder stringHashData = data;

        //レスポンスデータ追加 Delete時はレスポンスデータが無いため追加しない
        if (responseByte != null && responseData != "")
        {
            // 通常時
            stringHashData.Append("\n" + responseData);
        }
        else if (responseByte != null)
        {
            // ファイル取得時など
            stringHashData.Append("\n" + NCMBConnection.AsHex(responseByte));
        }

        //シグネチャ再生成
        String _clientKey = NCMBSettings.ClientKey;
        String stringData = stringHashData.ToString();
        //署名(シグネチャ)生成
        string result = null;                                      //シグネチャ結果の収納

        byte[] secretKeyBArr = Encoding.UTF8.GetBytes(_clientKey); //秘密鍵(クライアントキー)
        byte[] contentBArr   = Encoding.UTF8.GetBytes(stringData); //認証データ
                                                                   //秘密鍵と認証データより署名作成
        HMACSHA256 HMACSHA256 = new HMACSHA256();

        HMACSHA256.Key = secretKeyBArr;
        byte[] final = HMACSHA256.ComputeHash(contentBArr);
        //Base64実行。シグネチャ完成。
        result = System.Convert.ToBase64String(final);

        return(result);
    }