Registry values not getting stored in database - c#

I am reading Registry key values and storing them in string variables, and passing these values as parameters in NewReg method to store them into database, but i am getting this error message you must use an updateable query and therefore this message user not added in database,
where I am going wrong? How I can achieve this ?
public partial class LoginForm : Form
{
DBHandling db = new DBHandling();
public LoginForm()
{
try
{
RegistryKey key = Registry.ClassesRoot;
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(#"Software\StudentExm");
string usrname = registryKey.GetValue("UserName").ToString();
string password = registryKey.GetValue("Password").ToString();
string emailId = registryKey.GetValue("EmailID").ToString();
string contctno = registryKey.GetValue("ContactNo").ToString();
string regDate = registryKey.GetValue("RegDate").ToString();
registryKey.Close();
if (NewReg(usrname, password, emailId, contctno, regDate))
{
MessageBox.Show("User Name: " + usrname + "\n" +
"Password: " + password + "\n" +
"Email ID: " + emailId + "\n" +
"Contact No: " + contctno + "\n" +
"Reg Date: " + regDate);
}
else
{
MessageBox.Show("User not added in the database.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
NewReg method in DBHandling Class
public bool NewReg(string usrName, string passwrd, string emailID, string contactNo,string regdat)
{
bool flag = false;
try
{
//string sql = "INSERT INTO test(nametest,pass,email,contact,regdate) Values('" + usrName + "','" + passwrd + "','" + emailID + "','" + contactNo + "','" + System.DateTime.Now + "')";
string sql = "INSERT INTO UserInfo([UserName],[Password],[email],[contact],[regdate]) Values(#UserInfo,#Password,#email,#contact,#regdate)";
cmd = new OleDbCommand(sql, acccon);
cmd.Parameters.AddRange(new[] {
new OleDbParameter("#UserName", usrName),
new OleDbParameter("#Password", passwrd),
new OleDbParameter("#EmailID", emailID),
new OleDbParameter("#ContactNo", contactNo),
new OleDbParameter("#RegDate", regdat)
});
cmd.ExecuteNonQuery();
flag = true;
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
return flag;
}
Thanks in advance for any help

I Guess the Problem Because of this Line:
string usrname = registryKey.GetValue("UserName") + Environment.NewLine;
The Code U can change like this and Try.
string usrname = registryKey.GetValue("UserName").ToString();
Were as you are assigning the Value with + Environment.NewLine;. It should not be.,
That is why you must use an updateable query error message.
And this is Your Custom Message user not added in database. Because of Condition Fails its getting displayed.
Hope it helps., :)

As I said in my comment, it's a file permissions issue.
This error USUALLY occurs when you attempts to perform an UPDATE or
some other action that alters the information in the database.
This error occurs because dataobjects what ever ado or ADO.NET is
unable to write to the Microsoft Access database due to insufficient
write/modify permissions, which can be easily fixed by granting
read/write to IUSR_ and IWAM_.
IUSR_<machineName> and IWAM_<machineName> come into focus when an anonymous web user needs to modify the Microsoft Access
database & while doing so Jet creates an .ldb file to handle database
locking. If the above mentioned 2 users don't have the necessary
permissions, the lock file isn't created & ultimately the Microsoft
Access database can't be modified..
FIX:
To fix this problem, right click on the folder which holds the
Microsoft Access database & choose properties. Use the Security tab in
Explorer to adjust the properties for this folder so that the Internet
Guest account has the correct writable permissions.
Also make sure that the MDB file itself isn't marked as read-only, and
that you don't have the MDB file open; particularly in exclusive mode;
while trying to reach the Microsoft Access database from ASP
source: http://forums.asp.net/t/154273.aspx/9/10

Try like this
string keyName = #"HKEY_CURRENT_USER\...\Node[Name]";
string valueName = "Value"; // Value in registry Ex. RegDate
object Obj = Registry.GetValue(keyName, valueName, "Exist");
if (Obj == null)
{
}
else
{
Do your Code ....
}

Related

How can I search for both the user's last name AND the first name in the Active Directory using C#

I have this code that works very well when I want to search JUST for the user's last name
public static string GetPhoneFromAD()
{
try
{
DirectoryEntry entryDomain = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher ds = new DirectorySearcher(entryDomain);
string currentContextIdentity = System.Web.HttpContext.Current.User.Identity.Name;
string lastName = currentContextIdentity.Split(' ')[currentContextIdentity.Split(' ').Length - 1];
ds.Filter = "(sn=" + lastName + ")";
SearchResult sr = ds.FindOne();
string telephoneNumber = sr.Properties["telephoneNumber"][0].ToString();
return FormatPhone(telephoneNumber);
}
catch (Exception exception)
{
drmsda.InsertErrorlog("manage.aspx.cs", "Error in an attempt to get the phone number", exception.Source, exception.Message + " " + exception.StackTrace, "");
drmsda.sendErrorEmail("Error: SetPhone generated email", exception.Message);
return string.Empty;
}
}
However, if the user's last name is common, like Smith, I won't the right entry. Thus, I would like to add another criteria, such as first name. However, the query I came up with is not working. I did try the following
ds.Filter = "(givenName=" + firstName + "&sn=" + lastName + ")";
But that is not working, can somebody help?
Thank you in advance
LDAP filter syntax is a bit different to that; you want:
(&(givenName=joe)(sn=bloggs))
See here for many examples.

StackOverflow in WCF caused by R.Net

Good Day,
i am trying to write an R code in .net to run as a WCF function. this function is suppose to import a csv file to MSSQL using R using .net code.
I am getting a stackoverflow error when i try to reference the odbc library over wcf, however if i try to run the function using debug instance it passes that point.
public string R_to_MSSQL_Server(string data, string Server, string Database,string Tablename)
{
StartupParameter rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = #"C:\Program Files\R\R-3.4.4\";
rinit.Home = #"C:\R";
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null, true, rinit);
StringBuilder Data = new StringBuilder();
Data.Append(data);
string filepath = Path.Combine(Path.GetTempPath(), "RTable.csv");
//"UID= Tester;" +
//"PWD= rstudioapi::askForPassword(\"password\"); " +
try
{
UploadCSV(Data);
filepath = PathCleaning(filepath);
engine.Evaluate("Data <- read.csv(file<- '" + filepath + "', heade= TRUE, sep=',')");
engine.Evaluate("Table <- data.frame(Data)");
engine.Evaluate("connectionString <- ' " +
"driver={SQL Server}; " +
"server= "+ Server + "; " +
"database=" + Database + ";" +
"UID= Tester;" +
"PWD= rstudioapi::askForPassword(\"password\"); " +
"'");
engine.Evaluate("library(odbc)");
engine.Evaluate("library(healthcareai)");
engine.Evaluate("con<- DBI::dbConnect(odbc::odbc(),.connection_string=connectionString)");
engine.Evaluate("DBI::dbwriteTable(conn=con," + Tablename + " , Table)");
return "Completed successfully";
}
catch( Exception x)
{
return "Fail to complete" + x;
}
}
the error when i run it through WCF hits at "engine.evaluate("library(odbc)");"
This is where its being called by another machine accessing it through wcf.
static void Main(string[] args)
{
MainServiceClient client = new MainServiceClient();
string tablename = "Test Table";
string Table = "";
string Pkey ="Name";
Table=File.ReadAllText(#"\\lonvmfs02\Home\kr.williams\TestTable2.csv");
string query = client.R_to_MSSQL_Server(Table, "stage04", "CWDataSets", "Tester");
this is the error thats being thrown inside the WCF Machine ( W3wp debugging ).
System.StackOverflowException
HResult=0x800703E9
Source=
StackTrace:
this is all the exception details give.
how do it increase the size of the stack / get around this problem?
Thanks

Embedded In Person Signing process?

I've been trying like mad to get this to work, and I'm sure it's something simple, but I'm at a loss right now.
I'm using the SDK for DocuSign example. I've modified it lightly to try to get an InPersonSigner embedded:
private Recipient[] ConstructRecipients()
{
// Construct the recipients
var runningList = new List<Recipient>();
for (int i = 1; i <= Request.Form.Count; i++)
{
if (null !=Request.Form[Keys.RecipientName + i])
{
var r = new Recipient
{
UserName = Request.Form[Keys.RecipientName + i],
Email = Request.Form[Keys.RecipientEmail + i] // <-- Using my DocuSign account email for simplicity
};
// Get and set the security settings
string security = Request.Form[Keys.RecipientSecurity + i];
if (null != security)
{
//...Code still here, just making this post shorter
}
}
// Try InPerson Signing
r.RequireIDLookup = false;
r.UserName = "AccountUserName"; //<-- Again, My Account user name for simplicity
r.SignerName = Request.Form[Keys.RecipientName + i]; // "BB King"
r.Type = RecipientTypeCode.InPersonSigner;
r.ID = i.ToString();
//r.Type = RecipientTypeCode.Signer;
if (null == Request.Form[Keys.RecipientInviteToggle + i])
{
// we want an embedded signer
r.CaptiveInfo = new RecipientCaptiveInfo {ClientUserId = i.ToString()};
}
runningList.Add(r);
}
else
{
break;
}
}
return runningList.ToArray();
}
When sending via email, it works, the Host (me) receives the Email, and is able to go through the "In Person Singing Process".
When sending for embedded results (remember I'm using the SDK out of the box for the embedded part - which includes ClientID), it errors with this message: "The recipient you have identified is not a valid recipient of the specified envelope."
What do I need to add to make the Embedded SDK sample work with a In Person Signing Session?
---- EDIT ----
I found the issue, but don't know the best solution. Apparently, the GetStatusAndDocs.aspx.cs file has this line:
DocuSignAPI.FilteredEnvelopeStatuses statuses = client.RequestStatusesEx(filter);
Statuses contains an EnvelopeStatus object, and that contains a RecipientStatus object. The RecipientStatus objects returns the UserName field as the SignerName that I entered, not the UserName that I entered.
This RecipientStatus object doesn't even have a SignerName property/field??? Why?
What property/field should I use to pass to the RequestRecipientToken username parameter? If it's one of my field agents, I need to know how to fully identify the person and their account to determine they went to the field, fired up the app, and then did an in person signing.
Still at a lost although I have figured this out so far?
I found the answer:
For an embedded RecipientTypeCode.InPersonSigner, the email address can be bogus, fake, junk, etc., (as long as it's in email format "somethingdotsomething#someplacedotsomething.whatever").
When it's RecipientTypeCode.InPersonSigner, the username you pass to the RequestRecipientToken() is the Actual Account Holder userName. Not the account that you may have given access to your main account as an Agent or someone part of a group, and not the signer/recipient name, but the account holder name that is on the account credentials being used for embedded signature.
The code on page GetStatusAndDocs.aspx.cs can be modified as follows to accomplish this:
protected System.Web.UI.HtmlControls.HtmlGenericControl CreateEnvelopeTable(DocuSignAPI.EnvelopeStatus status)
{
var envelopeDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
int recipIndex = 0;
foreach (DocuSignAPI.RecipientStatus recipient in status.RecipientStatuses)
{
var info = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
String recipId = "Recipient_Detail_" + status.EnvelopeID + "_" + recipient.RoutingOrder + "_" + recipient.UserName + "_" + recipient.Email + "_" + recipIndex++;
info.InnerHtml = "<img src=\"images/plus.png\"> Recipient - " +
recipient.UserName + ": " + recipient.Status.ToString();
if (recipient.Status != DocuSignAPI.RecipientStatusCode.Completed && null != recipient.ClientUserId)
{
// For InPersonSigner, this will not work because the recipient.UserName needs to be the credentialed account actual user name, not the recipieint userName.
//info.InnerHtml += " <input type=\"submit\" id=\"" + status.EnvelopeID + "\" value=\"Start Signing\" name=\"DocEnvelope+" + status.EnvelopeID + "&Email+" + recipient.Email + "&UserName+" +
// recipient.UserName + "&CID+" + recipient.ClientUserId + "\">";
// In order to make this work for InPersonSigner, we need the envelope account (the credentialed account) userName instead of recipient.UserName
// Get correct user name depending on recipient type
string userName = (recipient.Type == RecipientTypeCode.InPersonSigner) ? status.ACHolder : recipient.UserName;
info.InnerHtml += " <input type=\"submit\" id=\"" + status.EnvelopeID + "\" value=\"Start Signing\" name=\"DocEnvelope+" + status.EnvelopeID + "&Email+" + recipient.Email + "&UserName+" +
userName + "&CID+" + recipient.ClientUserId + "\">";
}
if (null != recipient.TabStatuses)
{
// Code here is the same, just making it shorter for this response
}
envelopeDiv.Controls.Add(info);
}
// Code between here and return is the same, just making it shorter for this response
return envelopeDiv;
}

Unauthoriezed Access Exception

i have a cloud database server like application on my computer that i'm hosting my game on. However, every time an user tries to save data i get an UnauthorizedAccessException.
Im running it by admin and i dont have any specias right in my folder so i have no idea what's the problem.
Here's my code:
public const string root = "D:/DATABASE/";
public static void WriteData(string playername, string type, string data)
{
if (!Directory.Exists("D:/DATABASE/" + playername))
{
Directory.CreateDirectory("D:/DATABASE/" + playername);
Directory.CreateDirectory("D:/DATABASE/" + playername + "/weapons");
}
if (type != "Weapon")
{
using (StreamWriter sw = new StreamWriter("D:/DATABASE/" + playername + "/" + type + ".sav"))
{
sw.WriteLine(data);
}
}
else
{
string[] dat = data.Split('%');
using (StreamWriter sw = new StreamWriter("D:/DATABASE/" + playername + "/weapons/" + dat[0] + ".gfa"))
{
string[] lines = dat[1].Split('#');
foreach (string cline in lines)
{
sw.WriteLine(cline);
}
}
}
}
public static string ReadLoadout(string playername)
{
string output = "";
string[] items = new string[2];
using (StreamReader sr = new StreamReader(root + playername + "/loadout.gfl"))
{
items[0] = sr.ReadLine();
items[1] = sr.ReadLine();
}
int c = 0;
foreach (string citem in items)
{
if (c > 0) output += "$";
output += citem + "%" + GetCompressedWeaponFile(playername, citem);
c++;
}
return output;
}
public static string GetCompressedWeaponFile(string playerName, string weaponName)
{
string output = "";
using (StreamReader sr = new StreamReader(root + playerName + "/weapons/" + weaponName))
{
string line = " ";
int c = 0;
while (line != null)
{
line = sr.ReadLine();
if (line != null)
{
if (c > 0) output += "#";
output += line;
}
c++;
}
}
return output;
}
public static void RegisterNewUser(string username, string password, string email)
{
string udir = root + username;
Directory.CreateDirectory(udir);
Directory.CreateDirectory(udir + "/weapons");
Directory.CreateDirectory(udir + "/loadouts");
File.WriteAllText(udir + "/password.sav", password);
File.WriteAllText(udir + "/level.sav", "1");
File.WriteAllText(udir + "/money.sav", "1000");
File.WriteAllText(udir + "/email.sav", email);
File.WriteAllText(udir + "/loadout.gfl", "");
using (StreamWriter sw = new StreamWriter(root + "emails.txt", true))
{
sw.WriteLine(email);
}
Email.Send(email, "New Account Registration", string.Format(mailTemplate, username, password));
}
public static void EditLoadout(string username, string items)
{
File.WriteAllLines(root + username + "/loadout.gfl",items.Split('#'));
}
It is difficult to provide specific help without more information. Here are a few of troubleshooting suggestions:
1) Try running your code on a different machine. Specifically your development computer. Do you still have the same error? If not, then there is indeed a permission problem.
2) Have you tried checking the stack trace of the exception?
When you run the application on your own computer, try using the IDE to display the exception. Yes, the problem may ultimately be in a low-level class, but you should be able to break on the error and go back in the call stack to see which method in your code is actually throwing the error.
3) Check the actual exception, even for a system-level exception.
Chances are, if you are able to debug this in the IDE, that you will see property information that will give you a hint. Is it in a directory method or a file write method? Check additional properties. Somewhere it might give you the text of the path (assuming it's a file issue) that it failed on that that could help narrow things down too.
4) Add Exception handling to your code
This is a good rule of thumb, and you should really do this anyway to make a stronger program. Regardless of who's method you are calling (yours, someone else's, or a system method) you need to determine where it should be handled.
For example, in your code, in the RegisterNewUser() method, consider something like:
public static void RegisterNewUser(string username, string password, string email)
{
try
{
string udir = root + username;
Directory.CreateDirectory(udir);
Directory.CreateDirectory(udir + "/weapons");
Directory.CreateDirectory(udir + "/loadouts");
File.WriteAllText(udir + "/password.sav", password);
File.WriteAllText(udir + "/level.sav", "1");
File.WriteAllText(udir + "/money.sav", "1000");
File.WriteAllText(udir + "/email.sav", email);
File.WriteAllText(udir + "/loadout.gfl", "");
using (StreamWriter sw = new StreamWriter(root + "emails.txt", true))
{
sw.WriteLine(email);
}
Email.Send(email, "New Account Registration", string.Format(mailTemplate, username, password));
}
catch (Exception ex)
{
// Create a method to display or log the exception, with it's own error handler
LogAndDisplayExceptions(ex);
// Send the user a message that we failed to add them. Put this in it's own try-catch block
// ideally, for readability, in it's own method.
try
{
Email.Send(email, "Failed to register", "An error occurred while trying to add your account.");
}
catch (Exception exNested)
{
LogAndDisplayExceptions(exNested);
}
}
}
5) Add a "crash-and-burn" exception handler to "main"
In the method that is your "top method" (it's hard to tell in the snippet you provided since there are few methods that would attempt to write to the disk) you could wrap your code in a try - catch block and print the exception or write it to disk.
If you have having trouble writing the exception to disk, I would suggest creating an error file first, make sure that the user account that is running the program can write to it, and then in the catch block open the file for APPEND. This should make it easier to get to the error text.
6) When all else fails, use the Debug class or Console class to write the traditional "I made it to line x."
While this will not solve your problem, it should help you get more information that will provide more insight into where your code is causing an error.

Connecting to Public Folders using RDO & MAPI

I am trying to connect to my companies Exchange 2003 server using RDO & MAPI which I've never done before. I have found a pretty good site that uses Outlook's Redemption (http://www.dimastr.com/redemption/home.htm) but with all of the examples on the site using VB.NET and me not being great at programming it's a bit difficult to get this working.
So far I have this code
static void ConnectToExchange()
{
object oItems;
//string outLookUser = "My Profile Name";
string outLookUser = "username#xxx.xxxx";
string ToEmailAddress = "username#xxxx.com";
string FromEmailAddress = "username#xxx.com";
string outLookServer = "xxservernamexx";
string sMessageBody =
"\n outLookUser: " + outLookUser +
"\n outLookServer: " + outLookServer +
"\n\n";
RDOSession Session = new RDOSession();
try
{
Session.LogonExchangeMailbox(outLookUser,outLookServer);
int mailboxCount = Session.Stores.Count;
string defaultStore = Session.Stores.DefaultStore.Name;
RDOFolder TestTaxCert = Session.GetFolderFromPath(#"\\Public Folders\All Public Folders\TestTaxCert");
}
catch (Exception ex)
{
Session = null;
//System.Web.Mail.SmtpMail.Send(ToEmailAddress, FromEmailAddress, "Error", sMessageBody + " " + ex.Message);
}
finally
{
if ((Session != null))
{
if (Session.LoggedOn)
{
Session.Logoff();
}
}
}
}
}
My problem is that once the program hits the Session.LogonExchangeMailbox(outLookUser,outLookServer); line, a prompt appears asking for my credentials (username, domain, password) and no matter what information I fed the prompt it denied permission.
SO if someone can help me with that and then also with connecting to the public folders...that'd be greaaat
Make sure your code is running as the domain user specified in the call to LogonExchangeMailbox.
Did you really mean 2003, or is it Exchange 2013?

Categories

Resources