This query in Linq to Sql - linq-to-sql

i have in my DB table TBus fields like s1,s2.s3.s4,...sn
i get the seatNumber as a parameter and want to get that field just like i have it in my code.
Any idea please.
private string checkSeatValue(int busTripId, int seatNumber)
{
string sNumber = "s" + seatNumber.ToString();
// Some code here
string sqlCommand = "SELECT " + sNumber + " FROM TBus WHERE Id=" + busTripId + "";
// More code here
}

If you want pure Linq2SQL code, you should get the TBus object:
var bus = yourDataContext.GetTable<TBus>().Where(bus => bus.BusTripId == busTripId).SingleOrDefault();
And then switch your seat variable to get the desired field:
var seat;
switch(seatNumber)
{
case "s1":
seat = bus.Seat1;
break;
case "s2":
seat = bus.Seat2;
break;
// And so it goes on...
}
However, you can do pure SQL code via Linq also or play with reflection.
-- EDIT
As I said in the comment, I believe your database model can be improved. My advice would be having two tables:
TBus Table
TBusId - int [PK]
...
TBusSeat Table
TBusSeatId - int [PK]
TBusIs - int [FK referencing TBus.TBusId]
SeatNumber - int
...
That way, you have more natural flexibility to deal with those king of situations. Consider the following set of data:
TBus Table
TBusId
------
1
2
TBusSeat Table
TBusSeatId | TBusId | SeatNumber | PassengerName
------------------------------------------------
1 1 1 Josh Doe
2 1 2 John Doe
3 1 3 Jane Doe
4 2 1 Jack Doe
So, to deal with your desired query with Linq2SQL, it would be simple as this:
var seat = yourDataContext.GetTable<TBusSeat>().Where(seat => seat.TBusId == 1 && seat.SeatNumber == 2).SingleOrDefault();
And calling seat.PassengerName would result in John Doe.

Related

Checking discord messages with sql

So I've been trying to check each message from a sql table. My sql table structure is down below:
Example:
| id | | triggervalue | | triggermessage |
| 633666515413237791 | | hello, world, test | | Trigger works! |
(array like string is something like: hello, world, test)
I want to check each message from each triggervalue column to see if message contains a string from array like string.
Here is what I've done:
I tried to merge every single array like string then send(triggermessage) where the same row of the found array contains, then checking for word.
connection.query(`SELECT * FROM triggervalue`, (err, rows) => {
let array = []
for(i = 0; i < rows.length; i++) {
let received = rows[i].jsonstring;
var intarray = received.replace(/^\[|\]$/g, "").split(", ");
array.concat(intarray)
// continue code here...
}
})
However, I can't get the triggermessage of the same row of found array. How would I go for it? I've been stuck here for quite a while... Sorry if this way of asking is wrong, thanks!
(Sorry if my english is bad)

Parsing variable length record to table columns where specific column is dynamic in SSIS 2016

