NullReferenceException was unhandledby user code - vb.net

I am making a registration page and while using an input tag to upload image of the user, it is giving an error while running the website: "NullReferenceException was unhandledby user code". Please help me to sort this out. The method which is giving error is:
protected void Button2_Click(object sender, EventArgs e)
{
var path = "Memberimg";
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Memberimg") + "\\" + fn;
if ((f1.PostedFile != null) && (f1.PostedFile.ContentLength > 0))
{
try
{
f1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
else
{
Response.Write("Please select a file to upload.");
}
}

You are referring to f1.PostedFile before checking to see if it is null, in the line with:
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);

Related

Is there any way to message on whatsapp without opening the application

I've been searching for the solution to send the message on whatsapp from the Application or via REST-APIs without opening it.
As I have mentioned below the code will validate for the Whatsapp-type installed in device and then it will send it to user but in this case it launch the whatsapp.
private void launchWhatsapp(String msg) {
try {
boolean installed2 = obj.appInstalledOrNot("com.whatsapp.w4b");
if (installed2) try {
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setPackage("com.whatsapp.w4b");
String url = "https://api.whatsapp.com/send?" +
"phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
"&text=" + msg;
sendIntent.setData(Uri.parse(url));
if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
startActivityForResult(sendIntent, 104);
}
} catch (Exception e) {
e.printStackTrace();
}
else {
boolean installed = obj.appInstalledOrNot("com.whatsapp");
if (installed) {
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setPackage("com.whatsapp");
String url = "https://api.whatsapp.com/send?" +
"phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
"&text=" + msg;
sendIntent.setData(Uri.parse(url));
if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
startActivityForResult(sendIntent, 104);
}
} else {
Toast.makeText(InvoiceReport.this, "Whatsapp not available", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
//Log.e("Error", "ERROR_OPEN_MESSANGER"+e.toString());
}
}
I am expecting if anyone click on the browser on send message then this redirect to whatsapp application.

How to get the method name and line number in Exception in ASP Core 5

I want to get the method name and line number when an error occur, I am using Core 5.
try
{
//My code
}
catch (Exception ex)
{
_logger.LogError(ex, "Method Name / Line Number");
}
Update:
I found a Solution like this:
_logger.LogError(ex, "\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());
A simple call to ToString() on exception will give you the complete information needed. For example when we run the following code:
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The output would be somewhat like:
System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
where Main() is the method name and 20 is the line number.
To get the format as required in question we can write a wrapper around the exception and fetch the line number from it:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}
public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
}
Note: In the extract line method, we are fetching the top most exception. This comes in handy when we have a chain of exceptions in our stack trace.

Using Dispatcher with thread

I have a list of rtf strings that are needed to convert to html. I am using a richtextbox control to convert rtf to html. My problem is this
The solution should also work but how do i implement this solution in my code?
public string ConvertRtfToHtml(string rtfText)
{
try
{
var thread = new Thread(ConvertRtfInSTAThread);
var threadData = new ConvertRtfThreadData { RtfText = rtfText };
thread.SetApartmentState(ApartmentState.STA);
thread.Start(threadData);
try
{
thread.Join();
}
catch(ThreadStateException e){
logger.Error("ThreadStateException " + e.Message);
}
catch (ThreadInterruptedException e) {
logger.Error("ThreadInterruptedException " + e.Message);
}
return threadData.HtmlText;
}
catch (Exception e){
logger.Error("ConvertRtfToHtml: " + e.InnerException.Message);
return "Error";
}
}
private void ConvertRtfInSTAThread(object rtf)
{
MarkupConverter.MarkupConverter markupConverter = new MarkupConverter.MarkupConverter();
var threadData = rtf as ConvertRtfThreadData;
try
{
threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);
}
catch(Exception e){
logger.Error("ConvertRtfInSTAThread: " + e.Message);
}
}
this markupconverter.convertrtftohtml uses richtextbox control.
Where do i fit the Dispatcher in above code?
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
Dispatcher.Run();
I used it as follows
private void ConvertRtfInSTAThread(object rtf)
{
MarkupConverter.MarkupConverter markupConverter = new MarkupConverter.MarkupConverter();
var threadData = rtf as ConvertRtfThreadData;
try
{
threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
Dispatcher.Run();
}
catch(Exception e){
logger.Error("ConvertRtfInSTAThread: " + e.Message);
}
}

