How can I get Cookie value by declare a Local variable in asp.net - asp.net

When I Debug this line it shows like
Request.Cookies["Login"]["Username"].ToString()="Raju"
But when I declare a String type variable like
String ss;
ss = Request.Cookies["Login"]["Username"].ToString();
After debugging ss shows like
ss=null;
why?

public ActionResult Login()
{
UserAccount u = new UserAccount();
if (Request.Cookies["Login"] != null)
{
u.UserName = Request.Cookies["Login"].Values["UserName"];
}
return View(u);
}

You can define like this
String ss;
ss = Request.Cookies["Login"].Values["UserName"];

Related

Xunit CSV streamReader.ReadToEnd returns System.ArgumentOutOfRangeException

I would like to evaluate a CSV data series with Xunit.
For this I need to read in a string consisting of int, bool, double and others.
With the following code, the transfer basically works for one row.
But since I want to test for predecessor values, I need a whole CSV file for evaluation.
My [Theory] works with InlineData without errors.
But when I read in a CSV file, the CSVDataHandler gives a System.ArgumentOutOfRangeException!
I can't find a solution for the error and ask for support.
Thanks a lot!
[Theory, CSVDataHandler(false, "C:\\MyTestData.txt", Skip = "")]
public void TestData(int[] newLine, int[] GetInt, bool[] GetBool)
{
for (int i = 0; i < newLine.Length; i++)
{
output.WriteLine("newLine {0}", newLine[i]);
output.WriteLine("GetInt {0}", GetInt[i]);
output.WriteLine("GetBool {0}", GetBool[i]);
}
}
[DataDiscoverer("Xunit.Sdk.DataDiscoverer", "xunit.core")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class DataArribute : Attribute
{
public abstract IEnumerable<object> GetData(MethodInfo methodInfo);
public virtual string? Skip { get; set; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class CSVDataHandler : DataAttribute
{
public CSVDataHandler(bool hasHeaders, string pathCSV)
{
this.hasHeaders = hasHeaders;
this.pathCSV = pathCSV;
}
public override IEnumerable<object[]> GetData(MethodInfo methodInfo)
{
var methodParameters = methodInfo.GetParameters();
var paramterTypes = methodParameters.Select(p => p.ParameterType).ToArray();
using (var streamReader = new StreamReader(pathCSV))
{
if (hasHeaders) { streamReader.ReadLine(); }
string csvLine = string.Empty;
// ReadLine ++
//while ((csvLine = streamReader.ReadLine()) != null)
//{
// var csvRow = csvLine.Split(',');
// yield return ConvertCsv((object[])csvRow, paramterTypes);
//}
// ReadToEnd ??
while ((csvLine = streamReader.ReadToEnd()) != null)
{
if (Environment.NewLine != null)
{
var csvRow = csvLine.Split(',');
yield return ConvertCsv((object[])csvRow, paramterTypes); // System.ArgumentOutOfRangeException
}
}
}
}
private static object[] ConvertCsv(IReadOnlyList<object> cswRow, IReadOnlyList<Type> parameterTypes)
{
var convertedObject = new object[parameterTypes.Count];
for (int i = 0; i < parameterTypes.Count; i++)
{
convertedObject[i] = (parameterTypes[i] == typeof(int)) ? Convert.ToInt32(cswRow[i]) : cswRow[i]; // System.ArgumentOutOfRangeException
convertedObject[i] = (parameterTypes[i] == typeof(double)) ? Convert.ToDouble(cswRow[i]) : cswRow[i];
convertedObject[i] = (parameterTypes[i] == typeof(bool)) ? Convert.ToBoolean(cswRow[i]) : cswRow[i];
}
return convertedObject;
}
}
MyTestData.txt
1,2,true,
2,3,false,
3,10,true,
The first call to streamReader.ReadToEnd() will return the entire contents of the file in a string, not just one line. When you call csvLine.Split(',') you will get an array of 12 elements.
The second call to streamReader.ReadToEnd() will not return null as your while statement appears to expect, but an empty string. See the docu at
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.readtoend?view=net-7.0
If the current position is at the end of the stream, returns an empty
string ("").
With the empty string, the call to call csvLine.Split(',') will return an array of length 0, which causes your exception when its first element (index 0) is accessed.
All of this could have been easily discovered by simply starting the test in a debugger.
It looks like you have some other issues here as well.
I don't understand what your if (Environment.NewLine != null) is intended to do, the NewLine property will never be null but should have one of the values "\r\n" or "\n" so the if will always be taken.
The parameters of your test method are arrays int[] and bool[], but you are checking against the types int, double and bool in your ConvertCsv method, so the alternative cswRow[i] will always be returned. You'll wind up passing strings to your method expecting int[] and bool[] and will at latest get an error there.
This method reads a data series from several rows and columns and returns it as an array for testing purposes.
The conversion of the columns can be adjusted according to existing pattern.
Thanks to Christopher!
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class CSVDataHandler : Xunit.Sdk.DataAttribute
{
public CSVDataHandler(string pathCSV)
{
this.pathCSV = pathCSV;
}
public override IEnumerable<object[]> GetData(MethodInfo methodInfo)
{
List<int> newLine = new();
List<int> GetInt = new();
List<bool> GetBool = new();
var reader = new StreamReader(pathCSV);
string readData = string.Empty;
while ((readData = reader.ReadLine()) != null)
{
string[] split = readData.Split(new char[] { ',' });
newLine.Add(int.Parse(split[0]));
GetInt.Add(int.Parse(split[1]));
GetBool.Add(bool.Parse(split[2]));
// Add more objects ...
}
yield return new object[] { newLine.ToArray(), GetInt.ToArray(), GetBool.ToArray() };
}
}

how we can return a status code for the serialized JSON object using Newtonsoft.net

I have this Action method which act as an API end point inside our ASP.NET MVC-5, where it search for a username and return the username Phone number and Department from Active Directory (we are serializing the object using Newtonsoft.net):-
public ActionResult UsersInfo2()
{
DomainContext result = new DomainContext();
try
{
// create LDAP connection object
DirectoryEntry myLdapConnection = createDirectoryEntry();
string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
string ADusername = System.Web.Configuration.WebConfigurationManager.AppSettings["ADUserName"];
string ADpassword = System.Web.Configuration.WebConfigurationManager.AppSettings["ADPassword"];
using (var context = new DirectoryEntry("LDAP://mydomain.com:389/DC=mydomain,DC=com", ADusername, ADpassword))
using (var search = new DirectorySearcher(context))
{
// create search object which operates on LDAP connection object
// and set search object to only find the user specified
// DirectorySearcher search = new DirectorySearcher(myLdapConnection);
// search.PropertiesToLoad.Add("telephoneNumber");
search.Filter = "(&(objectClass=user)(sAMAccountName=test.test))";
SearchResult r = search.FindOne();
ResultPropertyCollection fields = r.Properties;
foreach (String ldapField in fields.PropertyNames)
{
// cycle through objects in each field e.g. group membership
// (for many fields there will only be one object such as name)
string temp;
// foreach (Object myCollection in fields[ldapField])
// {
// temp = String.Format("{0,-20} : {1}",
// ldapField, myCollection.ToString());
if (ldapField.ToLower() == "telephonenumber")
{
foreach (Object myCollection in fields[ldapField])
{
result.Telephone = myCollection.ToString();
}
}
else if (ldapField.ToLower() == "department")
{
foreach (Object myCollection in fields[ldapField])
{
result.Department = myCollection.ToString();
}
}
// }
}
string output = JsonConvert.SerializeObject(result);
return Json(output,JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return View(result);
}
now the return JSON will be as follow:-
"\"DisplayName\":null,\"Telephone\":\"123123\",\"Department\":\"IT\",\"Name\":null,\"SamAccountName\":null,\"DistinguishedName\":null,\"UserPrincipalName\":null}"
but in our case we need to return a status code beside the return json data. for example inccase there is an exception we need to return an error code,also if we are able to get the user's info we need to pass succes code 200, and so on.. so how we can achieve this?
you can try something like this
var statusCode=200;
string output = JsonConvert.SerializeObject( new { result = result, StatusCode = statusCode);
but nobody usually do this. When users call API they can check status code that HTTP Client returns, using code like this
var response = await client.GetAsync(api);
//or
var response = await client.PutAsJsonAsync(api, data);
var statusCode = response.StatusCode.ToString();
//or usually
if (response.IsSuccessStatusCode) {...}
else {...}

netcore - elegant way to check var A or B is not null/empty to get it

Is there any operator like || to get first non-null/empty value like we can do in other languages?
I can achieve the same using ifs:
public static void Main(string[] args)
{
string a = "value";
string b = null;
string c = b;
if (string.IsNullOrEmpty(c)) {
c = a;
if(string.IsNullOrEmpty(c)){
throw new System.Exception("...");
}
}
}
If I have more variables to check, it will become a mess. Is there other way to achieve it?
You can use extensions for this
public static string IfNullOrEmptyGet(this string str, string newValue)
{
if (!string.IsNullOrEmpty(str))
return str;
if (string.IsNullOrEmpty(newValue))
throw new Exception($"{nameof(newValue)} is null or empty");
else
return newValue;
}
and use like c = c.IfNullOrEmptyGet(a)

"Current user did not login to the application!" error when function call from service

In a service I have wrote a simple function to get tenant id of particular user
[AbpAuthorize]
public int? FindTenancyNameByUserNameOrEmail(string userNameOrEmail)
{
var qry = (from p in _memberRepository.GetAll()
where p.UserName == userNameOrEmail || p.EmailAddress == userNameOrEmail
select p).FirstOrDefault();
if (qry != null)
{
return qry.TenantId;
}
else
{
throw new Exception("User not found");
}
}
I am calling this function from login function of account controller.
public async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl = "", string returnUrlHash = "")
{
var tenancyid = _memberAppService.FindTenancyNameByUserNameOrEmail(loginModel.UsernameOrEmailAddress.Trim());
//bla bla code
}
I get following error:
Exception thrown: 'Abp.Authorization.AbpAuthorizationException' in
Abp.dll
Additional information: Current user did not login to the application!
The issue was the user was not belonging to the tenant.
Used the following line to set the tenant id and code worked.
CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, intTenancyId);
added the [AbpAllowAnonymous] attribute to the service method
The problem is in first line
var qry = (from p in _memberRepository.GetAll()
.GetAll() function create this error as you cannot use Builtin function in linq query.
Instead use
var Myvariable = _memberRepository.GetAll().ToList();
var qry = (from p in Myvariable where p.UserName == userNameOrEmail || p.EmailAddress == userNameOrEmail select p).FirstOrDefault();
The problem is AbpAuthorize Attribute [AbpAuthorize] remove it.

How to get username without domain

In an aspx page I get the Windows username with the function Request.LogonUserIdentity.Name. This function returns a string in the format "domain\user".
Is there some function to only get the username, without resorting to the IndexOf and Substring, like this?
public static string StripDomain(string username)
{
int pos = username.IndexOf('\\');
return pos != -1 ? username.Substring(pos + 1) : username;
}
If you are using Windows Authentication.
This can simply be achieved by calling System.Environment.UserName which will give you the user name only.
If you want only the Domain name you can use System.Environment.UserDomainName
I don't believe so. I have got the username using these methods before-
var user = System.Web.HttpContext.Current.User;
var name = user.Identity.Name;
var slashIndex = name.IndexOf("\\");
return slashIndex > -1
? name.Substring(slashIndex + 1)
: name.Substring(0, name.IndexOf("#"));
or
var name = Request.LogonUserIdentity.Name;
var slashIndex = name.IndexOf("\\");
return slashIndex > -1
? name.Substring(slashIndex + 1)
: name.Substring(0, name.IndexOf("#"));
Getting parts[1] is not a safe approach. I would prefer use LINQ .Last():
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
if (windowsIdentity == null)
throw new InvalidOperationException("WindowsIdentity is null");
string nameWithoutDomain = windowsIdentity.Name.Split('\\').Last();
If you are using .NET 3.5 you could always create an extension method to the WindowsIdentity class that does this work for you.
public static string NameWithoutDomain( this WindowsIdentity identity )
{
string[] parts = identity.Name.Split(new char[] { '\\' });
//highly recommend checking parts array for validity here
//prior to dereferencing
return parts[1];
}
that way all you have to do anywhere in your code is reference:
Request.LogonUserIdentity.NameWithoutDomain();
static class IdentityHelpers
{
public static string ShortName(this WindowsIdentity Identity)
{
if (null != Identity)
{
return Identity.Name.Split(new char[] {'\\'})[1];
}
return string.Empty;
}
}
If you include this code, you could then just do something like:
WindowsIdentity a = WindowsIdentity.GetCurrent();
Console.WriteLine(a.ShortName);
Obviously in a web environment, you wouldn't write to the console - just an example...
An alternative way of doing the same thing as the other answers:
var usernameWithoutDomain = Path.GetFileName(#"somedomain\someusername")
It is just unsafe as not checking for the # variant of usernames.
I was suggesting to use regexpes but they would be overkill.
[System.String.Split](http://msdn.microsoft.com/en-us/library/b873y76a(VS.80).aspx) do the job.
string[] parts= username.Split( new char[] {'\\'} );
return parts[1];

Resources