C# parsing cookie get null - c#

This is my cookie value:
email%3Drrr%2540test.com%26password%3Da8f5f167f44f4964e6c998dee827110c
and that's my code:
Request.Cookies["SolidDomain"]["email"];
Request.Cookies["SolidDomain"]["password"];
or
string email1 = Request.Cookies.Get("SolidDomain").Values.Get("email");
string password2 = Request.Cookies.Get("SolidDomain").Values.Get("password");
in both cases I get null. what's wrong here?

You can have subkey cookie without problem but I think the string you gave us is not using subkey. In fact, the string you posted can be accessed directly with :
Request.Cookies["email"];
Request.Cookies["password"];
If you can to check to structure of the subkey you can use this snippet of code :
for(int i=0; i<Request.Cookies.Count; i++)
{
aCookie = Request.Cookies[i];
output.Append("Name = " + aCookie.Name + "<br />");
if(aCookie.HasKeys)
{
for(int j=0; j<aCookie.Values.Count; j++)
{
subkeyName = Server.HtmlEncode(aCookie.Values.AllKeys[j]);
subkeyValue = Server.HtmlEncode(aCookie.Values[j]);
output.Append("Subkey name = " + subkeyName + "<br />");
output.Append("Subkey value = " + subkeyValue +
"<br /><br />");
}
}
else
{
output.Append("Value = " + Server.HtmlEncode(aCookie.Value) +
"<br /><br />");
}
}
And check the output variable to see Value and SubKey value.
If you want to allow cookie to a domain (I guess this is what you are trying to achieve) you can do it by using the domain property :
Response.Cookies["password"].Domain = "SolidDomain";

Related

Extract elements from List string built using c #

I have this string
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
that is composed of this c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('value1:\\n" +
string.Join(",", value1) + "');", true);
Using the code above the output is
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
Now I need to extract from this string from element number 5 to all subsequent elements, that is
2022-006,related,2022-007,related
and storing a row for each string value in a database table, that is
t
q
2022-006
related
2022-017
related
Expected output
2022-006
related
2022-017
related
But the expected ouput now is empty...
This is my c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
List<string> value2 = item.Split(',').ToList();
for (int i = 4; i < value2.Count; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
}
}
Thanks in advance for any help, really appreciated.
Solution
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
var requestDLL = string.Join(",", value1);
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
Output
2022-006
related
2022-017
related
Here you can find the code that return the expected output https://dotnetfiddle.net/8aBrZj
using System;
public class Program
{
public static void Main()
{
var requestDLL = "Dispatching System,proposal,to be sent,main,2022-006,related,2022-017,related";
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Console.Write(value2[i] + "\n" + value2[i + 1] + "\n \n");
i++;
}
}
}

How can I do a header for a CSV using StringBuilder? C#

I will edit my post because I couldn't express very well.
I want to do this:
This
And I don't know how to do a unique header. I achieved this:
Achieved
but now I need to do the header. I will post more of my code here:
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (CurrentBars[0] < Shift)
return;
string header = "Time" + ";" + "Close[0]" + ";" + "ATR_7" + ";" + "VOL_7" + ";" + "LABEL";
string Label = "NULL";
if(Alcista)
{
if(Open[0] >= Open[Shift - 1] && Open[0]/Open[Shift - 1] >= 1.0001)
{
Label = "UP";
}
else
{
Label = "DOWN";
}
}
switch(Indicar2_Sesgo)
{
case Sesgo.Alcista:
StringBuilder csvcontent = new StringBuilder();
csvcontent.AppendLine(Convert.ToString(Times[0][0].TimeOfDay + ";" + Close[0] + ";" + ATR1[0] + ";" + VOL1[0] + ";" + Label));
string csvpath = "D:\\xyz.csv";
File.AppendAllText(csvpath, csvcontent.ToString());
break;
}
}
It is a little difficult to know what your output is supposed to look like, but if you are simply trying to write a header, your code may look something like this:
var csvPath = "D:\\xyz.csv";
var csvHeader = "Time;Close;Atr1;Atr2";
File.WriteAllText(csvPath, csvHeader + Environment.NewLine);
As others have mentioned you would be better off using a helper library (like csvhelper) and setting the delimiter to a semicolon.

Prevent last key in string to have a comma

