HTTPContext.Request Method Equivalent in .Net 6 - .net-6.0

We used to write code in .Net Framework for DataTable filtering on server side.
This was the old code where HttpContext.Request was working fine. Now in .Net 6 how we can establish the same search and get HttpContext as well in any controller or model class from jquery.
This function is static and I am stuck in HttpContext.Request line where this is throwing exception "Httpcontext does not exist" even if we use IHttpContextAccessor here. How can we access that variable as that is defined in Program.cs.
public static DataTable FilterTable(DataTable dt, ref int Fcount, JQPM p)
{
p.sColumnslist = p.sColumns.Split(',');
string Fstring = ""; Int32 intVal = 0;
if (!string.IsNullOrEmpty(p.sSearch))
{
string[] Arr = p.sSearch.Trim().Split(' ');
for (int i = 0; i < Arr.Length; i++)
{
if (Arr[i] != "")
{
Fstring = "0=1 ";
for (int j = 0; j < p.sColumnslist.Length; j++)
{
if (Convert.ToBoolean(System.Web.HttpContext.Request["bSearchable_" + j]))
{
if (dt.Columns[p.sColumnslist[j]].DataType.Name == "String")
{
Fstring += " or " + p.sColumnslist[j] + " LIKE '%" + Arr[i] + "%'";
}
else if (dt.Columns[p.sColumnslist[j]].DataType.Name == "DateTime")
{
Fstring += " or " + p.sColumnslist[j] + "Format LIKE '%" + Arr[i] + "%'";
}
else
{
if (Int32.TryParse(Arr[i], out intVal))
{
Fstring += " or " + p.sColumnslist[j] + " = " + intVal;
}
}
}
}
//Fstring += " PartyName LIKE '%" + Arr[i] + "%'";
//if (Int32.TryParse(Arr[i], out intVal))
//{
// Fstring += " or SaleVoucherNo = " + intVal;
//}
//Fstring += " or SaleDateFormat LIKE '%" + Arr[i] + "%'";
//dt = GetDatatable(dt, Fstring, ref Fcount, p); Fstring = "";
dt = SearchDatatable(dt, Fstring, ref Fcount, p); Fstring = "";
}
}
}
//else
//{
//dt = GetDatatable(dt, Fstring, ref Fcount, p);
dt = GetDatatable(dt, ref Fcount, p);
//}
return dt;
}

System.Web.HttpContext has changed to Microsoft.AspNetCore.Http.HttpContext; you will need to pass the instance of this from where HttpContext is available into this function.
public static DataTable FilterTable(DataTable dt, ref int Fcount, JQPM p)
becomes
public static DataTable FilterTable(Microsoft.AspNetCore.Http.HttpContext httpContext, DataTable dt, ref int Fcount, JQPM p)
If you are retrieving "bSearchable_" + j from the QueryString and it will only contain that key once you can then use
httpContext.Request.Query["bSearchable_" + j].ToString();
where httpContext is the instance you pass in.
See:
https://learn.microsoft.com/en-us/aspnet/core/migration/http-modules?view=aspnetcore-6.0#migrating-to-the-new-httpcontext
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0

Related

h2o DeepLearning failed: Illegal argument for field: hidden of schema: DeepLearningParametersV3: cannot convert ""200"" to type int