I have a table that has 45 columns for tax values
| Tax1 | Tax2 | .......... | Tax 44 | Tax45 |
I read in a variable length positional record that can contain zero to 90 values. The record is structured so that the first 3 characters are the tax code (values 001 - 045) and the next 7 characters are the tax value:
Examples:
0010013.990140005.00
0040002.00
0150001.150320002.200410014.250420012.990430000.500440001.750450004.68
What I would like to do is, for each record:
if ISNULL(record) or LEN(record) < 10 (3 characters for the code, 7 characters for the value)
quit
else
determine the amount of 10 character sections
for each 10 character section
taxCode = SUBSTRING(record, 1, 3)
taxValue = SUBSTRING(record, 4, 10)
table.Tax(taxCode).Value = taxValue (ex: using the first example record, column Tax1 will hold a value of 0013.99, Tax14 will be 0005.00)
next section
all other Tax[n] columns will have a value of 0.00
end if
Is there a way to do this without having to create 45 variables, one for each corresponding column?
EDIT:
I apologize for the lack of clarity. I receive a flat file from our VMS database. This file has multiple record types per file (ie: IT01, IT02, IT03, IT04, IT05, IT06, IT07). Each record type is on its own line. I read this file into a staging table, which the record type from the data on the line. For example (this is the record type I am referring to in my question):
IT06404034001005.000031013.000
This gets loaded into my staging table as:
RecordType | RecordData |
------------------------------------------
IT06 | 404034001005.000031013.000
The RecordData field is then able to be broken down further as:
ItemNumber | RecordData |
-------------------------------------
404034 | 001005.000031013.000
With a little bit of up-front work, I was able to create a script task to do exactly as I needed it to.
Step 1: add a script component. set it up as a transformation
Step 2: define all of the output columns necessary (long and tedious task, but it worked)
Step 3: put the following code in the script
public override void Input0_ProcessInputRow(Input0Buffer Row){
int sizeOfDataSegment = 11; // size of single record to be parsed (item number/next price)
string recordDetail = Row.RecordDetail.ToString().Trim();
string itemNumber = recordDetail.Substring(0, 6);
//System.Windows.Forms.MessageBox.Show(String.Format("Record Detail: {0}", recordDetail));
// we need a record for every item number, regardless if there are taxes or not
Row.Company = Variables.strCompanyName;
Row.ItemNumber = itemNumber;
if (recordDetail.Length > 6){
string taxData = recordDetail.Substring(6);
if (string.IsNullOrEmpty(taxData)){
}
else{
if (taxData.Length % sizeOfDataSegment == 0){
int numberOfTaxes = taxData.Length / sizeOfDataSegment;
//System.Windows.Forms.MessageBox.Show(String.Format("Number of taxe codes: {0}", numberOfTaxes.ToString()));
int posTaxCode = 0;
for (int x = 0; x < numberOfTaxes; x++){
string taxCode = taxData.Substring(posTaxCode, 3);
string taxValue = taxData.Substring(posTaxCode + 3, 8);
string outputColumnName = "TaxOut" + Convert.ToInt32(taxCode).ToString();
//System.Windows.Forms.MessageBox.Show(String.Format("TaxCode: {0}" + Environment.NewLine + "TaxValue: {1}", taxCode, taxValue));
//using taxCode value (ie: 001), find and set the value for the corresponding table column (ie: Tax1)
//foreach (System.Reflection.PropertyInfo dataColumn in Row.GetType().GetProperties()){
foreach (System.Reflection.PropertyInfo dataColumn in Row.GetType().GetProperties()){
if (dataColumn.Name == outputColumnName){
if (Convert.ToDecimal(taxValue) < 0){
// taxValue is a negative number, and therefore a percentage value
taxValue = (Convert.ToDecimal(taxValue) * -1).ToString() + "%";
}
else{
// taxValue is a positive number, and therefore a dollar value
taxValue = "$" + Convert.ToDecimal(taxValue).ToString();
}
dataColumn.SetValue(Row, taxValue);
}
}
posTaxCode += sizeOfDataSegment;
}
}
else{
System.Windows.Forms.MessageBox.Show(String.Format("Invalid record length({0}): {1}", taxData.Length, taxData));
}
}
}
}

Kendo Grid (Java Script) : Multiple columns each column from a record from DB with inline batch Edit/Update?

What I want: Columns with Weekdays in Kendo grid where each column may or may not coming from DB. Also, batch edit/Update functionality. Is this feasible somehow if so any help will be appreciated to get me started else any other suggestion, please?
In DB:
Date | in | out | User ID
5/1/2017 | datetime | datetime | int
5/3/2017 | datetime | datetime | int
5/5/2017 | datetime | datetime | int
Output:
User Name | 5/1/2017 | 5/2/2017 | 5/3/2017 | 5/4/2017 | 5/5/2017
Where cell for [5/1/2017], [5/3/2017] and [5/5/2017] will be editable.
It is possible to define the grid column schema dynamically where:
for (var i = 0; i < 5; i++) {
var entryIndex = "entries[" + i + "]";
columns.push({
field: entryIndex,
title: "Column " + i
});
}
would become something like:
// first column for username
columns.push({ field: valuesFromDatabase.UserName });
// loop to append each available date in the list as a column
for (var i = 0; i < valuesFromDatabase.Dates; i++) {
columns.push({
field: i.NumberOfVisits,
title: i.Date
});
}
valuesFromDatabase being a list of objects holding your data (Dates containing a list of whatever content you wish to show in the associated column, in this example a number of visits). I haven't got a chance to test this but it should get you on the right track.
A few other examples of dynamically creating columns:
JSFiddle with editable grid
Example using Razor

Copy previous values kettle pentaho

