Adding dynamic values to the a 2-dimensional array of string - asp.net

I have a 2-dimensional array of string I need to add items to this array based on certain conditions.
Dim mainColumnsSummary(,) As String
mainColumnsSummary = { _
{"slNo", "#", "Number", "30", True, ""}, _
{"assessmentDate", "Assessment Date", "DateTime", "100", True, ""}, _
{"assetDescription", "Description and function of asset", "String", "100", True, ""}, _
{"assetScope", "Scope of assessment", "String", "100", True, ""}, _
{"assetHazards", "Hazard identification", "String", "100", True, ""} _
} if dtTable.rows.count>0 then
' I need to add dtTable.rows(x)("Question") to this array. where x should take values from 0 to dtTable.row.count-1
How can i get this result.
Please help me with code in vb.net.

A .NET array is a data structure with a fixed length. Once created, the .Length property tells you how much elements there are in the array, and the length is constant. You cannot add to an array.
You need to look at System.Collections.Generic.List(Of T).
My VB is not very good, but try something like this:
Dim mainColumnsSummary As New List(Of String())
mainColumnsSummary.Add({"slNo", "#", "Number", "30", True, ""})
You should then be able to add as many "rows" to this list as you want.

Related

Flask restx api model not showing model data

I have a model as follows:
class Menu(db.Model):
itemId = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(255),index=True)
price = db.Column(db.Numeric)
description = db.Column(db.String(255),index=True)
image = db.Column(db.LargeBinary)
restaurantId = db.Column(db.Integer, db.ForeignKey('restaurants.id'))
createdOn = db.Column(db.DateTime,server_default=db.func.now())
status = db.Column(db.Integer,server_default="1")
orders = db.relationship('Orders', backref='menu', lazy='dynamic')
def __repr__(self):
return '<Menu of restaurant id {}>'.format(self.restaurantId)
And I have the following api model corresponding to it:
menu_model = api.model('Menu',
{'itemId':fields.Integer(),
'name':fields.String(),
'price':fields.Float(),
'description':fields.String(),
'restaurantId':fields.Integer(),
'createdOn:':fields.DateTime(),
'status':fields.Integer()})
The problem is that even though the createdOn values are correctly generated on DB side, the response shows the createdOn field as null. What could be the reason?
"menu":
{
"itemId": 1,
"name": "Menu item",
"price": 30.0,
"description": "Menu item description",
"restaurantId": 1,
"createdOn:": null,
"status": 1
}
this will accept the desired output. The first parameter is a label, not part of the json
menus = api.model(
"menu_item",
{
'itemId':fields.Integer(),
'name':fields.String(),
'price':fields.Float(),
'description':fields.String(),
'restaurantId':fields.Integer(),
'createdOn:':fields.DateTime(),
'status':fields.Integer()
},
)
menu_model = api.model(
"Menu",
{
"menu": Nested(menus),
},
)

Conditional if/then/else for JMESPath?