I wanted to execute the DeepLearning example by using H2O. But it went wrong when running "DeepLearningV3 dlBody = h2o.train_deeplearning(dlParams);"
The error message:
Illegal argument for field:
hidden of schema:
DeepLearningParametersV3:
cannot convert ""200"" to type int
This is my code, I used the default value of dlParam except "responseColumn". After it went wrong, I added one line to set value of "hidden", but the results didn't change.
private void DL() throws IOException {
//H2O start
String url = "http://localhost:54321/";
H2oApi h2o = new H2oApi(url);
//STEP 0: init a session
String sessionId = h2o.newSession().sessionKey;
//STEP 1: import raw file
String path = "hdfs://kbmst:9000/user/spark/datasets/iris.csv";
ImportFilesV3 importBody = h2o.importFiles(path, null);
System.out.println("import: " + importBody);
//STEP 2: parse setup
ParseSetupV3 parseSetupParams = new ParseSetupV3();
parseSetupParams.sourceFrames = H2oApi.stringArrayToKeyArray(importBody.destinationFrames, FrameKeyV3.class);
ParseSetupV3 parseSetupBody = h2o.guessParseSetup(parseSetupParams);
System.out.println("parseSetupBody: " + parseSetupBody);
//STEP 3: parse into columnar Frame
ParseV3 parseParams = new ParseV3();
H2oApi.copyFields(parseParams, parseSetupBody);
parseParams.destinationFrame = H2oApi.stringToFrameKey("iris.hex");
parseParams.blocking = true;
ParseV3 parseBody = h2o.parse(parseParams);
System.out.println("parseBody: " + parseBody);
//STEP 4: Split into test and train datasets
String tmpVec = "tmp_" + UUID.randomUUID().toString();
String splitExpr =
"(, " +
" (tmp= " + tmpVec + " (h2o.runif iris.hex 906317))" +
" (assign train " +
" (rows iris.hex (<= " + tmpVec + " 0.75)))" +
" (assign test " +
" (rows iris.hex (> " + tmpVec + " 0.75)))" +
" (rm " + tmpVec + "))";
RapidsSchemaV3 rapidsParams = new RapidsSchemaV3();
rapidsParams.sessionId = sessionId;
rapidsParams.ast = splitExpr;
h2o.rapidsExec(rapidsParams);
// STEP 5: Train the model
// (NOTE: step 4 is polling, which we don't require because we specified blocking for the parse above)
DeepLearningParametersV3 dlParams = new DeepLearningParametersV3();
dlParams.trainingFrame = H2oApi.stringToFrameKey("train");
dlParams.validationFrame = H2oApi.stringToFrameKey("test");
dlParams.hidden=new int[]{200,200};
ColSpecifierV3 responseColumn = new ColSpecifierV3();
responseColumn.columnName = "class";
dlParams.responseColumn = responseColumn;
System.out.println("About to train DL. . .");
DeepLearningV3 dlBody = h2o.train_deeplearning(dlParams);
System.out.println("dlBody: " + dlBody);
// STEP 6: poll for completion
JobV3 job = h2o.waitForJobCompletion(dlBody.job.key);
System.out.println("DL build done.");
// STEP 7: fetch the model
ModelKeyV3 model_key = (ModelKeyV3)job.dest;
ModelsV3 models = h2o.model(model_key);
System.out.println("models: " + models);
DeepLearningModelV3 model = (DeepLearningModelV3)models.models[0];
System.out.println("new DL model: " + model);
// STEP 8: predict!
ModelMetricsListSchemaV3 predict_params = new ModelMetricsListSchemaV3();
predict_params.model = model_key;
predict_params.frame = dlParams.trainingFrame;
predict_params.predictionsFrame = H2oApi.stringToFrameKey("predictions");
ModelMetricsListSchemaV3 predictions = h2o.predict(predict_params);
System.out.println("predictions: " + predictions);
// STEP 9: end the session
h2o.endSession();
}
I found the relative source code, but I can't understand why it goes wrong.
This is the definition of hidden.
public class DeepLearningParametersV3 extends ModelParametersSchemaV3 {{
/**
* Hidden layer sizes (e.g. [100, 100]).
*/
public int[] hidden;
//other params
}
And this is the code where the error message showed.It was the line String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName();
static <E> Object parse(String field_name, String s, Class fclz, boolean required, Class schemaClass) {
if (fclz.isPrimitive() || String.class.equals(fclz)) {
try {
return parsePrimitve(s, fclz);
} catch (NumberFormatException ne) {
String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName();
throw new H2OIllegalArgumentException(msg);
}
}
// An array?
if (fclz.isArray()) {
// Get component type
Class<E> afclz = (Class<E>) fclz.getComponentType();
// Result
E[] a = null;
// Handle simple case with null-array
if (s.equals("null") || s.length() == 0) return null;
// Handling of "auto-parseable" cases
if (AutoParseable.class.isAssignableFrom(afclz))
return gson.fromJson(s, fclz);
// Splitted values
String[] splits; // "".split(",") => {""} so handle the empty case explicitly
if (s.startsWith("[") && s.endsWith("]") ) { // It looks like an array
read(s, 0, '[', fclz);
read(s, s.length() - 1, ']', fclz);
String inside = s.substring(1, s.length() - 1).trim();
if (inside.length() == 0)
splits = new String[]{};
else
splits = splitArgs(inside);
} else { // Lets try to parse single value as an array!
// See PUBDEV-1955
splits = new String[] { s.trim() };
}
// Can't cast an int[] to an Object[]. Sigh.
if (afclz == int.class) { // TODO: other primitive types. . .
a = (E[]) Array.newInstance(Integer.class, splits.length);
} else if (afclz == double.class) {
a = (E[]) Array.newInstance(Double.class, splits.length);
} else if (afclz == float.class) {
a = (E[]) Array.newInstance(Float.class, splits.length);
} else {
// Fails with primitive classes; need the wrapper class. Thanks, Java.
a = (E[]) Array.newInstance(afclz, splits.length);
}
for (int i = 0; i < splits.length; i++) {
if (String.class == afclz || KeyV3.class.isAssignableFrom(afclz)) {
// strip quotes off string values inside array
String stripped = splits[i].trim();
if ("null".equals(stripped.toLowerCase()) || "na".equals(stripped.toLowerCase())) {
a[i] = null;
continue;
}
// Quotes are now optional because standard clients will send arrays of length one as just strings.
if (stripped.startsWith("\"") && stripped.endsWith("\"")) {
stripped = stripped.substring(1, stripped.length() - 1);
}
a[i] = (E) parse(field_name, stripped, afclz, required, schemaClass);
} else {
a[i] = (E) parse(field_name, splits[i].trim(), afclz, required, schemaClass);
}
}
return a;
}
// Are we parsing an object from a string? NOTE: we might want to make this check more restrictive.
if (! fclz.isAssignableFrom(Schema.class) && s != null && s.startsWith("{") && s.endsWith("}")) {
return gson.fromJson(s, fclz);
}
if (fclz.equals(Key.class))
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else
return Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s); // If the key name is in an array we need to trim surrounding quotes.
if (KeyV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
if (!required && (s == null || s.length() == 0)) return null;
return KeyV3.make(fclz, Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s)); // If the key name is in an array we need to trim surrounding quotes.
}
if (Enum.class.isAssignableFrom(fclz)) {
return EnumUtils.valueOf(fclz, s);
}
// TODO: these can be refactored into a single case using the facilities in Schema:
if (FrameV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isFrame()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Frame", v.get().getClass());
return new FrameV3((Frame) v.get()); // TODO: version!
}
}
if (JobV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isJob()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Job", v.get().getClass());
return new JobV3().fillFromImpl((Job) v.get()); // TODO: version!
}
}
// TODO: for now handle the case where we're only passing the name through; later we need to handle the case
// where the frame name is also specified.
if (FrameV3.ColSpecifierV3.class.isAssignableFrom(fclz)) {
return new FrameV3.ColSpecifierV3(s);
}
if (ModelSchemaV3.class.isAssignableFrom(fclz))
throw H2O.fail("Can't yet take ModelSchemaV3 as input.");
/*
if( (s==null || s.length()==0) && required ) throw new IllegalArgumentException("Missing key");
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (! v.isModel()) throw new IllegalArgumentException("Model argument points to a non-model object.");
return v.get();
}
*/
throw H2O.fail("Unimplemented schema fill from " + fclz.getSimpleName());
} // parse()
It looks like this could be a bug. A jira ticket has been created for this issue, you can track it here: https://0xdata.atlassian.net/browse/PUBDEV-5454?filter=-1.

