select * from c
where c.__type = #type
and CONTAINS(c.title, #search, #ignoretest)
and (NOT IS_DEFINED(c.archived) or c.archived = false)
and (NOT IS_DEFINED(c.deleted) or c.deleted = null)
var sqlParams = new SqlParameterCollection();
sqlParams.Add(new SqlParameter { Name = "#ignoretest", Value = true });
If I have boolean #ignoreTest param then my query is not working. What are the reasons? documentation is saying I can use this optional param https://learn.microsoft.com/en-us/azure/cosmos-db/sql/sql-query-contains
Related
I want testing pagination.
I want add some fake content to my Page mocked class.
How can I?
This is my test (refactoring it from a previous test), I'm using Junit5 and of course I get that No valut at JSON path $.content.lenght() and so on (of course, Page is empty):
/**
* index
*/
#WithMockUser("username")
#Test
void testCanIndex() throws Exception {
var transaction01 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(1L,
new BigDecimal(99.99), "First Transaction");
var transaction02 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(2L,
new BigDecimal(150.00), "Second Transaction");
var result = new ArrayList<BankAccountTransactionsEntity>();
result.add(transaction01);
result.add(transaction02);
Page<BankAccountTransactionsEntity> items = mock(Page.class);
when(bankAccountTransactionsService.index(0, 1, "id", "desc")).thenReturn(items);
mvc.perform(get("/api/v1/bank-account-transactions/")).andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()", is(2))).andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$.content[1].id", is(2))).andExpect(jsonPath("$[0].amount", is(new BigDecimal(99.99))))
.andExpect(jsonPath("$.content[1].amount", is(150)))
.andExpect(jsonPath("$.content[0].purpose", is("First Transaction")))
.andExpect(jsonPath("$.content[1].purpose", is("Second Transaction")))
.andExpect(jsonPath("$.content[0]", Matchers.hasKey("transactionDate")))
.andExpect(jsonPath("$.content[1]", Matchers.hasKey("transactionDate")));
}
Edit
I made a change, calling directly a PageImpl
#Test
void testCanIndex() throws Exception {
var transaction01 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(1L,
new BigDecimal(99.99), "First Transaction");
var transaction02 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(2L,
new BigDecimal(150.00), "Second Transaction");
var result = new ArrayList<BankAccountTransactionsEntity>();
result.add(transaction01);
result.add(transaction02);
Page<BankAccountTransactionsEntity> items = new PageImpl<>(result);
when(bankAccountTransactionsService.index(0, 1, "id", "desc")).thenReturn(items);
mvc.perform(get("/api/v1/bank-account-transactions/")).andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()", is(2)));
}
But body returned is empty
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/v1/bank-account-transactions/
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = com.bitbank.controllers.BankAccountTransactionsController
Method = com.bitbank.controllers.BankAccountTransactionsController#index(Integer, Integer, String, String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
I have a list of objects (buckets) that I'd like to create with my module
buckets = [
{
name = "my_bucket",
location = "EU"
storage_class = "STANDARD"
force_destroy = false
versioning = true
uniform_bucket_level_access = false
public_bucket = true
labels = {
"app" = "my_app"
}
some fields are required, (like name and location) some are not and I gave them default value in resources if not provided in here; - the full module and everything is operational, but it worked without defining 'type' in variable - so it just took everything, but my question is how do I define that object in variable block ?
variable "buckets" {
#type = list(object()) #?
type = set(object({
name = string
location = string
storage_class = string
force_destroy = boolean
versioning = boolean
uniform_bucket_level_access = boolean
public_bucket = boolean
labels = object({
string = string # ?
})
}))
}
how would and object look like that has optional fields
https://github.com/hashicorp/terraform/issues/19898
https://discuss.hashicorp.com/t/map-object-with-optional-attributes/6714
It Doesn't seem possible yet apparently..
When you try and serialize a Guid that is empty (not null, but empty) the result will be omitted if you set ExcludeDefaultValues = true.
But, if you then set ExcludeDefaultValues = false it will generate the string ""
JsConfig.IncludeNullValues = false;
JsConfig.ExcludeDefaultValues = false;
var tt = new { Name="Fred", Value=Guid.Empty, Value2=Guid.NewGuid() };
var test = JSON.stringify(tt);
Console.WriteLine(test);
Gives
{"Name":"Fred","Value":"00000000000000000000000000000000","Value2":"598a6e08af224db9a08c2d0e2f6cff11"}
But we want the Guid's formatted as a Microsoft format Guid at the client end, so we add a serializer:
JsConfig.IncludeNullValues = false;
JsConfig.ExcludeDefaultValues = false;
JsConfig<Guid>.SerializeFn = guid => guid.ToString();
var tt = new { Name="Fred", Value=Guid.Empty, Value2=Guid.NewGuid() };
var test = JSON.stringify(tt);
Console.WriteLine(test);
Gives
{"Name":"Fred","Value2":"07a2d8c0-48ad-4e72-b6f3-4fec81c36a1d"}
So the presence of a SerializeFn seems to make it ignore the config settings so it's impossible to generate the empty Guid.
The same bug applies to numbers, so if (like us) you reformat all Double to three decimal places they are omitted if zero, which is wrong.
Has anyone found a workaround for this?
Stepping through the source, it appears you need to explicitly call out what Types you want to include the default value for if there is a SerializeFn for that Type. Source reference. Note the JsConfig<Guid>.IncludeDefaultValue = true; line below.
Example Source
JsConfig.Reset();
JsConfig.IncludeNullValues = false;
JsConfig.ExcludeDefaultValues = false;
JsConfig<Guid>.SerializeFn = guid => guid.ToString();
JsConfig<Guid>.IncludeDefaultValue = true;
var tt = new { Name = "Fred", Value = Guid.Empty, Value2 = Guid.NewGuid() };
var test = tt.ToJson();
Console.WriteLine(test);
Output
{"Name":"Fred","Value":"00000000-0000-0000-0000-000000000000","Value2":"b86c4a18-db07-42f8-b618-6263148219ad"}
Your problem statement: Gistlyn: Note how it does not return the default GUID in the console.
The answer proposed above: Gistlyn: Notice how it does return the default GUID in the console.
I have an entity LeaveType with two attributes, 1. Type, 2. Available Days, where Type is an optionset and Available days is a text field. I want to fetch all such LeaveType records where the Type = 'Annual' selected in the optionset. I am not able to find how to add a filter the query expression for the option set value. Below is my in progress method:
public Entity Getleavetype(Guid LeaveDetailsId, IOrganizationService _orgService, CodeActivityContext Acontext)
{
QueryExpression GetLeavedetails = new QueryExpression();
GetLeavedetails.EntityName = "sgfdhr_leavetype";
GetLeavedetails.ColumnSet = new ColumnSet("new_type");
GetLeavedetails.ColumnSet = new ColumnSet("new_availabledays");
GetLeavedetails.Criteria.AddCondition("new_type", ConditionOperator.Equal, "Annual" ); //Is this correct????
GetLeavedetails.Criteria.AddCondition("new_employeeleavecalculation", ConditionOperator.Equal, LeaveDetailsId); //ignore this
//((OptionSetValue)LeaveDetailsId["new_leavetype"]).Value
EntityCollection LeaveDetails = _orgService.RetrieveMultiple(GetLeavedetails);
return LeaveDetails[0];
}
In your condition you need to set the integer value of the optionset, not the label.
Assuming that Annual value is for example 2, the code will be:
GetLeavedetails.Criteria.AddCondition("new_type", ConditionOperator.Equal, 2);
You should use RetrieveAttributeRequest to find an int value of OptionSet text.
In my code it looks like:
private static int findParkedOptionValue(IOrganizationService service)
{
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = Model.Invite.ENTITY_NAME,
LogicalName = Model.Invite.COLUMN_STATUS,
RetrieveAsIfPublished = false
};
// Execute the request
RetrieveAttributeResponse attributeResponse =
(RetrieveAttributeResponse)service.Execute(attributeRequest);
var attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;
// Get the current options list for the retrieved attribute.
var optionList = (from o in attributeMetadata.OptionSet.Options
select new { Value = o.Value, Text = o.Label.UserLocalizedLabel.Label }).ToList();
int value = (int)optionList.Where(o => o.Text == "Парковка")
.Select(o => o.Value)
.FirstOrDefault();
return value;
}
In https://community.dynamics.com/enterprise/b/crmmemories/archive/2017/04/20/retrieve-option-set-metadata-in-c you found a perfect example.
The new API for Servicestack.OrmLite dictates that when calling fx a stored procedure you should use either SqlScalar or SqlList like this:
List<Poco> results = db.SqlList<Poco>("EXEC GetAnalyticsForWeek 1");
List<Poco> results = db.SqlList<Poco>("EXEC GetAnalyticsForWeek #weekNo", new { weekNo = 1 });
List<int> results = db.SqlList<int>("EXEC GetTotalsForWeek 1");
List<int> results = db.SqlList<int>("EXEC GetTotalsForWeek #weekNo", new { weekNo = 1 });
However the named parameters doesn't work. You HAVE to respect the order of the parameters in the SP. I think it is because the SP is executed using CommandType=CommandType.Text instead of CommandType.StoredProcedure, and the parameters are added as dbCmd.Parameters.Add(). It seems that because the CommandType is Text it expects the parameters to be added in the SQL querystring, and not as Parameters.Add(), because it ignores the naming.
An example:
CREATE PROCEDURE [dbo].[sproc_WS_SelectScanFeedScanRecords]
#JobNo int = 0
,#SyncStatus int = -1
AS
BEGIN
SET NOCOUNT ON;
SELECT
FSR.ScanId
, FSR.JobNo
, FSR.BatchNo
, FSR.BagNo
, FSR.ScanType
, FSR.ScanDate
, FSR.ScanTime
, FSR.ScanStatus
, FSR.SyncStatus
, FSR.JobId
FROM dbo.SCAN_FeedScanRecords FSR
WHERE ((FSR.JobNo = #JobNo) OR (#JobNo = 0) OR (ISNULL(#JobNo,1) = 1))
AND ((FSR.SyncStatus = #SyncStatus) OR (#SyncStatus = -1) OR (ISNULL(#SyncStatus,-1) = -1))
END
When calling this SP as this:
db.SqlList<ScanRecord>("EXEC sproc_WS_SelectScanFeedScanRecords #SyncStatus",new {SyncStatus = 1});
It returns all records with JobNo = 1 instead of SyncStatus=1 because it ignores the named parameter and add by the order in which they are defined in the SP.
I have to call it like this:
db.SqlList<ScanRecord>("EXEC sproc_WS_SelectScanFeedScanRecords #SyncStatus=1");
Is this expected behavior? I think it defeats the anonymous type parameters if I can't trust it
TIA
Bo
My solution was to roll my own methods for stored procedures. If people finds them handy, I could add them to the project
public static void StoredProcedure(this IDbConnection dbConn, string storedprocedure, object anonType = null)
{
dbConn.Exec(dbCmd =>
{
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.CommandText = storedprocedure;
dbCmd.SetParameters(anonType, true);
dbCmd.ExecuteNonQuery();
});
}
public static T StoredProcedureScalar<T>(this IDbConnection dbConn, string storedprocedure, object anonType = null)
{
return dbConn.Exec(dbCmd =>
{
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.CommandText = storedprocedure;
dbCmd.SetParameters(anonType, true);
using (IDataReader reader = dbCmd.ExecuteReader())
return GetScalar<T>(reader);
});
}
public static List<T> StoredProcedureList<T>(this IDbConnection dbConn, string storedprocedure, object anonType = null)
{
return dbConn.Exec(dbCmd =>
{
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.CommandText = storedprocedure;
dbCmd.SetParameters(anonType, true);
using (var dbReader = dbCmd.ExecuteReader())
return IsScalar<T>()
? dbReader.GetFirstColumn<T>()
: dbReader.ConvertToList<T>();
});
}
They are just modified versions of the SqlScalar and SqlList plus the ExecuteNonQuery