Having trouble figuring out how to prevent the last key in my array to not have a comma. Since its being exported to a .Json file the last key shouldn't have a ",".
I know you can detect it by using .Last();, but I can't seem to make that work. Any recommendations?
//Data Path
string dataPath = #"..\..\FileIOExtraFiles\DataFieldsLayout.txt";
string[] dataList = File.ReadAllLines(dataPath);
//save Data data
using (StreamWriter outStream = new StreamWriter(outputFolder + #"\CharacterStringData3.json"))
{
outStream.WriteLine("{");
for (int i = 0; i < dataFile.Length; i++)
{
string s = dataFile[i];
char last = s.Last();
if (s == "")
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
}
else
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\",");
}
}
outStream.WriteLine("}");
}
Output:
{
"data1":"item1",
"data2":item2",
"lastKey":item3",//trying to remove comma from last key in array.
}
As others have pointed out, it doesn't make sense that you are building json manually, but given that this is a question more about technique, here is one approach: you could change it to this:
var commaSuffix = (i == dataFile.Length - 1) ? "," : string.Empty;
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\"" + commaSuffix);
The suffix would be used on every iteration except the last.
Change this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
To this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \""+(i==dataFile.Length?",":""));
Instead of using outStream.WriteLine() at every step, store it in a string. Then you can remove the last comma from that string and write the whole string at once:
//Get last index of comma
int lastCommaIndex = outputString.LastIndexOf(',');
//Create new StringBuilder with everything before the last comma
StringBuilder sb = new StringBuilder(outputString.Substring(0,lastCommaIndex));
//Add everything after the last comma, or just add a closing brace
//sb.Append("}"); //This instead of next line
sb.Append(outputString.Substring(lastCommaIndex+1));
//Add contents of StringBuilder to the Stream
outSteam.WriteLine(sb);

MVC 3 to MVC 4 Razor Compiler Error

I am getting a runtime error, saying that I am missing a closing paren. The error occurs on the line where I set emailText
This code works in MVC 3 but not MVC 4. I know the new Razor is more strict but syntactically this code still looks right. All parens match, etc.
Any ideas?
#if (Model.Counselors != null)
{
for (var i = 0; i < Model.Counselors.Count; i++)
{
string counselorDivId = "counselorname" + i.ToString();
string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + #counselorDivId + "\" data-attr-id=" + #Model.Counselors[i].Id + " style=\"float:right;\"></a>";
string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
}
}
Strangely, but I guess logically, nested "#" blow up MVC 4/Razor 2. By removing the nested "#" prefixes, the code was successfully parsed and executed
#if (Model.Counselors != null)
{
for (var i = 0; i < Model.Counselors.Count; i++)
{
string counselorDivId = "counselorname" + i.ToString();
string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + counselorDivId + "\" data-attr-id=" + Model.Counselors[i].Id + " style=\"float:right;\"></a>";
string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
}
}
try
#(if (Model.Counselors != null)
{
for (var i = 0; i < Model.Counselors.Count; i++)
{
string counselorDivId = "counselorname" + i.ToString();
string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + #counselorDivId + "\" data-attr-id=" + #Model.Counselors[i].Id + " style=\"float:right;\"></a>";
string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
}
})
It appears to be an issue with the last line that starts with "string emailText ...". For some reason razor does not like the less than sign in your ternary statement. When I switched it around to be a greater than sign, then it looks like it worked. I am not sure if this is a bug in razor or not.

ASP.NET How to use Counter with '<%=

I want to make a multiple upload, iam using some script from this forum.
the scripts is perfectly works, but when i merge it with my project.
javascript can't get the value of my element.
i found out the problem is because i have many ID PANEL in the page, i need to change to getElementByID('<%="FileUpdate.ClientID%>').value (the original : getElementByID("FileUpdate").value)
THE PROBLEM IS :
I have to use counter, ex: getElementByID('<%="txtFileUpdate' + counter + '%>').value but it FAIL.
the error says "too many characters in character literal" pointing to that line.
Please someone help, is there any solution for this problem ?
Here is the script
-----> Error " to many characters in character literal"
<script type="text/javascript" language="javascript">
var counter = 1;
function AddFileUpload() {
if (counter < 5) {
counter++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="FileUpload' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainers").appendChild(div);
}
else {
alert("Cannot attach more than 5 file");
}
}
function GetFile() {
var temp;
var error = "";
var stringx = "";
var exCounter = 1 ;
for (exCounter; exCounter <= counter; exCounter++) {
-----> stringx = document.getElementById('<%=FileUpload'+exCounter+'.ClientID%>').value;
if (stringx != "")
temp += stringx + "#;";
else
error += exCounter + ", ";
}
if (error != "") {
alert("Field " + error + " Still Empty");
return;
}
document.getElementById('<%=HiddenField1.ClientID%>').value = temp;
}
Try this:
getElementByID('FileUpdate<%=counter%>').value
or
getElementByID('<%=txtFileUpdate + counter.ToString()%>').value

Categories

Resources