Object reference not set to an instance of an object - c#

I've searched through many threads and websites looking for this problem. So far, I haven't been able to find anything wrong with this code.
The "bad" code is this: request.AddComment(v, c);
Also, I don't know what a stack trace is.
Thanks for all your help in advance.
Here is my code:
string devkey = "1";
string username = "2";
string password = "3";
YouTubeRequestSettings a =
new YouTubeRequestSettings("test", devkey, username, password);
YouTubeRequest request = new YouTubeRequest(a);
Uri uri = new Uri("b");
Video v = request.Retrieve<Video>(uri);
Comment c = new Comment();
c.Content = "asdf";
request.AddComment(v, c);

The only way this snippet might throw a NullReferenceException is if request.Retrieve returned null and request.AddComment throws an exception if either parameter is null.
The solution is to test v:
Video v = request.Retrieve<Video>(uri);
if(v != null)
{
Comment c = new Comment();
c.Content = "asdf";
request.AddComment(v, c);
}
else
{
// something went wrong when getting the video...
}

Null check the objects that are being referenced. The video request definately should be checked. Code below does a video null check.
string devkey = "1";
string username = "2";
string password = "3";
YouTubeRequestSettings a = new YouTubeRequestSettings("test", devkey, username, password);
YouTubeRequest request = new YouTubeRequest(a);
Uri uri = new Uri("b");
Video v = request.Retrieve<Video>(uri);
Comment c = new Comment();
c.Content = "asdf";
if (v!= null)
{
request.AddComment(v, c);
}
else
{
//Handle the null, try to get the video again, report to user, etc.
}

Related

NullReferenceException When Using VerifyHashedPassword in asp.net core

Here's what happen i am working on login controller where i need to verify user input password with password hash that is in the database. When i'm trying to verify the correct password it is returning NullReferenceException: Object reference not set to an instance of an object. But when i debug it, the line with this code :
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
is skipped and does not executed but when i return the value of verified.toString() directly after calling above line of code, it is printing a "Success" string. But when it is failed to verify, the code just work properly. Here's the full code :
public dbSearchResponse dbSearch(string username, string password, ADResponse ldapResult)
{
LoginResponse finalResult = new LoginResponse();
TableSystemUser resultData = new TableSystemUser();
PasswordHasher<OldLoginParamModel> hasher = new PasswordHasher<OldLoginParamModel>(
new OptionsWrapper<PasswordHasherOptions>(
new PasswordHasherOptions()
{
CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
}));
OldLoginParamModel inputModel = new OldLoginParamModel();
inputModel.grant_type = "password";
inputModel.password = password;
inputModel.username = username;
string hashedPassword = hasher.HashPassword(inputModel, inputModel.password);
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
var value = connection.Query<TableSystemUser>(
"SELECT id, email, emailconfirmed, passwordhash, phonenumber, username, fullname, dateofbirth, gender, COALESCE(usercredit.saldo, 0) as saldo, pricing.psc, pricing.psm, pricing.plc, pricing.plm, pricing.csc, pricing.csm, pricing.clc, pricing.clm, pricing.ssc, pricing.ssm, pricing.slc, pricing.slm FROM systemuser LEFT OUTER JOIN usercredit ON systemuser.id = usercredit.systemuserid INNER JOIN userpricing ON UUID(systemuser.id) = userpricing.systemuserid INNER JOIN pricing ON userpricing.pricingid = pricing.pricingid WHERE systemuser.email= '" + username + "' and systemuser.emailconfirmed = true;"
);
resultData = value.First();
}
catch (Exception e)
{
//Failed response
dbSearchResponse dbRespNRErr = new dbSearchResponse();
dbRespNRErr.loginResponse = null;
dbRespNRErr.userid = null;
dbRespNRErr.response = "Email not registered.";
return dbRespNRErr;
}
}
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
/*But when return the verified.toString() value here, it is returning "Success"
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = verified.toString();
return dbRespErr; */
if (verified.toString() == "Success")
{
finalResult.FullName = resultData.fullname;
finalResult.Gender = resultData.gender;
//11/26/1998 12:00:00 AM
finalResult.DateOfBirth = resultData.dateofbirth.ToString("MM/dd/yyyy HH:mm:ss tt");
finalResult.Phone = resultData.phonenumber;
finalResult.Email = resultData.email;
finalResult.UserName = resultData.username;
finalResult.PLC = resultData.plc.ToString();
finalResult.PLM = resultData.plm.ToString();
finalResult.PSC = resultData.psc.ToString();
finalResult.PSM = resultData.psm.ToString();
finalResult.SLC = resultData.slc.ToString();
finalResult.SLM = resultData.slm.ToString();
finalResult.SSC = resultData.ssc.ToString();
finalResult.SSM = resultData.ssm.ToString();
finalResult.CLC = resultData.clc.ToString();
finalResult.CLM = resultData.clm.ToString();
finalResult.CSC = resultData.csc.ToString();
finalResult.CSM = resultData.csm.ToString();
finalResult.PayLater = ldapResult.memberof;
finalResult.Credit = resultData.saldo.ToString();
dbSearchResponse dbResp = new dbSearchResponse();
dbResp.loginResponse = finalResult;
dbResp.userid = resultData.id;
dbResp.response = "success";
return dbResp;
}
//Failed response
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = "The user name or password is incorrect.";
return dbRespErr;
}
Anyone know what happen and how to solve it? Thanks
After i do some detailed run check, i notice that the null part of the code is,
finalResult.PayLater = ldapResult.memberof;
But i don't understand why is the error response given suggest that the null was this line of code
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
so in that case, i thanks to everyone who have responded to my question.