Error: file doesn't exist

Now am working on a project where I need to create a folder in sdcard which am able to do. Also I need to hide/unhide it according to need. The code is working fine on emulator but not in device this is my code what went wrong ?
public class FolderCreate extends MIDlet {
private Form form;
private Display display;
FileConnection fc;
String path;
public void startApp() {
form = new Form("Hello World");
String msg = "Hello World!!!!!!!";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
System.out.println("WWWW");
try {
path = System.getProperty("fileconn.dir.memorycard");
System.out.println("Path : "+path+"/sample");
fc = (FileConnection)Connector.open(path+"/ABCD/");
if(!fc.exists())
{
fc.mkdir();
System.out.println("directory created");
}
} catch (IOException e) {
// TODO Auto-generated catch block
//System.out.println("ERROR "+e.getMessage());
Alert alert = new Alert("Alert");
alert.setString(e.getMessage());
display.setCurrent(alert);
}
try
{
//fc = (FileConnection)Connector.open(path+"/sample/");
if(fc.isHidden())
{
fc.setHidden(false);
}
else{
fc.setHidden(true);
}
fc.close();
}
catch (Exception e)
{
Alert alert = new Alert("Alert2");
alert.setString(e.toString());
display.setCurrent(alert);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
System.out.println("Destroyed");
notifyDestroyed();
}
}
The error am getting is: java.io.IOException: file does not exist
Check if path starts with "file://". If not, add the suffix.
path = System.getProperty("fileconn.dir.memorycard");
if (path != null && !path.startsWith("file://")) {
path = "file://" + path;
}
I think you are doing mistake at following line,
path = System.getProperty("fileconn.dir.memorycard");
When you are working with phone and SD-Card you should use e: drive for referring to SD Card as follows,
path = file:///e:/<folder-name>/

why pwcb.getPassword is null in this code

I try to add the rampart security to my axis2 web service using rampart module.
So here is what I have made:
I have stored in a database the hashed value of "bobWWW" password and the salt
In my PWCBHandler.java class
•I select the stored in the database password and hash
•I try to hash with same algorithm pwcb.getPassword() with the same stored salt
•check if this new hashed password is equal to the stored password
But I constantly was receiving nullpointerexception so I decide to check and wrote this code
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I see that pwcb.getPassword() is empty. So here is the code of PWCBHandler.java
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
try {
pasandsalt = getdataforChecking();
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
passwordforchecking = hash(pwcb.getPassword(),Base64.decodeBase64(pasandsalt[1]));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if((pwcb.getIdentifier().equals("bob")) && (passwordforchecking.equals(pasandsalt[0])) )
{
return;
}
}
And here is my soaprequest with the sequeiry header
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soapenv:Envelope " +
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:nilo=\"http://nilo\">"+
"<soapenv:Header>"+
'<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" soapenv:mustUnderstand="1">'+
'<wsse:UsernameToken xmlns:wsu="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="123">'+
'<wsse:Username>bob</wsse:Username>'+
'<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>'+
'</wsse:UsernameToken>'+
'</wsse:Security>'+
"</soapenv:Header>"+
"<soapenv:Body>" +
"<nilo:getdataForChecking>" +
'<nilo:data>'+tranXml+'</nilo:data>' +
' </nilo:getdataForChecking>'+
'</soapenv:Body>' +
'</soapenv:Envelope>';
According to your soap headers i can see you are using a Plain text password instead of Password Digest. You might need to change the rampart configuration
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>
this might be helpful to you. http://wso2.com/library/240/