Nopoc Execute() method returns -1 - npoco

Iam trying to pass table valued parameter to Stored procedure using NPoco
{var parameters = new SqlParameter[]
{
new SqlParameter
{
SqlDbType=SqlDbType.Structured,
ParameterName="#MetricInfoTableType",
SqlValue=table,
TypeName="dbo.InfoTableType"
}
};
cdc.Execute("[dbo].[usp_Rules_INS]", parameters);
}
then Iam geting return type is -1

You might want to try something like this
cdc.Execute(";EXEC [dbo].[usp_Rules_INS] ##MetricInfoTableType = #0", parameters);

Related

Access properties of Entities

I'm getting all active countries via the service id country.repository
public function getCountries(Context $context): EntityCollection
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
return $this->countryRepository->search($criteria, $context)->getEntities();
}
This gives me this CountryCollection:
How can I access each element to get the id and the name?
I tried to loop over
public function test($context): array
{
$countryIds = $this->getCountries($context);
$ids = [];
foreach ($countryIds as $countryId) {
$ids[] = $countryId['id'];
}
return $ids;
}
Obviously this doesn't work. It gives this error:
Cannot use object of type Shopware\Core\System\Country\CountryEntity
as array
If you are only interested in the ids of the countries you can use
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
$ids = $this->countryRepository->searchIds($criteria, $context)->getIds();
searchIds() will only return the ids of the entities and not all of their properties, the benefit is that not all values have to be loaded from the DB and hydrated, therefore searchIds() is faster then the normal search().
You need to call the function like this
public function test($context): array
{
$countries = $this->getCountries($context);
$ids = [];
foreach ($countries as $country) {
$ids[] = $country->getId();//or $country->getName()
}
return $ids;
}
Usually you need to open the entity file. In your case it is CountryEntity.php to check the function to get the id or other fields there.

Add/Update parameter for a Context

In Dialogflow fulfillment I am trying to add or update parameters for a context.
let currentContext = agent.context.get('setupcall-followup');
console.log(agent.context.get('setupcall-followup').parameters); //1
currentContext.parameters.date = '2019-09-18T12:00:00-04:00';
currentContext.parameters.time = '2019-09-17T13:00:00-04:00';
currentContext.parameters['Test'] = 'Test';
console.log(agent.context.get('setupcall-followup').parameters); //2
agent.context.set(currentContext); //Seems to not be needed, since it is by reference
console.log(agent.context.get('setupcall-followup').parameters); //3, same as #2
By #2 & #3 the log shows that it was updated.
But in the Diagnostic Info > Raw API Response, the outputContext information is still the original inputContext, before modification.
What I can do:
Add a new context, with it's own parameters.
What I can't do
Get a context & change a parameter
This is the only way I finally got it to work.
Use a custom context & recreate it completely, every-time.
FYI Code below requires lodash for _.merge
function getSessionData() {
if(agent.context.get('session_details')) {
return agent.context.get('session_details').parameters.sessionDetails;
} else {
return;
}
}
function setSessionData(data) {
if(agent.context.get('session_details')) {
let session = agent.context.get('session_details').parameters.sessionDetails; //Extract the data from the existing "session_details" context
_.merge(session, data); //Update our data
let sessionContext = { //Define the complete context object again
name: "session_details",
lifespan: 5,
parameters: {
sessionDetails: session
}
}
agent.context.set(sessionContext);
} else {
let sessionContext = { //Define the complete context object again
name: "session_details",
lifespan: 5,
parameters: {
sessionDetails: data
}
}
agent.context.set(sessionContext);
}
}
I think this may help.
const parameters = {'param1':value, 'param2': value};
agent.context.set(context, 5, parameters); //here "5" is lifespan.
Tell me if it worked.

ServiceStack OrmLite SqlList<object>

I have a request that takes a stored procedure name with a list of parameters. It could be any SP so the result could be a list of anything and that is why I use SqlList<object>.
When I use
return db.SqlList<object>(spName, cmd =>
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach (var p in parameters)
{
cmd.AddParam(p.Key, p.Value, ParameterDirection.Input);
}
}
cmd.CommandTimeout = 90;
});
I get a system.dynamic.expendo object as: {[result, 1.7783336]}
On the client, I want to get the decimal value but I struggle...
I created a class on the client that has a decimal property "result" and tried to convert to it but it doesn't work. I tried to take that string and convert it using FromJson and it doesn't work either...
See the docs for the recommended APIs for calling stored procedures with OrmLite.
The return type needs to match what the Stored Procedure returns, if the SP just returns a decimal you should be able to access it with:
var result = db.SqlScalar<decimal>("EXEC MyProc #p1 #p2", new { p1, p2 });
Or if you don't know what Type it will return as you can use object, e.g:
var result = db.SqlScalar<object>("EXEC MyProc #p1 #p2", new { p1, p2 });
If it doesn't return a naked scalar result you'll need to match the shape of the return type, e.g. if it's returning a single row you can access the row values in a List<object> with:
var result = db.Single<List<object>>("EXEC MyProc #p1 #p2", new { p1, p2 });

Session variable fine in one action, null in next

I have a simple application. When a user logs in it creates a session variable and redirects them to another controller that pull up some info from the database. I need to store this to a session variable then return it to the view. The initial part is fine, it returns it and I see the information. However, when I try to create a search query it returns that the session is null even though I never clear it.
public ActionResult ShowCourses()
{
if (Session["Username"] != null)
{
string Username = Session["Username"].ToString();
using (DefaultConnection db = new DefaultConnection())
{
var model = from c in db.Courses
where c.Username == Username
select c;
Session["Courses"] = model.ToList();
var Courses = Session["Courses"];
return View(Courses);
}
}
else
{
return RedirectToAction("Login", "Users");
}
}
But when I try to run a search query to loop through the session, it brings back that Courses is null. The problem is that coursesQuery returns null and I'm not sure why.
public ActionResult SearchCourses(string query)
{
if (Session["Username"] != null)
{
var coursesQuery = Session["Courses"] as IEnumerable<Course>;
if (coursesQuery != null)
{
// Do Something
}
}
}
You did a .ToList() on the course colleciton before setting to Session.
Try this. Use List<Course> when you read it back.
if (Session["Courses"] != null)
{
var coursesQuery = (List<Course>) Session["Courses"];
}

Moq callback method with object parameter

In my scenario I want to mock 1 of the service framework method which takes object parameter and reset it with strongly typed class object.
public void Updatedata(object pvm)
{
var vm = new datamodel()
{
name = "test",
age = 100
};
pvm = vm;
}
It gives compilation error "Invalid callback. Setup on method with parameters (Object) cannot invoke callback with parameters (datamodel)." with below code for mocking.
mockderived.Setup(p => p.Updatedata(It.IsAny<datamodel>()))
.Callback<datamodel>(p =>
{
p.name ="My name is test";
});
The mock works fine if I change my updatedata method to accepts datamodel as parameter instead of object type. To avoid compilation errors I changed code by passing object as parameter:
mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
.Callback<object>(p =>
{
p = new datamodel() {name = "My name is test"};
});
Code get executed by it did not reulted in change of values of datamodel as expected.
After using reflection to set properties of the object parameter in the callback method, I am able to mock method proerly.
mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
.Callback<object>(p =>
{
var temp = new datamodel();
var t = temp.GetType();
var nameprop = "no name";
var prop = t.GetProperties();
prop[0].SetValue(p, nameprop, null);
});

Resources