C# Active Directory - Read out Email NullReferencesException

I'm trying to get the e-mail adresses of all user's in our company domain.
99% work but sometimes there is y NullReferenceException in my Output.
Code:
string dom = "mydomain";
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + dom); //domain, user, password
System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(entry);
ds.Filter = ("(objectClass=User)");
int count = 1;
foreach (System.DirectoryServices.SearchResult resEnt in ds.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
String email = de.Properties["mail"].Value.ToString();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
There might be a NullReferenceException in the line
String email = de.Properties["mail"].Value.ToString();
If in the Properties["mail"] returns a null value or its Value property is null, then the attempt to call ToString() will lead to an exception.
This will help in this case (C# 6 syntax)
String email = de.Properties["mail"]?.Value?.ToString();
or
String email = null;
if (de.Properties["mail"] != null && de.Properties["mail"].Value != null)
{
email = de.Properties["mail"].Value.ToString();
}

ASP.NET PayPal Parallel Payments

I am needing some assistance with paypal Parallel payments C# I have tried the Classic API and the REST API that paypal has. I am running into cycles and don't know what else to do, I have tried to get chained payments working and I have google'd and there is a huge lack of support so Im now trying Parallel. Let you know i get an 500 internal Server error..
ReceiverList receiverList = new ReceiverList();
receiverList.receiver = new List<Receiver>();
Receiver secondaryReceiver = new Receiver((decimal?)2.00);
secondaryReceiver.email = "xxxxxxxxx#gmail.com";
secondaryReceiver.primary = false;
secondaryReceiver.paymentType = "GOODS";
receiverList.receiver.Add(secondaryReceiver);
Receiver primaryReceiver = new Receiver((decimal?)10.00);
primaryReceiver.email = "xxxxxxxxxxxxxxxxxx-facilitator#gmail.com ";
primaryReceiver.primary = true;
primaryReceiver.paymentType = "GOODS";
primaryReceiver.invoiceId = "123456789";
receiverList.receiver.Add(primaryReceiver);
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
string actionType = "Pay";
string returnUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?success=true";
string cancelUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?cancel=true";
string currencyCode = "USD";
PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
payRequest.ipnNotificationUrl = "http://replaceIpnUrl.com";
payRequest.feesPayer = "PRIMARYRECEIVER";
payRequest.trackingId = "123456789";
Dictionary<string, string> paypalConfig = new Dictionary<string, string>();
paypalConfig.Add("account1.apiUsername", "xxxxxxxxxxxxxxx-facilitator_api1.gmail.com");
paypalConfig.Add("account1.apiPassword", "xxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.apiSignature", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.applicationId", "APP-80W284485P519543T");
paypalConfig.Add("IPNEndpoint", "https://www.paypal.com/cgi-bin/webscr");
paypalConfig.Add("url", "https://www.paypal.com/webscr&cmd=_express-checkout&token=");
paypalConfig.Add("endpoint", "https://api-3t.paypal.com/2.0/");
paypalConfig.Add("mode", "sandbox");
PayPal.AdaptivePayments.AdaptivePaymentsService service = new PayPal.AdaptivePayments.AdaptivePaymentsService(paypalConfig);
PayResponse response = service.Pay(payRequest);
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" + response.payKey;
}
Now as for the web.config I dont know exactly how to do it or really what to do. i Have found a few things but need of help.
Thanks

Creating User in dotnetnuke and Assign Role using c#

I'm trying to create a user programatically using C# in dnn. When ever I execute the code below, it throws object reference error. I tried breaking the code and I found out that its not getting inside the if (result == UserCreateStatus.Success) statement. Whenever I point my mouse to the result instant, it shows an invalid password message. The thing is that I have used this same code before somewhere else and its working fine. I even copied what I used earlier on but its keeps showing the same error. Please is there anything I'm missing?
//Generating 8 char passwor
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[A-Za-z0-9]")) ;
rndString += c;
}
string space = " ";
UserInfo oUser = new UserInfo();
oUser.PortalID = this.PortalId;
oUser.IsSuperUser = false;
oUser.FirstName = Session["fname"].ToString();
oUser.LastName = Session["lname"].ToString();
oUser.Email = Session["email"].ToString();
oUser.Username = Session["username"].ToString();
oUser.DisplayName = Session["fname"].ToString() + space.ToString() + Session["lname"].ToString();
//Fill MINIMUM Profile Items (KEY PIECE)
oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
//oUser.Profile.PreferredTimeZone =PortalSettings.TimeZoneOffset;
oUser.Profile.FirstName = oUser.FirstName;
oUser.Profile.LastName = oUser.LastName;
//Set Membership 17:
UserMembership oNewMembership = new UserMembership();
oNewMembership.Approved = true;
oNewMembership.CreatedDate = System.DateTime.Now;
oNewMembership.Email = oUser.Email;
oNewMembership.IsOnLine = false;
oNewMembership.Username = oUser.Username;
oNewMembership.Password = rndString;
UserCreateStatus result = UserController.CreateUser(ref oUser);
if (result == UserCreateStatus.Success)
{
RoleController oDnnRoleController = new RoleController();
//Get the role information
RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, Request.QueryString["TSORole"].ToString());
// RoleInfo oCurrentRole1 = oDnnRoleController.GetRoleByName(this.PortalId, " Subscribers");
//Assign to user
oDnnRoleController.AddUserRole(this.PortalId, oUser.UserID, oCurrentRole.RoleID, Null.NullDate, Null.NullDate);
// oDnnRoleController.DeleteUserRole(this.PortalId, int.Parse(oUser.UserID.ToString()), oCurrentRole.RoleID);
}
The reason why same code works for one and not the other could be different password rules for these websites. Make sure you are generating a password that complies with the password requirements of the target website.

