Object reference not set to an instance of an object - asp.net

I am facing an issue while inserting some items into database in asp.net web service application.
Here is my code ..
public void DoRequestLog(HttpRequest request)
{
string UserAgent = request.Headers["User-Agent"];
string Date = "4/14/2011";//request.Headers["Date"];
string HostIP = request.Headers["Host"];
string URL = request.Headers["Referer"];
string MethodName = request.HttpMethod;
string VersionNo = "";
string IMEINo = "";
string dbString = Configuration.GetDBConnectionString();
SqlConnection DardSqlConnection = new SqlConnection(dbString);
DardSqlConnection.Open();
SqlCommand log = DardSqlConnection.CreateCommand();
log.CommandText = "insert into ConnectionLog values('"+UserAgent+"','"+Date+"','"+HostIP+"','"+URL+"','"+MethodName+"','"+VersionNo+"','"+IMEINo+"');";
log.ExecuteNonQuery();
}
Please Help
Since I am new to .net environment.

Try this:
public void DoRequestLog(HttpRequest request)
{
// We don’t need to log anything if there is no HTTP request.
if (request == null)
return;
string UserAgent = request.Headers["User-Agent"];
string Date = "4/14/2011";//request.Headers["Date"];
...

Related

Sqllite SQLiteDataReader returns enpty reader while SQLiteDataAdapter returns the right result

I have trouble with Sqllite SQLiteDataReader. Using the same connection string and the same sql statement SQLiteDataReader returns empty reader while SQLiteDataAdapter returns suspected record.
I this case I try to get the record with the highest value in the Id field.
The database contains several records with unique values in the Id field, but the reader return is empty when using SQLiteDataReader. When I use the same connection string and sql statement with SQLiteDataAdapter suspected results appears. I supply a part of the static class I use for communication with the database. The method SenasteBokning using SQLiteDataReader isn’t working. The method SenasteBokning2 using SQLiteDataAdapter works perfect.
What’s wrong with the method SenasteBokning?
I use:
Windows 10
Visual Studio 2017
.net framework 4.5.2 (Was default at creation of Windows Forms application)
Nuget package System.Data.SQLite.Core 1.0.108
static class Databas
{
private static string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string dbPath = #"\BokningarConvention.db";
private static string connectionString = "Data Source= " + appPath + dbPath;
private static SQLiteConnection con;
private static SQLiteCommand cmd;
private static SQLiteDataReader reader;
private static SQLiteDataAdapter adapter;
private static SQLiteCommandBuilder commandBuilder;
private static DataTable table;
private static string senaste = "SELECT Nummer, NrSammaDag, Datum FROM Bekraftelser WHERE Id = (SELECT MAX (Id) FROM Bekraftelser)";
// This don't work
public static Bokning SenasteBokning()
{
Bokning bokning = new Bokning();
using (SQLiteConnection con2 = new SQLiteConnection(connectionString))
{
con2.Open();
SQLiteCommand cmd2 = new SQLiteCommand(senaste, con2);
SQLiteDataReader reader2 = cmd2.ExecuteReader();
// Here the reader is empty
while (reader2.Read())
{
// Error at first read
// should handle results the same way as in SenasteBokning2
// removed during testing
}
}
return bokning;
}
//This works perfekt
public static Bokning SenasteBokning2()
{
Bokning bokning = new Bokning();
using (SQLiteConnection db = new SQLiteConnection(connectionString))
{
adapter = new SQLiteDataAdapter(senaste, connectionString);
commandBuilder = new SQLiteCommandBuilder(adapter);
table = new DataTable();
db.Open();
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
int nummer;
int samma;
DateTime datum;
nummer = (int)((long)row["Nummer"]);
datum = Verktyg.FromDateInteger((int)((long)row["Datum"]));
if (!row.IsNull("NrSammaDag"))
{
samma = (int)((long)row["NrSammaDag"]);
bokning = new Bokning(nummer, samma, datum);
}
else
{
bokning = new Bokning(nummer, datum);
}
}
}
return bokning;
}
}

Encrypting email in Microsoft.Exchange.WebServices.Data

I am trying to send an encrypted email using Microsoft.Exchange.WebServices.Data.
public void SendMessage(FacadeModel.EmailMessage message)
{
var item = new EWS.EmailMessage(_mailService);
var handler = new SecureMimeMessageHandler();
byte[] con = handler.encry("test", "me#mail.com.au");
item.MimeContent = new EWS.MimeContent(Encoding.ASCII.HeaderName, con);
item.ToRecipients.Add("me#mail.com.au");
item.From = new EWS.EmailAddress("", "me#mail.com.au");
item.Body = "test";
item.Send();
}
public byte[] encry(string body, string to)
{
var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates;
X509Certificate2 cert1 = GetMatchingCertificate(certs[1], "me#mail.com.au", X509KeyUsageFlags.KeyEncipherment);
StringBuilder msg = new StringBuilder();
msg.AppendLine(string.Format("Content-Type: application/pkcs7-mime; smime-type=signed-data;name=smime.p7m"));
msg.AppendLine("Content-Transfer-Encoding: 7bit");
msg.AppendLine();
msg.AppendLine(body);
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert1);
envelope.Encrypt(recipient);
return envelope.Encode();
}
But still i am getting a plain email with no encryption in outlook. where have i gone wrong?
I posted a suggestion on the MSDN forum. Try setting the ItemClass to "IPM.Note.SMIME".

