public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
           
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            AuthContext _auth = new AuthContext();
            UserManager<IdentityUser> _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_auth));
            RoleManager<IdentityRole> _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_auth));

            AuthRepository _repo = new AuthRepository();
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
                
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }


            var userIdentity = await _userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);

            foreach (IdentityUserRole role in user.Roles)
            {
                var iRole = _roleManager.FindById(role.RoleId);
                userIdentity.AddClaim(new Claim(ClaimTypes.Role, iRole.Name));
            }
            
            userIdentity.AddClaim(new Claim("sub", context.UserName));
            userIdentity.AddClaim(new Claim("role", "user"));
            
            var ticket = new AuthenticationTicket(userIdentity, null);

            context.Validated(ticket);
        }
Example #2
0
 /*
 ** Pop an authorization context that was previously pushed
 ** by sqlite3AuthContextPush
 */
 void sqlite3AuthContextPop(AuthContext *pContext)
 {
     if( pContext->pParse ){
     pContext->pParse->zAuthContext = pContext->zAuthContext;
     pContext->pParse = 0;
     }
 }
        public async Task<Confirmed> Get(string id)
        {
           string uid = Encoding.ASCII.GetString(HttpServerUtility.UrlTokenDecode(id));
            Confirmed c = new Confirmed();
            string fullstring = Util.Decrypt(uid, true);
            int index = fullstring.IndexOf("{GreenTime}");
           string  UserName = fullstring.Substring(0, index);
            string Password = fullstring.Substring(index + 11);

            AuthContext context = new AuthContext();
           IdentityUser user = null;
          
            People ps = context.Peoples.Where(p => p.email == UserName).SingleOrDefault();
            ps.emailConfirmed = true;

            using (AuthRepository _repo = new AuthRepository())
            {

                user = await _repo.FindUser(UserName, Password);


                if (user != null)
                {
                    context.updatePeople(ps);
                    c.isConfirmed = true;

                    return c;
                }
            }
        
            return c;
        }
 public AuthRepository()
 {
     _db = new DataContext();
     _ctx = new AuthContext();
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
     _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_ctx));
 }
Example #5
0
 public AuthRepository(IContextFactory contextFactory)
 {
     _contextFactory = contextFactory;
     _authContext = new AuthContext();
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_authContext));
     _userManager.UserTokenProvider = new TotpSecurityStampBasedTokenProvider<IdentityUser, string>();
 }
Example #6
0
 public LoginViewModel(DataRetrieval dataRetrieval, AuthContext authContext)
 {
     _dataRetrieval = dataRetrieval;
     _authContext = authContext;
     LoginCommand = new DelegateCommand(LoginExecuted, LoginCanExecute);
     UserName = "******";
     Password = "******";
 }
 public AuthContext Get()
 {
     if (dataContext == null)
     {
         dataContext = new AuthContext();
     }
     return dataContext;
 }
Example #8
0
 private void AuthContextPop(AuthContext ctx)
 {
     if (ctx.Parse != null)
     {
         ctx.Parse._authContext = ctx.Context;
         ctx.Parse = null;
     }
 }
 public ApplicationRepository()
 {
     _ctx = new AuthContext();
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
     RefreshTokens = new RefreshTokenRepository(_ctx);
     Audiences = new AudienceRepository(_ctx);
     Files = new FileRepository(_ctx);
 }
Example #10
0
       public UserRepository()
       {
           _authContext = new AuthContext();
           _userManager = new UserManager<User>(new UserStore<User>(_authContext));



       }
 //private UserManager<MemberUser> _userInfo;
 public AuthRepository()
 {
     _ctx = new AuthContext();
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
     _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_ctx));
     //_userroleManager = new UserManager<IdentityUserRole>();
     //_userInfo = new UserManager<MemberUser>(new UserStore<MemberUser>(_ctx));
     
     
 }
    public AccountController()
    {
        _repo = new AuthRepository();
        _ctx = new AuthContext();

        UserStore<UserModel> userStore = new UserStore<UserModel>(_ctx);
        _userManager = new UserManager<UserModel>(userStore);

        _userBCA = new UserBusinessComponentAdapter();
    }
Example #13
0
        /*
        ** Push an authorization context.  After this routine is called, the
        ** zArg3 argument to authorization callbacks will be zContext until
        ** popped.  Or if pParse==0, this routine is a no-op.
        */
        void sqlite3AuthContextPush(
Parse *pParse,
AuthContext *pContext,
string zContext
)
        {
            Debug.Assert( pParse );
            pContext->pParse = pParse;
            pContext->zAuthContext = pParse->zAuthContext;
            pParse->zAuthContext = zContext;
        }
Example #14
0
 public AuthRepository()
 {
     _ctx = new AuthContext();
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
     _userManager.PasswordValidator = new PasswordValidator() {
         RequiredLength = 3,
         RequireNonLetterOrDigit = false,
         RequireDigit = false,
         RequireLowercase = false,
         RequireUppercase = false
     };
 }
 public async Task<IdentityResult> UpdateUser(IdentityUser user)
 {
     IdentityResult user1 = null;
     try
     {
         _ctx = new AuthContext();
         _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
         user1 = await _userManager.UpdateAsync(user);
     }
     catch (Exception ex) { }
     return user1;
 }
        public IHttpActionResult Get()
        {

            AuthContext context = new AuthContext();

            //ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            //var Name = ClaimsPrincipal.Current.Identity.Name;
            //var Name1 = User.Identity.Name;

            //var userName = principal.Claims.Where(c => c.Type == "sub").Single().Value;

             return Ok(Helper.createUsers());
        }
        public AuthRepository()
        {
            try
            {
                _ctx = new AuthContext();
                _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("AuthRepository Exception.",ex.Message);

                //throw;
            }
        }
Example #18
0
 public static void AddUserIfNotExists(string userName, string pwd)
 {
     using (var ctx = new AuthContext())
     {
         using (var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(ctx)))
         {
             var userExists = userManager.Users.Any(u => u.UserName == userName);
             if (!userExists)
             {
                 userManager.Create(new IdentityUser(userName), pwd);
             }
         }
     } 
 }
 public AuthRepository()
 {
     var provider = new DpapiDataProtectionProvider("Microbrew.it");
     _ctx = new AuthContext();
     //_userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx))
     {
         EmailService = new EmailService()
     };
     _userManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(provider.Create("ASP.NET Identity"))
     {
         //Sets the lifespan of the confirm email token and the reset password token.
         TokenLifespan = TimeSpan.FromMinutes(1),
     };
 }
Example #20
0
        public void Execute()
        {

            var container = new WindsorContainer().Install(FromAssembly.This());

            GlobalConfiguration.Configuration.Services.Replace(
                typeof(IHttpControllerActivator),
                new WindsorControllerActivator(container.Kernel));

            var locator = new WindsorServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => locator);

            var securityContext = new AuthContext();
            securityContext.Database.Initialize(true);

            var context = new RMSContext();
            context.Database.Initialize(true);
        }
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var pagePathValue = filterContext.RouteData.Values["pagePath"];
            if (pagePathValue == null)
                return;

            var authorizer = DependencyResolver.Current.GetService<IWikiAuthorizationFilter>();

            if (authorizer != null)
            {
                var ctx = new AuthContext
                              {
                                  AuthorizationContext = filterContext,
                                  PagePath = new PagePath(pagePathValue.ToString())
                              };

                authorizer.Authorize(ctx);
            }
        }
 public Dictionary<string, string> GetCredentials(AuthContext context, string bucketName)
 {
     switch (context)
     {
         case AuthContext.BucketKv:
         case AuthContext.BucketN1Ql:
             string bucketPassword;
             if (BucketCredentials.TryGetValue(bucketName, out bucketPassword))
             {
                 return new Dictionary<string, string> {{bucketName, bucketPassword}};
             }
             throw new AuthenticationException(ExceptionUtil.GetMessage(ExceptionUtil.BucketCredentialsMissingMsg, bucketName));
         case AuthContext.ClusterCbft:
         case AuthContext.ClusterN1Ql:
             return new Dictionary<string, string>(BucketCredentials);
         case AuthContext.ClusterMgmt:
             return new Dictionary<string, string> { { ClusterUsername, ClusterPassword } };
         default:
             throw new ArgumentOutOfRangeException("context", context, null);
     }
 }
		public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {

			context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

			AuthContext _ctx = new AuthContext();
			using (UserManager<IdentityUser> _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx))) {
				IdentityUser user = await _userManager.FindAsync(context.UserName, context.Password);

				if (user == null) {
					context.SetError("invalid_grant", "The user name or password is incorrect.");
					return;
				}
			}

			var identity = new ClaimsIdentity(context.Options.AuthenticationType);
			identity.AddClaim(new Claim("sub", context.UserName));
			identity.AddClaim(new Claim("role", "user"));
			identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

			context.Validated(identity);

		}
        public static List <Inventory> ReturnAllInventory(AuthContext _context)
        {
            List <Inventory> inv = _context.Inventory.ToList();

            return(inv);
        }
        public static List <Order> ReturnCustomerOrderByEmail(AuthContext _context, string email)
        {
            List <Order> orders = _context.Order.Where(b => (b.ApplicationUser.Email == email)).ToList();

            return(orders);
        }
