While using floor database can we set an action which will turn as a boolean like below example?
Future<bool> isItAdded(in user_id) async{
var = dbClient = await db;
List<Map> list = await dbClient.rawQuery{SELECT * FROM Users WHERE user_id}, [user_id]}
return list.lenght > 0 ? true : false
}
You may write DAO object:
#dao
abstract class UsersDao {
#Query('SELECT * FROM users WHERE user_id = :userId')
Future<List<User>> findUsers(Int userId);
}
Before that you neeed to create entity:
#Entity(tableName: 'users')
class User{
#PrimaryKey(autoGenerate: true)
final int id;
#ColumnInfo(name: 'user_id')
final int userId;
}
Also you need to create database access object:
part 'database.g.dart'; // the generated code will be there
#Database(version: 1, entities: [User])
abstract class AppDatabase extends FloorDatabase {
UsersDao get usersDao;
}
Then generate additional code by command:
flutter packages pub run build_runner build
And then write check function inside database access object:
Future<bool> isItAdded(in user_id) async {
List<User> list = await usersDao.findUsers(user_id);
return list.lenght > 0;
}
The best solution is not to add user_id column and use only unique id column.
I have a trigger that i have written that I need tested to be able to get code coverage in salesforce:
here is the trigger:
Trigger MyCh_SALESFORCETRIGGERUPDATE_tr_I on Account (after insert)
{
set<ID> ids = Trigger.newMap.keyset();
for(ID id : ids)
{
MyCh_Account__c change = new MyCh_Account__c();
change.Action__c = 'insert';
change.Link__c = id;
change.Processed__c = false;
change.Map__c = 'SALESFORCE TRIGGER UPDATE';
insert change;
}
}
I have tried :
#isTest
public class MyAccountcreationTest
{
static testMethod void testMethod1()
{
Account testAccount = new Account();
testAccount.Name='Test Account' ;
insert testAccount;
Account acc1 = [Select Id, Link__c, Action__c, Processed__c, Map__c from Account where Id =: testAccount.Id];
System.assertEquals(acc1.Name,'Test Account');
System.assertEquals(acc1.Link__c, acc1.Id);
System.assertEquals(acc1.Processed__c,false);
System.assertEquals(acc1.Map__c,'SALESFORCE TRIGGER UPDATE');
System.assertEquals(acc1.Action__c,'insert');
}
}
I expect the test to pass but it gives an error :
Map__c , Action__c , Link__c are not fields of Account object.
Also , how does the test actually link to the trigger itself ?
You are creating a MyCh_Account__c record in your trigger but you're not testing that in your test. You need to query for the record created in your trigger and assert that the fields are correct.
I am trying to implement a simple change for an apex class in production. I have the proper class and proper test class. The test class runs successfully in sandbox without errors, but apparently the error is coming from the TestHelper default test class in Salesforce. When trying to deploy in production it throws the error "Method does not exist or incorrect signature: void createUser(Id, String, String, Date, Integer) from the type TestHelper"
I've tried the usual of changing the method it references to public static void, but to no avail, it throws errors in code
This is my test class:
#isTest
private class OppLineItemInvntryBO_AType_OppStge_Test {
#testSetup public static void setup() {
Profile p = [SELECT Id FROM Profile
WHERE Name = 'profile1' LIMIT 1];
Date myDate = Date.newinstance(2019,07,01);
User testUser = TestHelper.createUser(p.Id,
'company1','legalentity1',myDate,327001);
And this is my TestHelper class:
public with sharing class TestHelper {
public static User createUser(Id profileId, String company) {
Integer rnd = getRandomNumber(10000);
User user = new User(
Username = 'john.doe#acme.com' + String.valueOf(rnd),
Email = 'john.doe' + String.valueOf(rnd) + '#acme.com',
LastName = 'Doe',
FirstName = 'John',
Alias = 'JD' + String.valueOf(rnd),
ProfileId = profileId,
LocaleSidKey = 'en_US',
LanguageLocaleKey = 'en_US',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey='UTF-8',
CompanyName = company);
insert user;
return user;
}
public static Integer getRandomNumber(Integer size){
Double d = math.random() * size;
return d.intValue();
}
}
The full error is this:
API Name - OppLineItemInvntryBO_AType_OppStge_Test
Type - Apex Class
Line - 14
Column - 36
Error Message - Method does not exist or incorrect signature: void createUser(Id, String, String, Date, Integer) from the type TestHelper
You are invoking the createUser method with 5 parameters in OppLineItemInvntryBO_AType_OppStge_Test class where as in the TestHelper class , the createUser method accepts only 2 parameters. Thats why you are getting this error. Try to invoke the method with correct parameters.
#isTest
public static void TestEmptySearchQuery() {
User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
System.runAs ( thisUser ) { // running as thisUser to Avoid Error: MIXED_DML_OPERATION
setupData(); // inside setupData, community is created successfully
generateUser(); // List of user assigned with some profile, as required for project.
list<PermissionSetAssignment> PSA = new list<PermissionSetAssignment> ();
PermissionSet ps = [SELECT Id, name FROM PermissionSet where name='Some_Access'];
system.debug('PermissionSet ' + ps);
for(user u:userList)
PSA.add(new PermissionSetAssignment(AssigneeId = u.id, PermissionSetId = ps.Id)); // all the user assgined with some_access based on requirement of project
insert PSA;
}
Test.startTest();
User usr = [select Id from User where Id = :userList[0].id];
System.runAs(usr) {
system.debug('Network ommunityId ****' + Network.getNetworkId()); //getting null
SomeClass obj = new SomeClass();
Id Nid=obj.fetchNetworkId(); // return null;
system.debug('network id ' + Nid); // null
}
Test.stopTest();
}
class SomeClass {
//some code
public id fetchNetworkId() {
system.debug('network id ' + Network.getNetworkId()); // network id null;
return Network.getNetworkId(); // return null
}
// some code
}
While running normally page, controller returns proper network id,
when try to write a test class for this, community network id always return null.
the user you use for the runAs needs to be part of a community, so you need to basically create an account, create a contact and then a user for that contact. That makes the runAS user to be part of a community
I am new to NHibernate and am running into some issues getting the Automap functionality to work properly. Here are a couple of issues I am having.
The getting started wiki for Fluent NHibernate (http://wiki.fluentnhibernate.org/Getting_started) defines a sample with store, product, and employee classes--as well as the mapping for those classes. I replaced the manual mapping with AutoMapping and used Fluent NHibernate to generate the schema. Every thing generated properly. However, when the application attempted to save sample store, product, and employee objects, I received an error "TransientObjectException was Unhandled: object references an unsaved transient instance - save the transient instance before flushing. Type: FluentExample.Entities.Employee, Entity: FluentExample.Entities.Employee".
The automap looks like:
.Mappings(m=>
m.AutoMappings.Add(
AutoMap.AssemblyOf<FluentExample.Entities.Employee>(type => type.Namespace == "FluentExample.Entities")))
The object creation code (straight from the wiki) looks like the following. I should mention that the object creation works fine when using the manual fluent mapping.
// create a couple of Stores each with some Products and Employees
var barginBasin = new Store { Name = "Bargin Basin" };
var superMart = new Store { Name = "SuperMart" };
var potatoes = new Product { Name = "Potatoes", Price = 3.60 };
var fish = new Product { Name = "Fish", Price = 4.49 };
var milk = new Product { Name = "Milk", Price = 0.79 };
var bread = new Product { Name = "Bread", Price = 1.29 };
var cheese = new Product { Name = "Cheese", Price = 2.10 };
var waffles = new Product { Name = "Waffles", Price = 2.41 };
var daisy = new Employee { FirstName = "Daisy", LastName = "Harrison" };
var jack = new Employee { FirstName = "Jack", LastName = "Torrance" };
var sue = new Employee { FirstName = "Sue", LastName = "Walkters" };
var bill = new Employee { FirstName = "Bill", LastName = "Taft" };
var joan = new Employee { FirstName = "Joan", LastName = "Pope" };
// add products to the stores, there's some crossover in the products in each
// store, because the store-product relationship is many-to-many
AddProductsToStore(barginBasin, potatoes, fish, milk, bread, cheese);
AddProductsToStore(superMart, bread, cheese, waffles);
// add employees to the stores, this relationship is a one-to-many, so one
// employee can only work at one store at a time
AddEmployeesToStore(barginBasin, daisy, jack, sue);
AddEmployeesToStore(superMart, bill, joan);
// save both stores, this saves everything else via cascading
session.SaveOrUpdate(barginBasin);
session.SaveOrUpdate(superMart);
transaction.Commit();
When attempting to use the AutoMap functionality on one of my own classes, a class is
created, but for some reason I get errors when I attempt to actually
insert a record. The main error message says "AssertionFailure was
unhandled: null value". Here is a sample of my class, the config/
mapping, the error, and the create table script. (Note: The attributes
in the class are for use with ASP.NET MVC and have nothing to do with
NH.)
namespace Credit.Data.Entities
{
[Serializable]
public class EthnicityType
{
public EthnicityType()
{
}
[DisplayName("Id")]
[Required(ErrorMessage = "Id is required.")]
public virtual Guid Id { get; private set; }
[DisplayName("Title")]
[Required(ErrorMessage = "Title is required.")]
[StringLength(80, ErrorMessage = "Title must be less than 80 characters.")]
public virtual string Title { get; set; }
[DisplayName("Description")]
[StringLength(255, ErrorMessage = "Description must be less than 255 characters.")]
public virtual string Description { get; set; }
[DisplayName("Is Active")]
[Required(ErrorMessage = "Is Active is required.")]
public virtual bool IsActive { get; set; }
}
}
Here is the Fluent NHibernate configuration.
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey ("CreditConnectionString"))
.UseReflectionOptimizer()
.AdoNetBatchSize(25)
.DefaultSchema("dbo")
.Cache(c => c
.UseQueryCache()
.ProviderClass<HashtableCacheProvider>())
.ShowSql())
.Mappings(m =>
m.AutoMappings.Add(AutoMap.AssemblyOf<Credit.Data.Entities.EthnicityType>(type => type.Namespace == "Credit.Data.Entities")))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
}
And the error. Yuk!
NHibernate.AssertionFailure was unhandled
Message="null identifier"
Source="NHibernate"
StackTrace:
at NHibernate.Engine.EntityKey..ctor(Object identifier, String
rootEntityName, String entityName, IType identifierType, Boolean
batchLoadable, ISessionFactoryImplementor factory, EntityMode
entityMode)
at NHibernate.Engine.EntityKey..ctor(Object id,
IEntityPersister persister, EntityMode entityMode)
at
NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate
(Object entity, EntityKey key, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess)
at
NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object
entity, Object id, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess)
at
NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId
(Object entity, String entityName, Object anything, IEventSource
source, Boolean requiresImmediateIdAccess)
at
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId
(SaveOrUpdateEvent event)
at
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient
(SaveOrUpdateEvent event)
at
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformSaveOrUpdate
(SaveOrUpdateEvent event)
at
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate
(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdate
(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)
at FluentExample.Program.PopulateRecordTest(ISessionFactory
sessionFactory) in C:\Code\FluentExample\FluentExample\Program.cs:line
52
at FluentExample.Program.BootstrapNH() in C:\Code\FluentExample
\FluentExample\Program.cs:line 32
at FluentExample.Program.Main() in C:\Code\FluentExample
\FluentExample\Program.cs:line 24
at System.AppDomain._nExecuteAssembly(Assembly assembly, String
[] args)
at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
And the table schema--just for kicks.
USE [Credit]
GO
/****** Object: Table [dbo].[EthnicityType] Script Date:
08/30/2009 04:59:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EthnicityType](
[ID] [uniqueidentifier] NOT NULL,
[Title] [nvarchar](80) NOT NULL,
[Description] [nvarchar](255) NULL,
[IsActive] [bit] NOT NULL
CONSTRAINT [PK_EthnicityType_Title] PRIMARY KEY NONCLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY
= OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[EthnicityType] ADD CONSTRAINT
[DF_EthnicityType_ID] DEFAULT (newid()) FOR [ID]
GO
ALTER TABLE [dbo].[EthnicityType] ADD CONSTRAINT
[DF_EthnicityType_IsActive] DEFAULT ((1)) FOR [IsActive]
GO
I've tried a number of things to get automapping working in my environment but just have not yet been fully successful. Some variations I have tried include
Using a static map and allowing Fluent Nhibernate to recreate my table.
Changing the private set on Id to public
Creating a primarykeyconvention to try and set the Guid in case that was the issue and adding this to my mapping.
Primary Key Convention:
public class PrimaryKeyConvention : IIdConvention
{
public void Apply(IIdentityInstance instance)
{
instance.GeneratedBy.GuidComb();
//instance.GeneratedBy.Native();
}
}
Any advice or feedback is very much appreciated.
The Fluent NHibernate example entities are in the Examples.FirstProject.Entities namespace, while you're limiting the AutoMap to FluentExample.Entities (in type => type.Namespace == "FluentExample.Entities").
The first error message points to that by stating "references an unsaved transient instance [...] FluentExample.Entities.Employee"
You should update the AutoMap code to point to the correct interface. If you have classes in multiple interfaces, you can modify the criteria to include an or.