Example #1
0
        private void tvTable_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TablePermission tp = (TablePermission)e.Node.Tag;

            switch (tp.ttTableType)
            {
            case TableType.ttBase:
            case TableType.ttExtraBase:
            case TableType.ttStaticBase:
            case TableType.ttMain:
            case TableType.ttExtraMain:
            case TableType.ttRelation:
            case TableType.ttSubTable:
            case TableType.ttSystem:
            case TableType.ttViewMain:
            case TableType.ttViewBase:
            {
                chkDBInsert.Checked     = tp.blnInsert;
                chkDBInsert.Enabled     = true;
                chkDBEdit.Checked       = tp.blnEdit;
                chkDBEdit.Enabled       = true;
                chkDBDelete.Checked     = tp.blnDelete;
                chkDBDelete.Enabled     = true;
                chkDBPost.Checked       = true;
                chkDBPost.Enabled       = false;
                chkDBCancel.Checked     = true;
                chkDBCancel.Enabled     = false;
                chkDBFind.Checked       = tp.blnFind;
                chkDBFind.Enabled       = true;
                chkDBFindNext.Checked   = chkDBFind.Checked;
                chkDBFindNext.Enabled   = false;
                chkDBFilter.Checked     = tp.blnFilter;
                chkDBFilter.Enabled     = true;
                chkPrintPreview.Checked = tp.blnPrintPreview;
                chkPrintPreview.Enabled = true;
                chkDataPrint.Checked    = tp.blnPrint;
                chkDataPrint.Enabled    = true;
                chkQuit.Checked         = true;
                chkQuit.Enabled         = false;
                break;
            }

            default:
            {
                chkDBInsert.Checked     = chkDBInsert.Enabled = false;
                chkDBEdit.Checked       = chkDBEdit.Enabled = false;
                chkDBDelete.Checked     = chkDBDelete.Enabled = false;
                chkDBPost.Checked       = chkDBPost.Enabled = false;
                chkDBCancel.Checked     = chkDBCancel.Enabled = false;
                chkDBFind.Checked       = chkDBFind.Enabled = false;
                chkDBFindNext.Checked   = chkDBFindNext.Enabled = false;
                chkDBFilter.Checked     = chkDBFilter.Enabled = false;
                chkPrintPreview.Checked = chkPrintPreview.Enabled = false;
                chkDataPrint.Checked    = chkDataPrint.Enabled = false;
                chkQuit.Checked         = chkQuit.Enabled = false;
                break;
            }
            }
        }
Example #2
0
        /// <summary>
        /// Create a new instance.
        /// </summary>
        /// <param name="table">Get the table you revoke the permission</param>
        /// <param name="user">Get the user you revoke the permission</param>
        /// <param name="permission">The permission to revoke</param>
        public TablePermissionOperation(string table, string user, TablePermission permission)
            : base(null)
        {
            Check.NotEmpty(table, "table");
            Check.NotEmpty(user, "user");

            Table      = table;
            User       = user;
            Permission = permission;
        }
Example #3
0
        public bool CheckTablePermission(String strTableName, TablePermission permission)
        {
            Guid?iUserID = GetCurrentUserID();

            if (iUserID.HasValue == false)
            {
                return(false);
            }

            return(ABCUserProvider.CheckTablePermission(iUserID.Value, strTableName, permission));
        }
Example #4
0
        private TablePermission SetTreeTablePermission(int intTableCode)
        {
            DataRow[]       drDataRow = dtPermission.Select("pk_FKTableCode = " + intTableCode.ToString());
            TablePermission tp        = new TablePermission();

            tp.intTableCode    = intTableCode;
            tp.blnInsert       = false;
            tp.blnEdit         = false;
            tp.blnDelete       = false;
            tp.blnFind         = false;
            tp.blnFilter       = false;
            tp.blnPrintPreview = false;
            tp.blnPrint        = false;
            tp.blnSelect       = false;
            for (int RowIndex = 0; (RowIndex < drDataRow.Length); RowIndex++)
            {
                switch ((Macro.Action)Convert.ToInt16(drDataRow[RowIndex]["pk_FKActionCode"].ToString()))
                {
                case Macro.Action.aInsert:
                    tp.blnInsert = true;
                    break;

                case Macro.Action.aUpdate:
                    tp.blnEdit = true;
                    break;

                case Macro.Action.aDelete:
                    tp.blnDelete = true;
                    break;

                case Macro.Action.aFind:
                    tp.blnFind = true;
                    break;

                case Macro.Action.aFilter:
                    tp.blnFilter = true;
                    break;

                case Macro.Action.aPrintPreview:
                    tp.blnPrintPreview = true;
                    break;

                case Macro.Action.aPrint:
                    tp.blnPrint = true;
                    break;

                case Macro.Action.aSelect:
                    tp.blnSelect = true;
                    break;
                }
            }
            return(tp);
        }
