GridView Remove Item C# 2.0 - c#-2.0

What I need to do is to have the ability to remove an item from a Grid View and then update the recordset that it was removed.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" Font-Size="X-Small">
<Columns>
<asp:BoundField DataField="File" HeaderText="File" />
<asp:BoundField DataField="Remove" HeaderText="Remove" />
</Columns>
</asp:GridView>
// Backend...
private void BindGridview(ArrayList list)
{
DataTable dt = new DataTable();
dt.Columns.Add("File");
dt.Columns.Add("Remove");
int c = list.Count;
for (int i = 0; i < c; i++)
{
dt.Rows.Add();
dt.Rows[i]["file"] = list[i].ToString();
dt.Rows[i]["Remove"] = ""; // <--- Have a remove action here????
}
GridView1.DataSource = dt;
GridView1.DataBind();
}

Related

how can I fetch the value in html file I used entity framework

I wrote this below code on controller section
DateTime start = student.Timestamp;
for (int i = 0; i < 1000; i++)
{
}
DateTime end = student.Endstamp;
How can I fetch the value start and end Variable in the cshtml file(text box) ?
Please note that I am using in Entity Framework.
You can use viewbag to get values from a controller to view. e.g:
In controller
Public ActionResult Index(){
...
ViewBag.start = student.Timestamp;
for (int i = 0; i < 1000; i++)
{
//your code
}
ViewBag.end = student.Endstamp;
...
return View();
}
In View index.cshtml
<input type="text" id="txtStart" value="#ViewBag.start" />
<input type="text" id="txtEnd" value="#ViewBag.end" />
or
<p>this is start: #ViewBag.start</p>
<p>this is end: #ViewBag.End</p>

How do you convert a List query result to view model?