Example #26
0
        private async Task ProcessRecordAsync()
        {
            using (NoSynchronizationContext)
            {
                IAuthContext authContext = new AuthContext {
                    TenantId = TenantId
                };
                // Set selected environment to the session object.
                GraphSession.Instance.Environment = environment;

                switch (ParameterSetName)
                {
                case Constants.UserParameterSet:
                {
                    // 2 mins timeout. 1 min < HTTP timeout.
                    TimeSpan authTimeout = new TimeSpan(0, 0, Constants.MaxDeviceCodeTimeOut);
                    // To avoid re-initializing the tokenSource, use CancelAfter
                    _cancellationTokenSource.CancelAfter(authTimeout);
                    authContext.AuthType = AuthenticationType.Delegated;
                    string[] processedScopes = ProcessScopes(Scopes);
                    authContext.Scopes = processedScopes.Length == 0 ? new string[] { "User.Read" } : processedScopes;
                    // Default to CurrentUser but allow the customer to change this via `ContextScope` param.
                    authContext.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.CurrentUser;
                }
                break;

                case Constants.AppParameterSet:
                {
                    authContext.AuthType = AuthenticationType.AppOnly;
                    authContext.ClientId = ClientId;
                    authContext.CertificateThumbprint = CertificateThumbprint;
                    authContext.CertificateName       = CertificateName;
                    authContext.Certificate           = Certificate;
                    // Default to Process but allow the customer to change this via `ContextScope` param.
                    authContext.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.Process;
                }
                break;

                case Constants.AccessTokenParameterSet:
                {
                    authContext.AuthType     = AuthenticationType.UserProvidedAccessToken;
                    authContext.ContextScope = ContextScope.Process;
                    // Store user provided access token to a session object.
                    GraphSession.Instance.UserProvidedToken = new NetworkCredential(string.Empty, AccessToken).SecurePassword;
                }
                break;
                }

                try
                {
                    // Gets a static instance of IAuthenticationProvider when the client app hasn't changed.
                    IAuthenticationProvider authProvider      = AuthenticationHelpers.GetAuthProvider(authContext);
                    IClientApplicationBase  clientApplication = null;
                    if (ParameterSetName == Constants.UserParameterSet)
                    {
                        clientApplication = (authProvider as DeviceCodeProvider).ClientApplication;
                    }
                    else if (ParameterSetName == Constants.AppParameterSet)
                    {
                        clientApplication = (authProvider as ClientCredentialProvider).ClientApplication;
                    }

                    // Incremental scope consent without re-instantiating the auth provider. We will use a static instance.
                    GraphRequestContext graphRequestContext = new GraphRequestContext();
                    graphRequestContext.CancellationToken = _cancellationTokenSource.Token;
                    graphRequestContext.MiddlewareOptions = new Dictionary <string, IMiddlewareOption>
                    {
                        {
                            typeof(AuthenticationHandlerOption).ToString(),
                            new AuthenticationHandlerOption
                            {
                                AuthenticationProviderOption = new AuthenticationProviderOption
                                {
                                    Scopes       = authContext.Scopes,
                                    ForceRefresh = ForceRefresh
                                }
                            }
                        }
                    };

                    // Trigger consent.
                    HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
                    httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), graphRequestContext);
                    await authProvider.AuthenticateRequestAsync(httpRequestMessage);

                    IAccount account = null;
                    if (clientApplication != null)
                    {
                        // Only get accounts when we are using MSAL to get an access token.
                        IEnumerable <IAccount> accounts = clientApplication.GetAccountsAsync().GetAwaiter().GetResult();
                        account = accounts.FirstOrDefault();
                    }
                    DecodeJWT(httpRequestMessage.Headers.Authorization?.Parameter, account, ref authContext);

                    // Save auth context to session state.
                    GraphSession.Instance.AuthContext = authContext;
                }
                catch (AuthenticationException authEx)
                {
                    if ((authEx.InnerException is TaskCanceledException) && _cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        // DeviceCodeTimeout
                        throw new Exception(string.Format(
                                                CultureInfo.CurrentCulture,
                                                ErrorConstants.Message.DeviceCodeTimeout,
                                                Constants.MaxDeviceCodeTimeOut));
                    }
                    else
                    {
                        throw authEx.InnerException ?? authEx;
                    }
                }
                catch (Exception ex)
                {
                    throw ex.InnerException ?? ex;
                }

                WriteObject("Welcome To Microsoft Graph!");
            }
        }
        public static List <ApplicationUser> ReturnCustomerByEmail(AuthContext _context, string email)
        {
            List <ApplicationUser> user = _context.ApplicationUsers.Where(b => (b.Email == email)).ToList();

            return(user);
        }
 public PermissionService(AuthContext context)
 {
     _context = context;
 }
 public AssignRolesController()
 {
     context     = new AuthContext();
     UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
     RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
 }
        public static List <Inventory> ReturnInventoryById(AuthContext _context, int id)
        {
            var inventory = _context.Inventory.Where(b => (b.StoreId == id) && (b.Quantity > 0)).Include(m => m.Product).ToList();

            return(inventory);
        }
Example #31
0
        public void Inicializar(int bloqueId)
        {
            AuthContext db = new AuthContext();

            bloque = db.Bloques.Include(s => s.SubTema.Tema).Include(s => s.Tests).Include(s => s.TipoEjercicio).SingleOrDefault(bl => bl.BloqueId == bloqueId);
        }
Example #32
0
 public AuthRepository()
 {
     _ctx = new AuthContext();
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
 }
        public static List <OrderDetails> ReturnOrderDetailsByOrderId(AuthContext _context, int id)
        {
            List <OrderDetails> stuff1 = _context.OrderDetails.Where(b => (b.Order.OrderId == id)).Include(m => m.Product).ToList();

            return(stuff1);
        }
Example #34
0
		/*
		** Process an UPDATE statement.
		**
		**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
		**          \_______/ \________/     \______/       \________________/
		*            onError   pTabList      pChanges             pWhere
		*/
		static void sqlite3Update(
		Parse pParse,         /* The parser context */
		SrcList pTabList,     /* The table in which we should change things */
		ExprList pChanges,    /* Things to be changed */
		Expr pWhere,          /* The WHERE clause.  May be null */
		int onError           /* How to handle constraint errors */
		)
		{
			int i, j;                   /* Loop counters */
			Table pTab;                 /* The table to be updated */
			int addr = 0;               /* VDBE instruction address of the start of the loop */
			WhereInfo pWInfo;           /* Information about the WHERE clause */
			Vdbe v;                     /* The virtual database engine */
			Index pIdx;                 /* For looping over indices */
			int nIdx;                   /* Number of indices that need updating */
			int iCur;                   /* VDBE Cursor number of pTab */
			sqlite3 db;                 /* The database structure */
			int[] aRegIdx = null;       /* One register assigned to each index to be updated */
			int[] aXRef = null;         /* aXRef[i] is the index in pChanges.a[] of the
** an expression for the i-th column of the table.
** aXRef[i]==-1 if the i-th column is not changed. */
			bool chngRowid;             /* True if the record number is being changed */
			Expr pRowidExpr = null;     /* Expression defining the new record number */
			bool openAll = false;       /* True if all indices need to be opened */
			AuthContext sContext;       /* The authorization context */
			NameContext sNC;            /* The name-context to resolve expressions in */
			int iDb;                    /* Database containing the table being updated */
			bool okOnePass;             /* True for one-pass algorithm without the FIFO */
			bool hasFK;                 /* True if foreign key processing is required */

#if !SQLITE_OMIT_TRIGGER
			bool isView;            /* True when updating a view (INSTEAD OF trigger) */
			Trigger pTrigger;      /* List of triggers on pTab, if required */
			int tmask = 0;         /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
#endif
			int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */

			/* Register Allocations */
			int regRowCount = 0;         /* A count of rows changed */
			int regOldRowid;             /* The old rowid */
			int regNewRowid;             /* The new rowid */
			int regNew;
			int regOld = 0;
			int regRowSet = 0;           /* Rowset of rows to be updated */

			sContext = new AuthContext(); //memset( &sContext, 0, sizeof( sContext ) );
			db = pParse.db;
			if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
			{
				goto update_cleanup;
			}
			Debug.Assert(pTabList.nSrc == 1);

			/* Locate the table which we want to update.
			*/
			pTab = sqlite3SrcListLookup(pParse, pTabList);
			if (pTab == null)
				goto update_cleanup;
			iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);

			/* Figure out if we have any triggers and if the table being
			** updated is a view.
			*/
#if !SQLITE_OMIT_TRIGGER
			pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, out tmask);
			isView = pTab.pSelect != null;
			Debug.Assert(pTrigger != null || tmask == 0);
#else
	  const Trigger pTrigger = null;//# define pTrigger 0
	  const int tmask = 0;          //# define tmask 0
#endif
#if SQLITE_OMIT_TRIGGER || SQLITE_OMIT_VIEW
//    # undef isView
	  const bool isView = false;    //# define isView 0
