How to insert into a table field with value from a display method dependent of string - x++

as you might know, this is a nice way to dynamically set values to fields.
myTable.(fieldName2Id(myTable.TableId, fieldNameStr)) = "This value";
myTable.insert();
What I am wondering about is if there is any way to do it in a similar fashion with display methods, just dynamically get the values from them?
If i have the Display method name (i.e. itemName()) how can I do this...?
something like this to demonstrate how i think:
methodNameStr = "ItemName";
myTable.myField = mytable.(methodName2Id(myTable.TableId, methodNameStr));
myTable.insert();

Use DictTable.callObject(medhodName, buffer).
Common myTable;
DictTable dt;
//<SampleOnly>
str methodNameStr = "itemDescriptionOrName";
InventTable tmpTab;
select firstOnly tmpTab;
myTable = tmpTab;
//</SampleOnly>
dt = new DictTable(myTable.TableId);
dt.callObject(methodNameStr, myTable);
info(strFmt("%1", dt.callObject(methodNameStr, myTable)));

Related

How would I use Automapper in this query?

Given
Dim postviewmodel As IEnumerable(Of be_PostsViewModel)
postviewmodel = _postRepository.SelectAll.Select(Function(S) New
be_PostsViewModel With {.PostIsPublished = S.PostIsPublished, .Id =
S.PostId, .PostSummary = S.PostSummary, .PostDateCreated =
S.PostDateCreated,
.PostCategory = S.PostCategory, .PostTitle =
S.PostTitle}).Where(Function(p)
p.PostIsPublished = True).Where(Function(a) Not
a.PostCategory.FirstOrDefault.CategoryName = "Lead Story")
.Skip((Page - 1) * PageSize).Take(PageSize)
How would I use Automapper so I don't do all thmapping of properties by hand? I am completely new to it and have been doing a lot of reading but don't quite understand how to actually do it. I know I have to create the map and then call Mapper.map. But what goes where in Mapper.map?
I would do this:
Mapper.CreateMap<Post, be_postsViewModel>();
Do that in your application startup (App_Start etc). Then in your code above:
postViewModel = _postRepository.SelectAll.Project.To(Of be_PostsViewModel)
However, I'd put the "Project.To" AFTER all of your Where/Skip/Take pieces. The projection is the last thing you want to do. Project.To creates that exact Select expression, passes it to the query provider to modify the SQL at its base.
Unless SelectAll doesn't return IQueryable, then you have other, larger problems.

lua: user input to reference table