Npgsql.NpgsqlException: ERROR: 42601: syntax error at or near "where"

I have the followinf web service in asp.net
//setup profile
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void SetProfile(string userName, string firstName, string lastName, string imageUrl)
{
//create and open connection
NpgsqlConnection profileConnection = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["PrevueConnString"].ToString());
profileConnection.Open();
//create query and command
string query = "INSERT into \"Users\" (\"FirstName\", \"LastName\", \"ImageUrl\") values(:fname, :lname, :imageUrl) where \"UserName\" = :user";
NpgsqlCommand profileCommand = new NpgsqlCommand(query, profileConnection);
profileCommand.Parameters.Add(new NpgsqlParameter("user", DbType.String));
profileCommand.Parameters.Add(new NpgsqlParameter("fname", DbType.String));
profileCommand.Parameters.Add(new NpgsqlParameter("lname", DbType.String));
profileCommand.Parameters.Add(new NpgsqlParameter("imageUrl", DbType.String));
profileCommand.Parameters[0].Value = userName;
profileCommand.Parameters[1].Value = firstName;
profileCommand.Parameters[2].Value = lastName;
profileCommand.Parameters[3].Value = imageUrl;
int result = profileCommand.ExecuteNonQuery();
profileCommand.Dispose();
profileConnection.Close();
string json = new JavaScriptSerializer().Serialize(result);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Flush();
Context.Response.Write(json);
}
On invoking the web service, I get the following error:
Npgsql.NpgsqlException: ERROR: 42601: syntax error at or near "where"
I guess i figured out the error, i used the 'Where' clause with an Insert command, changed that to Update and things are smooth now... :) Appreciate your help..!!

Not able to get query string

I am using the below code for setting URL in the current http context
public HttpContext SetNewHttpContext(string uRL)
{
var httpRequest = new HttpRequest("", uRL, "");
var httpResponse = new HttpResponse(new StringWriter());
return new HttpContext(httpRequest, httpResponse);
}
Invoking it as under
HttpContext.Current = SetNewHttpContext("http://root/test.aspx?userid=319279549&name=xyz");
var val = HttpContext.Current.Request.QueryString["userid"];
But i am not able to get the value of the querystring(userid here) and getting null.
Why?
Please help
Uri tempUri = new Uri("http://root/test.aspx?userid=319279549&name=xyz");
string sQuery = tempUri.Query;
NameValueCollection queryString =
System.Web.HttpUtility.ParseQueryString(sQuery ,Encoding.UTF8);

The distinguished name contains invalid syntax error

I'm trying using LDAP to authenticate user, but I have a problem with LDAP.
This is my code:
string hostOrDomainName = "MrHand-PC";
string targetOu = "cn=Huy Pham,ou=people,dc=example,dc=com";
// create a search filter to find all objects
string ldapSearchFilter = "uid=pdhuy";
// establish a connection to the directory
LdapConnection connection = new LdapConnection(hostOrDomainName);
Console.WriteLine("\r\nPerforming a simple search ...");
SearchRequest searchRequest = new SearchRequest(targetOu, ldapSearchFilter,
System.DirectoryServices.Protocols.SearchScope.OneLevel, null);
// cast the returned directory response as a SearchResponse object
SearchResponse searchResponse =
(SearchResponse)connection.SendRequest(searchRequest);
The last line throws an exception: The distinguished name contains invalid syntax.
Can anyone help my solve this problem?
To authenticate against LDAP, you can try the following (domain, username and password are arguments):
bool IsAuthenticated = false;
string domainAndUsername = domain + #"\" + username;
string dirContext = GetAuthenticatingDirectory(domain);
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + dirContext, domainAndUsername, password))
{
try
{
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result != null)
{
IsAuthenticated = true;
}
}
catch (Exception e)
{
//handle appropriately according to your requirements
}
}
return IsAuthenticated;
where GetAuthenticatingDirectory() is defined as
private string GetAuthenticatingDirectory(string domain)
{
string authenticatingDirectory = string.Empty;
string dotComDomain = domain + #".com";
// Connect to RootDSE
using (DirectoryEntry RootDSE = new DirectoryEntry("LDAP://rootDSE"))
{
// Retrieve the Configuration Naming Context from RootDSE
string configNC = RootDSE.Properties["configurationNamingContext"].Value.ToString();
// Connect to the Configuration Naming Context
using (DirectoryEntry configSearchRoot = new DirectoryEntry("LDAP://" + configNC))
{
// Search for all partitions where the NetBIOSName is set.
using (DirectorySearcher configSearch = new DirectorySearcher(configSearchRoot))
{
configSearch.Filter = ("(NETBIOSName=*)");
// Configure search to return dnsroot and ncname attributes
configSearch.PropertiesToLoad.Add("dnsroot");
configSearch.PropertiesToLoad.Add("ncname");
using (SearchResultCollection forestPartitionList = configSearch.FindAll())
{
// Loop through each returned domain in the result collection
foreach (SearchResult domainPartition in forestPartitionList)
{
// domainName like "domain.com". ncName like "DC=domain,DC=com"
string domainName = domainPartition.Properties["dnsroot"][0].ToString();
string ncName = domainPartition.Properties["ncname"][0].ToString();
if (dotComDomain.Equals(domainName, StringComparison.OrdinalIgnoreCase))
{
authenticatingDirectory = ncName;
break;
}
}
}
}
}
}
return authenticatingDirectory;
}

Resources