#endif

			if (sqlite3ViewGetColumnNames(pParse, pTab) != 0)
			{
				goto update_cleanup;
			}
			if (sqlite3IsReadOnly(pParse, pTab, tmask))
			{
				goto update_cleanup;
			}
			aXRef = new int[pTab.nCol];// sqlite3DbMallocRaw(db, sizeof(int) * pTab.nCol);
			//if ( aXRef == null ) goto update_cleanup;
			for (i = 0; i < pTab.nCol; i++)
				aXRef[i] = -1;

			/* Allocate a cursors for the main database table and for all indices.
			** The index cursors might not be used, but if they are used they
			** need to occur right after the database cursor.  So go ahead and
			** allocate enough space, just in case.
			*/
			pTabList.a[0].iCursor = iCur = pParse.nTab++;
			for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
			{
				pParse.nTab++;
			}

			/* Initialize the name-context */
			sNC = new NameContext();// memset(&sNC, 0, sNC).Length;
			sNC.pParse = pParse;
			sNC.pSrcList = pTabList;

			/* Resolve the column names in all the expressions of the
			** of the UPDATE statement.  Also find the column index
			** for each column to be updated in the pChanges array.  For each
			** column to be updated, make sure we have authorization to change
			** that column.
			*/
			chngRowid = false;
			for (i = 0; i < pChanges.nExpr; i++)
			{
				if (sqlite3ResolveExprNames(sNC, ref pChanges.a[i].pExpr) != 0)
				{
					goto update_cleanup;
				}
				for (j = 0; j < pTab.nCol; j++)
				{
					if (pTab.aCol[j].zName.Equals(pChanges.a[i].zName, StringComparison.InvariantCultureIgnoreCase))
					{
						if (j == pTab.iPKey)
						{
							chngRowid = true;
							pRowidExpr = pChanges.a[i].pExpr;
						}
						aXRef[j] = i;
						break;
					}
				}
				if (j >= pTab.nCol)
				{
					if (sqlite3IsRowid(pChanges.a[i].zName))
					{
						chngRowid = true;
						pRowidExpr = pChanges.a[i].pExpr;
					}
					else
					{
						sqlite3ErrorMsg(pParse, "no such column: %s", pChanges.a[i].zName);
						pParse.checkSchema = 1;
						goto update_cleanup;
					}
				}
#if !SQLITE_OMIT_AUTHORIZATION
{
int rc;
rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab.zName,
pTab.aCol[j].zName, db.aDb[iDb].zName);
if( rc==SQLITE_DENY ){
goto update_cleanup;
}else if( rc==SQLITE_IGNORE ){
aXRef[j] = -1;
}
}
#endif
			}

			hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid ? 1 : 0) != 0;

			/* Allocate memory for the array aRegIdx[].  There is one entry in the
			** array for each index associated with table being updated.  Fill in
			** the value with a register number for indices that are to be used
			** and with zero for unused indices.
			*/
			for (nIdx = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, nIdx++)
			{
			}
			if (nIdx > 0)
			{
				aRegIdx = new int[nIdx]; // sqlite3DbMallocRaw(db, Index*.Length * nIdx);
				if (aRegIdx == null)
					goto update_cleanup;
			}
			for (j = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, j++)
			{
				int reg;
				if (hasFK || chngRowid)
				{
					reg = ++pParse.nMem;
				}
				else
				{
					reg = 0;
					for (i = 0; i < pIdx.nColumn; i++)
					{
						if (aXRef[pIdx.aiColumn[i]] >= 0)
						{
							reg = ++pParse.nMem;
							break;
						}
					}
				}
				aRegIdx[j] = reg;
			}

			/* Begin generating code. */
			v = sqlite3GetVdbe(pParse);
			if (v == null)
				goto update_cleanup;
			if (pParse.nested == 0)
				sqlite3VdbeCountChanges(v);
			sqlite3BeginWriteOperation(pParse, 1, iDb);

#if !SQLITE_OMIT_VIRTUALTABLE
			/* Virtual tables must be handled separately */
			if (IsVirtual(pTab))
			{
				updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
								   pWhere, onError);
				pWhere = null;
				pTabList = null;
				goto update_cleanup;
			}
#endif

			/* Allocate required registers. */
			regOldRowid = regNewRowid = ++pParse.nMem;
			if (pTrigger != null || hasFK)
			{
				regOld = pParse.nMem + 1;
				pParse.nMem += pTab.nCol;
			}
			if (chngRowid || pTrigger != null || hasFK)
			{
				regNewRowid = ++pParse.nMem;
			}
			regNew = pParse.nMem + 1;
			pParse.nMem += pTab.nCol;

			/* Start the view context. */
			if (isView)
			{
				sqlite3AuthContextPush(pParse, sContext, pTab.zName);
			}

			/* If we are trying to update a view, realize that view into
			** a ephemeral table.
			*/
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
			if (isView)
			{
				sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
			}
#endif

			/* Resolve the column names in all the expressions in the
** WHERE clause.
*/
			if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0)
			{
				goto update_cleanup;
			}

			/* Begin the database scan
			*/
			sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
			ExprList NullOrderby = null;
			pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref NullOrderby, WHERE_ONEPASS_DESIRED);
			if (pWInfo == null)
				goto update_cleanup;
			okOnePass = pWInfo.okOnePass != 0;

			/* Remember the rowid of every item to be updated.
			*/
			sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
			if (!okOnePass)
			{
				regRowSet = ++pParse.nMem;
				sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
			}

			/* End the database scan loop.
			*/
			sqlite3WhereEnd(pWInfo);

			/* Initialize the count of updated rows
			*/
			if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab)
			{
				regRowCount = ++pParse.nMem;
				sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
			}

			if (!isView)
			{
				/*
				** Open every index that needs updating.  Note that if any
				** index could potentially invoke a REPLACE conflict resolution
				** action, then we need to open all indices because we might need
				** to be deleting some records.
				*/
				if (!okOnePass)
					sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
				if (onError == OE_Replace)
				{
					openAll = true;
				}
				else
				{
					openAll = false;
					for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
					{
						if (pIdx.onError == OE_Replace)
						{
							openAll = true;
							break;
						}
					}
				}
				for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++)
				{
					if (openAll || aRegIdx[i] > 0)
					{
						KeyInfo pKey = sqlite3IndexKeyinfo(pParse, pIdx);
						sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur + i + 1, pIdx.tnum, iDb,
						pKey, P4_KEYINFO_HANDOFF);
						Debug.Assert(pParse.nTab > iCur + i + 1);
					}
				}
			}

			/* Top of the update loop */
			if (okOnePass)
			{
				int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
				addr = sqlite3VdbeAddOp0(v, OP_Goto);
				sqlite3VdbeJumpHere(v, a1);
			}
			else
			{
				addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
			}

			/* Make cursor iCur point to the record that is being updated. If
			** this record does not exist for some reason (deleted by a trigger,
			** for example, then jump to the next iteration of the RowSet loop.  */
			sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

			/* If the record number will change, set register regNewRowid to
			** contain the new value. If the record number is not being modified,
			** then regNewRowid is the same register as regOldRowid, which is
			** already populated.  */
			Debug.Assert(chngRowid || pTrigger != null || hasFK || regOldRowid == regNewRowid);
			if (chngRowid)
			{
				sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
				sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
			}

			/* If there are triggers on this table, populate an array of registers 
			** with the required old.* column data.  */
			if (hasFK || pTrigger != null)
			{
				u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
				oldmask |= sqlite3TriggerColmask(pParse,
					pTrigger, pChanges, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onError
				);
				for (i = 0; i < pTab.nCol; i++)
				{
					if (aXRef[i] < 0 || oldmask == 0xffffffff || (i < 32 && 0 != (oldmask & (1 << i))))
					{
						sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld + i);
					}
					else
					{
						sqlite3VdbeAddOp2(v, OP_Null, 0, regOld + i);
					}
				}
				if (chngRowid == false)
				{
					sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
				}
			}

			/* Populate the array of registers beginning at regNew with the new
			** row data. This array is used to check constaints, create the new
			** table and index records, and as the values for any new.* references
			** made by triggers.
			**
			** If there are one or more BEFORE triggers, then do not populate the
			** registers associated with columns that are (a) not modified by
			** this UPDATE statement and (b) not accessed by new.* references. The
			** values for registers not modified by the UPDATE must be reloaded from 
			** the database after the BEFORE triggers are fired anyway (as the trigger 
			** may have modified them). So not loading those that are not going to
			** be used eliminates some redundant opcodes.
			*/
			newmask = (int)sqlite3TriggerColmask(
				pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
			);
			for (i = 0; i < pTab.nCol; i++)
			{
				if (i == pTab.iPKey)
				{
					sqlite3VdbeAddOp2(v, OP_Null, 0, regNew + i);
				}
				else
				{
					j = aXRef[i];
					if (j >= 0)
					{
						sqlite3ExprCode(pParse, pChanges.a[j].pExpr, regNew + i);
					}
					else if (0 == (tmask & TRIGGER_BEFORE) || i > 31 || (newmask & (1 << i)) != 0)
					{
						/* This branch loads the value of a column that will not be changed 
						** into a register. This is done if there are no BEFORE triggers, or
						** if there are one or more BEFORE triggers that use this value via
						** a new.* reference in a trigger program.
						*/
						testcase(i == 31);
						testcase(i == 32);
						sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i);
						sqlite3ColumnDefault(v, pTab, i, regNew + i);
					}
				}
			}

			/* Fire any BEFORE UPDATE triggers. This happens before constraints are
			** verified. One could argue that this is wrong.
			*/
			if ((tmask & TRIGGER_BEFORE) != 0)
			{
				sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab.nCol);
				sqlite3TableAffinityStr(v, pTab);
				sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
					TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);

				/* The row-trigger may have deleted the row being updated. In this
				** case, jump to the next row. No updates or AFTER triggers are 
				** required. This behaviour - what happens when the row being updated
				** is deleted or renamed by a BEFORE trigger - is left undefined in the
				** documentation.
				*/
				sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

				/* If it did not delete it, the row-trigger may still have modified 
				** some of the columns of the row being updated. Load the values for 
				** all columns not modified by the update statement into their 
				** registers in case this has happened.
				*/
				for (i = 0; i < pTab.nCol; i++)
				{
					if (aXRef[i] < 0 && i != pTab.iPKey)
					{
						sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i);
						sqlite3ColumnDefault(v, pTab, i, regNew + i);
					}
				}
			}

			if (!isView)
			{
				int j1;                       /* Address of jump instruction */

				/* Do constraint checks. */
				int iDummy;
				sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
					  aRegIdx, (chngRowid ? regOldRowid : 0), true, onError, addr, out iDummy);

				/* Do FK constraint checks. */
				if (hasFK)
				{
					sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
				}

				/* Delete the index entries associated with the current record.  */
				j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
				sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);

				/* If changing the record number, delete the old record.  */
				if (hasFK || chngRowid)
				{
					sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
				}
				sqlite3VdbeJumpHere(v, j1);

				if (hasFK)
				{
					sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
				}

				/* Insert the new index entries and the new record. */
				sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, true, false, false);

				/* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
				** handle rows (possibly in other tables) that refer via a foreign key
				** to the row just updated. */
				if (hasFK)
				{
					sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
				}
			}

			/* Increment the row counter 
			*/
			if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab)
			{
				sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
			}

			sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
				TRIGGER_AFTER, pTab, regOldRowid, onError, addr);

			/* Repeat the above with the next record to be updated, until
			** all record selected by the WHERE clause have been updated.
			*/
			sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
			sqlite3VdbeJumpHere(v, addr);

			/* Close all tables */
			for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++)
			{
				if (openAll || aRegIdx[i] > 0)
				{
					sqlite3VdbeAddOp2(v, OP_Close, iCur + i + 1, 0);
				}
			}
			sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);

			/* Update the sqlite_sequence table by storing the content of the
			** maximum rowid counter values recorded while inserting into
			** autoincrement tables.
			*/
			if (pParse.nested == 0 && pParse.pTriggerTab == null)
			{
				sqlite3AutoincrementEnd(pParse);
			}

			/*
			** Return the number of rows that were changed. If this routine is 
			** generating code because of a call to sqlite3NestedParse(), do not
			** invoke the callback function.
			*/
			if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab && 0 == pParse.nested)
			{
				sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
				sqlite3VdbeSetNumCols(v, 1);
				sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
			}

		update_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