I am having trouble with my tables, I am making a text adventure in lua
local locxy = {}
locxy[1] = {}
locxy[1][1] = {}
locxy[1][1]["locdesc"] = "dungeon cell"
locxy[1][1]["items"] = {"nothing"}
locxy[1][1]["monsters"] = {monster1}
The [1][1] refers to x,y coordinates and using a move command I can successfully move into different rooms and receive the description of said room.
Items and monsters are nested tables since multiple items can be held there (each with their own properties).
The problem I am having is getting the items/monsters part to work. I have a separate table such as:
local monsters = {}
monsters["rat"] = {}
monsters["rat"]["Name"] = "a rat"
monsters["rat"]["Health"] = 5
monsters["rat"]["Attack"] = 1
I am using a table like this to create outlines for various enemy types. The monster1 is a variable I can insert into the location table to call upon one of these outlines, however I don't know how to reference it.
print("You are in ", locxy[x][y]["locdesc"]) -- this works
print("You can see a ", locxy[x][y]["monsters]["Name"],".") - does not work
So I would like to know how I can get that to work, I may need a different approach which is fine since I am learning. But I would also specifically like to know how to / if it possible to use a variable within a table entry that points to data in a separate table.
Thanks for any help that can be offered!
This line
locxy[x][y]["monsters]["Name"]
says
look in the locxy table for the x field
then look in the y field of that value
look in the "monsters"` field of that value
then look in the "Name" field of that value
The problem is that the table you get back from locxy[x][y]["monsters"] doesn't have a "Name" field. It has some number of entries in numerical indices.
locxy[x][y]["monsters][1]["Name"] will get you the name of the first monster in that table but you will need to loop over the monsters table to get all of them.
Style notes:
Instead of:
tab = {}
tab[1] = {}
tab[1][1] = {}
you can just use:
tab = {
[1] = {
{}
}
}
and instead of:
monsters = {}
monsters["rat"] = {}
monsters["rat"]["Name"] = "foo"
you can just use:
monsters = {
rat = {
Name = "foo"
}
}
Or ["rat"] and ["Name"] if you want to be explicit in your keys.
Similarly instead of monsters["rat"]["Name"] you can use monsters.rat.Name.

How can I check results for select statement in MVC?

Hi this is the SP I have :
USE [Tracker_Entities]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[uspHub]
#id int
AS
BEGIN
SELECT DISTINCT table1.UID, table1.url, Scope.ID
FROM table1 INNER JOIN
Scope ON table1.UID = Scope.newBrand
WHERE (table1.value = 0) AND (Scope.ID = #id)
ORDER BY table1.url
END
GO
When i run this SP in sql server by passing ID as parameter i am getting expected result. Now I need to check this SP in mvc. This is the way I am calling this SP in my MVC :
using (var ctx = new database_Entities())
{
int ID = 122;
ctx.uspHub(ID);
ctx.SaveChanges();
}
But when I put breakpoint in using statement and check for results, it is not displaying any results. I am struggling here for long time and i am not getting proper solution for this. So what are the steps in MVC to check results for SP which has select statements??
Update :
I got solution for this after using tolist. Now i am getting three results in list and i need to grab one result that is URL and pass it as input parameter.
My code :
int ID = 413;
var x = ctx.uspdHub(ID).ToList();
Here x has 3 results. I need to take one result from it.I tried doing x. but it doesn't show results after i type dot. How can i achieve this??
You have to Get the result into proper model/object.
List<YourEntity> model;
using (var ctx = new database_Entities())
{
int ID = 122;
model = ctx.uspHub(ID).toList();
//ctx.SaveChanges(); - no need to call SaveChanges
// - as you are not updating anything
}
Go through this article if you need more info. Call Stored Procedure From Entity Framework (The code above will work anyways...)
use...
using (var ctx = new database_Entities())
{
int ID = 122;
var result = ctx.uspHub(ID);
}
and add a break after the result to see whats in the result variable. Obviously, the sope of result will need to be moved, but I'm only showing here how you can see the data returned.
Try to use something like this:
using (var dataContext= new database_Entities())
{
int ID = 122;
SomeEntity[] result = dataContext.Database.SqlQuery<SomeEntity>("[dbo].[uspHub] #id",new SqlParameter("#id", ID)).ToArray();
}
It is good for me. I have used ORM EntityFramework to connect with DB.

Passing query parameters in Dapper using OleDb

This query produces an error No value given for one or more required parameters:
using (var conn = new OleDbConnection("Provider=..."))
{
conn.Open();
var result = conn.Query(
"select code, name from mytable where id = ? order by name",
new { id = 1 });
}
If I change the query string to: ... where id = #id ..., I will get an error: Must declare the scalar variable "#id".
How do I construct the query string and how do I pass the parameter?
The following should work:
var result = conn.Query(
"select code, name from mytable where id = ?id? order by name",
new { id = 1 });
Important: see newer answer
In the current build, the answer to that would be "no", for two reasons:
the code attempts to filter unused parameters - and is currently removing all of them because it can't find anything like #id, :id or ?id in the sql
the code for adding values from types uses an arbitrary (well, ok: alphabetical) order for the parameters (because reflection does not make any guarantees about the order of members), making positional anonymous arguments unstable
The good news is that both of these are fixable
we can make the filtering behaviour conditional
we can detect the category of types that has a constructor that matches all the property names, and use the constructor argument positions to determine the synthetic order of the properties - anonymous types fall into this category
Making those changes to my local clone, the following now passes:
// see https://stackoverflow.com/q/18847510/23354
public void TestOleDbParameters()
{
using (var conn = new System.Data.OleDb.OleDbConnection(
Program.OleDbConnectionString))
{
var row = conn.Query("select Id = ?, Age = ?", new DynamicParameters(
new { foo = 12, bar = 23 } // these names DO NOT MATTER!!!
) { RemoveUnused = false } ).Single();
int age = row.Age;
int id = row.Id;
age.IsEqualTo(23);
id.IsEqualTo(12);
}
}
Note that I'm currently using DynamicParameters here to avoid adding even more overloads to Query / Query<T> - because this would need to be added to a considerable number of methods. Adding it to DynamicParameters solves it in one place.
I'm open to feedback before I push this - does that look usable to you?
Edit: with the addition of a funky smellsLikeOleDb (no, not a joke), we can now do this even more directly:
// see https://stackoverflow.com/q/18847510/23354
public void TestOleDbParameters()
{
using (var conn = new System.Data.OleDb.OleDbConnection(
Program.OleDbConnectionString))
{
var row = conn.Query("select Id = ?, Age = ?",
new { foo = 12, bar = 23 } // these names DO NOT MATTER!!!
).Single();
int age = row.Age;
int id = row.Id;
age.IsEqualTo(23);
id.IsEqualTo(12);
}
}
I've trialing use of Dapper within my software product which is using odbc connections (at the moment). However one day I intend to move away from odbc and use a different pattern for supporting different RDBMS products. However, my problem with solution implementation is 2 fold:
I want to write SQL code with parameters that conform to different back-ends, and so I want to be writing named parameters in my SQL now so that I don't have go back and re-do it later.
I don't want to rely on getting the order of my properties in line with my ?. This is bad. So my suggestion is to please add support for Named Parameters for odbc.
In the mean time I have hacked together a solution that allows me to do this with Dapper. Essentially I have a routine that replaces the named parameters with ? and also rebuilds the parameter object making sure the parameters are in the correct order.
However looking at the Dapper code, I can see that I've repeated some of what dapper is doing anyway, effectively it each parameter value is now visited once more than what would be necessary. This becomes more of an issue for bulk updates/inserts.
But at least it seems to work for me o.k...
I borrowed a bit of code from here to form part of my solution...
The ? for parameters was part of the solution for me, but it only works with integers, like ID. It still fails for strings because the parameter length isn't specifed.
OdbcException: ERROR [HY104] [Microsoft][ODBC Microsoft Access Driver]Invalid precision value
System.Data.Odbc. OdbcParameter.Bind(OdbcStatementHandle hstmt,
OdbcCommand command, short ordinal, CNativeBuffer parameterBuffer, bool allowReentrance)
System.Data.Odbc.OdbcParameterCollection.Bind(OdbcCommand command, CMDWrapper cmdWrapper, CNativeBuffer parameterBuffer)
System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader, object[] methodArguments, SQL_API odbcApiMethod)
System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader)
System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
Dapper.SqlMapper.QueryAsync(IDbConnection cnn, Type effectiveType, CommandDefinition command) in SqlMapper.Async.cs
WebAPI.DataAccess.CustomerRepository.GetByState(string state) in Repository.cs
var result = await conn.QueryAsync(sQuery, new { State = state });
WebAPI.Controllers.CustomerController.GetByState(string state) in CustomerController .cs
return await _customerRepo.GetByState(state);
For Dapper to pass string parameters to ODBC I had to specify the length.
var result = await conn.QueryAsync<Customer>(sQuery, new { State = new DbString { Value = state, IsFixedLength = true, Length = 4} });

how to dynamically name element in a lua table

I have the following test code:
local luatable = {}
luatable.item1 = 'abc'
luatable.item2 = 'def'
I'd like to know how to change it so that I can dynamically assign the names becuase I don't know how many "items" I have. I'd like to do something like this:
(pseudo code)
n = #someothertable
local luatable = {}
for i = 1, n do
luatable.item..i = some value...
end
Is there a way to do this?
I'd like to do something like this: luatable.item..i = value
That would be
luatable['item'..i] = value
Because table.name is a special case shorthand for the more general indexing syntax table['name'].
However, you should be aware that Lua table indexes can be of any type, including numbers, so in your situation you most likely just want:
luatable[i] = value
Yes, and the correct code is
for i = 1, n do
luatable["item"..i] = some value...
end
Recall that luatable.item1 is just sugar for luatable["item1"].

Resources