label control not displaying the text on production server. It works fine in development

<asp:Label ID="lblWarehouse" runat="server" Text="" CssClass="lbl" Visible="true"></asp:Label>
lblImagePath.Text = getWarehouse(strImgPath);
private string getWarehouse(string ImgPath)
{
String strPath = "";
String strfolderPath = "";
int intFolderNo = 0;
for (int i = 0; i < 50; i++)
{
intFolderNo = i + 1;
// Begin Change by Triveni Gadipalli on 02/03/2014.
//strfolderPath = #"\\\\\\\\CHC29\Warehouse" + intFolderNo.ToString() + "\\\\" + ImgPath+ "\\\\";
String FolderNo = intFolderNo.ToString();
if (intFolderNo < 10)
{
FolderNo = "0" + FolderNo;
}
strfolderPath = #"\\\\\\\\\\pnasxl40001.chcpa.loc\emrscans\wh" + FolderNo + "\\\\" + ImgPath + "\\\\";
// strfolderPath = #"\\\\\\\\pnasxl40001.chcpa.loc\emrscans\wh" + folderno + "\\\\" + ImgPath + "\\\\";
//End Change by Triveni Gadipalli on 02/03/2014.
if (Directory.Exists(strfolderPath))
{
strPath = strfolderPath;
i = 50;
}
}
if (strPath == "")
{
return strfolderPath;
}
else
{
return strPath;
}
}
Shouldn't the line:
lblImagePath.Text = getWarehouse(strImgPath);
reference lblWarehouse - that's the only label in your example code at least?

C#. Search array of strings for longest element