sqlite3AuthContextPop(sContext);
#endif
			sqlite3DbFree(db, ref aRegIdx);
			sqlite3DbFree(db, ref aXRef);
			sqlite3SrcListDelete(db, ref pTabList);
			sqlite3ExprListDelete(db, ref pChanges);
			sqlite3ExprDelete(db, ref pWhere);
			return;
		}
Example #35
0
 public ConstController(AuthContext context)
 {
     _context = context;
 }
Example #36
0
 public VoipPhone(AuthContext authContext, TenantUtil tenantUtil, SecurityContext securityContext, BaseCommonLinkUtility baseCommonLinkUtility)
 {
     Settings = new VoipSettings(authContext, tenantUtil, securityContext, baseCommonLinkUtility);
 }
        public static List <Order> ReturnStoreOrdersByStoreId(AuthContext _context, int id)
        {
            List <Order> orders = _context.Order.Where(b => (b.StoreId == id)).Include(m => m.Details).Include(z => z.ApplicationUser).ToList();

            return(orders);
        }
        public static List <Store> ReturnStores(AuthContext _context)
        {
            var stores = _context.Store.ToList();

            return(stores);
        }
Example #39
0
        public async Task<IHttpActionResult> DeleteUser(int id)
        {
            User user = this.db.Users.Find(id);
            string aspNetUserId = user.ASPNetUserId;

            if (user == null)
            {
                return this.NotFound();
            }

            this.db.Users.Remove(user);
            this.db.SaveChanges();

            // delete from [AspNetUser] table
            using (var authDb = new AuthContext())
            {
                IdentityUser identityUser = authDb.Users.Find(aspNetUserId);
                authDb.Users.Remove(identityUser);
                authDb.SaveChanges();
            }

            return this.Ok(user);
        }
Example #40
0
 public UserRepository(AuthContext authContext) : base(authContext)
 {
 }
        public static List <Product> ReturnProductById(AuthContext _context, int id)
        {
            var product = _context.Product.Where(b => b.ProductId == id).ToList();

            return(product);
        }
Example #42
0
        public void Inicializar(int juegoOnlineId)
        {
            AuthContext db = new AuthContext();

            juegoOnline = db.JuegoOnlines.Include(s => s.SubTema.Tema).Include(s => s.BeatTheGoalies).Include(s => s.TipoJuegoOnline).SingleOrDefault(bl => bl.JuegoOnlineId == juegoOnlineId);
        }
        public static Store ReturnStoreById(AuthContext _context, int id)
        {
            var store = _context.Store.Find(id);

            return(store);
        }
Example #44
0
 public RoleStoreRepository(AuthContext context)
     : base(context)
 {
 }
        public static List <Product> ReturnAllProduct(AuthContext _context)
        {
            List <Product> prod = _context.Product.ToList();

            return(prod);
        }
Example #46
0
 /// <summary>
 /// Método construtor
 /// </summary>
 /// <param name="context"></param>
 public GroupUsersRepository(AuthContext context) : base(context)
 {
 }
 public AuthUserController(AuthContext context, IMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
        public static List <ApplicationUser> ReturnAllCustomer(AuthContext _context)
        {
            List <ApplicationUser> user = _context.ApplicationUsers.ToList();

            return(user);
        }
 public PermissionContext(IPermissionResolver permissionResolver, AuthContext authContext)
 {
     PermissionResolver = permissionResolver;
     AuthContext        = authContext;
 }
Example #50
0
 public UnitOfWork(AuthContext dbContext)
 {
     _dbContext = dbContext;
 }
        internal static List <PreguntaMistake> ObtenerPreguntasMistakes(List <Mistake> mistakes)
        {
            AuthContext db = new AuthContext();

            List <int> listaBloquesIds = mistakes.Select(mis => mis.BloqueId).Distinct().ToList();

            var bloquesIds = db.Tests.Where(test =>
                                            listaBloquesIds.Contains(test.BloqueId)).Select(test => test.BloqueId).ToList();
            List <int> listaPreguntasIds = mistakes.Where(mis => bloquesIds.Contains(mis.BloqueId))
                                           .Select(mis => mis.PreguntaId).ToList();
            List <PreguntaMistake> preguntasMistakes = db.Tests.Where(test =>
                                                                      listaPreguntasIds.Contains(test.Id)).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Area)
                                                       .Select(cont => new PreguntaMistake()
            {
                bloque      = cont.Bloque,
                enunciado   = cont.Descripcion,
                bloqueId    = cont.BloqueId,
                preguntaId  = cont.Id,
                area        = cont.Bloque.Area.Descripcion,
                subtema     = cont.Bloque.SubTema.Descripcion,
                tema        = cont.Bloque.SubTema.Tema.Descripcion,
                controlador = cont.Bloque.TipoEjercicio.Controlador
            }).ToList();

            bloquesIds = db.Skillwises.Where(test =>
                                             listaBloquesIds.Contains(test.BloqueId)).Select(test => test.BloqueId).ToList();
            listaPreguntasIds = mistakes.Where(mis => bloquesIds.Contains(mis.BloqueId))
                                .Select(mis => mis.PreguntaId).ToList();

            preguntasMistakes.AddRange(db.Skillwises.Where(test =>
                                                           listaPreguntasIds.Contains(test.Id)).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Area)
                                       .Select(cont => new PreguntaMistake()
            {
                bloque      = cont.Bloque,
                enunciado   = cont.Descripcion,
                bloqueId    = cont.BloqueId,
                preguntaId  = cont.Id,
                area        = cont.Bloque.Area.Descripcion,
                subtema     = cont.Bloque.SubTema.Descripcion,
                tema        = cont.Bloque.SubTema.Tema.Descripcion,
                controlador = cont.Bloque.TipoEjercicio.Controlador
            }).ToList());

            bloquesIds = db.FillTheGaps.Where(test =>
                                              listaBloquesIds.Contains(test.BloqueId)).Select(test => test.BloqueId).ToList();
            listaPreguntasIds = mistakes.Where(mis => bloquesIds.Contains(mis.BloqueId))
                                .Select(mis => mis.PreguntaId).ToList();
            preguntasMistakes.AddRange(db.FillTheGaps.Where(test =>
                                                            listaPreguntasIds.Contains(test.Id)).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Area)
                                       .Select(cont => new PreguntaMistake()
            {
                bloque      = cont.Bloque,
                enunciado   = cont.Descripcion,
                bloqueId    = cont.BloqueId,
                preguntaId  = cont.Id,
                area        = cont.Bloque.Area.Descripcion,
                subtema     = cont.Bloque.SubTema.Descripcion,
                tema        = cont.Bloque.SubTema.Tema.Descripcion,
                controlador = cont.Bloque.TipoEjercicio.Controlador
            }).ToList());


            bloquesIds = db.AudioSentenceExercises.Where(test =>
                                                         listaBloquesIds.Contains(test.BloqueId)).Select(test => test.BloqueId).ToList();
            listaPreguntasIds = mistakes.Where(mis => bloquesIds.Contains(mis.BloqueId))
                                .Select(mis => mis.PreguntaId).ToList();
            preguntasMistakes.AddRange(db.AudioSentenceExercises.Where(test =>
                                                                       listaPreguntasIds.Contains(test.Id)).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Area)
                                       .Select(cont => new PreguntaMistake()
            {
                bloque      = cont.Bloque,
                enunciado   = cont.Descripcion,
                bloqueId    = cont.BloqueId,
                preguntaId  = cont.Id,
                area        = cont.Bloque.Area.Descripcion,
                subtema     = cont.Bloque.SubTema.Descripcion,
                tema        = cont.Bloque.SubTema.Tema.Descripcion,
                controlador = cont.Bloque.TipoEjercicio.Controlador
            }).ToList());

            bloquesIds = db.WordByWords.Where(test =>
                                              listaBloquesIds.Contains(test.BloqueId)).Select(test => test.BloqueId).ToList();
            listaPreguntasIds = mistakes.Where(mis => bloquesIds.Contains(mis.BloqueId))
                                .Select(mis => mis.PreguntaId).ToList();
            preguntasMistakes.AddRange(db.WordByWords.Where(test =>
                                                            listaPreguntasIds.Contains(test.Id)).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Area)
                                       .Select(cont => new PreguntaMistake()
            {
                bloque      = cont.Bloque,
                enunciado   = cont.Bloque.Descripcion,
                bloqueId    = cont.BloqueId,
                preguntaId  = cont.Id,
                area        = cont.Bloque.Area.Descripcion,
                subtema     = cont.Bloque.SubTema.Descripcion,
                tema        = cont.Bloque.SubTema.Tema.Descripcion,
                controlador = cont.Bloque.TipoEjercicio.Controlador
            }).ToList());

            bloquesIds = db.TrueFalses.Where(test =>
                                             listaBloquesIds.Contains(test.BloqueId)).Select(test => test.BloqueId).ToList();
            listaPreguntasIds = mistakes.Where(mis => bloquesIds.Contains(mis.BloqueId))
                                .Select(mis => mis.PreguntaId).ToList();
            preguntasMistakes.AddRange(db.TrueFalses.Where(test =>
                                                           listaPreguntasIds.Contains(test.Id)).Include(test => test.Bloque.SubTema).Include(test => test.Bloque.SubTema.Tema).Include(test => test.Area)
                                       .Select(cont => new PreguntaMistake()
            {
                bloque      = cont.Bloque,
                enunciado   = cont.Descripcion,
                bloqueId    = cont.BloqueId,
                preguntaId  = cont.Id,
                area        = cont.Bloque.Area.Descripcion,
                subtema     = cont.Bloque.SubTema.Descripcion,
                tema        = cont.Bloque.SubTema.Tema.Descripcion,
                controlador = cont.Bloque.TipoEjercicio.Controlador
            }).ToList());
            return(preguntasMistakes);
        }