I have an MVC controller method List<DataRow> GetUserCriteria() which runs a standard SQL Query, no EF or automapper. After running the query it does:
DataTable dt = new DataTable();
SqlDataAdapter sdp = new SqlDataAdapter(objCommand)
conn.Open();
sdp.Fill(dt)
list = dt.AsEnumerable().ToList();
return list;
Question is in my ActionResultMethod which returns the relevant view, how can I convert that list to the right type for the view model to consume and use in the view?
public ActionResult ClientProfile() {
var rawData = GetUserCriteria();
//Convert to type for view model here and pass into the view below.
return View()
}
You can avoid converting, and make it simple:
public class aDataTableView
{
public DataTable aTable { get; set; }
}
public class HomeController : Controller
{
//use any action or code that goes here
public ActionResult Index63()
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(#"data source=.\sqlexpress;initial catalog=Breaz;integrated security=True");
//conn.Open();
SqlCommand objCommand = new SqlCommand("Select * from dbo.Example", conn);
SqlDataAdapter sdp = new SqlDataAdapter(objCommand);
sdp.Fill(dt);
//you are not explicitely disposing of dt
//dt.Dispose();
aDataTableView dtw = new aDataTableView { aTable = dt };
objCommand.Dispose();
sdp.Dispose();
conn.Close();
conn.Dispose();
return View(dtw);
}
#model Testy20161006.Controllers.aDataTableView
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index63</title>
</head>
<body>
#using (Html.BeginForm())
{
<table border="1">
<thead>
<tr>
#foreach (System.Data.DataColumn col in Model.aTable.Columns) {
<th>#col.Caption</th>
}
</tr>
</thead>
<tbody>
#foreach(System.Data.DataRow row in Model.aTable.Rows) {
<tr>
#foreach (var cell in row.ItemArray) {
<td>#cell.ToString() </td>
}
</tr>
}
</tbody>
</table>
<input type="submit" value="click" />
}
</body>
</html>
The above answer worked for the data part. I will just add that in the case of what I am doing, I was able to achieve it by doing the following in my controller:
public ActionResult Index63() {
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(#"data source=.\sqlexpress;initial catalog=Breaz;integrated security=True");
//conn.Open();
SqlCommand objCommand = new SqlCommand("Select * from dbo.Example", conn);
SqlDataAdapter sdp = new SqlDataAdapter(objCommand);
sdp.Fill(dt);
aDataTableView dtw = new aDataTableView { aTable = dt };
//Cast Each Row Element to an object
object FirstNameField = dt.Row[0][3]
//Map user values to model backing view
Index63ViewModel userViewModel = new Index63ViewModel();
userViewModel.FirstName = FirstNameField.ToString();
return(userViewModel)
}
This approach works for passing a single user profile data to the view which is what I needed in this case. Credit is also given to the above link as well. Thank you!

Exporting a list to Excel and OpenOffice

I have one list where I need to export data in excel. The Code in View:
$("#btnExport").click(function () {
//Used for Export to excel
window.open('#Url.Action("ExportHotelUtilizationListToExcel","DutyTravel")');
});
<input type="button" value="Export to Excel" name="submitButton" id="btnExport" class="k-button" />
and below is my controller method
public FileResult ExportHotelUtilizationListToExcel()
{
var grid = new System.Web.UI.WebControls.GridView();
List<DutyTravelHotelUtilization> lstSeparation = null;
if (Session["HotelUtilizationDetails"] != null)
{
lstSeparation = (List<DutyTravelHotelUtilization>)HttpContext.Session["HotelUtilizationDetails"];
grid.DataSource = from d in lstSeparation
select new
{
RequestCode = d.DutyTravelReqId,
StffNumber = d.StaffNumber,
StaffName = d.StaffName,
CityCode = d.CityCode,
CityName = d.CityName,
HotelCategory = d.HotelCategory,
HotelName = d.HotelName,
CurrencyInQAR = d.QurrencyQAR,
CheckInDate = Convert.ToDateTime(d.CheckInDate).ToString("dd-MMM-yyyy"),
CheckOutDate = Convert.ToDateTime(d.CheckOutDate).ToString("dd-MMM-yyyy"),
Duration = d.Duration
};
}
grid.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
return File(new System.Text.UTF8Encoding().GetBytes(sw.ToString()), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Contacts.xlsx");
}
It is showing download option and able to open in OpenOffice but in MS Office 2010 showing error message about some format issue.

multilevel tree with struts2

I am new in Struts2 and jQuery.
I am try to make a tree with TreeTag struts2-jquery.
But I try to make two levels.
This is my code.
In action.
public class TreeCategoriasAction extends ActionSupport {
private static final long serialVersionUID = 1421993767228006685L;
private FMCategorias fMCategorias;
public FMCategorias getCategorias() { return fMCategorias; }
private TreeNode nodes = new TreeNode();
public String execute() throws Exception {
SmpConsultaCategorias smpConsultaCategorias = new SmpConsultaCategorias();
smpConsultaCategorias.setCategoriaFilter(new SoCategoriaFilter());
smpConsultaCategorias.getCategoriaFilter().setCoIdioma(ActionContext.getContext().getLocale().getLanguage().toUpperCase());
SWGestionarCategoriasProxy proxy = new SWGestionarCategoriasProxy(TiendaWebProperties.getProperty(TiendaWebProperties.SERVICIO_CATEGORIAS_ENDPOINT));
SoCategoria[] soCategoriaArray = proxy.consultaCategorias(smpConsultaCategorias);
fMCategorias = Mapeador.mapear(soCategoriaArray);
ServletActionContext.getRequest().setAttribute("categorias", fMCategorias);
nodes.setId("Categorias");
nodes.setState(TreeNode.NODE_STATE_OPEN);
nodes.setTitle("Categorias");
TreeNode [] nodo = new TreeNode[soCategoriaArray.length];
Collection<TreeNode> children = new ArrayList<TreeNode>();
for (int i = 0; i < soCategoriaArray.length; i++) {
if (soCategoriaArray[i].getIdCategoriaPadre() == null) {
nodo[i]=new TreeNode();
nodo[i].setId(soCategoriaArray[i].getIdCategoria());
nodo[i].setState(TreeNode.NODE_STATE_OPEN);
nodo[i].setTitle(soCategoriaArray[i].getDeCategoria());
children.add(nodo[i]);
for (int j = 0; j < soCategoriaArray.length; j++){
if (soCategoriaArray[j].getIdCategoriaPadre() == soCategoriaArray[i].getIdCategoria()){
Collection<TreeNode> children2 = new ArrayList<TreeNode>();
nodo[j]=new TreeNode();
nodo[j].setId(soCategoriaArray[j].getIdCategoria());
nodo[j].setState(TreeNode.NODE_STATE_CLOSED);
nodo[j].setTitle(soCategoriaArray[j].getDeCategoria());
children2.add(nodo[j]);
nodo[i].setChildren(children2);
}
}
}
nodes.setChildren(children);
}
return SUCCESS;
}
public TreeNode getNodes() {
return nodes;
}
}
In jsp
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<%# taglib prefix="sjt" uri="/struts-jquery-tree-tags"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<sj:head jqueryui="true" customBasepath="css" jquerytheme="jquery_tree_ui"debug="true" />
<s:url var="treeCategoriasUrl" action="TreeCategorias.action"/>
<sjt:tree
id="treeDynamicAjax"
jstreetheme="apple"
rootNode="nodes"
nodeHref="%{echo}"
nodeTitleProperty="title"
nodeIdProperty="id"
nodeHrefParamName="echo"
childCollectionProperty="children"
/>
<s:iterator value=#nodo[i]>
<sjt:tree
id="treeDynamicAjax2"
jstreetheme="apple"
rootNode="#nodo[i]"
nodeHref="%{echo}"
nodeTitleProperty="title"
nodeIdProperty="id"
nodeHrefParamName="echo"
childCollectionProperty="children2"
/>
</s:iterator>
Only works the first for and the first tree.
Can anybody help me?
In action
nodes.setId("Bricor");
nodes.setState(TreeNode.NODE_STATE_OPEN);
nodes.setTitle("Bricor");
getTreeNode (soCategoriaArray, nodes, null);
private void getTreeNode(SoCategoria[] soCategoriaArray, TreeNode nodoPadre, String idCategoriaPadre) {
List<TreeNode> nodos = new ArrayList<TreeNode>();
for (int i = 0; i < soCategoriaArray.length; i++){
if ((idCategoriaPadre == null && soCategoriaArray[i].getIdCategoriaPadre() == null) || (soCategoriaArray[i].getIdCategoriaPadre() != null && soCategoriaArray[i].getIdCategoriaPadre().equals(idCategoriaPadre))){
TreeNode nodo = new TreeNode();
nodo.setId(soCategoriaArray[i].getIdCategoria());
nodo.setState(TreeNode.NODE_STATE_OPEN);
nodo.setTitle(soCategoriaArray[i].getDeCategoria());
nodos.add(nodo);
getTreeNode(soCategoriaArray, nodo, soCategoriaArray[i].getIdCategoria());
}
}
nodoPadre.setChildren(nodos);
}
In jsp
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<%# taglib prefix="sjt" uri="/struts-jquery-tree-tags"%>
%#taglib prefix="s" uri="/struts-tags" %>
<sj:head jqueryui="true" customBasepath="css" jquerytheme="jquery_tree_ui" debug="true" />
<s:url var="treeCategoriasUrl" action="TreeCategorias.action"/>
<sjt:tree
id="treeDynamicAjax"
jstreetheme="apple"
rootNode="nodes"
nodeHref="%{echo}"
nodeTitleProperty="title"
nodeIdProperty="id"
nodeHrefParamName="echo"
childCollectionProperty="children"
/>

How to maintain state between page redirection JSf 2.0

I am making pages where you can upload pictures and then preview them. Both upload and preview work fine. But the problem is if I upload images, then preview it and then come back to the upload images page, the images are gone. Here is my code
<h:panelGrid columns="4"
border=""
width="20%"
style="position: absolute; top: 50px;"
columnClasses="asteriskColumns, nameColumns" >
<h:outputText value="*" />
<h:outputText value="Map: " />
<p:fileUpload id="cityMap"
description="Image"
update="mapImage messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="mapImage"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" />
<h:outputText value="*" />
<h:outputText value="Image1: " />
<p:fileUpload id="cityImage1"
description="Image"
update="city_Image1 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="city_Image1"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" />
<h:outputText value="*" />
<h:outputText value="Image2: " />
<p:fileUpload id="cityImage2"
description="Image"
update="city_Image2 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="city_Image2"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" />
Here is my bean
#ManagedBean
#ViewScoped
#SessionScoped
public class CityDetail {
private StreamedContent image;
private ArrayList images;
private ArrayList imageNames;
private String imagePath = "/resources/images/Untitled.jpg";
private String imagePath1 = "/resources/images" + "/";
public CityDetail() {
images = new ArrayList();
images.add(null);
images.add(null);
images.add(null);
images.add(null);
images.add(null);
imageNames = new ArrayList();
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
// Getting session ID from seession variable that is set in the City_Review Page
cityID = Integer.parseInt(ConnectionUtil.session.getAttribute("CityID").toString());
System.out.println();
}
public void imageUpload(FileUploadEvent event) {
imagePath = "";
// Variable to ensure that the query is always enter to same index.
int index = -1;
String query = "";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// File
UploadedFile uploadedFile = event.getFile();
// File Name
String fileName = uploadedFile.getFileName();
//File Extension
String fileExtension = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
String path = externalContext.getRealPath("/resources/images") + "/" ;
try {
//<p:fileUpload id="cityMap" .../>
String componentID = event.getComponent().getClientId();
if (componentID.equalsIgnoreCase("cityMap")) {
index = 0;
/**
* UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
*/
query = "UPDATE city set citymap=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityMap_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityMap_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityMap_" + cityID + fileExtension);
setImage(imagePath1, "cityMap_" + cityID + fileExtension);
//imagePath = imagePath + "cityMap" + fileExtension;
}
} else if (componentID.equalsIgnoreCase("cityImage1")) {
index = 1;
query = "UPDATE city set cityimage1=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage1_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityImage1_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityImage1_" + cityID + fileExtension);
setImage(imagePath1, "cityImage1_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage2")) {
index = 2;
query = "UPDATE city set cityimage2=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage2_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityImage2_", fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityImage2_" + cityID + fileExtension);
setImage(imagePath1, "cityImage2_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage3")) {
index = 3;
query = "UPDATE city set cityimage3=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage3_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityImage3_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityImage3_" + cityID + fileExtension);
setImage(imagePath1, "cityImage3_" + cityID + fileExtension);
}
} catch (Exception e) {
FacesMessage msg = new FacesMessage("Exception happen");
FacesContext.getCurrentInstance().addMessage(null, msg);
e.printStackTrace();
// return null;
}
} //end of imageUpload()
private void setImage(String path, String fileName) {
imagePath = path + fileName;
}
Now when I come back to this page after previewing then the images gone. How can I prevent this? Do I make 5 image path variables and then save it somewhere else? But what if I have 50 images. Is there any better option? That when I again come back to upload the page everything remains as it is to this page?
A few things are weird with your code:
You have to select a single scope for your bean, ViewScoped or SesssionScoped.
Should all h:graphicImage components be bound to the same value really?
I can't see the imagePath property of your bean.
Either you store the images in a #SessionScoped bean, or you store them to some persistent storage after you upload them.
Hi here how i done this. First here is my html
<h:form id="cityDetailForm" prependId="false" >
<p:growl id="messages"
showDetail="true" />
<p:panel id="panel1"
style="border-color: #000000;width: 954px;position: absolute;left: 150px;height: 450px;-moz-border-radius: 11px; -webkit-border-radius: 11px; border-radius: 11px; behavior: url(../PIE/PIE.htc)">
<strong Class="MainHeader">
<p:spacer width="10"/> City Detail
</strong>
<h:panelGrid columns="5"
border=""
width="20%"
style="position: absolute; top: 50px;"
columnClasses="asteriskColumns, nameColumns" >
<h:outputText value="*" />
<h:outputText value="Map: " />
<p:fileUpload id="cityMap"
description="Image"
update="city messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="city"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false">
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="city"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image1: " />
<p:fileUpload id="cityImage1"
description="Image"
update="Image1 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image1"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image1"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image2: " />
<p:fileUpload id="cityImage2"
description="Image"
update="Image2 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image2"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image2"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image3: " />
<p:fileUpload id="cityImage3"
description="Image"
update="Image3 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image3"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image3"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image4: " />
<p:fileUpload id="cityImage4"
description="Image"
update="Image4 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image4"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image4"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
</h:panelGrid>
<h:commandButton id="preview"
value="Preview"
action="#{cityDetail.preview}"
style="position: absolute; top: 350px;"
styleClass="ButtonStyle" />
<h:commandButton id="save"
value="Save"
actionListener="#{cityDetail.sendImagesToDatabase}"
action="#{cityDetail.save}"
style="position: absolute; top: 350px; left: 90px;"
styleClass="ButtonStyle" />
<h:commandButton id="cancel"
value="Cancel"
action="#{cityDetail.cancel}"
style="position: absolute; top: 350px; left: 165px;"
styleClass="ButtonStyle" />
</p:panel>
</h:form>
and now here is my bean
#ManagedBean
#ViewScoped
#SessionScoped
public class CityDetail {
private StreamedContent image;
private ArrayList images;
private ArrayList imageNames;
private String imagePath = "/resources/images/Untitled.jpg";
private String imagePath1 = "/resources/images" + "/";
private boolean remove = false;
private String once;
private static int x = 0;
// Set in the City_Review Page, in session variable
public int cityID;
/** Creates a new instance of CityDetail */
public CityDetail() {
/**
* If we come from cityView.xhtml page then this contain value. We are using this because we
* want that when user come from cityView.xhtml page then old values should be retain.
*/
imageNames = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImageNames");
images = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImages");
if (imageNames == null) {
imageNames = new ArrayList();
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
} //end of if()
if (images == null) {
images = new ArrayList();
images.add("");
images.add("");
images.add("");
images.add("");
images.add("");
}
// Getting session ID from seession variable that is set in the City_Review Page
cityID = Integer.parseInt(ConnectionUtil.session.getAttribute("CityID").toString());
once = ConnectionUtil.session.getAttribute("once").toString();
if (once.equalsIgnoreCase("true")) {
//SELECT column_name(s) FROM table_name WHERE column_name operator value
String cityMapQuery = "SELECT citymap From city Where cityid='" + cityID + "'";
String cityImage1Query = "SELECT cityimage1 From city Where cityid='" + cityID + "'";
String cityImage2Query = "SELECT cityimage2 From city Where cityid='" + cityID + "'";
String cityImage3Query = "SELECT cityimage3 From city Where cityid='" + cityID + "'";
String cityImage4Query = "SELECT cityimage4 From city Where cityid='" + cityID + "'";
ArrayList cityMapQueryArray = new ArrayList();
cityMapQueryArray.add(cityMapQuery);
ArrayList cityImage1QueryArray = new ArrayList();
cityImage1QueryArray.add(cityImage1Query);
ArrayList cityImage2QueryArray = new ArrayList();
cityImage2QueryArray.add(cityImage2Query);
ArrayList cityImage3QueryArray = new ArrayList();
cityImage3QueryArray.add(cityImage3Query);
ArrayList cityImage4QueryArray = new ArrayList();
cityImage4QueryArray.add(cityImage4Query);
ArrayList mainArray = new ArrayList();
mainArray.add(cityMapQueryArray);
mainArray.add(cityImage1QueryArray);
mainArray.add(cityImage2QueryArray);
mainArray.add(cityImage3QueryArray);
mainArray.add(cityImage4QueryArray);
} //end of if
System.out.println();
} //end of constructor()
//Getters and setters ---------------------
public StreamedContent getImage() {
return image;
}
public void setImage(StreamedContent image) {
this.image = image;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
//public String imageUpload(FileUploadEvent event) {
public void imageUpload(FileUploadEvent event) {
imagePath = "";
// Variable to ensure that the query is always enter to same index.
int index = -1;
String query = "";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// File
UploadedFile uploadedFile = event.getFile();
// File Name
String fileName = uploadedFile.getFileName();
//File Extension
String fileExtension = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
String path = externalContext.getRealPath("/resources/images") + "/" ;
try {
//<p:fileUpload id="cityMap" .../>
String componentID = event.getComponent().getClientId();
if (componentID.equalsIgnoreCase("cityMap")) {
index = 0;
/**
* UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
*/
query = "UPDATE city set citymap=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityMap_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityMap_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityMap_" + cityID + fileExtension);
// setImage(imagePath1, "cityMap_" + cityID + fileExtension, index);
// imagePath = imagePath1 + "cityMap_" + cityID + fileExtension;
}
} else if (componentID.equalsIgnoreCase("cityImage1")) {
index = 1;
query = "UPDATE city set cityimage1=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage1_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage1_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage1_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage2")) {
index = 2;
query = "UPDATE city set cityimage2=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage2_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage2_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage2_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage3")) {
index = 3;
query = "UPDATE city set cityimage3=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage3_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage3_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage3_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage4")) {
index = 4;
query = "UPDATE city set cityimage4=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage4_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage4_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage4_" + cityID + fileExtension);
}
} //end of else if()
// Convert file from input stream to bytes
byte[] byteArray = event.getFile().getContents();
/**
* Add images to list so we can retrieve them when user click on save button
*/
// boolean add = images.add(new Images(query, byteArray));
//Check for multiple clicks on the same Browse Button
// If index has value then replace the value rather then add new value to List
images.set(index, new Images(query, byteArray));
//byteArray used to store picture into database
InputStream ist = new ByteArrayInputStream(byteArray);
/*
* StreamedContent Object used to show the picture in jsf pages. We need to convert
* again bytearray to InputStream
*/
image = new DefaultStreamedContent(ist, "image/jpg");
FacesMessage msg = new FacesMessage(fileName + " succesfully uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
//we dont need to use faces-config to navigate in jsf 2
// return null ;
} catch (Exception e) {
FacesMessage msg = new FacesMessage("Exception happen");
FacesContext.getCurrentInstance().addMessage(null, msg);
e.printStackTrace();
// return null;
} //end of catch (Exception e)
} //end of imageUpload()
/**
* This method called when user click on "save" button on page cityDetail.xhtml .
* This method is called before save() function is executed. Because action listener
* runs first.
* #return
*/
public void sendImagesToDatabase(ActionEvent e) {
ArrayList mainArray = new ArrayList();
for(int i=0; i<images.size(); i++) {
ArrayList innerArray = new ArrayList();
if (images.get(i).equals("")) {
continue;
} else {
Images imageObject =(Images)images.get(i);
String query = imageObject.getQuery();
byte[] image = imageObject.getImageBytes();
innerArray.add(query);
innerArray.add(image);
mainArray.add(innerArray);
}
} //end of for()
int executeDocumentUpdateBatch = ConnectionUtil.executeDocumentUpdateBatch(mainArray);
System.out.println(executeDocumentUpdateBatch);
} //end of sendImagesToDatabase()
/**
* This method is called when user click on "preview" button on page cityDetail.xhtml
* #return
*/
public String preview() {
ConnectionUtil.session.setAttribute("cityDetailImageNames", imageNames);
ConnectionUtil.session.setAttribute("cityDetailImages", images);
return "cityView?faces-redirect=true";
} //end of preview()
/**
* This method called when user click on "save" button on page cityDetail.xhtml .
* This method is called after sendImagesToDatabase() function is executed. Because action listener
* runs first.
* #return
*/
public String save() {
ConnectionUtil.session.setAttribute("cityDetailImageNames", imageNames);
ConnectionUtil.session.setAttribute("cityDetailImages", images);
return "cityDetail?faces-redirect=true";
//return null;
} //end of save()
public String cancel() {
ConnectionUtil.session.setAttribute("cityDetailImageNames", null);
ConnectionUtil.session.setAttribute("cityDetailImages", null);
return "City_AddUpdate?faces-redirect=true";
} //end of cancel()
private void addImageNameToList(int index, String fileName) {
imageNames.set(index, fileName);
} //end of addImageNameToList()
/**
* This method is called when user click on remove link on page cityDetail.xhtml beside each image.
* We simply set boolean variable "remove" to true so when "update = <p:graphicImage Id />"
* in <p:commandLink /> is called then <p:graphicImage /> with the mentioned ID is called and
* its putImage() method is called. Then in the method we handle remove image procedure.
*/
public void removeImage() {
remove = true;
} //end of removeImage()
/**
* This method is called for every <p:graphicImage /> because we use "type = preRenderComponent"
* on every <p:graphicImage /> . In this method we we set image path and also check whether
* user coming from preview page so we can again set images to the same position.
* #param event
*/
public void putImage(ComponentSystemEvent event) {
boolean test = remove;
boolean found = false;
x++;
int y = x;
GraphicImage image1 = (GraphicImage)event.getComponent();
String imageURL = image1.getUrl();
String imageDir = image1.getDir();
String imageValue = image1.getValue().toString();
String imageId = image1.getClientId();
ArrayList imagesNames = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImageNames");
if (imagesNames == null) {
for (int i=0; i<imageNames.size(); i++) {
String fileName = imageNames.get(i).toString();
if (fileName.contains(imageId)) {
if (remove) {
imagePath = "";
imagePath = "/resources/images/Untitled.jpg";
//also remove from list so when on preview page this list called using session
// it contains "" for the remove value. Otherwise image deleted from
//cityDetail page but shown when preview is clicked
imageNames.set(i, "");
remove = false;
break;
} else {
imagePath = "";
imagePath = imagePath1 + fileName;
break;
}
} //end of if
} //end of for()
} else { //handle when retrun from preview page
for(int i=0; i<imagesNames.size(); i++) {
String fileName = imagesNames.get(i).toString();
if (fileName.contains(imageId)) {
if (remove) {
imagePath = "";
imagePath = "/resources/images/Untitled.jpg";
imageNames.set(i, ""); //also remove from list
remove = false;
break;
} else {
imagePath = "";
imagePath = imagePath1 + fileName;
break;
}
} else if (fileName.equalsIgnoreCase("")) {
imagePath = "";
imagePath = "/resources/images/Untitled.jpg";
break;
}
} //end of for
}
System.out.println();
System.out.println();
System.out.println();
} //end of putImage
} //end of class CityDetail
Now if i done anything wrong and unusal then please let me know ? because this code is working fine but working fine doesn't mean that it is perfect or correct.
Thanks

Resources