Perforce Api - How to command "get revision [changelist number]"

I would like to implement the Perforce command "Get Revision [Changelist Number]" using the Perforce .NET API (C#). I currently have code that will "Get Latest Revision", but I need to modify it to get a specific changelist.
To sync the data with a changelist number, what should I do?
Source
// --------Connenct----------------
Perforce.P4.Server server = new Perforce.P4.Server(
new Perforce.P4.ServerAddress("127.0.0.1:9999"));
Perforce.P4.Repository rep = new Perforce.P4.Repository(server);
Perforce.P4.Connection con = rep.Connection;
con.UserName = m_P4ID;
string password = m_P4PASS;
Perforce.P4.Options opconnect = new Perforce.P4.Options();
opconnect.Add("-p", password);
con.Connect(opconnect);
if (con.Credential == null)
con.Login(password);
//----------Download----------
string clientPath = #"C:\P4V\";
string ws_client = clientPath;
Perforce.P4.Client client = new Perforce.P4.Client();
client.Name = ws_client;
client.Initialize(con);
con.CommandTimeout = new TimeSpan(0);
IList<Perforce.P4.FileSpec> fileList = client.SyncFiles(new Perforce.P4.Options());
//----------Disconnect------------
con.Disconnect();
con.Dispose();
Edit: Attempt 1
Perforce.P4.DepotPath depot = new Perforce.P4.DepotPath("//P4V//");
Perforce.P4.LocalPath local = new Perforce.P4.LocalPath(ws_client);
Perforce.P4.FileSpec fs = new Perforce.P4.FileSpec(depot, null, local,
Perforce.P4.VersionSpec.Head);
IList<Perforce.P4.FileSpec> listFiles = new List<Perforce.P4.FileSpec>();
listFiles.Add(fs);
IList<Perforce.P4.FileSpec> foundFiles = rep.GetDepotFiles(listFiles,
new Perforce.P4.Options(1234)); // 1234 = Changelist number
client.SyncFiles(foundFiles, null);
Error Message
Usage: files/print [-o localFile -q] files...Invalid option: -c.
I do not know the problem of any argument.
Or there will not be related to this reference source?
Edit 2
I tried to solve this problem. However, it does not solve the problem yet.
Perforce.P4.Changelist changelist = rep.GetChangelist(1234);
IList<Perforce.P4.FileMetaData> fileMeta = changelist.Files;
In this case, I could get only the files in the changelist. I would like to synchronize all files of the client at the moment of changelist 1234.
SyncFiles takes an optional FileSpec arg. You can specify a file path and a revision specifier with that FileSpec arg. Here are the relevant docs:
FileSpec object docs
SyncFiles method docs
You don't need to run GetDepotFiles() to get the FileSpec object; you can just create one directly as shown in the FileSpec object docs. The error you are getting with GetDepotFiles() is because it expects the change number to be specified as part of the FileSpec object passed into as the first argument to GetDepotFiles().
To expand further, GetDepotFiles() calls the 'p4 files' command when it talks to Perforce. new Perforce.P4.Options(1234) generates an option of '-c 1234' which 'p4 files' doesn't accept. That's why the error message is 'Usage: files/print [-o localFile -q] files...Invalid option: -c.'
I struggled with the same problem as well. Finally based on Matt's answer I got it working. Please see simple example below.
using (Connection con = rep.Connection)
{
//setting up client object with viewmap
Client client = new Client();
client.Name = "p4apinet_solution_builder_sample_application_client";
client.OwnerName = "p4username";
client.Root = "c:\\clientRootPath";
client.Options = ClientOption.AllWrite;
client.LineEnd = LineEnd.Local;
client.SubmitOptions = new ClientSubmitOptions(false, SubmitType.RevertUnchanged);
client.ViewMap = new ViewMap();
client.ViewMap.Add("//depotpath/to/your/file.txt", "//" + client.Name + "/clientpath/to/your/file.txt", MapType.Include);
//connecting to p4 and creating client on p4 server
Options options = new Options();
options["Password"] = "p4password";
con.UserName = "p4username";
con.Client = new Client();
con.Connect(options);
con.Client = rep.CreateClient(client);
//syncing all files (in this case 1) defined in client's viewmap to the changelist level of 12345
Options syncFlags = new Options(SyncFilesCmdFlags.Force, 100);
VersionSpec changeListLevel = new ChangelistIdVersion(12345);
List<FileSpec> filesToBeSynced = con.Client.ViewMap.Select<MapEntry, FileSpec>(me => new FileSpec(me.Left, changeListLevel)).ToList();
IList<FileSpec> results = con.Client.SyncFiles(filesToBeSynced, syncFlags);
}
The following code should allow you to sync a depot to a particular revision (changelist number).
string uri = "...";
string user = "...";
string workspace = "...";
string pass = "...";
int id = 12345; // the actual changelist number
string depotPath = "//depot/foo/main/...";
int maxItemsToSync = 10000;
Server server = new Server(new ServerAddress(uri));
Repository rep = new Repository(server);
server = new Server(new ServerAddress(uri));
rep = new Repository(server);
Connection con = rep.Connection;
con.UserName = user;
con.Client = new Client();
con.Client.Name = workspace;
// connect
bool connected = con.Connect(null);
if (connected)
{
try
{
// attempt a login
Perforce.P4.Credential cred = con.Login(pass);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
con.Disconnect();
connected = false;
}
if (connected)
{
// get p4 info and show successful connection
ServerMetaData info = rep.GetServerMetaData(null);
Console.WriteLine("CONNECTED TO " + info.Address.Uri);
Console.WriteLine("");
try
{
Options opts = new Options();
// uncomment below lines to only get a preview of the sync w/o updating the workspace
//SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.Preview, maxItemsToSync);
SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.None, maxItemsToSync);
VersionSpec version = new ChangelistIdVersion(id);
PathSpec path = new DepotPath(depotPath);
FileSpec depotFile = new FileSpec(path, version);
IList<FileSpec> syncedFiles = rep.Connection.Client.SyncFiles(syncOpts, depotFile);
//foreach (var file in syncedFiles)
//{
// Console.WriteLine(file.ToString());
//}
Console.WriteLine($"{syncedFiles.Count} files got synced!");
}
catch (Exception ex)
{
Console.WriteLine("");
Console.WriteLine(ex.Message);
Console.WriteLine("");
}
finally
{
con.Disconnect();
}
}
}
If you are looking for other ways to build the file spec, like for example sync only a specific list of files to "head", etc, visit this link and search for "Building a FileSpec"

Categories

Resources