Example #52
0
 public CatalogController(AuthContext context)
 {
     _context = context;
 }
Example #53
0
 public Authentication()
 {
     _ctx = new AuthContext();
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
 }
Example #54
0
        /*
        ** Process an UPDATE statement.
        **
        **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
        **          \_______/ \________/     \______/       \________________/
        *            onError   pTabList      pChanges             pWhere
        */
        static void sqlite3Update(
            Parse pParse,      /* The parser context */
            SrcList pTabList,  /* The table in which we should change things */
            ExprList pChanges, /* Things to be changed */
            Expr pWhere,       /* The WHERE clause.  May be null */
            int onError        /* How to handle constraint errors */
            )
        {
            int       i, j;                 /* Loop counters */
            Table     pTab;                 /* The table to be updated */
            int       addr = 0;             /* VDBE instruction address of the start of the loop */
            WhereInfo pWInfo;               /* Information about the WHERE clause */
            Vdbe      v;                    /* The virtual database engine */
            Index     pIdx;                 /* For looping over indices */
            int       nIdx;                 /* Number of indices that need updating */
            int       iCur;                 /* VDBE Cursor number of pTab */
            sqlite3   db;                   /* The database structure */

            int[] aRegIdx = null;           /* One register assigned to each index to be updated */
            int[] aXRef   = null;           /* aXRef[i] is the index in pChanges.a[] of the
                                            ** an expression for the i-th column of the table.
                                            ** aXRef[i]==-1 if the i-th column is not changed. */
            bool        chngRowid;          /* True if the record number is being changed */
            Expr        pRowidExpr = null;  /* Expression defining the new record number */
            bool        openAll    = false; /* True if all indices need to be opened */
            AuthContext sContext;           /* The authorization context */
            NameContext sNC;                /* The name-context to resolve expressions in */
            int         iDb;                /* Database containing the table being updated */
            bool        okOnePass;          /* True for one-pass algorithm without the FIFO */
            bool        hasFK;              /* True if foreign key processing is required */

#if !SQLITE_OMIT_TRIGGER
            bool    isView;    /* True when updating a view (INSTEAD OF trigger) */
            Trigger pTrigger;  /* List of triggers on pTab, if required */
            int     tmask = 0; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
#endif
            int newmask;       /* Mask of NEW.* columns accessed by BEFORE triggers */

            /* Register Allocations */
            int regRowCount = 0;   /* A count of rows changed */
            int regOldRowid;       /* The old rowid */
            int regNewRowid;       /* The new rowid */
            int regNew;
            int regOld    = 0;
            int regRowSet = 0;            /* Rowset of rows to be updated */

            sContext = new AuthContext(); //memset( &sContext, 0, sizeof( sContext ) );
            db       = pParse.db;
            if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */)
            {
                goto update_cleanup;
            }
            Debug.Assert(pTabList.nSrc == 1);

            /* Locate the table which we want to update.
             */
            pTab = sqlite3SrcListLookup(pParse, pTabList);
            if (pTab == null)
            {
                goto update_cleanup;
            }
            iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);

            /* Figure out if we have any triggers and if the table being
            ** updated is a view.
            */
#if !SQLITE_OMIT_TRIGGER
            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, out tmask);
            isView   = pTab.pSelect != null;
            Debug.Assert(pTrigger != null || tmask == 0);
#else
            const Trigger pTrigger = null; //# define pTrigger 0
            const int     tmask    = 0;    //# define tmask 0
#endif
#if SQLITE_OMIT_TRIGGER || SQLITE_OMIT_VIEW
//    # undef isView
            const bool isView = false; //# define isView 0
#endif

            if (sqlite3ViewGetColumnNames(pParse, pTab) != 0)
            {
                goto update_cleanup;
            }
            if (sqlite3IsReadOnly(pParse, pTab, tmask))
            {
                goto update_cleanup;
            }
            aXRef = new int[pTab.nCol];// sqlite3DbMallocRaw(db, sizeof(int) * pTab.nCol);
            //if ( aXRef == null ) goto update_cleanup;
            for (i = 0; i < pTab.nCol; i++)
            {
                aXRef[i] = -1;
            }

            /* Allocate a cursors for the main database table and for all indices.
            ** The index cursors might not be used, but if they are used they
            ** need to occur right after the database cursor.  So go ahead and
            ** allocate enough space, just in case.
            */
            pTabList.a[0].iCursor = iCur = pParse.nTab++;
            for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
            {
                pParse.nTab++;
            }

            /* Initialize the name-context */
            sNC          = new NameContext();// memset(&sNC, 0, sNC).Length;
            sNC.pParse   = pParse;
            sNC.pSrcList = pTabList;

            /* Resolve the column names in all the expressions of the
            ** of the UPDATE statement.  Also find the column index
            ** for each column to be updated in the pChanges array.  For each
            ** column to be updated, make sure we have authorization to change
            ** that column.
            */
            chngRowid = false;
            for (i = 0; i < pChanges.nExpr; i++)
            {
                if (sqlite3ResolveExprNames(sNC, ref pChanges.a[i].pExpr) != 0)
                {
                    goto update_cleanup;
                }
                for (j = 0; j < pTab.nCol; j++)
                {
                    if (pTab.aCol[j].zName.Equals(pChanges.a[i].zName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (j == pTab.iPKey)
                        {
                            chngRowid  = true;
                            pRowidExpr = pChanges.a[i].pExpr;
                        }
                        aXRef[j] = i;
                        break;
                    }
                }
                if (j >= pTab.nCol)
                {
                    if (sqlite3IsRowid(pChanges.a[i].zName))
                    {
                        chngRowid  = true;
                        pRowidExpr = pChanges.a[i].pExpr;
                    }
                    else
                    {
                        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges.a[i].zName);
                        pParse.checkSchema = 1;
                        goto update_cleanup;
                    }
                }
#if !SQLITE_OMIT_AUTHORIZATION
                {
                    int rc;
                    rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab.zName,
                                          pTab.aCol[j].zName, db.aDb[iDb].zName);
                    if (rc == SQLITE_DENY)
                    {
                        goto update_cleanup;
                    }
                    else if (rc == SQLITE_IGNORE)
                    {
                        aXRef[j] = -1;
                    }
                }
#endif
            }

            hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid ? 1 : 0) != 0;

            /* Allocate memory for the array aRegIdx[].  There is one entry in the
            ** array for each index associated with table being updated.  Fill in
            ** the value with a register number for indices that are to be used
            ** and with zero for unused indices.
            */
            for (nIdx = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, nIdx++)
            {
            }
            if (nIdx > 0)
            {
                aRegIdx = new int[nIdx]; // sqlite3DbMallocRaw(db, Index*.Length * nIdx);
                if (aRegIdx == null)
                {
                    goto update_cleanup;
                }
            }
            for (j = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, j++)
            {
                int reg;
                if (hasFK || chngRowid)
                {
                    reg = ++pParse.nMem;
                }
                else
                {
                    reg = 0;
                    for (i = 0; i < pIdx.nColumn; i++)
                    {
                        if (aXRef[pIdx.aiColumn[i]] >= 0)
                        {
                            reg = ++pParse.nMem;
                            break;
                        }
                    }
                }
                aRegIdx[j] = reg;
            }

            /* Begin generating code. */
            v = sqlite3GetVdbe(pParse);
            if (v == null)
            {
                goto update_cleanup;
            }
            if (pParse.nested == 0)
            {
                sqlite3VdbeCountChanges(v);
            }
            sqlite3BeginWriteOperation(pParse, 1, iDb);

#if !SQLITE_OMIT_VIRTUALTABLE
            /* Virtual tables must be handled separately */
            if (IsVirtual(pTab))
            {
                updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
                                   pWhere, onError);
                pWhere   = null;
                pTabList = null;
                goto update_cleanup;
            }
#endif

            /* Allocate required registers. */
            regOldRowid = regNewRowid = ++pParse.nMem;
            if (pTrigger != null || hasFK)
            {
                regOld       = pParse.nMem + 1;
                pParse.nMem += pTab.nCol;
            }
            if (chngRowid || pTrigger != null || hasFK)
            {
                regNewRowid = ++pParse.nMem;
            }
            regNew       = pParse.nMem + 1;
            pParse.nMem += pTab.nCol;

            /* Start the view context. */
            if (isView)
            {
                sqlite3AuthContextPush(pParse, sContext, pTab.zName);
            }

            /* If we are trying to update a view, realize that view into
            ** a ephemeral table.
            */
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
            if (isView)
            {
                sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
            }