Example #5
0
        public static bool CheckTablePermission(Guid iUserID, String strTableName, TablePermission permission)
        {
            bool result = false;

            String strKey = iUserID.ToString() + strTableName + permission.ToString();

            if (TablePermissionList.TryGetValue(strKey, out result))
            {
                return(result);
            }

            ADUsersInfo user = new ADUsersController().GetObjectByID(iUserID) as ADUsersInfo;

            if (user != null && user.FK_ADUserGroupID.HasValue)
            {
                ADUserGroupsInfo group = new ADUserGroupsController().GetObjectByID(user.FK_ADUserGroupID.Value) as ADUserGroupsInfo;
                if (group != null)
                {
                    result = (user.No == "sysadmin");
                    String strQuery = String.Format(@"SELECT A.* FROM  GEPermissionTables A JOIN ADUserPermissions B ON A.TableName ='{0}' AND B.FK_GEPermissionID = A.FK_GEPermissionID AND  (B.FK_ADUserGroupID ='{1}' OR B.FK_ADUserID ='{2}') ORDER BY B.FK_ADUserID  DESC", strTableName, user.FK_ADUserGroupID.Value, user.ADUserID);
                    foreach (GEPermissionTablesInfo tablePermission in new GEPermissionTablesController().GetList(strQuery).Cast <GEPermissionTablesInfo>().ToList())
                    {
                        switch (permission)
                        {
                        case TablePermission.AllowView:
                            result = (result || tablePermission.AllowView);
                            break;

                        case TablePermission.AllowNew:
                            result = (result || tablePermission.AllowNew);
                            break;

                        case TablePermission.AllowEdit:
                            result = (result || tablePermission.AllowEdit);
                            break;

                        case TablePermission.AllowDelete:
                            result = (result || tablePermission.AllowDelete);
                            break;
                        }
                    }
                }
            }
            if (SystemProvider.SystemConfig.IsRelease)
            {
                TablePermissionList.Add(strKey, result);
            }
            return(result);
        }
Example #6
0
        private void AddRole(Tom.ModelRole role)
        {
            Dax.Metadata.Role daxRole = new Role(DaxModel)
            {
                RoleName = new DaxName(role.Name)
            };
            foreach (var tablePermission in role.TablePermissions)
            {
                Dax.Metadata.Table           table = DaxModel.Tables.SingleOrDefault(t => t.TableName.Name == tablePermission.Table.Name);
                Dax.Metadata.TablePermission daxTablePermission = new TablePermission(daxRole)
                {
                    Table            = table,
                    FilterExpression = DaxExpression.GetExpression(tablePermission.FilterExpression)
                };

                daxRole.TablePermissions.Add(daxTablePermission);
            }

            DaxModel.Roles.Add(daxRole);
        }
