I have a site that can upload three pictures, that page saves some other data in the table in SQL Server, but it saves the name of one the pictures the same for pictures in database.
Of course, the name of the pictures are different in the folder that save.
My code:
foreach (var item in FileUpload)
{
if (item != null)
{
Random rnd = new Random();
string Pic = rnd.Next().ToString() + ".jpg";
// string Pic = System.IO.Path.GetFileName(file.FileName);
string Path = System.IO.Path.Combine(Server.MapPath("~/images/cover/"));
item.SaveAs(Path + Pic);
using (MemoryStream ms = new MemoryStream())
{
item.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
lstName.Add(Pic);
}
}
else
{
lstName.Add("9.jpg");
}
RContact.InsertContact(t, lstNam);
ViewBag.Style = "color:green;";
}
and I write in the Repository:
public bool InsertContact(tbl_contact t, List<string> PicsName)
{
db.tbl_contact.Add(t);
foreach (var item in PicsName)
{
t.picname = PicsName[0];
t.picnamet = PicsName[1];
t.picnametr = PicsName[2];
db.tbl_contact.Add(t);
}
return Convert.ToBoolean(db.SaveChanges());
}
but it save the same name.
Related
I am created an rest API for generate the PDF file using itext API. Please help me out how to generate this and send to UI for download that PDF.
Here I am Using Angularjs,SpringBoot and Mysql as DB.
#RequestMapping(value = "/generateGeneralLedgerReportPdf", method =
RequestMethod.GET)
public void generateSalesReportPdf(#RequestParam("ledgerStartDate")
String ledgerStartDate,
#RequestParam("ledgerEndDate") String ledgerEndDate) {
try {
SimpleDateFormat simpleDateFormat = new
SimpleDateFormat("yyyy-MM-dd");
Date startDate =
simpleDateFormat.parse(ledgerStartDate);
Date endDate = simpleDateFormat.parse(ledgerEndDate);
List<GeneralLedger> listLedgerDetails = null;
int count = 0;
File file = new File("E:\\GeneralLedgerReport.pdf");
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new
FileOutputStream(file));
document.open();
//create PDF
PdfPTable table = new PdfPTable(6); // 10 columns.
table.setWidthPercentage(100); //Width 100%
PdfPCell c1 = new PdfPCell(new Phrase("#"));
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
c1.setBackgroundColor(BaseColor.GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("DATE"));
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
c1.setBackgroundColor(BaseColor.GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("INCOME CATEGORY"));
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
c1.setBackgroundColor(BaseColor.GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("AMOUNT"));
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
c1.setBackgroundColor(BaseColor.GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("EXPENSE CATEGORY"));
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
c1.setBackgroundColor(BaseColor.GRAY);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("AMOUNT"));
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
c1.setBackgroundColor(BaseColor.GRAY);
table.addCell(c1);
listLedgerDetails = generalLedgerService.generateGeneralLedgerPdfByRange(startDate, endDate);
if (!listLedgerDetails.isEmpty()) {
for (GeneralLedger ledger : listLedgerDetails) {
count ++;
Double incomeAmount = ledger.getIncomeAmount();
if(incomeAmount==null) {
incomeAmount = 0.0d;
}
Double expenseAmount = ledger.getExpenseAmount();
if(expenseAmount==null) {
expenseAmount = 0.0d;
}
table.addCell(String.valueOf(count));
table.addCell(String.valueOf(ledger.getLedgerDate()));
table.addCell(ledger.getIncomeCategory());
table.addCell(String.valueOf(incomeAmount));
table.addCell(ledger.getExpenseCategory());
table.addCell(String.valueOf(expenseAmount));
}
}
document.add(table);
document.close();
writer.close();
}catch (Exception e) {
e.printStackTrace();
}
}
Angularjs
$scope.generateGeneralLedgerReportPdf = function(startDate,endDate){
$http({
url:
'service/generalLedger/generateGeneralLedgerReportPdf',
method: "GET",
params: {ledgerStartDate:startDate,ledgerEndDate:endDate}
})
.success(function(response){
console.log("Success");
})
.error(function(response) {
console.log("Failed");
});
};
It is giving me proper OUTPUT but it is storing in local system E: drive. but i want to download in browser window.
Your code to download is missing also that depends on file created is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().
If it's not, you'll need to manually copy it to response output stream:
Add the below code to your code.
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
You'll need to handle the appropriate exceptions, of course.
I added only these lines of code and it worked for me.
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
String mimeType =
URLConnection.guessContentTypeFromStream(inputStream);
if(mimeType==null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setContentLength((int)file.length());
response.setHeader("Content-Disposition",String.format("attachment; fileName=\"%s\"", file.getName()));
FileCopyUtils.copy(inputStream, response.getOutputStream());
I've made a windows forms app that imports data to my sql database.
This is how data can look in the database
Problem If I now want to import more data and say that there is a entry in the new data that I'm importing that already exist in my sql data table, that is, an entry with the exact same value that already exist in my sql table. Then I would like to not import this particular entry and move on the next one.
The code I'm using for this is paintstakingly slow and I would like to find a quicker/better way of doing this. Please see #region DAX for the code and the try catch.
Here is the code that executes on my button click for import :)
Thanks!
private void dataImportButton_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
int candle = 0;
string candleStick = "";
foreach (var item in checkedListBox1.CheckedItems)
{
candleStick += item.ToString();
}
Regex regex = new Regex(#"\d*");
Match match = regex.Match(candleStick);
if (match.Success)
{
candle = Convert.ToInt32(match.Value);
}
string nameOfTable = string.Empty;
foreach (var item in checkedListBox2.CheckedItems)
{
nameOfTable += item.ToString();
}
string filePath = textBox1.Text;
var listaNerladdat = System.IO.File.ReadLines(filePath);
if (nameOfTable == "DAX")
#region DAX
{
foreach (var item in listaNerladdat)
{
var splitLista = item.Split(';').ToList();
if (splitLista.Count < 5)
continue;
var tmpSplitInfo = new DaxSuperTabell();
DateTime tmpDate;
if (DateTime.TryParse(splitLista[0], out tmpDate))
tmpSplitInfo.TimeStampMVCR = tmpDate;
double tmpX;
if (Double.TryParse(splitLista[1].Replace('.', ','), out tmpX))
tmpSplitInfo.HighPriceMVCR = tmpX;
if (Double.TryParse(splitLista[2].Replace('.', ','), out tmpX))
tmpSplitInfo.LowPriceMVCR = tmpX;
if (Double.TryParse(splitLista[3].Replace('.', ','), out tmpX))
tmpSplitInfo.OpenPriceMVCR = tmpX;
if (Double.TryParse(splitLista[4].Replace('.', ','), out tmpX))
tmpSplitInfo.ClosePriceMVCR = tmpX;
tmpSplitInfo.CandleStick = candle;
try{
_context.DaxSuperTabell.AddRange(tmpSplitInfo);
_context.SaveChanges();
}
catch{MessageBox.Show("This entry is a double")}
}
}
#endregion
}
i have uploaded my files to ftb server, now i want to display that files in my local windows application gridview
i want to display that files in datagridview.
public List<string> ListFiles()
{
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create("ftp://ipaddress/Requests/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential("username", "password");
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
files.Add(line.Split(new[] { ' ', '\t' }).Last());
}
}
return files;
}
}
}
following is the code on my load form.
FTPItility is my class in which listfiles is a method
FTPUtility obj = new FTPUtility();
List<string> strings = new List<string>();
dataGridViewRequest.DataSource = obj.ListFiles();
Here is the code you can use.
Here is code of FtpUtility:
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}
And here is the code of form:
I have created an instance of FtpUtility and passed requiered parameters to it, then get the files and put it in a friendly list(Name, Path) and bind to grid:
private void Form1_Load(object sender, EventArgs e)
{
this.LoadFiles();
}
public void LoadFiles()
{
var ftp = new FtpUtility();
ftp.UserName = "username";
ftp.Password = "password";
ftp.Path = "ftp://address";
this.dataGridView1.DataSource = ftp.ListFiles()
.Select(x => new
{
Name = x, //Name Column
Path = ftp.Path + x //Path Column
}).ToList();
}
Data drven framework, where the values are changing for every case
public static void main(String[] args) throws BiffException, IOException {
Sheet s;
WebDriver driver = new FirefoxDriver();
FileInputStream fi = new FileInputStream("D:\\Nikhil\\FGX\\DataDriven.xlsx");
Workbook W = Workbook.getWorkbook(fi);
s = W.getSheet(0);
for(int row = 0;row <= s.getRows();row++)
{
String Username = s.getCell(0,row).getContents();
System.out.println("Username" +Username);
driver.get("http://********");
driver.findElement(By.xpath("//*[#id='LoginName']")).sendKeys(Username);
String password= s.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.xpath("//*[#id='Password']")).sendKeys(password);
driver.findElement(By.xpath("html/body/form/div/div/div/div/fieldset/button")).click();
}
There are several reasons to get the BiffException look at Biff exception in Java.
Make sure you point the correct file, sheet, cell etc. You need to fetch and iterate the excel data. I may not answered directly to your answer, but the below code might help you,
List getData() { **Fetch the data
String path = "filepath";
List dataList = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(path));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("TestData");
java.util.Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
XSSFRow row = ((XSSFRow) rows.next());
// int r=row.getRowNum();
java.util.Iterator cells = row.cellIterator();
int i = 0;
String[] testData= new String[3];
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
String value = cell.getStringCellValue();
if (!value.equals(null)) {
testData [i] = value;
i++;
}
}
dataList.add(testData);
}
}
catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
public Object[][] data() { **Store the data in desired format
#SuppressWarnings("rawtypes")
List dataList= getData();
Object a[][]=new Object[dataList.size()][2];
for(int i=1;i<dataList.size();i++){
String[] test=(String[]) dataList.get(i);
String username = test[0];
String password=test[1];
a[i][0]=username;
a[i][1]=password;
}
return a;
Seems, like a very basic thing, but I could not find it.
I have a bunch of log4j/log4net log files. I would like to dump them into a database in order to be able to analyze them with ease.
I thought I would find a tool to do it in no time, apparently I am wrong.
Does anyone know of such a tool?
OK, so I found no utility. Had to write my own. Of course, it is strictly tailored to my immediate needs (time is money), however, it can save you a bit of time to start your own, in case of a need. Here is the complete code in C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
public class LogEntry
{
private const string PATTERN = #"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{4}) (\S+) \[(\d+)\] (\w+) (\S+) - (.*)$";
private static readonly Regex s_regex = new Regex(PATTERN, RegexOptions.Compiled);
public DateTime TS;
public string Machine;
public int Thread;
public string Level;
public string Logger;
public string Message;
public static LogEntry TryCreate(string line)
{
var match = s_regex.Match(line);
return match.Success ? new LogEntry
{
TS = DateTime.ParseExact(match.Groups[1].Value, "yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture),
Machine = match.Groups[2].Value,
Thread = int.Parse(match.Groups[3].Value),
Level = match.Groups[4].Value,
Logger = match.Groups[5].Value,
Message = match.Groups[6].Value,
} : null;
}
public void AppendToMessage(string line)
{
Message += Environment.NewLine + line;
}
}
static void Main()
{
const string SQL = #"
INSERT INTO log ( ts, machine, thread, level, logger, message, journalId)
VALUES (#ts, #machine, #thread, #level, #logger, #message, #journalId)
";
using (var connection = new SqlConnection("server=localhost;database=misc;uid=SantaClaus;pwd=MerryChristmas"))
{
connection.Open();
using (var command = new SqlCommand(SQL, connection))
{
var tsParam = new SqlParameter("#ts", SqlDbType.DateTime);
var machineParam = new SqlParameter("#machine", SqlDbType.NVarChar, 32);
var threadParam = new SqlParameter("#thread", SqlDbType.Int);
var levelParam = new SqlParameter("#level", SqlDbType.NVarChar, 10);
var loggerParam = new SqlParameter("#logger", SqlDbType.NVarChar, 128);
var messageParam = new SqlParameter("#message", SqlDbType.NVarChar, -1);
var journalIdParam = new SqlParameter("#journalId", SqlDbType.Int);
command.Parameters.Add(tsParam);
command.Parameters.Add(machineParam);
command.Parameters.Add(threadParam);
command.Parameters.Add(levelParam);
command.Parameters.Add(loggerParam);
command.Parameters.Add(messageParam);
command.Parameters.Add(journalIdParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
int i = 0;
foreach (var file in Directory.GetFiles(#"c:\tmp\dfbje01"))
{
journalIdParam.Value = OpenJournal(connection, file);
command.Transaction = connection.BeginTransaction();
foreach (var e in GetLogEntries(file))
{
tsParam.Value = e.TS;
machineParam.Value = e.Machine;
threadParam.Value = e.Thread;
levelParam.Value = e.Level;
loggerParam.Value = e.Logger;
messageParam.Value = e.Message;
command.ExecuteNonQuery();
++i;
if (i == 1000)
{
i = 0;
command.Transaction.Commit();
command.Transaction = connection.BeginTransaction();
}
}
command.Transaction.Commit();
CloseJournal(connection, journalIdParam.Value);
}
}
}
}
private static void CloseJournal(SqlConnection connection, object id)
{
const string SQL = "UPDATE journal SET done = 1 WHERE id = #id";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#id", id));
command.ExecuteNonQuery();
}
}
private static object OpenJournal(SqlConnection connection, string filePath)
{
const string SQL = "INSERT INTO journal (filePath) OUTPUT inserted.id VALUES (#filePath)";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#filePath", filePath));
return command.ExecuteScalar();
}
}
private static IEnumerable<LogEntry> GetLogEntries(string filePath)
{
LogEntry prev = null;
foreach (var line in File.ReadLines(filePath))
{
var logEntry = LogEntry.TryCreate(line);
if (logEntry != null)
{
if (prev != null)
{
yield return prev;
}
prev = logEntry;
}
else if (prev != null)
{
prev.AppendToMessage(line);
}
else
{
// Oops
Console.WriteLine(line);
}
}
if (prev != null)
{
yield return prev;
}
}
}
}
Mind trying out the filtering, search, colorizing features of the latest developer snapshot of Chainsaw? It has a good number of features which may avoid the need to use a DB. If you use a VFSLogFilePatternReceiver, it can parse and tail any regular text file, including those created by log4net.
Latest developer snapshot of Chainsaw is available here:
http://people.apache.org/~sdeboy