The issue I am having is with the "Office" String. I get this: java.lang.NumberFormatException: For input string: "Office:" I feel like I need to do something else with the parseline down in the tokenizer section? Am I on the right track? I am basically trying to read from a file than I will calculate total sales and write to another file. This is the error I get even when I try to display my people.txt file to an output screen on my GUI. I just need a little advice to where to look to fix this. I have looked up many things but have not came close.
public class PersonReader {
public static void main(String args[]) throws IOException {
PersonReader reader = new PersonReader();
List<person> people = reader.readPeople("people.txt");
System.out.println(people);
}
public List<person> readPeople(String filename) throws IOException {
File f = new File(filename);
FileReader reader = new FileReader(f);
BufferedReader breader = new BufferedReader(reader);
List<person> people = new ArrayList<person>();
String line = breader.readLine();
while (line != null) {
person p = null;
try {
p = parseLine(line);
} catch (Exception e) {
e.printStackTrace();
}
if (p == null) {
System.out.println("This row is bad." + line);
} else {
people.add(p);
}
line = breader.readLine();
}
return people;
}
private static person parseLine(String line) {
int repID;
String firstName;
String lastName;
double books;
double paper;
double office;
String district;
String contact;
String next;
StringTokenizer st = new StringTokenizer(line, ", ");
repID = Integer.parseInt(st.nextToken().trim());
firstName = st.nextToken().trim();
lastName = st.nextToken().trim();
books = Double.parseDouble(st.nextToken().trim());
parseLine(line);
paper = Double.parseDouble(st.nextToken().trim());
parseLine(line);
office = Double.parseDouble(st.nextToken().trim());
parseLine(line);
district = st.nextToken().trim();
parseLine(line);
contact = st.nextToken().trim();
parseLine(line);
if (repID < 1) {
return null;
}
if (firstName.length() == 0) {
return null;
}
if (lastName.length() == 0) {
return null;
}
if (books < 1) {
return null;
}
if (paper < 1) {
return null;
}
if (office < 1) {
return null;
}
if (district.length() == 0) {
return null;
}
if (contact.length() == 0) {
return null;
}
person p = new person();
p.setRepID(repID);
p.setFirstName(firstName);
p.setLastName(lastName);
p.setBooks(books);
p.setPaper(paper);
p.setOffice(office);
p.setDistrict(district);
p.setContact(contact);
return p;
}
}
Related
In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}
How can i append a pdf into another?
I tried using this code, but I am getting java.lang.NullPointerException when i try to getContentInputStream.
what am I doing wrong? How can I attach one pdf to another?
PDDocument pdfTarget = null;
InputStream is = null;
InputStream tis = null;
for (ChildAssociationRef file: quotationsFiles) {
try {
NodeRef toAppend = file.getChildRef(); //workspace://SpacesStore/11bce382-45bf-4c67-95bc-a65361b323ef
ContentReader append = getReader(toAppend);
is = append.getContentInputStream(); // Here iam getting java.lang.NullPointerException
NodeRef targetNodeRef = reportFile.getNodeRef();
ContentReader targetReader = getReader(targetNodeRef);
tis = targetReader.getContentInputStream();
String fileName = String.valueOf(serviceRegistry.getNodeService().getProperty(targetNodeRef, ContentModel.PROP_NAME));
// stream the document in
pdf = PDDocument.load(is);
pdfTarget = PDDocument.load(tis);
// Append the PDFs
PDFMergerUtility merger = new PDFMergerUtility();
merger.appendDocument(pdfTarget, pdf);
merger.setDestinationFileName(fileName);
merger.mergeDocuments();
} catch (Exception e) {
//throw new AlfrescoRuntimeException("IOException", e);
ColorLogUtil.debug(LOGGER, "IOException Error caused by :" + e);
}
}
private ContentReader getReader(NodeRef nodeRef) {
if (serviceRegistry.getNodeService().exists(nodeRef) == false) {
throw new AlfrescoRuntimeException("NodeRef: " + nodeRef + " does not exist");
}
QName typeQName = serviceRegistry.getNodeService().getType(nodeRef);
if (serviceRegistry.getDictionaryService().isSubClass(typeQName, ContentModel.TYPE_CONTENT) == false) {
throw new AlfrescoRuntimeException("The selected node is not a content node");
}
ContentReader contentReader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
if (contentReader == null) {
throw new AlfrescoRuntimeException("The content reader for NodeRef: " + nodeRef + "is null");
}
return contentReader;
}
See if this code works for you:
public NodeRef mergePdfs(List<NodeRef> nodeRefList, String fileName,NodeRef destinationNode)
throws FileNotFoundException,FileExistsException,Exception {
InputStream originalInputStream = null;
ContentReader reader = null;
NodeRef newDocNoderef = null;
PDFMergerUtility PDFmerger = new PDFMergerUtility();
ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
try {
LOGGER.debug("Merging of Doc Started");
for (NodeRef node : nodeRefList) {
reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
originalInputStream = reader.getContentInputStream();
PDFmerger.addSource(originalInputStream);
}
PDFmerger.setDestinationStream(outputstream);
PDFmerger.mergeDocuments();
if(originalInputStream!=null) {
originalInputStream.close();
}
newDocNoderef = writeContentToAlfresco(outputstream, nodeRefList, fileName,destinationNode);
LOGGER.debug("Documents are merged and new pdf is created at "+newDocNoderef);
} finally {
if(outputstream!=null)
outputstream.close();
}
return newDocNoderef;
}
public NodeRef writeContentToAlfresco(ByteArrayOutputStream outputstream, List<NodeRef> childRefList,
String fileName,NodeRef destinationNode) throws FileExistsException,IOException,Exception {
NodeRef pdf = null;
Map<QName, Serializable> props = new HashMap<>();
Map<Date, NodeRef> dateMap = new HashMap<Date, NodeRef>();
NodeRef parentNodeRef=null;
try {
LOGGER.debug("Upload to Alfresco Started");
for(NodeRef noderef : childRefList) {
Date date = (Date) nodeService.getProperty(noderef, ContentModel.PROP_MODIFIED);
dateMap.put(date, noderef);
}
Map<Date, NodeRef> m1 = new TreeMap<Date, NodeRef>(dateMap);
Map.Entry<Date, NodeRef> entry = m1.entrySet().iterator().next();
NodeRef finalnodeRef = entry.getValue();
if(destinationNode!=null) {
parentNodeRef = destinationNode;
}else {
parentNodeRef = nodeService.getPrimaryParent(finalnodeRef).getParentRef();
}
QName[] myModelProps = CommonConstants.myModelProps;
for (QName myModelProp : myModelProps) {
Serializable object = nodeService.getProperty(finalnodeRef, myModelProp);
props.put(myModelProp, object);
}
FileInfo pdfInfo = fileFolderService.create(parentNodeRef, fileName + ".pdf",
MyModel.TYPE_CUSTOM_MYMODEL_TYPE);
pdf = pdfInfo.getNodeRef();
nodeService.setProperties(pdf,props);
nodeService.setProperty(pdf, ContentModel.PROP_TITLE,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_TITLE));
nodeService.setProperty(pdf, ContentModel.PROP_DESCRIPTION,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_DESCRIPTION));
nodeService.setProperty(pdf,ContentModel.PROP_NAME,fileName + ".pdf");
ContentWriter writer = contentService.getWriter(pdf, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
writer.setEncoding("UTF-8");
writer.putContent(new ByteArrayInputStream(outputstream.toByteArray()));
LOGGER.debug("Upload to Alfresco Ended");
} catch(FileExistsException fee) {
ExceptionUtils.printRootCauseStackTrace(fee);
throw new FileExistsException(parentNodeRef, fileName);
}
catch (Exception e) {
ExceptionUtils.printRootCauseStackTrace(e);
throw new Exception(e);
} finally {
if (outputstream != null)
outputstream.close();
}
return pdf;
}
This actually seems like one of the features we support in alfresco-pdf-toolkit out of the box. You could either use that addon, or get some inspiration from the code backing it.
I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
following is the code on Placementsearch.aspx.cs
protected void Ok_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
int course_id = Convert.ToInt32(course.SelectedValue);
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int currentBacklog = Convert.ToInt32(currrentBacklogDDL.SelectedValue);
int sex = Convert.ToInt32(gender.SelectedValue);
int? eGap = null;
int? firstYrPercent = null;
int? secondYrPercent = null;
int? thirdYrPercent = null;
int? finalYearpercent = null;
int? currentDegeePercentage = null;
int? highSchoolPercentge = null;
int? higherSchoolPercentage = null;
int? grauationPercentage = null;
int? diplomaPercentage = null;
int? noOfAtkt = null;
DateTime? date = null;
if (!string.IsNullOrEmpty(DOB.Text.Trim()))
{
string dateOfBirth = DOB.Text.Trim();
DateTime birthDate = DateTime.ParseExact(dateOfBirth, "dd/mm/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string outPut = birthDate.ToString("mm/dd/YYYY");
date = Convert.ToDateTime(outPut);
}
if (!String.IsNullOrEmpty(educationGap.Text.Trim()))
{
eGap = Convert.ToInt32(educationGap.Text.Trim());
}
if (!string.IsNullOrEmpty(firstYear.Text))
{
firstYrPercent = Convert.ToInt32(firstYear.Text.Trim());
}
if (!string.IsNullOrEmpty(secondYear.Text.Trim()))
{
secondYrPercent = Convert.ToInt32(secondYear.Text.Trim());
}
if (!string.IsNullOrEmpty(thirdYear.Text))
{
thirdYrPercent = Convert.ToInt32(thirdYear.Text.Trim());
}
if (!string.IsNullOrEmpty(finalyear.Text.Trim()))
{
finalYearpercent = Convert.ToInt32(finalyear.Text.Trim());
}
if (!string.IsNullOrEmpty(currentDegree.Text.Trim()))
{
currentDegeePercentage = Convert.ToInt32(currentDegree.Text.Trim());
}
if (!string.IsNullOrEmpty(higherSchool.Text.Trim()))
{
higherSchoolPercentage = Convert.ToInt32(higherSchool.Text.Trim());
}
if (!string.IsNullOrEmpty(highSchool.Text.Trim()))
{
highSchoolPercentge = Convert.ToInt32(highSchool.Text.Trim());
}
if (!string.IsNullOrEmpty(graduation.Text.Trim()))
{
grauationPercentage = Convert.ToInt32(graduation.Text.Trim());
}
if (!string.IsNullOrEmpty(diploma.Text.Trim()))
{
diplomaPercentage = Convert.ToInt32(diploma.Text.Trim());
}
if (!string.IsNullOrEmpty(atkt.Text.Trim()))
{
noOfAtkt = Convert.ToInt32(atkt.Text.Trim());
}
Dictionary<string, object> paramList = new Dictionary<string, object>();
paramList.Add("#courseId", course_id);
paramList.Add("#passoutYear", passoutYear);
paramList.Add("#currentBacklog", currentBacklog);
paramList.Add("#sex", sex);
paramList.Add("#eGap", eGap);
paramList.Add("#firstYrPercent", firstYrPercent);
paramList.Add("#secondYrPercent", secondYrPercent);
paramList.Add("#thirdYrPercent", thirdYrPercent);
paramList.Add("#finalYearpercent", finalYearpercent);
paramList.Add("#currentDegeePercentage", currentDegeePercentage);
paramList.Add("#highSchoolPercentge", highSchoolPercentge);
paramList.Add("#higherSchoolPercentage", higherSchoolPercentage);
paramList.Add("#grauationPercentage", grauationPercentage);
paramList.Add("#diplomaPercentage", diplomaPercentage);
paramList.Add("#noOfAtkt", noOfAtkt);
paramList.Add("#date", date);
StringBuilder branchId= new StringBuilder();
foreach (ListItem li in branch.Items)
{
if (li.Selected)
{
branchId.Append(Convert.ToInt32(li.Value));
}
}
DataTable dt = searchManager.GetEligibleStudent(paramList, branchId);
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error On Button click Ok", ex);
}
this is the method which is called from above page. this method is on class searchstudentDAO.cs
public DataTable GetEligibleStudent(Dictionary<string, object> paramList, StringBuilder branchId)
{
try
{
string cmd = #"SELECT * FROM [tbl_students] WHERE course_id=#courseId
AND branch_id IN(" + branchId + #")
AND (#firstYrPercent is null OR first_year_percent>=#firstYrPercent)
AND (#secondYrpercent is null OR second_year_percent>=#secondYrPercent)
AND (#thirdYrPercent is null OR third_year_percent>=#thirdYrPercent)
AND (#finalYearpercent is null OR final_year_percent>=#finalYearpercent)
AND (#currentDegeePercentage is null OR current_degree_percent>=#currentDegeePercentage)
AND (#passoutYear is null OR passing_year>=#passoutYear)
AND (#currentBacklog is null OR current_backlog<=#currentBacklog)
AND gender=#sex
AND (#eGap is null OR gapin_education<=#eGap)
AND (#highSchoolPercentge is null OR highschool_percentage>=#highSchoolPercentge)
AND (#higherSchoolPercentage is null OR ssc_percentage>=#higherSchoolPercentage)
AND (#grauationPercentage is null OR graduation_percentage>=#grauationPercentage)
AND (#diplomaPercentage is null OR diploma_percentage>=#diplomaPercentage)
AND (#noOfAtkt is null OR number_of_ATKT<=#noOfAtkt)
AND (#date is null OR DOB>=#date)";
//string cmd = "SELECT * FROM [tbl_branch] WHERE course_id IN(" + sb + ")";
if (dbManager.OpenConnection())
{
dt = dbManager.GetDataTable(cmd, paramList);
return dt;
}
else
{
dt = null;
return dt;
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error ON Method Getting Eligible Students:SearchStudentDAO", ex);
dt = null;
return dt;
throw;
}
finally
{
dbManager.CloseConnection();
}
}
And followin is code called from the above method on paage App_Code/DBManager.cs
public DataTable GetDataTable(string strCmd, Dictionary<string, object> paramList)
{
try
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(strCmd, _sqlCon);
foreach (KeyValuePair<string, object> kvp in paramList)
{
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
logger.Error("Error when executing Query " + strCmd, ex);
throw;
return null;
}
}
Now i am getting exception for those null parameter which are not provided
"Parameterized Query '(#courseId int,#passoutYear int,#currentBacklog int,#sex int,#eG' expects parameter #finalYearpercent, which was not supplied."
please correct me where i am wrong
Instead of simply not adding those parameters if they're null, you need to add them, but with the "value" set to DBNull.Value.
I have a problem with my ASP.NET website, it got hacked. One hacker found a bug in my login system and he can login with every account he wants, even if the account is normal user, moderator or administrator. He can delete everything he wants.
Please can anyone help me, tell me if there is any vulnerable function or something
P.S. I'm not myself an ASP.NET programmer, I know only PHP, so please tell me exactly what I need to edit in the code, because I don't know ASP.NET at all.
ThanksAS
public void loginButton_Click(object sender, EventArgs e)
{
string username = nicknameTextBox.Text;
string password = passwordTextBox.Text;
string returnUrl = Request.QueryString["returnUrl"];
if (returnUrl == null) returnUrl = Convert.ToBase64String(Encoding.ASCII.GetBytes(Request.Url.ToString()));
string message = CurrentPlayer.LoginRequest(username, password, returnUrl);
if(message != null)
Response.Redirect("AccountLogin.aspx?returnUrl=" + returnUrl);
}
LoginRequest:
public static string LoginRequest(string username, string password, string returnUrl)
{
Player player = null;
string message = InputValidator.CheckLoginRequest(username, password, out player);
if (message != null) return message;
message = LoginCookie.CheckLoginRequest(player);
if (message != null) return message;
SessionPlayer sessionPlayer = new SessionPlayer(
player.ID, player.ActivationGuid, (PlayerRole)player.IdRole,
player.Nickname, player.CreationDate);
SessionMessages sessionMessages = new SessionMessages(player.ID);
SessionOwnedCounts ownedCounts = new SessionOwnedCounts(player.ID);
SessionGuestCounts guestCounts = new SessionGuestCounts(player.ID);
SessionMatchCounts matchCounts = new SessionMatchCounts(player.ID);
CurrentPlayer.Login(sessionPlayer, sessionMessages, ownedCounts, guestCounts, matchCounts);
Player.UpdateLastLogin(player.ID);
returnUrl = Encoding.ASCII.GetString(Convert.FromBase64String(returnUrl));
HttpContext.Current.Response.Redirect(returnUrl);
return null;
}[/code]
Login:
private static void Login(SessionPlayer player, SessionMessages messages, SessionOwnedCounts ownedCounts, SessionGuestCounts guestCounts, SessionMatchCounts matchCounts)
{
HttpContext.Current.Session["player"] = player;
HttpContext.Current.Session["messages"] = messages;
HttpContext.Current.Session["ownedCounts"] = ownedCounts;
HttpContext.Current.Session["guestCounts"] = guestCounts;
HttpContext.Current.Session["matchCounts"] = matchCounts;
if (LoginCookie.Exists() == false)
LoginCookie.AddForFirstTime(player.Nickname, player.Guid);
else
LoginCookie.SetToLoginAction();
}
And checkloginrequest:
public static string CheckLoginRequest(string username, string password, out Player player)
{
player = null;
object lastLoginTryDateObj = HttpContext.Current.Session["lastLoginTryDate"];
if (lastLoginTryDateObj == null)
{
HttpContext.Current.Session["lastLoginTryDate"] = DateTime.Now;
HttpContext.Current.Session["lastLoginTryCount"] = 1;
}
else
{
DateTime lastLoginTryDate = (DateTime)HttpContext.Current.Session["lastLoginTryDate"];
int lastLoginTryCount = (int)HttpContext.Current.Session["lastLoginTryCount"];
TimeSpan ts = DateTime.Now - lastLoginTryDate;
if (ts.TotalSeconds < 60)
{
if (lastLoginTryCount >= Settings.AllowedLoginTriesPerMinute)
{
return "Ai depasit numarul maxim de incercari pe minut .<br/>Vino inapoi dupa " + (60 - (int)ts.TotalSeconds).ToString() + " secunde.";
}
else
{
HttpContext.Current.Session["lastLoginTryCount"] = lastLoginTryCount + 1;
}
}
else
{
HttpContext.Current.Session["lastLoginTryDate"] = DateTime.Now;
HttpContext.Current.Session["lastLoginTryCount"] = 1;
}
}
player = Player.GetPlayer(username, password);
if (player == null)
{
return "Usernameul si parola nu se potrivesc.";
}
if (player != null && player.IsActive == false)
{
return "Contul a fost creat dar nu e activat.<br/> Verifica mailul " + player.Email + " si activeaza-ti contul.";
}
PlayerSuspended ps = BLL.PlayerSuspended.SuspendedGet(player.ID);
if (ps != null)
{
return "Contul tau e suspendat pana in data de " + ps.SuspendedEndDate.ToString("dd-MM-yyyy") + ".<br/>Motivul: " + ps.SuspendedReason;
}
return null;
}
GetPlayer:
public static Player GetPlayer(string nickname, string password)
{
Player player = null;
object[] values = DAL.Player.GetPlayer(nickname, password);
if (values != null)
{
player = new Player();
player.SetFromValues(values);
}
return player;
}
DAL.Player.GetPlayer:
public static object[] GetPlayer(string nickname, string password)
{
password = Convert.ToBase64String(Encoding.ASCII.GetBytes(password));
List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(new SqlParameter("#Nickname", nickname));
sqlParams.Add(new SqlParameter("#Password", password));
return DataBase.GetFirstRow("[spPlayer.Get]", sqlParams);
}
Your site is vulnerable to session fixation
Why are you not using asp.net forms authentication and membership?