I have an issue and i'm looping on it! :| I hope someone can help me..
So i have an input file (.xls), that is simple but there are a row (lets say its "ROW1") that is like this:
ROW1 | ROW2 | ROW3 | ROW_N
765 | 1 | AAAA-MM-DD | ...
null | 1 | AAAA-MM-DD | ...
null | 1 | AAAA-MM-DD | ...
944 | 2 | AAAA-MM-DD | ...
null | 2 | AAAA-MM-DD | ...
088 | 7 | AAAA-MM-DD | ...
555 | 2 | AAAA-MM-DD | ...
null | 2 | AAAA-MM-DD | ...
There are no stardard here, like you can see.. There are some lines null (ROW1) and in ROW2, there are equal numbers, with different association to ROW1 (like in line 5 and 6, then in line 8 and 9).
My objective is to copy and paste the values from ROW1, in the ROW1 after when is null, till isn't null. Basically is to copy form previous step, when is null...
I'm trying to use the "Formula" step, by using something like:
=IF(AND(ISBLANK([ROW1]);NOT(ISBLANK([ROW2]));ROW_n=ROW1;IF(AND(NOT(ISBLANK([ROW1]));NOT(ISBLANK([ROW2]));ROW_n=ROW1;ROW_n=""));
But nothing yet..
I've tried "Analytic Query" but nothing too..
I'm using just stream a xls file input..
Tks very much, any help is very much appreciiated!!
Best Regardsd!
Well i discover a solution, adding a "User Defined Java Class" with the code below:
import java.util.HashMap;
private FieldHelper output_field, card_field;
private RowSet out, log;
private String previou_card =null;
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
if (first)
{
first = false;
out = findTargetRowSet("out");
output_field = get(Fields.Out, "previous_card");
} else {
Object[] r = getRow();
if (r == null) {
setOutputDone();
return false;
}
r = createOutputRow(r, data.outputRowMeta.size());
if (previous_card != null) {
output_field.setValue(r, previous_card);
}
if (card_field == null) {
card_field = get(Fields.In, "Grupo de Cartões");
}
String card = card_field.getString(r);
if (card != null && !card.isEmpty()) {
previous_card = card;
}
// Send the row on to the next step.
putRowTo(data.outputRowMeta, r, out);
}
return true;
After this i have to put a few steps but this help very much.
Thank you mates!!
Finally i got result. Please follow below steps
Below image is full transformation screen.
Data Grid Data will be like these. Sorry for that in my local i don't have Microsoft because of that i took Data Grid. Instead of Data Grid you can drag and drop Microsoft Excel Input step.
Drag and Drop one java script step and write below code.
Last step of transformation, drag and drop Select values step and select the columns.( These step is no necessary)
Final result will be like these.
Hope this helps.

Representing relational tables in ActionScript 3.0

I'm struggling to make a flexible data structure (like a relational database) for a quiz in ActionScript 3.0.
I have a number of questions, each with 2 alternatives:
Questions
| id | alt1 | alt2 | correctAlt |
---------------------------------------
| 0 | Sweden | Denmark | 1 |
| 1 | Norway | Finland | 2 |
| 2 | Iceland | Ireland | 1 |
And a number of users with unique IDs:
Users
| id | age | sex | profession | totalCorrect |
-------------------------------------------------
| A5 | 25 | 0 | "Lorem" | 0 |
| A6 | 45 | 1 | "Ipsum" | 0 |
| A7 | 32 | 1 | "Dolor" | 0 |
And each user might answer a question:
Answers
| question_id | user_id | answer |
----------------------------------
| 0 | A5 | 1 |
| 1 | A6 | 2 |
| 2 | A7 | 1 |
How can I represent this in AS3?
And how can I, when I've collected all the data, answer questions such as:
a. How many users answered question 1?
b. How many % of the users answering question 1 were correct?
c. And how can I sum the number of correct answers for each user and update the totalCorrect column?
Whether you use a database or not, it's still possible to represent this data with objects. You can create specific classes.
Here's a basic example for a Question class.
public class Question
{
private var _id:int;
private var _alternatives:Array;
private var _correctAnswer:int;
public function Question()
{
}
//----------- Group: Getters & Setters
// follow the same principle as alternatives for id & correctAnswer
public function set alternatives(value:Array):void
{
_alternatives = value;
}
public function get alternatives():Array
{
return _alternatives;
}
// etc.....
}
var question1:Question = new Question();
question1.alternatives = ["Sweden" , "Denmark"]
question.correctAnswer = 1;
question.id = 0;
It's also possible to pass parameters to the constructor
public class Question
{
private var _id:int;
private var _alternatives:Array;
private var _correctAnswer:int;
public function Question(id:int , alt:Array, correct:int)
{
_id = id;
_alternatives = alt;
_correctAnswer = correct;
}
var question1:Question = new Question(0 , ["Sweden" , "Denmark"] , 1);
Do something similar for the Users , then create another class where you'll manipulate the data.
Try and find some resources about Classes in general and Object Oriented Programming in particular.
I suggest you to store this data in a SQL database.
A SQL database will help you to extract data by your questions.
If you are using Air, this should be easy as Air supports SQLite, a local database.
If you are developing a .swf file, you can connect to a SQL database using AMF or using POST or GET methods to a server who will fetch the data by the SQL request sended using the URLRequest() method.
I strongly recommend to use a SQL database as this is made for your type of questions.
Here's your questions translated to SQL
How many users answered question 1?
You forgot to add id to your answers table
SELECT users.id FROM users, answers, questions WHERE questions.id = 0 AND answers.question_id = questions.id AND answers.answer = questions.correctAlt;
How many users answered question 1?
This can be done in two queries. Both will return a number of users. First, all users who answered the question. Secondly, the same as the first question translated.
SELECT users.id FROM users, answers, questions WHERE questions.id = 0 AND answers.question_id = questions.id;
SELECT users.id FROM users, answers, questions WHERE questions.id = 0 AND answers.question_id = questions.id AND answers.answer = questions.correctAlt;
How can I sum the number of correct answers for each user and update the totalCorrect column?
You don't even need this sort of column in your table as it can be resolved by a simple query.
SELECT answers.id FROM users, answers, questions WHERE answers.question_id = questions.id;
I took the time to look into your problem in more detail. I created three classes as models for the Question, User & Answer and an AnswerEvent class.
The main class serves as a central point to manipulate data. When a user answers a question , the user's answer(Answer class ) dispatches an event to inform the main class. The answer has a user property , a question property and a isCorrect property, the AnswerEvent contains an Answer object that can be stored in the main class.
After the event has been dispatched , the answer is stored in an array of answers. Since each answer contains the user data as well as the question answered & how it was answered , you can use this array to answer your a, b & c questions.
As for the classes, I followed a similar principle to that exposed in my first reply. I don't think there's enough space here to post all the code so I just posted some excerpts.
//Inside the main class
private var answers:Array = [];
private function init():void
{
this.addEventListener(AnswerEvent.ANSWER , answerEventListener );
var q1:Question = new Question( 0 , ["Sweden" , "Denmark"] , 0 );
var q2:Question = new Question( 1 , ["Norway" , "Finland"] , 1 );
var q3:Question = new Question( 2 , ["Iceland" , "Ireland"] , 0 );
var user1:User = new User( 5 , 25 , 0 , "Lorem" );
var user2:User = new User( 6 , 45 , 1 , "Ipsum" );
var user3:User = new User( 7 , 32 , 1 , "Dolor" );
//if the answer is correct , the totalCorrect property is incremented
// in the User class, check the Answer class below for an explanation of the
//parameters
user1.answer( new Answer( this , user1 , q1 , 1 ));
}
private function answerEventListener(event:AnswerEvent):void
{
answers.push(event.answer);
trace( this , event.answer.isCorrect );
trace( this , event.answer.user.age );
}
Here's a model for the Answer class, I didn't add the getters for lack of space. The AnswerEvent extends the Event class and add an answer property of type Answer
public class Answer
{
private var _question:Question;
private var _answer:int;
private var _user:User;
private var _isCorrect:Boolean;
public function Answer(dispatcher:EventDispatcher , user:User , question:Question , answer:int)
{
this._user = user;
this._question = question;
this._answer = answer;
// not essential but will help iterate thru correct answers
// the _answer property should be _answerIndex really, in order not to be confused
// with an Answer object ( quick job ! )
if( question.correctAnswer == answer )
_isCorrect = true;
// the this keyword corresponds to this answer
dispatcher.dispatchEvent( new AnswerEvent(AnswerEvent.ANSWER , this) );
}
}