#endif

            /* Resolve the column names in all the expressions in the
            ** WHERE clause.
            */
            if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0)
            {
                goto update_cleanup;
            }

            /* Begin the database scan
             */
            sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
            ExprList NullOrderby = null;
            pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref NullOrderby, WHERE_ONEPASS_DESIRED);
            if (pWInfo == null)
            {
                goto update_cleanup;
            }
            okOnePass = pWInfo.okOnePass != 0;

            /* Remember the rowid of every item to be updated.
             */
            sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
            if (!okOnePass)
            {
                regRowSet = ++pParse.nMem;
                sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
            }

            /* End the database scan loop.
             */
            sqlite3WhereEnd(pWInfo);

            /* Initialize the count of updated rows
             */
            if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab)
            {
                regRowCount = ++pParse.nMem;
                sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
            }

            if (!isView)
            {
                /*
                ** Open every index that needs updating.  Note that if any
                ** index could potentially invoke a REPLACE conflict resolution
                ** action, then we need to open all indices because we might need
                ** to be deleting some records.
                */
                if (!okOnePass)
                {
                    sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
                }
                if (onError == OE_Replace)
                {
                    openAll = true;
                }
                else
                {
                    openAll = false;
                    for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
                    {
                        if (pIdx.onError == OE_Replace)
                        {
                            openAll = true;
                            break;
                        }
                    }
                }
                for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++)
                {
                    if (openAll || aRegIdx[i] > 0)
                    {
                        KeyInfo pKey = sqlite3IndexKeyinfo(pParse, pIdx);
                        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur + i + 1, pIdx.tnum, iDb,
                                          pKey, P4_KEYINFO_HANDOFF);
                        Debug.Assert(pParse.nTab > iCur + i + 1);
                    }
                }
            }

            /* Top of the update loop */
            if (okOnePass)
            {
                int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
                addr = sqlite3VdbeAddOp0(v, OP_Goto);
                sqlite3VdbeJumpHere(v, a1);
            }
            else
            {
                addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
            }

            /* Make cursor iCur point to the record that is being updated. If
            ** this record does not exist for some reason (deleted by a trigger,
            ** for example, then jump to the next iteration of the RowSet loop.  */
            sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

            /* If the record number will change, set register regNewRowid to
            ** contain the new value. If the record number is not being modified,
            ** then regNewRowid is the same register as regOldRowid, which is
            ** already populated.  */
            Debug.Assert(chngRowid || pTrigger != null || hasFK || regOldRowid == regNewRowid);
            if (chngRowid)
            {
                sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
                sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
            }

            /* If there are triggers on this table, populate an array of registers
            ** with the required old.* column data.  */
            if (hasFK || pTrigger != null)
            {
                u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
                oldmask |= sqlite3TriggerColmask(pParse,
                                                 pTrigger, pChanges, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onError
                                                 );
                for (i = 0; i < pTab.nCol; i++)
                {
                    if (aXRef[i] < 0 || oldmask == 0xffffffff || (i < 32 && 0 != (oldmask & (1 << i))))
                    {
                        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld + i);
                    }
                    else
                    {
                        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld + i);
                    }
                }
                if (chngRowid == false)
                {
                    sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
                }
            }

            /* Populate the array of registers beginning at regNew with the new
            ** row data. This array is used to check constaints, create the new
            ** table and index records, and as the values for any new.* references
            ** made by triggers.
            **
            ** If there are one or more BEFORE triggers, then do not populate the
            ** registers associated with columns that are (a) not modified by
            ** this UPDATE statement and (b) not accessed by new.* references. The
            ** values for registers not modified by the UPDATE must be reloaded from
            ** the database after the BEFORE triggers are fired anyway (as the trigger
            ** may have modified them). So not loading those that are not going to
            ** be used eliminates some redundant opcodes.
            */
            newmask = (int)sqlite3TriggerColmask(
                pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
                );
            for (i = 0; i < pTab.nCol; i++)
            {
                if (i == pTab.iPKey)
                {
                    sqlite3VdbeAddOp2(v, OP_Null, 0, regNew + i);
                }
                else
                {
                    j = aXRef[i];
                    if (j >= 0)
                    {
                        sqlite3ExprCode(pParse, pChanges.a[j].pExpr, regNew + i);
                    }
                    else if (0 == (tmask & TRIGGER_BEFORE) || i > 31 || (newmask & (1 << i)) != 0)
                    {
                        /* This branch loads the value of a column that will not be changed
                        ** into a register. This is done if there are no BEFORE triggers, or
                        ** if there are one or more BEFORE triggers that use this value via
                        ** a new.* reference in a trigger program.
                        */
                        testcase(i == 31);
                        testcase(i == 32);
                        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i);
                        sqlite3ColumnDefault(v, pTab, i, regNew + i);
                    }
                }
            }

            /* Fire any BEFORE UPDATE triggers. This happens before constraints are
            ** verified. One could argue that this is wrong.
            */
            if ((tmask & TRIGGER_BEFORE) != 0)
            {
                sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab.nCol);
                sqlite3TableAffinityStr(v, pTab);
                sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
                                      TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);

                /* The row-trigger may have deleted the row being updated. In this
                ** case, jump to the next row. No updates or AFTER triggers are
                ** required. This behaviour - what happens when the row being updated
                ** is deleted or renamed by a BEFORE trigger - is left undefined in the
                ** documentation.
                */
                sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

                /* If it did not delete it, the row-trigger may still have modified
                ** some of the columns of the row being updated. Load the values for
                ** all columns not modified by the update statement into their
                ** registers in case this has happened.
                */
                for (i = 0; i < pTab.nCol; i++)
                {
                    if (aXRef[i] < 0 && i != pTab.iPKey)
                    {
                        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i);
                        sqlite3ColumnDefault(v, pTab, i, regNew + i);
                    }
                }
            }

            if (!isView)
            {
                int j1;               /* Address of jump instruction */

                /* Do constraint checks. */
                int iDummy;
                sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
                                                aRegIdx, (chngRowid ? regOldRowid : 0), true, onError, addr, out iDummy);

                /* Do FK constraint checks. */
                if (hasFK)
                {
                    sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
                }

                /* Delete the index entries associated with the current record.  */
                j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
                sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);

                /* If changing the record number, delete the old record.  */
                if (hasFK || chngRowid)
                {
                    sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
                }
                sqlite3VdbeJumpHere(v, j1);

                if (hasFK)
                {
                    sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
                }

                /* Insert the new index entries and the new record. */
                sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, true, false, false);

                /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
                ** handle rows (possibly in other tables) that refer via a foreign key
                ** to the row just updated. */
                if (hasFK)
                {
                    sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
                }
            }

            /* Increment the row counter
             */
            if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab)
            {
                sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
            }

            sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
                                  TRIGGER_AFTER, pTab, regOldRowid, onError, addr);

            /* Repeat the above with the next record to be updated, until
            ** all record selected by the WHERE clause have been updated.
            */
            sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
            sqlite3VdbeJumpHere(v, addr);

            /* Close all tables */
            for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++)
            {
                if (openAll || aRegIdx[i] > 0)
                {
                    sqlite3VdbeAddOp2(v, OP_Close, iCur + i + 1, 0);
                }
            }
            sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);

            /* Update the sqlite_sequence table by storing the content of the
            ** maximum rowid counter values recorded while inserting into
            ** autoincrement tables.
            */
            if (pParse.nested == 0 && pParse.pTriggerTab == null)
            {
                sqlite3AutoincrementEnd(pParse);
            }

            /*
            ** Return the number of rows that were changed. If this routine is
            ** generating code because of a call to sqlite3NestedParse(), do not
            ** invoke the callback function.
            */
            if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab && 0 == pParse.nested)
            {
                sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
                sqlite3VdbeSetNumCols(v, 1);
                sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
            }

update_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
            sqlite3AuthContextPop(sContext);
#endif
            sqlite3DbFree(db, ref aRegIdx);
            sqlite3DbFree(db, ref aXRef);
            sqlite3SrcListDelete(db, ref pTabList);
            sqlite3ExprListDelete(db, ref pChanges);
            sqlite3ExprDelete(db, ref pWhere);
            return;
        }
Example #55
0
    /*
    ** Process an UPDATE statement.
    **
    **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
    **          \_______/ \________/     \______/       \________________/
    *            onError   pTabList      pChanges             pWhere
    */
    static void sqlite3Update(
    Parse pParse,         /* The parser context */
    SrcList pTabList,     /* The table in which we should change things */
    ExprList pChanges,    /* Things to be changed */
    Expr pWhere,          /* The WHERE clause.  May be null */
    int onError           /* How to handle constraint errors */
    )
    {
      int i, j;                   /* Loop counters */
      Table pTab;                 /* The table to be updated */
      int addr = 0;               /* VDBE instruction address of the start of the loop */
      WhereInfo pWInfo;           /* Information about the WHERE clause */
      Vdbe v;                     /* The virtual database engine */
      Index pIdx;                 /* For looping over indices */
      int nIdx;                   /* Number of indices that need updating */
      int iCur;                   /* VDBE Cursor number of pTab */
      sqlite3 db;                 /* The database structure */
      int[] aRegIdx = null;       /* One register assigned to each index to be updated */
      int[] aXRef = null;         /* aXRef[i] is the index in pChanges.a[] of the
** an expression for the i-th column of the table.
** aXRef[i]==-1 if the i-th column is not changed. */
      bool chngRowid;             /* True if the record number is being changed */
      Expr pRowidExpr = null;     /* Expression defining the new record number */
      bool openAll = false;       /* True if all indices need to be opened */
      AuthContext sContext;       /* The authorization context */
      NameContext sNC;            /* The name-context to resolve expressions in */
      int iDb;                    /* Database containing the table being updated */
      int j1;                     /* Addresses of jump instructions */
      u8 okOnePass;               /* True for one-pass algorithm without the FIFO */

#if !SQLITE_OMIT_TRIGGER
      bool isView = false;         /* Trying to update a view */
      Trigger pTrigger;            /* List of triggers on pTab, if required */
#endif
      int iBeginAfterTrigger = 0;  /* Address of after trigger program */
      int iEndAfterTrigger = 0;    /* Exit of after trigger program */
      int iBeginBeforeTrigger = 0; /* Address of before trigger program */
      int iEndBeforeTrigger = 0;   /* Exit of before trigger program */
      u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
      u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */

      int newIdx = -1;             /* index of trigger "new" temp table       */
      int oldIdx = -1;             /* index of trigger "old" temp table       */

      /* Register Allocations */
      int regRowCount = 0;         /* A count of rows changed */
      int regOldRowid;             /* The old rowid */
      int regNewRowid;             /* The new rowid */
      int regData;                 /* New data for the row */
      int regRowSet = 0;           /* Rowset of rows to be updated */

      sContext = new AuthContext(); //memset( &sContext, 0, sizeof( sContext ) );
      db = pParse.db;
      if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
      {
        goto update_cleanup;
      }
      Debug.Assert( pTabList.nSrc == 1 );

      /* Locate the table which we want to update.
      */
      pTab = sqlite3SrcListLookup( pParse, pTabList );
      if ( pTab == null ) goto update_cleanup;
      iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );

      /* Figure out if we have any triggers and if the table being
      ** updated is a view
      */