Example #7
0
        private void tvTable_AfterCheck(object sender, TreeViewEventArgs e)
        {
            TablePermission tp = (TablePermission)e.Node.Tag;

            switch (e.Action)
            {
            case TreeViewAction.ByKeyboard:
            case TreeViewAction.ByMouse:
            {
                tvTable.SelectedNode = e.Node;
                switch (tp.ttTableType)
                {
                case TableType.ttBase:
                case TableType.ttExtraBase:
                case TableType.ttStaticBase:
                case TableType.ttMain:
                case TableType.ttExtraMain:
                case TableType.ttRelation:
                case TableType.ttSubTable:
                case TableType.ttSystem:
                case TableType.ttViewMain:
                case TableType.ttViewBase:
                {
                    chkDBInsert.Checked     = tp.blnInsert = e.Node.Checked;
                    chkDBEdit.Checked       = tp.blnEdit = e.Node.Checked;
                    chkDBDelete.Checked     = tp.blnDelete = e.Node.Checked;
                    chkDBFind.Checked       = tp.blnFind = e.Node.Checked;
                    chkDBFindNext.Checked   = e.Node.Checked;
                    chkDBFilter.Checked     = tp.blnFilter = e.Node.Checked;
                    chkPrintPreview.Checked = tp.blnPrintPreview = e.Node.Checked;
                    chkDataPrint.Checked    = tp.blnPrint = e.Node.Checked;
                    break;
                }
                }
                tp.blnSelect = e.Node.Checked;
                e.Node.Tag   = tp;
                blnIsUpdate  = true;
            }
            break;
            }
        }
        public static bool Authorize(string table, string action, List <Guid> roles)
        {
            //Validate if the user have admin role
            if (roles.Where(r => r.Equals(_adminRoleId)).Count() > 0)
            {
                return(true);
            }

            TablePermission permission = TablePermission.None;

            Enum.TryParse <TablePermission>(action, out permission);
            bool CanDelete = false, CanEdit = false, CanInsert = false;

            switch (permission)
            {
            case TablePermission.Delete:
                CanDelete = true;
                break;

            case TablePermission.Edit:
                CanEdit = true;
                break;

            case TablePermission.Insert:
                CanInsert = true;
                break;
            }

            foreach (Guid rol in roles)
            {
                List <RoleAction> permissionsOnTable = _actions.Where(a => a.Table.ToLowerInvariant().Equals(table.ToLowerInvariant()) &&
                                                                      a.Delete.Equals(CanDelete) &&
                                                                      a.Edit.Equals(CanEdit) &&
                                                                      a.Insert.Equals(CanInsert) &&
                                                                      a.RoleId.Equals(rol)).ToList();
            }

            return(false);
        }