I want to know how I can get out everyone of the the longest persons if there are several with the same length?
If only one person is the longest, then it works fine and the longest person with it´s name will show in MessageBox. But if there are more than one who are the longest, this code will not work...
public partial class Form1 : Form
{
int[] längdArray = new int[5];
string[] namnArray = new string[5];
int namn = 0;
int längd = 0;
public Form1()
{
InitializeComponent();
}
private void btnVisa_Click(object sender, EventArgs e)
{
int längst = 0;
int längdvärdet = 0;
int längdindex = 0;
string name = textBox1.Text;
namnArray[namn] = name;
namn = namn + 1;
textBox1.Clear();
int centimeter = int.Parse(textBox2.Text);
längdArray[längd] = centimeter;
längd++;
textBox2.Clear();
listBox1.Items.Add(name + " " + centimeter + " centimeter ");
if (längd == 5)
{
btnVisa.Enabled = false;
foreach (int antalLängder in längdArray)
{
if (antalLängder > längst)
{
längst = antalLängder;
längdvärdet = längdindex;
}
längdindex++;
}
string test = namnArray[längdvärdet]
MessageBox.Show(" Längsta person är " + test + " som är " + längst + " centimeter lång ");
}
Define behavior you want your app to present when there is more than one person. Should all display, or any one, or other? Try to use object constructions, it's easier to operate on them. C# is an object-oriented language. Put name and length in one structure then use LINQ.

Visual Studio If statement always going through

For some reason the If statements are always going through no matter what I put. Even if i did things like True == False or 0 == 1 it still goes through. What I am trying to do is detect if the text is null and set it to - so it doesn't error.
This is my code inside the button
private void SearchButton_Click(object sender, EventArgs e)
{
reg = String.IsNullOrWhiteSpace(RegText.Text);
if (reg == true);
{
RegText.ResetText();
RegText.AppendText("-");
}
model = String.IsNullOrWhiteSpace(ModelText.Text);
if (model == true) ;
{
ModelText.ResetText();
ModelText.AppendText("-");
}
for (int i = 0; i < MaxCars; i++)
{
if (regos[i].Equals(Convert.ToString(RegText.Text)) || models[i].Equals(Convert.ToString(ModelText.Text)) || price[i] == Convert.ToInt32(PriceText.Text))
{
Console.WriteLine(regos[i] + " " + models[i] + " " + price[i]);
}
}
}
You have put ; at the end of every if that is causing an error.
This is the code with fix:
private void SearchButton_Click(object sender, EventArgs e)
{
reg = String.IsNullOrWhiteSpace(RegText.Text);
if (reg == true)
{
RegText.ResetText();
RegText.AppendText("-");
}
model = String.IsNullOrWhiteSpace(ModelText.Text);
if (model == true)
{
ModelText.ResetText();
ModelText.AppendText("-");
}
for (int i = 0; i < MaxCars; i++)
{
if (regos[i].Equals(Convert.ToString(RegText.Text)) || models[i].Equals(Convert.ToString(ModelText.Text)) || price[i] == Convert.ToInt32(PriceText.Text))
{
Console.WriteLine(regos[i] + " " + models[i] + " " + price[i]);
}
}
}

How to replace a String at the end when Building a String with multiple Data?

HI all i am Building A string Which looks like this
[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
i am building this string with this data
public JsonResult ResourceBugReports()
{
int projectid;
int Releasphaseid;
projectid = 16;
Releasphaseid = 1;
var ResourceReports = db.ExecuteStoreQuery<ResourceModel>("ResourceBugReports #ProjectId,#ReleasePhaseId", new SqlParameter("#ProjectId", projectid), new SqlParameter("#ReleasePhaseId", Releasphaseid)).ToList();
DataSet ds = new DataSet();
var model1 = new WeeklyBugCount
{
Resources = ResourceReports
};
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
foreach (var row in model1.Resources)
{
BugsCount = BugsCount + row.Assignedbugs + ",";
}
foreach (var row in model1.Resources)
{
BugsCount1 = BugsCount1+ row.Closedbugs + ",";
}
foreach (var row in model1.Resources)
{
Bugscount2 = Bugscount2 + row.Fixedbugs + "," ;
}
foreach (var row in model1.Resources)
{
BugsCount3 = BugsCount3 + row.Reopenedbugs + ",";
}
ComboinedString = ResourceName1 + "/" + BugsCount + "/" + BugsCount1 + "/" + Bugscount2 + "/" + BugsCount3;
return Json(ComboinedString, JsonRequestBehavior.AllowGet);
}
my
ComboinedString =[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
but i want this string
ComboinedString =[Anil Kumar K,Niharika,Raghu/4,0,0/3,0,0,/1,1,1/1,0,0]
i want to remove this "," before the "/" in this strin or replace it..can any one help me
Add this statement
I hope it will help you
String CombinedString1 = CombinedString.Replace(",/", "/");
A simple solution is a search and replace on the string replacing ",/" with "/".
A better solution is, rather than using a for() loop and appending a comma at the end of each value, is use String.Join(). For example, replace:
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
with
ResourceName1 = string.Join(",", model1.Resources.ToArray())
This will remove the trailing comma.
A simple solution would be to use String.EndsWith() function i.e.
string str = "ksjf,sjsfj,sfs,";
if (str.EndsWith(","))
{
str = str.Remove(str.Length - 1);
}
Off the top of my head, you could try to replace with a simple regular expression:
string input = "dsgd,sdgsdg,dsgsdg,sdg,";
string output = Regex.Replace(input, ",$", "");
//output: "dsgd,sdgsdg,dsgsdg,sdg"
#user1542652's solution is simple and works just as well.

Resources