Am trying to do a simple if/then/else using JMESPath
For example: 'if the input is a string, return the string, else return the "value" property of the input'. An input of "abc" would return "abc". An input of {"value":"def"} would return "def"
With jq this is easy: if .|type == "string" then . else .value end
With JMESPath, I can get the type
type(#)
or the input:
#
or the value property:
value
but I have not found a way to combine them into an if-then-else. Is there any way to do this?
It is possible but not cleanly. The general form is to:
Make the value you are testing an array (wrap in square braces)
Apply the map function to map the filtered array to what value you want if true
At this point you have an array that is populated with one (true) item if the array filter passed, otherwise it is empty
Concat to that array one item (the false value)
Finally, take item at index 0 in this array - which will be the result of the condition
This should allow you to also derive possible transformations for both the false and true conditions
For example, if the test data is as so:
{
"test": 11
}
Depending on the value you can get either produce the results (using test data 11 and 2 as example):
"Yes, the value is 11 which is greater than 10"
OR
"No the value is 2 which is less than or equal to 10"
Like so:
[
map(
&join(' ', ['Yes, the value is', to_string(#), 'which is greater than 10']),
[test][? # > `10`]
),
join(' ', ['No the value is', to_string(test), ' which is less than or equal to 10'])
][] | #[0]
So to abstract a template:
[
map(
&<True Expression Here>,
[<Expression you are testing>][? # <Test Expression>]
),
<False Expression Here>)
][] | #[0]
people[?general.id !=100] || people
{
"people": [
{
"general": {
"id": 100,
"age": 20,
"other": "foo",
"name": "Bob"
},
"history": {
"first_login": "2014-01-01",
"last_login": "2014-01-02"
}
},
{
"general": {
"id": 101,
"age": 30,
"other": "bar",
"name": "Bill"
},
"history": {
"first_login": "2014-05-01",
"last_login": "2014-05-02"
}
}
]
}
if else condition works here

What is the best way to format a TSQL string to mimic SQL Manager using ASP.NET?

Using SMO and ASP.NET, I am trying to add Highlighting and line formatting to the script method of SMO objects ( table,view,etc..). Currently I am using the String.Replace method to match the Keywords, but that doesn't seem to catch all the Keywords. I have the Keywords in an Array, and then loop thru to match against the TSQL script. I am not sure of the characters that I need to match to get all the Keywords and to get the Line formatting that resembles SQL Manager.
Dim searchArr As Array = {"ADD", "EXTERNAL", "PROCEDURE", "ALL", "FETCH", "PUBLIC", "ALTER", "FILE", "RAISERROR", "AND", "FILLFACTOR", "READ", "ANY", "FOR", "READTEXT", "AS", "FOREIGN", "RECONFIGURE",
"ASC", "FREETEXT", "REFERENCES", "AUTHORIZATION", "FREETEXTTABLE", "REPLICATION", "BACKUP", "FROM", "RESTORE", "BEGIN", "FULL", "RESTRICT", "BETWEEN", "FUNCTION", "RETURN",
"BREAK", "GOTO", "REVERT", "BROWSE", "GRANT", "REVOKE", "BULK", "GROUP", "RIGHT", "BY", "HAVING", "ROLLBACK", "CASCADE", "HOLDLOCK", "ROWCOUNT", "CASE", "IDENTITY", "ROWGUIDCOL",
"CHECK", "IDENTITY_INSERT", "RULE", "CHECKPOINT", "IDENTITYCOL", "SAVE", "CLOSE", "IF", "SCHEMA", "CLUSTERED", "IN", "SECURITYAUDIT", "COALESCE", "INDEX", "SELECT",
"COLLATE", "INNER", "SEMANTICKEYPHRASETABLE", "COLUMN", "INSERT", "SEMANTICSIMILARITYDETAILSTABLE", "COMMIT", "INTERSECT", "SEMANTICSIMILARITYTABLE",
"COMPUTE", "INTO", "SESSION_USER", "CONSTRAINT", "IS", "SET", "CONTAINS", "JOIN", "SETUSER", "CONTAINSTABLE", "KEY", "SHUTDOWN", "CONTINUE", "KILL", "SOME",
"CONVERT", "LEFT", "STATISTICS", "CREATE", "LIKE", "SYSTEM_USER", "CROSS", "LINENO", "TABLE", "CURRENT", "LOAD", "TABLESAMPLE", "CURRENT_DATE", "MERGE", "TEXTSIZE",
"CURRENT_TIME", "NATIONAL", "THEN", "CURRENT_TIMESTAMP", "NOCHECK", "TO", "CURRENT_USER", "NONCLUSTERED", "TOP", "CURSOR", "NOT", "TRAN", "DATABASE", "NULL", "TRANSACTION",
"DBCC", "NULLIF", "TRIGGER", "DEALLOCATE", "OF", "TRUNCATE", "DECLARE", "OFF", "TRY_CONVERT", "DEFAULT", "OFFSETS", "TSEQUAL", "DELETE", "ON", "UNION", "DENY", "OPEN", "UNIQUE",
"DESC", "OPENDATASOURCE", "UNPIVOT", "DISK", "OPENQUERY", "UPDATE", "DISTINCT", "OPENROWSET", "UPDATETEXT", "DISTRIBUTED", "OPENXML", "USE", "DOUBLE", "OPTION", "USER",
"DROP", "Or", "VALUES", "DUMP", "ORDER", "VARYING", "ELSE", "OUTER", "VIEW", "END", "OVER", "WAITFOR", "ERRLVL", "PERCENT", "WHEN", "ESCAPE", "PIVOT", "WHERE", "EXCEPT", "PLAN", "WHILE",
"EXEC", "PRECISION", "WITH", "EXECUTE", "PRIMARY", "WITHIN GROUP", "EXISTS", "PRINT", "WRITETEXT", "EXIT", "PROC", "CREATE PROCEDURE", "NOCOUNT", "COUNT"}
Dim srv As Server
Dim name As String
Dim db As Database
Dim sp As StoredProcedure
Private Sub Admin_Props_Load(sender As Object, e As EventArgs) Handles Me.Load
openDB()
db = srv.Databases(databaseName)
If Len(Request.QueryString("name")) = 0 Then
lblData.Text = "Not a valid StoredProcedure"
Else
sp = db.StoredProcedures(Request.QueryString("name").ToString)
lblData.Text = addHighlight(sp.TextBody)
End If
End Sub
Sub openDB()
Dim sqlConn As New SqlConnection("Data Source=xxxx;Integrated Security=True;")
Dim SerCon As New Microsoft.SqlServer.Management.Common.ServerConnection(sqlConn)
srv = New Server(SerCon)
End Sub
Function addHighlight(ByVal strIn As String) As String
Dim keyWords As Array = searchArr
Dim keyInd As Integer
Dim str2() As String
str2 = strIn.Split(" ")
If Len(Trim(strIn)) > 0 And IsArray(keyWords) Then
For keyInd = LBound(keyWords) To UBound(keyWords)
For i As Integer = LBound(str2) To UBound(str2)
str2(i) = Replace(str2(i), UCase(keyWords(keyInd)), "*|*" & UCase(keyWords(keyInd)) & "*||*", 1, -1, 1)
'strIn = Replace(strIn, UCase(keyWords(keyInd)), "*|*" & UCase(keyWords(keyInd)) & "*||*", 1, -1, 1)
Next
Next
End If
strIn = Join(str2, " ")
strIn = Replace(strIn, Chr(13), "<br>", 1, -1, 1)
strIn = Replace(strIn, "*|*", "<span class=""Highlight"">")
strIn = Replace(strIn, "*||*", "</span>")
addHighlight = strIn
End Function
When I run this I get mixed results with the color formatting, as the replace will not only get the whole words, but also the substrings of bigger words; which should not happen.
The results should end up like this;
CREATE PROCEDURE AddCityToList
-- Add the parameters for the stored procedure here
#idCity int,
#idProduct int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO CityProductExclude (idCity,idProduct)
VALUES (#idCity,#idProduct)
END
The keywords not in remarks should be highlighted and capitalized, how ever I get the following back;
-- =============================================
-- AuthOR: OR,,Name>
-- CREATE date: <CREATE Date,,>
-- DESCriptiON: <DESCriptiON,,>
-- =============================================
CREATE PROCEDURE ADDCityTOLISt
-- ADD the parameters FOR the sTOred PROCEDURE here
#idCity INt,
#idProduct INt
AS
BEGIN
-- SET NOCOUNT ON ADDed TO prevent extra result SETs FROM
-- INterferINg WITH SELECT statements.
SET NOCOUNT ON;
-- INsert statements FOR PROCEDURE here
INSERT INTO CityProductExclude (idCity,idProduct)
VALUES (#idCity,#idProduct)
END
What am I missing? Any help will be much appreciated
Consider sp.TextBody is a long string containing stored procedure commands with newlines, splitting by whitespaces possibly isn't a good way to distinguish SQL keywords and comment parts there, hence better to split based from newline occurrences:
str2 = strIn.Split(New String() { Environment.NewLine }, StringSplitOptions.None)
By using assignment above, it is able to detect any strings begin with -- as SQL comments and leaving them intact, so that using Regex.Replace method can uppercase any exact SQL keywords which not marked as comment:
' Notes:
' (1) Using System.Text.RegularExpressions required to call Regex.Replace
' (2) StartsWith used to detect comment section in stored procedure body
' (3) "\b" + keyWords(keyInd) + "\b" used to replace by whole keywords only
If Len(Trim(strIn)) > 0 And IsArray(keyWords) Then
For keyInd = LBound(keyWords) To UBound(keyWords)
For i As Integer = LBound(str2) To UBound(str2)
If Not str2(i).StartsWith("--")
str2(i) = Regex.Replace(str2(i), "\b" + keyWords(keyInd) + "\b", "*|*" & UCase(keyWords(keyInd)) & "*||*", RegexOptions.IgnoreCase)
End If
Next
Next
End If
Then, putting all together in addHighlight function:
Function addHighlight(ByVal strIn As String) As String
Dim keyWords As Array = searchArr
Dim keyInd As Integer
Dim str2() As String
str2 = strIn.Split(New String() { Environment.NewLine }, StringSplitOptions.None)
If Len(Trim(strIn)) > 0 And IsArray(keyWords) Then
For keyInd = LBound(keyWords) To UBound(keyWords)
For i As Integer = LBound(str2) To UBound(str2)
If Not str2(i).StartsWith("--")
str2(i) = Regex.Replace(str2(i), "\b" + keyWords(keyInd) + "\b", "*|*" & UCase(keyWords(keyInd)) & "*||*", RegexOptions.IgnoreCase)
End If
Next
Next
End If
strIn = Join(str2, Environment.NewLine)
strIn = Replace(strIn, Chr(13), "<br />", 1, -1, 1)
strIn = Replace(strIn, "*|*", "<span class=""Highlight"">")
strIn = Replace(strIn, "*||*", "</span>")
addHighlight = strIn
End Function
NB: To make this trick work, set strIn content to include newlines before comment signs like this (only used if T-SQL string doesn't contain newlines before comments):
If Not strIn.Contains(Environment.NewLine) Then
strIn = Replace(strIn, "--", Environment.NewLine & "--")
End If
Demo: .NET Fiddle Example
Related:
Way to have String.Replace only hit "whole words"

JSON.Net error reading

I'm trying to parse some JSON data with Json.Net. Here is my data:
[
{
"UIDClan": "1",
"UIDKnjiga": "1",
"Naslov": "Title1",
"DatumZaKada": "2013-08-09 00:00:00",
"DatumIstekRez": null,
"Spremno": "0"
},
{
"UIDClan": "1",
"UIDKnjiga": "2",
"Naslov": "Title2",
"DatumZaKada": "2013-08-08 00:00:00",
"DatumIstekRez": null,
"Spremno": "0"
},
{
"UIDClan": "1",
"UIDKnjiga": "3",
"Naslov": "Title3",
"DatumZaKada": "2013-08-09 00:00:00",
"DatumIstekRez": "2013-10-09 00:00:00",
"Spremno": "1"
}
]
With this piece of code i want to extract UIDClan data:
JObject o = JObject.Parse(s);
Console.WriteLine(o["UIDClan"]);
The error is
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
I've checked with JSONLint and it's valid.
The examples that I found doesn't start with [.
Am I doing something wrong?
You could try using a JArray.
This JSON data is actually an array.
JArray v = JArray.Parse(s);
To get the first item.
var firstItem = v[0]["UIDClan"].ToString();
You can even use linq
var items = v.Where(x => x["UIDClan"].ToString() == "1").ToList();
To overcome the error plz serialize the jsonstring in below format.this serialize string we are able parse as Jobject
Newtonsoft.Json.JsonConvert.SerializeObject(new {JsonString})

How to use Dictionary in VB.net?

I have written this function to auto correct gender to M or F from different values in a string array. It works fine but my manager told me to use Dictionary which he said is more efficient. But I have no idea. Anyone like to help me to understand how this can be done ? Thanks.
Public Function AutoGender(ByVal dt As DataTable) As DataTable
Dim Gender As String = ""
Dim Mkeywords() As String = {"boy", "boys", "male", "man", "m", "men", "guy"}
Dim Fkeywords() As String = {"girl", "girls", "female", "woman", "f", "women", "chick"}
Dim row As DataRow
For Each row In dt.Rows
If Mkeywords.Contains(row("Gender").ToString.ToLower) Then
Gender = "M"
row("Gender") = Gender
ElseIf Fkeywords.Contains(row("Gender").ToString.ToLower) Then
Gender = "F"
row("Gender") = Gender
End If
Next
Return dt
End Function
Here is an example how you could implement the Dictionary(Of String, String) to lookup whether this synonym is known or not:
Shared GenderSynonyms As Dictionary(Of String, String) = New Dictionary(Of String, String) From
{{"boy", "M"}, {"boys", "M"}, {"male", "M"}, {"man", "M"}, {"m", "M"}, {"men", "M"}, {"guy", "M"},
{"girl", "F"}, {"girls", "F"}, {"female", "F"}, {"woman", "F"}, {"f", "F"}, {"women", "F"}, {"chick", "F"}}
Public Function AutoGender(ByVal dt As DataTable) As DataTable
If dt.Columns.Contains("Gender") Then
For Each row As DataRow In dt.Rows
Dim oldGender = row.Field(Of String)("Gender").ToLower
Dim newGender As String = String.Empty
If GenderSynonyms.TryGetValue(oldGender, newGender) Then
row.SetField("Gender", newGender)
End If
Next
End If
Return dt
End Function
Note that i've used the collection initializer to fill the Dictionary that is a convenient way to use literals to initialize collections. You could also use the Add method.
Edit: Just another approach that might be more concise is using two HashSet(Of String), one for the male synonyms and one for the female:
Shared maleSynonyms As New HashSet(Of String) From
{"boy", "boys", "male", "man", "m", "men", "guy"}
Shared femaleSynonyms As New HashSet(Of String) From
{"girl", "girls", "female", "woman", "f", "women", "chick"}
Public Function AutoGender(ByVal dt As DataTable) As DataTable
If dt.Columns.Contains("Gender") Then
For Each row As DataRow In dt.Rows
Dim oldGender = row.Field(Of String)("Gender").ToLower
Dim newGender As String = String.Empty
If maleSynonyms.Contains(oldGender) Then
row.SetField("Gender", "M")
ElseIf femaleSynonyms.Contains(oldGender) Then
row.SetField("Gender", "F")
End If
Next
End If
Return dt
End Function
A HashSet must also be unique, so it cannot contain duplicate Strings (like the key in the Dictionary), but it's not a key-value pair but only a set.
Simply change both of your arrays to dictionaries, and do a ContainsKey instead of Contains.
Dim Mkeywords = New Dictionary(Of String, String) From
{{"boy", ""}, {"boys", ""}, {"male", ""}, {"man", ""}, {"m", ""}, {"men", ""}, {"guy", ""}}
(and follow suit for the female)
However, as you might've noticed I put in all those empty strings. This is because dictionaries have values as well as keys, but since we're not using the values, I made them empty strings. To have the same O(1) lookup but avoiding all the extraneous values, you can use a HashSet in a similar manner.
All you have to change now is, like I said, use ContainsKey (or for HashSet if you go that route, it's still just Contains):
If Mkeywords.ContainsKey(row("Gender").ToString.ToLower) Then
One final note: this will only be "more efficient" if the data starts growing in size considerably. Right now as you have it, with only those few elements, it may even be slower to use a dictionary.

Resources