#if !SQLITE_OMIT_TRIGGER
      int iDummy = 0;
      pTrigger = sqlite3TriggersExist( pParse, pTab, TK_UPDATE, pChanges, ref iDummy );
      isView = pTab.pSelect != null;
#else
const Trigger pTrigger = null;
#if !SQLITE_OMIT_VIEW
const bool isView = false;
#endif
#endif
#if SQLITE_OMIT_VIEW
//    # undef isView
const bool isView = false;
#endif

      if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
      {
        goto update_cleanup;
      }
      if ( sqlite3IsReadOnly( pParse, pTab, ( pTrigger != null ? 1 : 0 ) ) )
      {
        goto update_cleanup;
      }
      aXRef = new int[pTab.nCol];// sqlite3DbMallocRaw(db, sizeof(int) * pTab.nCol);
      //if ( aXRef == null ) goto update_cleanup;
      for ( i = 0 ; i < pTab.nCol ; i++ ) aXRef[i] = -1;

      /* If there are FOR EACH ROW triggers, allocate cursors for the
      ** special OLD and NEW tables
      */
      if ( pTrigger != null )
      {
        newIdx = pParse.nTab++;
        oldIdx = pParse.nTab++;
      }

      /* Allocate a cursors for the main database table and for all indices.
      ** The index cursors might not be used, but if they are used they
      ** need to occur right after the database cursor.  So go ahead and
      ** allocate enough space, just in case.
      */
      pTabList.a[0].iCursor = iCur = pParse.nTab++;
      for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext )
      {
        pParse.nTab++;
      }

      /* Initialize the name-context */
      sNC = new NameContext();// memset(&sNC, 0, sNC).Length;
      sNC.pParse = pParse;
      sNC.pSrcList = pTabList;

      /* Resolve the column names in all the expressions of the
      ** of the UPDATE statement.  Also find the column index
      ** for each column to be updated in the pChanges array.  For each
      ** column to be updated, make sure we have authorization to change
      ** that column.
      */
      chngRowid = false;
      for ( i = 0 ; i < pChanges.nExpr ; i++ )
      {
        if ( sqlite3ResolveExprNames( sNC, ref pChanges.a[i].pExpr ) != 0 )
        {
          goto update_cleanup;
        }
        for ( j = 0 ; j < pTab.nCol ; j++ )
        {
          if ( sqlite3StrICmp( pTab.aCol[j].zName, pChanges.a[i].zName ) == 0 )
          {
            if ( j == pTab.iPKey )
            {
              chngRowid = true;
              pRowidExpr = pChanges.a[i].pExpr;
            }
            aXRef[j] = i;
            break;
          }
        }
        if ( j >= pTab.nCol )
        {
          if ( sqlite3IsRowid( pChanges.a[i].zName ) )
          {
            chngRowid = true;
            pRowidExpr = pChanges.a[i].pExpr;
          }
          else
          {
            sqlite3ErrorMsg( pParse, "no such column: %s", pChanges.a[i].zName );
            goto update_cleanup;
          }
        }
#if !SQLITE_OMIT_AUTHORIZATION
{
int rc;
rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab.zName,
pTab.aCol[j].zName, db.aDb[iDb].zName);
if( rc==SQLITE_DENY ){
goto update_cleanup;
}else if( rc==SQLITE_IGNORE ){
aXRef[j] = -1;
}
}
#endif
      }

      /* Allocate memory for the array aRegIdx[].  There is one entry in the
      ** array for each index associated with table being updated.  Fill in
      ** the value with a register number for indices that are to be used
      ** and with zero for unused indices.
      */
      for ( nIdx = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, nIdx++ ) { }
      if ( nIdx > 0 )
      {
        aRegIdx = new int[nIdx]; // sqlite3DbMallocRaw(db, Index*.Length * nIdx);
        if ( aRegIdx == null ) goto update_cleanup;
      }
      for ( j = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, j++ )
      {
        int reg;
        if ( chngRowid )
        {
          reg = ++pParse.nMem;
        }
        else
        {
          reg = 0;
          for ( i = 0 ; i < pIdx.nColumn ; i++ )
          {
            if ( aXRef[pIdx.aiColumn[i]] >= 0 )
            {
              reg = ++pParse.nMem;
              break;
            }
          }
        }
        aRegIdx[j] = reg;
      }

      /* Allocate a block of register used to store the change record
      ** sent to sqlite3GenerateConstraintChecks().  There are either
      ** one or two registers for holding the rowid.  One rowid register
      ** is used if chngRowid is false and two are used if chngRowid is
      ** true.  Following these are pTab.nCol register holding column
      ** data.
      */
      regOldRowid = regNewRowid = pParse.nMem + 1;
      pParse.nMem += pTab.nCol + 1;
      if ( chngRowid )
      {
        regNewRowid++;
        pParse.nMem++;
      }
      regData = regNewRowid + 1;


      /* Begin generating code.
      */
      v = sqlite3GetVdbe( pParse );
      if ( v == null ) goto update_cleanup;
      if ( pParse.nested == 0 ) sqlite3VdbeCountChanges( v );
      sqlite3BeginWriteOperation( pParse, 1, iDb );

#if !SQLITE_OMIT_VIRTUALTABLE
/* Virtual tables must be handled separately */
if ( IsVirtual( pTab ) )
{
updateVirtualTable( pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, pWhere );
pWhere = null;
pTabList = null;
goto update_cleanup;
}
#endif

      /* Start the view context
*/
#if !SQLITE_OMIT_AUTHORIZATION
if( isView ){
sqlite3AuthContextPush(pParse, sContext, pTab.zName);
}
#endif
      /* Generate the code for triggers.
*/
      if ( pTrigger != null )
      {
        int iGoto;

        /* Create pseudo-tables for NEW and OLD
        */
        sqlite3VdbeAddOp3( v, OP_OpenPseudo, oldIdx, 0, pTab.nCol );
        sqlite3VdbeAddOp3( v, OP_OpenPseudo, newIdx, 0, pTab.nCol );

        iGoto = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 );
        addr = sqlite3VdbeMakeLabel( v );
        iBeginBeforeTrigger = sqlite3VdbeCurrentAddr( v );
        if ( sqlite3CodeRowTrigger( pParse, pTrigger, TK_UPDATE, pChanges,
        TRIGGER_BEFORE, pTab, newIdx, oldIdx, onError, addr,
        ref old_col_mask, ref new_col_mask ) != 0 )
        {
          goto update_cleanup;
        }
        iEndBeforeTrigger = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 );
        iBeginAfterTrigger = sqlite3VdbeCurrentAddr( v );
#if !SQLITE_OMIT_TRIGGER
        if ( sqlite3CodeRowTrigger( pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab,
        newIdx, oldIdx, onError, addr, ref old_col_mask, ref new_col_mask ) != 0 )
        {
          goto update_cleanup;
        }
#endif
        iEndAfterTrigger = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 );
        sqlite3VdbeJumpHere( v, iGoto );
      }

      /* If we are trying to update a view, realize that view into
      ** a ephemeral table.
      */
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
      if ( isView )
      {
        sqlite3MaterializeView( pParse, pTab, pWhere, iCur );
      }