Example #9
0
        private void chkDBInsert_Click(object sender, EventArgs e)
        {
            CheckBox        chk = sender as CheckBox;
            TablePermission tp  = (TablePermission)tvTable.SelectedNode.Tag;

            switch (chk.Name)
            {
            case "chkDBInsert":
                tp.blnInsert = chk.Checked;
                break;

            case "chkDBEdit":
                tp.blnEdit = chk.Checked;
                break;

            case "chkDBDelete":
                tp.blnDelete = chk.Checked;
                break;

            case "chkDBFind":
                tp.blnFind = chkDBFindNext.Checked = chk.Checked;
                break;

            case "chkDBFilter":
                tp.blnFilter = chk.Checked;
                break;

            case "chkPrintPreview":
                tp.blnPrintPreview = chk.Checked;
                break;

            case "chkDataPrint":
                tp.blnPrint = chk.Checked;
                break;
            }
            tvTable.SelectedNode.Tag = tp;
            blnIsUpdate = true;
        }
        private static ZumoTest CreateCRUDTest(string tableName, string providerName, TablePermission tableType, bool userIsAuthenticated, bool usingSingleSignOnOrToken = false)
        {
            List<string> requiredRuntimeReatures = new List<string>() { ZumoTestGlobals.RuntimeFeatureNames.STRING_ID_TABLES };
            if (MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory.ToString().Equals(providerName))
            {
                requiredRuntimeReatures.Add(ZumoTestGlobals.RuntimeFeatureNames.AAD_LOGIN);
            }

            if (usingSingleSignOnOrToken || MicrosoftViaLiveSDK.Equals(providerName))
            {
                requiredRuntimeReatures.Add(ZumoTestGlobals.RuntimeFeatureNames.SSO_LOGIN);
            }

            string testName = string.Format(CultureInfo.InvariantCulture, "CRUD, {0}, table with {1} permissions",
                userIsAuthenticated ? ("auth by " + providerName) : "unauthenticated", tableType);
            return new ZumoTest(testName, async delegate(ZumoTest test)
            {
                var client = ZumoTestGlobals.Instance.Client;
                var currentUser = client.CurrentUser;
                var table = client.GetTable(tableName);
                var crudShouldWork = tableType == TablePermission.Public ||
                    tableType == TablePermission.Application ||
                    (tableType == TablePermission.User && userIsAuthenticated);
                var item = new JObject();
                item.Add("name", "John Doe");
                int id = 1;
                Dictionary<string, string> queryParameters = new Dictionary<string, string>
                {
                    { "userIsAuthenticated", userIsAuthenticated.ToString().ToLowerInvariant() },
                };
                MobileServiceInvalidOperationException ex = null;
                try
                {
                    var inserted = await table.InsertAsync(item, queryParameters);
                    item = (JObject)inserted;
                    Util.CamelCaseProps(item);

                    test.AddLog("Inserted item: {0}", item);
                    id = item["id"].Value<int>();
                    if (tableType == TablePermission.User)
                    {
                        // script added user id to the document. Validating it
                        var userId = item["userId"].Value<string>();
                        if (userId == currentUser.UserId)
                        {
                            test.AddLog("User id correctly added by the server script");
                        }
                        else
                        {
                            test.AddLog("Error, user id not set by the server script");
                            return false;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    item["id"] = 1; // used in other requests
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                if (tableType == TablePermission.Public)
                {
                    // Update, Read and Delete are public; we don't need the app key anymore
                    var oldClient = client;
                    client = new MobileServiceClient(oldClient.ApplicationUri);
                    if (oldClient.CurrentUser != null)
                    {
                        client.CurrentUser = new MobileServiceUser(oldClient.CurrentUser.UserId);
                        client.CurrentUser.MobileServiceAuthenticationToken = oldClient.CurrentUser.MobileServiceAuthenticationToken;
                    }

                    table = client.GetTable(tableName);
                }

                ex = null;
                try
                {
                    item["name"] = "Jane Roe";
                    var updated = await table.UpdateAsync(item, queryParameters);
                    test.AddLog("Updated item: {0}", updated);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    var item2 = await table.LookupAsync(id, queryParameters);
                    test.AddLog("Retrieved item via Lookup: {0}", item2);
                    var obj = item2 as JObject;
                    bool usersEnabled = false;
                    if (obj["UsersEnabled"] != null)
                    {
                        usersEnabled = obj["UsersEnabled"].Value<bool>();
                    }
                    if (obj["Identities"] != null)
                    {
                        string identities = obj["Identities"].Value<string>();
                        try
                        {
                            var identitiesObj = JObject.Parse(identities);
                            test.AddLog("Identities object: {0}", identitiesObj);
                            if (usersEnabled)
                            {
                                string userName = NameOrScreenName(providerName, identitiesObj);
                                test.AddLog("User name: {0}", userName ?? "<<null>>");
                                if (userName == null)
                                {
                                    test.AddLog("Error, with users feature enabled, user identity should have a name (or screen_name in case of twitter)");
                                    return false;
                                }
                            }

                            lastUserIdentityObject = identitiesObj;
                        }
                        catch (Exception ex2)
                        {
                            test.AddLog("Could not parse the identites object as JSON: {0}", ex2);
                            lastUserIdentityObject = null;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    JToken items = null;
                    if (ZumoTestGlobals.Instance.IsNetRuntime)
                    {
                        items = await table.ReadAsync("$filter=Id eq '" + id + "'", queryParameters);
                    }
                    else
                    {
                        items = await table.ReadAsync("$filter=id eq " + id, queryParameters);
                    }
                    test.AddLog("Retrieved items via Read: {0}", items);
                    if (((JArray)items).Count != 1)
                    {
                        test.AddLog("Error, query should have returned exactly one item");
                        return false;
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    await table.DeleteAsync(item, queryParameters);
                    test.AddLog("Deleted item: {0}", item);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                return true;
            }, requiredRuntimeReatures.ToArray());
        }
 /// <summary>
 /// Create a new instance of this operation
 /// </summary>
 /// <param name="table">The table you specify the permission</param>
 /// <param name="user">The user you specify the permission</param>
 /// <param name="permission">The permission to specify</param>
 public GrantTablePermissionOperation(string table, string user, TablePermission permission)
     : base(table, user, permission)
 {
 }
 /// <summary>
 /// Remove table permission to specified user
 /// </summary>
 /// <param name="migration">The DbMigration</param>
 /// <param name="table">The table you remove the permission</param>
 /// <param name="user">The user you remove the permission</param>
 /// <param name="permission">The permission to revoke</param>
 public static void RevokeTablePermission(this DbMigration migration, string table, string user, TablePermission permission)
 {
     ((IDbMigration)migration)
     .AddOperation(new RevokeTablePermissionOperation(table, user, permission));
 }
        private static ZumoTest CreateCRUDTest(string tableName, string providerName, TablePermission tableType, bool userIsAuthenticated)
        {
            string testName = string.Format(CultureInfo.InvariantCulture, "CRUD, {0}, table with {1} permissions",
                userIsAuthenticated ? ("auth by " + providerName) : "unauthenticated", tableType);
            return new ZumoTest(testName, async delegate(ZumoTest test)
            {
                var client = ZumoTestGlobals.Instance.Client;
                var currentUser = client.CurrentUser;
                var table = client.GetTable(tableName);
                var crudShouldWork = tableType == TablePermission.Public || 
                    tableType == TablePermission.Application || 
                    (tableType == TablePermission.User && userIsAuthenticated);
                var item = new JObject();
                item.Add("Name", "John Doe");
                int id = 1;
                Dictionary<string, string> queryParameters = new Dictionary<string, string>
                {
                    { "userIsAuthenticated", userIsAuthenticated.ToString().ToLowerInvariant() },
                };
                MobileServiceInvalidOperationException ex = null;
                try
                {
                    var inserted = await table.InsertAsync(item, queryParameters);
                    item = (JObject)inserted;
                    test.AddLog("Inserted item: {0}", item);
                    id = item["id"].Value<int>();
                    if (tableType == TablePermission.User)
                    {
                        // script added user id to the document. Validating it
                        var userId = item["userId"].Value<string>();
                        if (userId == currentUser.UserId)
                        {
                            test.AddLog("User id correctly added by the server script");
                        }
                        else
                        {
                            test.AddLog("Error, user id not set by the server script");
                            return false;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    item["id"] = 1; // used in other requests
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                if (tableType == TablePermission.Public)
                {
                    // Update, Read and Delete are public; we don't need the app key anymore
                    var oldClient = client;
                    client = new MobileServiceClient(oldClient.ApplicationUri);
                    if (oldClient.CurrentUser != null)
                    {
                        client.CurrentUser = new MobileServiceUser(oldClient.CurrentUser.UserId);
                        client.CurrentUser.MobileServiceAuthenticationToken = oldClient.CurrentUser.MobileServiceAuthenticationToken;
                    }

                    table = client.GetTable(tableName);
                }

                ex = null;
                try
                {
                    item["Name"] = "Jane Roe";
                    var updated = await table.UpdateAsync(item, queryParameters);
                    test.AddLog("Updated item: {0}", updated);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    var item2 = await table.LookupAsync(id, queryParameters);
                    test.AddLog("Retrieved item via Lookup: {0}", item2);
                    var obj = item2 as JObject;
                    if (obj["Identities"] != null)
                    {
                        string identities = obj["Identities"].Value<string>();
                        try
                        {
                            var identitiesObj = JObject.Parse(identities);
                            test.AddLog("Identities object: {0}", identitiesObj);
                            lastUserIdentityObject = identitiesObj;
                        }
                        catch (Exception ex2)
                        {
                            test.AddLog("Could not parse the identites object as JSON: {0}", ex2);
                            lastUserIdentityObject = null;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    var items = await table.ReadAsync("$filter=id eq " + id, queryParameters);
                    test.AddLog("Retrieved items via Read: {0}", items);
                    if (((JArray)items).Count != 1)
                    {
                        test.AddLog("Error, query should have returned exactly one item");
                        return false;
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    await table.DeleteAsync(item, queryParameters);
                    test.AddLog("Deleted item: {0}", item);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                return true;
            });
        }
        private static ZumoTest CreateCRUDTest(string tableName, string providerName, TablePermission tableType, bool userIsAuthenticated, bool usingSingleSignOnOrToken = false)
        {
            List <string> requiredRuntimeReatures = new List <string>()
            {
                ZumoTestGlobals.RuntimeFeatureNames.STRING_ID_TABLES
            };

            if (MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory.ToString().Equals(providerName))
            {
                requiredRuntimeReatures.Add(ZumoTestGlobals.RuntimeFeatureNames.AAD_LOGIN);
            }

            if (usingSingleSignOnOrToken || MicrosoftViaLiveSDK.Equals(providerName))
            {
                requiredRuntimeReatures.Add(ZumoTestGlobals.RuntimeFeatureNames.SSO_LOGIN);
            }

            string testName = string.Format(CultureInfo.InvariantCulture, "CRUD, {0}, table with {1} permissions",
                                            userIsAuthenticated ? ("auth by " + providerName) : "unauthenticated", tableType);

            return(new ZumoTest(testName, async delegate(ZumoTest test)
            {
                var client = ZumoTestGlobals.Instance.Client;
                var currentUser = client.CurrentUser;
                var table = client.GetTable(tableName);
                var crudShouldWork = tableType == TablePermission.Public ||
                                     tableType == TablePermission.Application ||
                                     (tableType == TablePermission.User && userIsAuthenticated);
                var item = new JObject();
                item.Add("name", "John Doe");
                int id = 1;
                Dictionary <string, string> queryParameters = new Dictionary <string, string>
                {
                    { "userIsAuthenticated", userIsAuthenticated.ToString().ToLowerInvariant() },
                };
                MobileServiceInvalidOperationException ex = null;
                try
                {
                    var inserted = await table.InsertAsync(item, queryParameters);
                    item = (JObject)inserted;
                    Util.CamelCaseProps(item);

                    test.AddLog("Inserted item: {0}", item);
                    id = item["id"].Value <int>();
                    if (tableType == TablePermission.User)
                    {
                        // script added user id to the document. Validating it
                        var userId = item["userId"].Value <string>();
                        if (userId == currentUser.UserId)
                        {
                            test.AddLog("User id correctly added by the server script");
                        }
                        else
                        {
                            test.AddLog("Error, user id not set by the server script");
                            return false;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    item["id"] = 1; // used in other requests
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                if (tableType == TablePermission.Public)
                {
                    // Update, Read and Delete are public; we don't need the app key anymore
                    var oldClient = client;
                    client = new MobileServiceClient(oldClient.ApplicationUri);
                    if (oldClient.CurrentUser != null)
                    {
                        client.CurrentUser = new MobileServiceUser(oldClient.CurrentUser.UserId);
                        client.CurrentUser.MobileServiceAuthenticationToken = oldClient.CurrentUser.MobileServiceAuthenticationToken;
                    }

                    table = client.GetTable(tableName);
                }

                ex = null;
                try
                {
                    item["name"] = "Jane Roe";
                    var updated = await table.UpdateAsync(item, queryParameters);
                    test.AddLog("Updated item: {0}", updated);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    var item2 = await table.LookupAsync(id, queryParameters);
                    test.AddLog("Retrieved item via Lookup: {0}", item2);
                    var obj = item2 as JObject;
                    bool usersEnabled = false;
                    if (obj["UsersEnabled"] != null)
                    {
                        usersEnabled = obj["UsersEnabled"].Value <bool>();
                    }
                    if (obj["Identities"] != null)
                    {
                        string identities = obj["Identities"].Value <string>();
                        try
                        {
                            var identitiesObj = JObject.Parse(identities);
                            test.AddLog("Identities object: {0}", identitiesObj);
                            if (usersEnabled)
                            {
                                string userName = NameOrScreenName(providerName, identitiesObj);
                                test.AddLog("User name: {0}", userName ?? "<<null>>");
                                if (userName == null)
                                {
                                    test.AddLog("Error, with users feature enabled, user identity should have a name (or screen_name in case of twitter)");
                                    return false;
                                }
                            }

                            lastUserIdentityObject = identitiesObj;
                        }
                        catch (Exception ex2)
                        {
                            test.AddLog("Could not parse the identites object as JSON: {0}", ex2);
                            lastUserIdentityObject = null;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    JToken items = null;
                    if (ZumoTestGlobals.Instance.IsNetRuntime)
                    {
                        items = await table.ReadAsync("$filter=Id eq '" + id + "'", queryParameters);
                    }
                    else
                    {
                        items = await table.ReadAsync("$filter=id eq " + id, queryParameters);
                    }
                    test.AddLog("Retrieved items via Read: {0}", items);
                    if (((JArray)items).Count != 1)
                    {
                        test.AddLog("Error, query should have returned exactly one item");
                        return false;
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    await table.DeleteAsync(item, queryParameters);
                    test.AddLog("Deleted item: {0}", item);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                return true;
            }, requiredRuntimeReatures.ToArray()));
        }
        private static ZumoTest CreateCRUDTest(string tableName, string providerName, TablePermission tableType, bool userIsAuthenticated)
        {
            string testName = string.Format(CultureInfo.InvariantCulture, "CRUD, {0}, table with {1} permissions",
                userIsAuthenticated ? "unauthenticated" : ("auth by " + providerName), tableType);
            return new ZumoTest(testName, async delegate(ZumoTest test)
            {
                var client = ZumoTestGlobals.Instance.Client;
                var table = client.GetTable(tableName);
                var crudShouldWork = tableType == TablePermission.Public || 
                    tableType == TablePermission.Application || 
                    (tableType == TablePermission.User && userIsAuthenticated);
                var item = new JsonObject();
                item.Add("Name", JsonValue.CreateStringValue("John Doe"));
                int id = 1;
                MobileServiceInvalidOperationException ex = null;
                try
                {
                    await table.InsertAsync(item);
                    test.AddLog("Inserted item: {0}", item.Stringify());
                    id = (int)item["id"].GetNumber();
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    item["id"] = JsonValue.CreateNumberValue(1); // used in other requests
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    item["Name"] = JsonValue.CreateStringValue("Jane Roe");
                    await table.UpdateAsync(item);
                    test.AddLog("Updated item: {0}", item.Stringify());
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    var item2 = await table.LookupAsync(id);
                    test.AddLog("Retrieved item: {0}", item2.Stringify());
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    await table.DeleteAsync(item);
                    test.AddLog("Deleted item: {0}", item.Stringify());
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                return true;
            });
        }
        private static ZumoTest CreateCRUDTest(string tableName, string providerName, TablePermission tableType, bool userIsAuthenticated)
        {
            string testName = string.Format(CultureInfo.InvariantCulture, "CRUD, {0}, table with {1} permissions",
                                            userIsAuthenticated ? ("auth by " + providerName) : "unauthenticated", tableType);

            return(new ZumoTest(testName, async delegate(ZumoTest test)
            {
                var client = ZumoTestGlobals.Instance.Client;
                var currentUser = client.CurrentUser;
                var table = client.GetTable(tableName);
                var crudShouldWork = tableType == TablePermission.Public ||
                                     tableType == TablePermission.Application ||
                                     (tableType == TablePermission.User && userIsAuthenticated);
                var item = new JObject();
                item.Add("Name", "John Doe");
                int id = 1;
                Dictionary <string, string> queryParameters = new Dictionary <string, string>
                {
                    { "userIsAuthenticated", userIsAuthenticated.ToString().ToLowerInvariant() },
                };
                MobileServiceInvalidOperationException ex = null;
                try
                {
                    var inserted = await table.InsertAsync(item, queryParameters);
                    item = (JObject)inserted;
                    test.AddLog("Inserted item: {0}", item);
                    id = item["id"].Value <int>();
                    if (tableType == TablePermission.User)
                    {
                        // script added user id to the document. Validating it
                        var userId = item["userId"].Value <string>();
                        if (userId == currentUser.UserId)
                        {
                            test.AddLog("User id correctly added by the server script");
                        }
                        else
                        {
                            test.AddLog("Error, user id not set by the server script");
                            return false;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    item["id"] = 1; // used in other requests
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                if (tableType == TablePermission.Public)
                {
                    // Update, Read and Delete are public; we don't need the app key anymore
                    var oldClient = client;
                    client = new MobileServiceClient(oldClient.ApplicationUri);
                    if (oldClient.CurrentUser != null)
                    {
                        client.CurrentUser = new MobileServiceUser(oldClient.CurrentUser.UserId);
                        client.CurrentUser.MobileServiceAuthenticationToken = oldClient.CurrentUser.MobileServiceAuthenticationToken;
                    }

                    table = client.GetTable(tableName);
                }

                ex = null;
                try
                {
                    item["Name"] = "Jane Roe";
                    var updated = await table.UpdateAsync(item, queryParameters);
                    test.AddLog("Updated item: {0}", updated);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    var item2 = await table.LookupAsync(id, queryParameters);
                    test.AddLog("Retrieved item via Lookup: {0}", item2);
                    var obj = item2 as JObject;
                    if (obj["Identities"] != null)
                    {
                        string identities = obj["Identities"].Value <string>();
                        try
                        {
                            var identitiesObj = JObject.Parse(identities);
                            test.AddLog("Identities object: {0}", identitiesObj);
                            lastUserIdentityObject = identitiesObj;
                        }
                        catch (Exception ex2)
                        {
                            test.AddLog("Could not parse the identites object as JSON: {0}", ex2);
                            lastUserIdentityObject = null;
                        }
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    var items = await table.ReadAsync("$filter=id eq " + id, queryParameters);
                    test.AddLog("Retrieved items via Read: {0}", items);
                    if (((JArray)items).Count != 1)
                    {
                        test.AddLog("Error, query should have returned exactly one item");
                        return false;
                    }
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                ex = null;
                try
                {
                    await table.DeleteAsync(item, queryParameters);
                    test.AddLog("Deleted item: {0}", item);
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    ex = e;
                }

                if (!ValidateExpectedError(test, ex, crudShouldWork))
                {
                    return false;
                }

                return true;
            }));
        }