#endif

      /* Resolve the column names in all the expressions in the
** WHERE clause.
*/
      if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 )
      {
        goto update_cleanup;
      }

      /* Begin the database scan
      */
      sqlite3VdbeAddOp2( v, OP_Null, 0, regOldRowid );
      ExprList NullOrderby = null;
      pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref NullOrderby, WHERE_ONEPASS_DESIRED );
      if ( pWInfo == null ) goto update_cleanup;
      okOnePass = pWInfo.okOnePass;

      /* Remember the rowid of every item to be updated.
      */
      sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regOldRowid );
      if ( 0 == okOnePass )
      {
        regRowSet = ++pParse.nMem;
        sqlite3VdbeAddOp2( v, OP_RowSetAdd, regRowSet, regOldRowid );
      }

      /* End the database scan loop.
      */
      sqlite3WhereEnd( pWInfo );

      /* Initialize the count of updated rows
      */
      if ( ( db.flags & SQLITE_CountRows ) != 0 && pParse.trigStack == null )
      {
        regRowCount = ++pParse.nMem;
        sqlite3VdbeAddOp2( v, OP_Integer, 0, regRowCount );
      }

      if ( !isView )
      {
        /*
        ** Open every index that needs updating.  Note that if any
        ** index could potentially invoke a REPLACE conflict resolution
        ** action, then we need to open all indices because we might need
        ** to be deleting some records.
        */
        if ( 0 == okOnePass ) sqlite3OpenTable( pParse, iCur, iDb, pTab, OP_OpenWrite );
        if ( onError == OE_Replace )
        {
          openAll = true;
        }
        else
        {
          openAll = false;
          for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext )
          {
            if ( pIdx.onError == OE_Replace )
            {
              openAll = true;
              break;
            }
          }
        }
        for ( i = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, i++ )
        {
          if ( openAll || aRegIdx[i] > 0 )
          {
            KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx );
            sqlite3VdbeAddOp4( v, OP_OpenWrite, iCur + i + 1, pIdx.tnum, iDb,
            pKey, P4_KEYINFO_HANDOFF );
            Debug.Assert( pParse.nTab > iCur + i + 1 );
          }
        }
      }

      /* Jump back to this point if a trigger encounters an IGNORE constraint. */
      if ( pTrigger != null )
      {
        sqlite3VdbeResolveLabel( v, addr );
      }

      /* Top of the update loop */
      if ( okOnePass != 0 )
      {
        int a1 = sqlite3VdbeAddOp1( v, OP_NotNull, regOldRowid );
        addr = sqlite3VdbeAddOp0( v, OP_Goto );
        sqlite3VdbeJumpHere( v, a1 );
      }
      else
      {
        addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, regRowSet, 0, regOldRowid );
      }

      if ( pTrigger != null )
      {
        int regRowid;
        int regRow;
        int regCols;

        /* Make cursor iCur point to the record that is being updated.
        */
        sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, regOldRowid );

        /* Generate the OLD table
        */
        regRowid = sqlite3GetTempReg( pParse );
        regRow = sqlite3GetTempReg( pParse );
        sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regRowid );
        if ( old_col_mask == 0 )
        {
          sqlite3VdbeAddOp2( v, OP_Null, 0, regRow );
        }
        else
        {
          sqlite3VdbeAddOp2( v, OP_RowData, iCur, regRow );
        }
        sqlite3VdbeAddOp3( v, OP_Insert, oldIdx, regRow, regRowid );

        /* Generate the NEW table
        */
        if ( chngRowid )
        {
          sqlite3ExprCodeAndCache( pParse, pRowidExpr, regRowid );
          sqlite3VdbeAddOp1( v, OP_MustBeInt, regRowid );
        }
        else
        {
          sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regRowid );
        }
        regCols = sqlite3GetTempRange( pParse, pTab.nCol );
        for ( i = 0 ; i < pTab.nCol ; i++ )
        {
          if ( i == pTab.iPKey )
          {
            sqlite3VdbeAddOp2( v, OP_Null, 0, regCols + i );
            continue;
          }
          j = aXRef[i];
          if ( ( i < 32 && ( new_col_mask & ( (u32)1 << i ) ) != 0 ) || new_col_mask == 0xffffffff )
          {
            if ( j < 0 )
            {
              sqlite3VdbeAddOp3( v, OP_Column, iCur, i, regCols + i );
              sqlite3ColumnDefault( v, pTab, i, -1 );
            }
            else
            {
              sqlite3ExprCodeAndCache( pParse, pChanges.a[j].pExpr, regCols + i );
            }
          }
          else
          {
            sqlite3VdbeAddOp2( v, OP_Null, 0, regCols + i );
          }
        }
        sqlite3VdbeAddOp3( v, OP_MakeRecord, regCols, pTab.nCol, regRow );
        if ( !isView )
        {
          sqlite3TableAffinityStr( v, pTab );
          sqlite3ExprCacheAffinityChange( pParse, regCols, pTab.nCol );
        }
        sqlite3ReleaseTempRange( pParse, regCols, pTab.nCol );
        /* if( pParse.nErr ) goto update_cleanup; */
        sqlite3VdbeAddOp3( v, OP_Insert, newIdx, regRow, regRowid );
        sqlite3ReleaseTempReg( pParse, regRowid );
        sqlite3ReleaseTempReg( pParse, regRow );

        sqlite3VdbeAddOp2( v, OP_Goto, 0, iBeginBeforeTrigger );
        sqlite3VdbeJumpHere( v, iEndBeforeTrigger );
      }

      if ( !isView )
      {

        /* Loop over every record that needs updating.  We have to load
        ** the old data for each record to be updated because some columns
        ** might not change and we will need to copy the old value.
        ** Also, the old data is needed to delete the old index entries.
        ** So make the cursor point at the old record.
        */
        sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, regOldRowid );

        /* If the record number will change, push the record number as it
        ** will be after the update. (The old record number is currently
        ** on top of the stack.)
        */
        if ( chngRowid )
        {
          sqlite3ExprCode( pParse, pRowidExpr, regNewRowid );
          sqlite3VdbeAddOp1( v, OP_MustBeInt, regNewRowid );
        }

        /* Compute new data for this record.
        */
        for ( i = 0 ; i < pTab.nCol ; i++ )
        {
          if ( i == pTab.iPKey )
          {
            sqlite3VdbeAddOp2( v, OP_Null, 0, regData + i );
            continue;
          }
          j = aXRef[i];
          if ( j < 0 )
          {
            sqlite3VdbeAddOp3( v, OP_Column, iCur, i, regData + i );
            sqlite3ColumnDefault( v, pTab, i, regData + i );
          }
          else
          {
            sqlite3ExprCode( pParse, pChanges.a[j].pExpr, regData + i );
          }
        }

        /* Do constraint checks
        */
        iDummy = 0;
        sqlite3GenerateConstraintChecks( pParse, pTab, iCur, regNewRowid,
           aRegIdx, chngRowid, true,
           onError, addr, ref iDummy );

        /* Delete the old indices for the current record.
        */
        j1 = sqlite3VdbeAddOp3( v, OP_NotExists, iCur, 0, regOldRowid );
        sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx );

        /* If changing the record number, delete the old record.
        */
        if ( chngRowid )
        {
          sqlite3VdbeAddOp2( v, OP_Delete, iCur, 0 );
        }
        sqlite3VdbeJumpHere( v, j1 );

        /* Create the new index entries and the new record.
        */
        sqlite3CompleteInsertion( pParse, pTab, iCur, regNewRowid,
        aRegIdx, true, -1, false, false );
      }

      /* Increment the row counter
      */
      if ( ( db.flags & SQLITE_CountRows ) != 0 && pParse.trigStack == null )
      {
        sqlite3VdbeAddOp2( v, OP_AddImm, regRowCount, 1 );
      }

      /* If there are triggers, close all the cursors after each iteration
      ** through the loop.  The fire the after triggers.
      */
      if ( pTrigger != null )
      {
        sqlite3VdbeAddOp2( v, OP_Goto, 0, iBeginAfterTrigger );
        sqlite3VdbeJumpHere( v, iEndAfterTrigger );
      }

      /* Repeat the above with the next record to be updated, until
      ** all record selected by the WHERE clause have been updated.
      */
      sqlite3VdbeAddOp2( v, OP_Goto, 0, addr );
      sqlite3VdbeJumpHere( v, addr );

      /* Close all tables */
      for ( i = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, i++ )
      {
        if ( openAll || aRegIdx[i] > 0 )
        {
          sqlite3VdbeAddOp2( v, OP_Close, iCur + i + 1, 0 );
        }
      }
      sqlite3VdbeAddOp2( v, OP_Close, iCur, 0 );
      if ( pTrigger != null )
      {
        sqlite3VdbeAddOp2( v, OP_Close, newIdx, 0 );
        sqlite3VdbeAddOp2( v, OP_Close, oldIdx, 0 );
      }

      /* Update the sqlite_sequence table by storing the content of the
      ** maximum rowid counter values recorded while inserting into
      ** autoincrement tables.
      */
      if ( pParse.nested == 0 && pParse.trigStack == null )
      {
        sqlite3AutoincrementEnd( pParse );
      }

      /*
      ** Return the number of rows that were changed. If this routine is
      ** generating code because of a call to sqlite3NestedParse(), do not
      ** invoke the callback function.
      */
      if ( ( db.flags & SQLITE_CountRows ) != 0 && pParse.trigStack == null && pParse.nested == 0 )
      {
        sqlite3VdbeAddOp2( v, OP_ResultRow, regRowCount, 1 );
        sqlite3VdbeSetNumCols( v, 1 );
        sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC );
      }

update_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
sqlite3AuthContextPop(sContext);
#endif
      //sqlite3DbFree( db, ref  aRegIdx );
      //sqlite3DbFree( db, ref  aXRef );
      sqlite3SrcListDelete( db, ref pTabList );
      sqlite3ExprListDelete( db, ref pChanges );
      sqlite3ExprDelete( db, ref pWhere );
      return;
    }
Example #56
0
 public JabberServiceClient(UserManager userManager, AuthContext authContext, TenantManager tenantManager)
 {
     UserManager   = userManager;
     AuthContext   = authContext;
     TenantManager = tenantManager;
 }
Example #57
0
        /// <summary>
        /// The get admins.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task<string> GetAdmins()
        {
            var authDb = new AuthContext();
            var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(authDb));
            var tree = new List<AdminUserTree>();

            // all [AspNetUsers] in the "Admin" role
            string[] adminIdentities = authDb.Users.ToArray().Where(x => userManager.IsInRole(x.Id, "Admin")).Select(x => x.Id).ToArray();

            // join clients and users
            var query = (from clients in this.db.Clients
                         join users in this.db.Users on clients.ClientId equals users.ClientId
                         where adminIdentities.Contains(users.ASPNetUserId)
                         select new
                            {
                                clients.ClientId, 
                                ClientName = clients.Name, 
                                users.FirstName, 
                                users.LastName, 
                                users.UserId
                            })
                            .ToArray();

            // add this to a tree so we can convert to kendo
            foreach (var node in query)
            {
                // check if client exist in tree
                if (!tree.Any(x => x.ClientId == node.ClientId))
                {
                    // add client to tree and initialise user list
                    tree.Add(new AdminUserTree
                                 {
                                     ClientId = node.ClientId, 
                                     ClientName = node.ClientName, 
                                     Users = new List<User>()
                                 });
                }

                // add user to tree
                AdminUserTree clientNode = tree.First(c => c.ClientId == node.ClientId);
                clientNode.Users.Add(new User
                                         {
                                             FirstName = node.FirstName, 
                                             LastName = node.LastName, 
                                             UserId = node.UserId
                                         });
            }

            // normalize AdminUserTree for Kendo Tree
            var returnKendo = tree.Select(c => new
                                                   {
                                                       id = c.ClientId, 
                                                       text = c.ClientName, 
                                                       expanded = true, 
                                                       spriteCssClass = "group", 
                                                       items = c.Users
                                                           .Select(u => new
                                                            {
                                                                id = u.UserId, 
                                                                text = u.FirstName + " " + u.LastName
                                                            })
                                                            .ToArray()
                                                   });

            var serializer = new JavaScriptSerializer();
            return serializer.Serialize(returnKendo);
        }
Example #58
0
 // https://stackoverflow.com/questions/51116403/how-to-get-client-ip-address-in-asp-net-core-2-1/51245326
 public AuthController(AuthContext dbContext, IHttpContextAccessor httpContext)
 {
     _dbContext   = dbContext;
     _httpContext = httpContext;
 }
Example #59
0
 public AuthRepository(AuthContext ctx)
 {
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(ctx));
 }
Example #60
0
 public AuthRepository()
 {
     _ctx         = new AuthContext();
     _userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(_ctx));
 }